1#!/usr/bin/env perl
2
3# Find functions making recursive calls to themselves.
4# (Multiple recursion where a() calls b() which calls a() not covered.)
5#
6# When the recursion depth might depend on data controlled by the attacker in
7# an unbounded way, those functions should use interation instead.
8#
9# Typical usage: scripts/recursion.pl library/*.c
10#
11# Copyright The Mbed TLS Contributors
12# SPDX-License-Identifier: Apache-2.0
13#
14# Licensed under the Apache License, Version 2.0 (the "License"); you may
15# not use this file except in compliance with the License.
16# You may obtain a copy of the License at
17#
18# http://www.apache.org/licenses/LICENSE-2.0
19#
20# Unless required by applicable law or agreed to in writing, software
21# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
22# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23# See the License for the specific language governing permissions and
24# limitations under the License.
25
26use warnings;
27use strict;
28
29use utf8;
30use open qw(:std utf8);
31
32# exclude functions that are ok:
33# - mpi_write_hlp: bounded by size of mbedtls_mpi, a compile-time constant
34# - x509_crt_verify_child: bounded by MBEDTLS_X509_MAX_INTERMEDIATE_CA
35my $known_ok = qr/mpi_write_hlp|x509_crt_verify_child/;
36
37my $cur_name;
38my $inside;
39my @funcs;
40
41die "Usage: $0 file.c [...]\n" unless @ARGV;
42
43while (<>)
44{
45    if( /^[^\/#{}\s]/ && ! /\[.*]/ ) {
46        chomp( $cur_name = $_ ) unless $inside;
47    } elsif( /^{/ && $cur_name ) {
48        $inside = 1;
49        $cur_name =~ s/.* ([^ ]*)\(.*/$1/;
50    } elsif( /^}/ && $inside ) {
51        undef $inside;
52        undef $cur_name;
53    } elsif( $inside && /\b\Q$cur_name\E\([^)]/ ) {
54        push @funcs, $cur_name unless /$known_ok/;
55    }
56}
57
58print "$_\n" for @funcs;
59exit @funcs;
60