This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flawfinder.py
1880 lines (1664 loc) · 76.9 KB
/
flawfinder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""flawfinder: Find potential security flaws ("hits") in source code.
Usage:
flawfinder [options] [source_code_file]+
See the man page for a description of the options."""
# The default output is as follows:
# filename:line_number [risk_level] (type) function_name: message
# where "risk_level" goes from 0 to 5. 0=no risk, 5=maximum risk.
# The final output is sorted by risk level, most risky first.
# Optionally ":column_number" can be added after the line number.
#
# Currently this program can only analyze C/C++ code.
#
# Copyright (C) 2001-2017 David A. Wheeler.
# This is released under the
# GNU General Public License (GPL) version 2 or later (GPL-2.0+):
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# This code is written to run on both Python 2.7 and Python 3.
# The Python developers did a *terrible* job when they transitioned
# to Python version 3, as I have documented elsewhere.
# Thankfully, more recent versions of Python 3, and the most recent version of
# Python 2, make it possible (though ugly) to write code that runs on both.
# That *finally* makes it possible to semi-gracefully transition.
import functools
import sys
import re
import string
import getopt
import pickle # To support load/save/diff of hitlist
import os
import glob
import operator # To support filename expansion on Windows
version = "2.0.9"
# Program Options - these are the default values.
# TODO: Switch to boolean types where appropriate.
# We didn't use boolean types originally because this program
# predates Python's PEP 285, which added boolean types to Python 2.3.
# Even after Python 2.3 was released, we wanted to run on older versions.
# That's irrelevant today, but since "it works" there hasn't been a big
# rush to change it.
show_context = 0
minimum_level = 1
show_immediately = 0
show_inputs = 0 # Only show inputs?
falsepositive = 0 # Work to remove false positives?
allowlink = 0 # Allow symbolic links?
skipdotdir = 1 # If 1, don't recurse into dirs beginning with "."
# Note: This doesn't affect the command line.
num_links_skipped = 0 # Number of links skipped.
num_dotdirs_skipped = 0 # Number of dotdirs skipped.
show_columns = 0
never_ignore = 0 # If true, NEVER ignore problems, even if directed.
list_rules = 0 # If true, list the rules (helpful for debugging)
patch_file = "" # File containing (unified) diff output.
loadhitlist = None
savehitlist = None
diffhitlist_filename = None
quiet = 1
showheading = 0 # --dataonly turns this off
ruleset_initialised = False
output_format = 0 # 0 = normal, 1 = html.
single_line = 0 # 1 = singleline (can 't be 0 if html)
omit_time = 0 # 1 = omit time-to-run (needed for testing)
required_regex = None # If non-None, regex that must be met to report
required_regex_compiled = None
ERROR_ON_DISABLED_VALUE = 999
error_level = ERROR_ON_DISABLED_VALUE # Level where we're return error code
error_level_exceeded = False
displayed_header = 0 # Have we displayed the header yet?
num_ignored_hits = 0 # Number of ignored hits (used if never_ignore==0)
def error(message):
sys.stderr.write("Error: %s\n" % message)
# Support routines: find a pattern.
# To simplify the calling convention, several global variables are used
# and these support routines are defined, in an attempt to make the
# actual calls simpler and clearer.
#
filename = "" # Source filename.
linenumber = 0 # Linenumber from original file.
ignoreline = -1 # Line number to ignore.
sumlines = 0 # Number of lines (total) examined.
sloc = 0 # Physical SLOC
# Send warning message. This is written this way to work on
# Python version 2.5 through Python 3.
def print_warning(message):
sys.stderr.write("Warning: ")
sys.stderr.write(message)
sys.stderr.write("\n")
sys.stderr.flush()
# For each file found in the file input_patch_file, keep the
# line numbers of the new file (after patch is applied) which are added.
# We keep this information in a hash table for a quick access later.
#
def htmlize(s):
# Take s, and return legal (UTF-8) HTML.
return s.replace("&", "&").replace("<", "<").replace(">", ">")
def h(s):
# htmlize s if we're generating html, otherwise just return s.
return htmlize(s) if output_format else s
def print_multi_line(text):
# Print text as multiple indented lines.
width = 78
prefix = " "
starting_position = len(prefix) + 1
#
print(prefix, end='')
position = starting_position
#
for w in text.split():
if len(w) + position >= width:
print()
print(prefix, end='')
position = starting_position
print(' ', end='')
print(w, end='')
position += len(w) + 1
# This matches references to CWE identifiers, so we can HTMLize them.
# We don't refer to CWEs with one digit, so we'll only match on 2+ digits.
link_cwe_pattern = re.compile(r'(CWE-([1-9][0-9]+))([,()!/])')
# This matches the CWE data, including multiple entries.
find_cwe_pattern = re.compile(r'\(CWE-[^)]*\)')
class Hit(object):
"""
Each instance of Hit is a warning of some kind in a source code file.
See the rulesets, which define the conditions for triggering a hit.
Hit is initialized with a tuple containing the following:
hook: function to call when function name found.
level: (default) warning level, 0-5. 0=no problem, 5=very risky.
warning: warning (text saying what's the problem)
suggestion: suggestion (text suggesting what to do instead)
category: One of "buffer" (buffer overflow), "race" (race condition),
"tmpfile" (temporary file creation), "format" (format string).
Use "" if you don't have a better category.
url: URL fragment reference.
other: A dictionary with other settings.
Other settings usually set:
name: function name
parameter: the function parameters (0th parameter null)
input: set to 1 if the function inputs from external sources.
start: start position (index) of the function name (in text)
end: end position of the function name (in text)
filename: name of file
line: line number in file
column: column in line in file
context_text: text surrounding hit
"""
# Set default values:
source_position = 2 # By default, the second parameter is the source.
format_position = 1 # By default, the first parameter is the format.
input = 0 # By default, this doesn't read input.
note = "" # No additional notes.
filename = "" # Empty string is filename.
extract_lookahead = 0 # Normally don't extract lookahead.
def __init__(self, data):
hook, level, warning, suggestion, category, url, other = data
self.hook, self.level = hook, level
self.warning, self.suggestion = warning, suggestion
self.category, self.url = category, url
# These will be set later, but I set them here so that
# analysis tools like PyChecker will know about them.
self.column = 0
self.line = 0
self.name = ""
self.context_text = ""
for key in other:
setattr(self, key, other[key])
def __getitem__(self, X): # Define this so this works: "%(line)" % hit
return getattr(self, X)
# return CWEs
def cwes(self):
result = find_cwe_pattern.search(self.warning)
return result.group()[1:-1] if result else ''
def show(self):
if csv_output:
self.show_csv()
return
if output_format:
print("<li>", end='')
sys.stdout.write(h(self.filename))
if show_columns:
print(":%(line)s:%(column)s:" % self, end='')
else:
print(":%(line)s:" % self, end='')
if output_format:
print(" <b>", end='')
# Extra space before risk level in text, makes it easier to find:
print(" [%(level)s]" % self, end=' ')
if output_format:
print("</b> ", end='')
print("(%(category)s)" % self, end=' ')
if output_format:
print("<i> ", end='')
print(h("%(name)s:" % self), end='')
main_text = h("%(warning)s. " % self)
if output_format: # Create HTML link to CWE definitions
main_text = link_cwe_pattern.sub(
r'<a href="https://cwe.mitre.org/data/definitions/\2.html">\1</a>\3',
main_text)
if single_line:
print(main_text, end='')
if self.suggestion:
print(" " + h(self.suggestion) + ".", end='')
print(' ' + h(self.note), end='')
else:
if self.suggestion:
main_text += h(self.suggestion) + ". "
main_text += h(self.note)
print()
print_multi_line(main_text)
if output_format:
print(" </i>", end='')
print()
if show_context:
if output_format:
print("<pre>")
print(h(self.context_text))
if output_format:
print("</pre>")
# The "hitlist" is the list of all hits (warnings) found so far.
# Use add_warning to add to it.
hitlist = []
def add_warning(hit):
global hitlist, num_ignored_hits
if show_inputs and not hit.input:
return
if required_regex and (required_regex_compiled.search(hit.warning) is
None):
return
if linenumber == ignoreline:
num_ignored_hits += 1
else:
hitlist.append(hit)
if show_immediately:
hit.show()
def internal_warn(message):
pass
# C Language Specific
def extract_c_parameters(text, pos=0):
"Return a list of the given C function's parameters, starting at text[pos]"
# '(a,b)' produces ['', 'a', 'b']
i = pos
# Skip whitespace and find the "("; if there isn't one, return []:
while i < len(text):
if text[i] == '(':
break
elif text[i] in string.whitespace:
i += 1
else:
return []
else: # Never found a reasonable ending.
return []
i += 1
parameters = [""] # Insert 0th entry, so 1st parameter is parameter[1].
currentstart = i
parenlevel = 1
instring = 0 # 1=in double-quote, 2=in single-quote
incomment = 0
while i < len(text):
c = text[i]
if instring:
if c == '"' and instring == 1:
instring = 0
elif c == "'" and instring == 2:
instring = 0
# if \, skip next character too. The C/C++ rules for
# \ are actually more complex, supporting \ooo octal and
# \xhh hexadecimal (which can be shortened),
# but we don't need to
# parse that deeply, we just need to know we'll stay
# in string mode:
elif c == '\\':
i += 1
elif incomment:
if c == '*' and text[i:i + 2] == '*/':
incomment = 0
i += 1
else:
if c == '"':
instring = 1
elif c == "'":
instring = 2
elif c == '/' and text[i:i + 2] == '/*':
incomment = 1
i += 1
elif c == '/' and text[i:i + 2] == '//':
while i < len(text) and text[i] != "\n":
i += 1
elif c == '\\' and text[i:i + 2] == '\\"':
i += 1 # Handle exposed '\"'
elif c == '(':
parenlevel += 1
elif c == ',' and (parenlevel == 1):
parameters.append(
p_trailingbackslashes.sub('', text[currentstart:i]).strip())
currentstart = i + 1
elif c == ')':
parenlevel -= 1
if parenlevel <= 0:
parameters.append(
p_trailingbackslashes.sub(
'', text[currentstart:i]).strip())
# Re-enable these for debugging:
# print " EXTRACT_C_PARAMETERS: ", text[pos:pos+80]
# print " RESULTS: ", parameters
return parameters
elif c == ';':
internal_warn(
"Parsing failed to find end of parameter list; "
"semicolon terminated it in %s" % text[pos:pos + 200])
return parameters
i += 1
internal_warn("Parsing failed to find end of parameter list in %s" %
text[pos:pos + 200])
return [] # Treat unterminated list as an empty list
# These patterns match gettext() and _() for internationalization.
# This is compiled here, to avoid constant recomputation.
# FIXME: assumes simple function call if it ends with ")",
# so will get confused by patterns like gettext("hi") + function("bye")
# In practice, this doesn't seem to be a problem; gettext() is usually
# wrapped around the entire parameter.
# The ?s makes it posible to match multi-line strings.
gettext_pattern = re.compile(r'(?s)^\s*' 'gettext' r'\s*\((.*)\)\s*$')
undersc_pattern = re.compile(r'(?s)^\s*' '_(T(EXT)?)?' r'\s*\((.*)\)\s*$')
def strip_i18n(text):
"""Strip any internationalization function calls surrounding 'text'.
In particular, strip away calls to gettext() and _().
"""
match = gettext_pattern.search(text)
if match:
return match.group(1).strip()
match = undersc_pattern.search(text)
if match:
return match.group(3).strip()
return text
p_trailingbackslashes = re.compile(r'(\s|\\(\n|\r))*$')
p_c_singleton_string = re.compile(r'^\s*L?"([^\\]|\\[^0-6]|\\[0-6]+)?"\s*$')
def c_singleton_string(text):
"Returns true if text is a C string with 0 or 1 character."
return 1 if p_c_singleton_string.search(text) else 0
# This string defines a C constant.
p_c_constant_string = re.compile(r'^\s*L?"([^\\]|\\[^0-6]|\\[0-6]+)*"$')
def c_constant_string(text):
"Returns true if text is a constant C string."
return 1 if p_c_constant_string.search(text) else 0
# Precompile patterns for speed.
p_memcpy_sizeof = re.compile(r'sizeof\s*\(\s*([^)\s]*)\s*\)')
p_memcpy_param_amp = re.compile(r'&?\s*(.*)')
def c_memcpy(hit):
if len(hit.parameters) < 4: # 3 parameters
add_warning(hit)
return
m1 = re.search(p_memcpy_param_amp, hit.parameters[1])
m3 = re.search(p_memcpy_sizeof, hit.parameters[3])
if not m1 or not m3 or m1.group(1) != m3.group(1):
add_warning(hit)
def c_buffer(hit):
source_position = hit.source_position
if source_position <= len(hit.parameters) - 1:
source = hit.parameters[source_position]
if c_singleton_string(source):
hit.level = 1
hit.note = "Risk is low because the source is a constant character."
elif c_constant_string(strip_i18n(source)):
hit.level = max(hit.level - 2, 1)
hit.note = "Risk is low because the source is a constant string."
add_warning(hit)
p_dangerous_strncat = re.compile(r'^\s*sizeof\s*(\(\s*)?[A-Za-z_$0-9]+'
r'\s*(\)\s*)?(-\s*1\s*)?$')
# This is a heuristic: constants in C are usually given in all
# upper case letters. Yes, this need not be true, but it's true often
# enough that it's worth using as a heuristic.
# We check because strncat better not be passed a constant as the length!
p_looks_like_constant = re.compile(r'^\s*[A-Z][A-Z_$0-9]+\s*(-\s*1\s*)?$')
def c_strncat(hit):
if len(hit.parameters) > 3:
# A common mistake is to think that when calling strncat(dest,src,len),
# that "len" means the ENTIRE length of the destination.
# This isn't true,
# it must be the length of the characters TO BE ADDED at most.
# Which is one reason that strlcat is better than strncat.
# We'll detect a common case of this error; if the length parameter
# is of the form "sizeof(dest)", we have this error.
# Actually, sizeof(dest) is okay if the dest's first character
# is always \0,
# but in that case the programmer should use strncpy, NOT strncat.
# The following heuristic will certainly miss some dangerous cases, but
# it at least catches the most obvious situation.
# This particular heuristic is overzealous; it detects ANY sizeof,
# instead of only the sizeof(dest) (where dest is given in
# hit.parameters[1]).
# However, there aren't many other likely candidates for sizeof; some
# people use it to capture just the length of the source, but this is
# just as dangerous, since then it absolutely does NOT take care of
# the destination maximum length in general.
# It also detects if a constant is given as a length, if the
# constant follows common C naming rules.
length_text = hit.parameters[3]
if p_dangerous_strncat.search(
length_text) or p_looks_like_constant.search(length_text):
hit.level = 5
hit.note = (
"Risk is high; the length parameter appears to be a constant, "
"instead of computing the number of characters left.")
add_warning(hit)
return
c_buffer(hit)
def c_printf(hit):
format_position = hit.format_position
if format_position <= len(hit.parameters) - 1:
# Assume that translators are trusted to not insert "evil" formats:
source = strip_i18n(hit.parameters[format_position])
if c_constant_string(source):
# Parameter is constant, so there's no risk of
# format string problems.
# At one time we warned that very old systems sometimes incorrectly
# allow buffer overflows on snprintf/vsnprintf, but those systems
# are now very old, and snprintf is an important potential tool for
# countering buffer overflows.
# We'll pass it on, just in case it's needed, but at level 0 risk.
hit.level = 0
hit.note = "Constant format string, so not considered risky."
add_warning(hit)
p_dangerous_sprintf_format = re.compile(r'%-?([0-9]+|\*)?s')
# sprintf has both buffer and format vulnerabilities.
def c_sprintf(hit):
source_position = hit.source_position
if hit.parameters is None:
# Serious parameter problem, e.g., none, or a string constant that
# never finishes.
hit.warning = "format string parameter problem"
hit.suggestion = "Check if required parameters present and quotes close."
hit.level = 4
hit.category = "format"
hit.url = ""
elif source_position <= len(hit.parameters) - 1:
source = hit.parameters[source_position]
if c_singleton_string(source):
hit.level = 1
hit.note = "Risk is low because the source is a constant character."
else:
source = strip_i18n(source)
if c_constant_string(source):
if not p_dangerous_sprintf_format.search(source):
hit.level = max(hit.level - 2, 1)
hit.note = "Risk is low because the source has a constant maximum length."
# otherwise, warn of potential buffer overflow (the default)
else:
# Ho ho - a nonconstant format string - we have a different
# problem.
hit.warning = "Potential format string problem (CWE-134)"
hit.suggestion = "Make format string constant"
hit.level = 4
hit.category = "format"
hit.url = ""
add_warning(hit)
p_dangerous_scanf_format = re.compile(r'%s')
p_low_risk_scanf_format = re.compile(r'%[0-9]+s')
def c_scanf(hit):
format_position = hit.format_position
if format_position <= len(hit.parameters) - 1:
# Assume that translators are trusted to not insert "evil" formats;
# it's not clear that translators will be messing with INPUT formats,
# but it's possible so we'll account for it.
source = strip_i18n(hit.parameters[format_position])
if c_constant_string(source):
if p_dangerous_scanf_format.search(source):
pass # Accept default.
elif p_low_risk_scanf_format.search(source):
# This is often okay, but sometimes extremely serious.
hit.level = 1
hit.warning = ("It's unclear if the %s limit in the "
"format string is small enough (CWE-120)")
hit.suggestion = ("Check that the limit is sufficiently "
"small, or use a different input function")
else:
# No risky scanf request.
# We'll pass it on, just in case it's needed, but at level 0
# risk.
hit.level = 0
hit.note = "No risky scanf format detected."
else:
# Format isn't a constant.
hit.note = ("If the scanf format is influenceable "
"by an attacker, it's exploitable.")
add_warning(hit)
p_dangerous_multi_byte = re.compile(r'^\s*sizeof\s*(\(\s*)?[A-Za-z_$0-9]+'
r'\s*(\)\s*)?(-\s*1\s*)?$')
p_safe_multi_byte = re.compile(
r'^\s*sizeof\s*(\(\s*)?[A-Za-z_$0-9]+\s*(\)\s*)?'
r'/\s*sizeof\s*\(\s*?[A-Za-z_$0-9]+\s*\[\s*0\s*\]\)\s*(-\s*1\s*)?$')
def c_multi_byte_to_wide_char(hit):
# Unfortunately, this doesn't detect bad calls when it's a #define or
# constant set by a sizeof(), but trying to do so would create
# FAR too many false positives.
if len(hit.parameters) - 1 >= 6:
num_chars_to_copy = hit.parameters[6]
if p_dangerous_multi_byte.search(num_chars_to_copy):
hit.level = 5
hit.note = (
"Risk is high, it appears that the size is given as bytes, but the "
"function requires size as characters.")
elif p_safe_multi_byte.search(num_chars_to_copy):
# This isn't really risk-free, since it might not be the destination,
# or the destination might be a character array (if it's a char pointer,
# the pattern is actually quite dangerous, but programmers
# are unlikely to make that error).
hit.level = 1
hit.note = "Risk is very low, the length appears to be in characters not bytes."
add_warning(hit)
p_null_text = re.compile(r'^ *(NULL|0|0x0) *$')
def c_hit_if_null(hit):
null_position = hit.check_for_null
if null_position <= len(hit.parameters) - 1:
null_text = hit.parameters[null_position]
if p_null_text.search(null_text):
add_warning(hit)
else:
return
add_warning(hit) # If insufficient # of parameters.
p_static_array = re.compile(r'^[A-Za-z_]+\s+[A-Za-z0-9_$,\s\*()]+\[[^]]')
def c_static_array(hit):
# This is cheating, but it does the job for most real code.
# In some cases it will match something that it shouldn't.
# We don't match ALL arrays, just those of certain types (e.g., char).
# In theory, any array can overflow, but in practice it seems that
# certain types are far more prone to problems, so we just report those.
if p_static_array.search(hit.lookahead):
add_warning(hit) # Found a static array, warn about it.
def cpp_unsafe_stl(hit):
# Use one of the overloaded classes from the STL in C++14 and higher
# instead of the <C++14 versions of theses functions that did not
# if the second iterator could overflow
if len(hit.parameters) <= 4:
add_warning(hit)
def normal(hit):
add_warning(hit)
# "c_ruleset": the rules for identifying "hits" in C (potential warnings).
# It's a dictionary, where the key is the function name causing the hit,
# and the value is a tuple with the following format:
# (hook, level, warning, suggestion, category, {other})
# See the definition for class "Hit".
# The key can have multiple values separated with "|".
# For more information on Microsoft banned functions, see:
# http://msdn.microsoft.com/en-us/library/bb288454.aspx
c_ruleset = {
"strcpy":
(c_buffer, 4,
"Does not check for buffer overflows when copying to destination [MS-banned] (CWE-120)",
"Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)",
"buffer", "", {}),
"strcpyA|strcpyW|StrCpy|StrCpyA|lstrcpyA|lstrcpyW|_tccpy|_mbccpy|_ftcscpy|_mbsncpy|StrCpyN|StrCpyNA|StrCpyNW|StrNCpy|strcpynA|StrNCpyA|StrNCpyW|lstrcpynA|lstrcpynW":
# We need more info on these functions; I got their names from the
# Microsoft "banned" list. For now, just use "normal" to process them
# instead of "c_buffer".
(normal, 4,
"Does not check for buffer overflows when copying to destination [MS-banned] (CWE-120)",
"Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)",
"buffer", "", {}),
"lstrcpy|wcscpy|_tcscpy|_mbscpy":
(c_buffer, 4,
"Does not check for buffer overflows when copying to destination [MS-banned] (CWE-120)",
"Consider using a function version that stops copying at the end of the buffer",
"buffer", "", {}),
"memcpy|CopyMemory|bcopy":
(c_memcpy, 2, # I've found this to have a lower risk in practice.
"Does not check for buffer overflows when copying to destination (CWE-120)",
"Make sure destination can always hold the source data",
"buffer", "", {}),
"strcat":
(c_buffer, 4,
"Does not check for buffer overflows when concatenating to destination [MS-banned] (CWE-120)",
"Consider using strcat_s, strncat, strlcat, or snprintf (warning: strncat is easily misused)",
"buffer", "", {}),
"lstrcat|wcscat|_tcscat|_mbscat":
(c_buffer, 4,
"Does not check for buffer overflows when concatenating to destination [MS-banned] (CWE-120)",
"",
"buffer", "", {}),
# TODO: Do more analysis. Added because they're in MS banned list.
"StrCat|StrCatA|StrcatW|lstrcatA|lstrcatW|strCatBuff|StrCatBuffA|StrCatBuffW|StrCatChainW|_tccat|_mbccat|_ftcscat|StrCatN|StrCatNA|StrCatNW|StrNCat|StrNCatA|StrNCatW|lstrncat|lstrcatnA|lstrcatnW":
(normal, 4,
"Does not check for buffer overflows when concatenating to destination [MS-banned] (CWE-120)",
"",
"buffer", "", {}),
"strncpy":
(c_buffer,
1, # Low risk level, because this is often used correctly when FIXING security
# problems, and raising it to a higher risk level would cause many false
# positives.
"Easily used incorrectly; doesn't always \\0-terminate or "
"check for invalid pointers [MS-banned] (CWE-120)",
"",
"buffer", "", {}),
"lstrcpyn|wcsncpy|_tcsncpy|_mbsnbcpy":
(c_buffer,
1, # Low risk level, because this is often used correctly when FIXING security
# problems, and raising it to a higher risk levle would cause many false
# positives.
"Easily used incorrectly; doesn't always \\0-terminate or "
"check for invalid pointers [MS-banned] (CWE-120)",
"",
"buffer", "", {}),
"strncat":
(c_strncat,
1, # Low risk level, because this is often used correctly when
# FIXING security problems, and raising it to a
# higher risk level would cause many false positives.
"Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add) [MS-banned] (CWE-120)",
"Consider strcat_s, strlcat, snprintf, or automatically resizing strings",
"buffer", "", {}),
"lstrcatn|wcsncat|_tcsncat|_mbsnbcat":
(c_strncat,
1, # Low risk level, because this is often used correctly when FIXING security
# problems, and raising it to a higher risk level would cause many false
# positives.
"Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add) [MS-banned] (CWE-120)",
"Consider strcat_s, strlcat, or automatically resizing strings",
"buffer", "", {}),
"strccpy|strcadd":
(normal, 1,
"Subject to buffer overflow if buffer is not as big as claimed (CWE-120)",
"Ensure that destination buffer is sufficiently large",
"buffer", "", {}),
"char|TCHAR|wchar_t": # This isn't really a function call, but it works.
(c_static_array, 2,
"Statically-sized arrays can be improperly restricted, "
"leading to potential overflows or other issues (CWE-119!/CWE-120)",
"Perform bounds checking, use functions that limit length, "
"or ensure that the size is larger than the maximum possible length",
"buffer", "", {'extract_lookahead': 1}),
"gets|_getts":
(normal, 5, "Does not check for buffer overflows (CWE-120, CWE-20)",
"Use fgets() instead", "buffer", "", {'input': 1}),
# The "sprintf" hook will raise "format" issues instead if appropriate:
"sprintf|vsprintf|swprintf|vswprintf|_stprintf|_vstprintf":
(c_sprintf, 4,
"Does not check for buffer overflows (CWE-120)",
"Use sprintf_s, snprintf, or vsnprintf",
"buffer", "", {}),
"printf|vprintf|vwprintf|vfwprintf|_vtprintf|wprintf":
(c_printf, 4,
"If format strings can be influenced by an attacker, they can be exploited (CWE-134)",
"Use a constant for the format specification",
"format", "", {}),
"fprintf|vfprintf|_ftprintf|_vftprintf|fwprintf|fvwprintf":
(c_printf, 4,
"If format strings can be influenced by an attacker, they can be exploited (CWE-134)",
"Use a constant for the format specification",
"format", "", {'format_position': 2}),
# The "syslog" hook will raise "format" issues.
"syslog":
(c_printf, 4,
"If syslog's format strings can be influenced by an attacker, "
"they can be exploited (CWE-134)",
"Use a constant format string for syslog",
"format", "", {'format_position': 2}),
"snprintf|vsnprintf|_snprintf|_sntprintf|_vsntprintf":
(c_printf, 4,
"If format strings can be influenced by an attacker, they can be "
"exploited, and note that sprintf variations do not always \\0-terminate (CWE-134)",
"Use a constant for the format specification",
"format", "", {'format_position': 3}),
"scanf|vscanf|wscanf|_tscanf|vwscanf":
(c_scanf, 4,
"The scanf() family's %s operation, without a limit specification, "
"permits buffer overflows (CWE-120, CWE-20)",
"Specify a limit to %s, or use a different input function",
"buffer", "", {'input': 1}),
"fscanf|sscanf|vsscanf|vfscanf|_ftscanf|fwscanf|vfwscanf|vswscanf":
(c_scanf, 4,
"The scanf() family's %s operation, without a limit specification, "
"permits buffer overflows (CWE-120, CWE-20)",
"Specify a limit to %s, or use a different input function",
"buffer", "", {'input': 1, 'format_position': 2}),
"strlen|wcslen|_tcslen|_mbslen":
(normal,
# Often this isn't really a risk, and even when it is, at worst it
# often causes a program crash (and nothing worse).
1,
"Does not handle strings that are not \\0-terminated; "
"if given one it may perform an over-read (it could cause a crash "
"if unprotected) (CWE-126)",
"",
"buffer", "", {}),
"MultiByteToWideChar": # Windows
(c_multi_byte_to_wide_char,
2, # Only the default - this will be changed in many cases.
"Requires maximum length in CHARACTERS, not bytes (CWE-120)",
"",
"buffer", "", {}),
"streadd|strecpy":
(normal, 4,
"This function does not protect against buffer overflows (CWE-120)",
"Ensure the destination has 4 times the size of the source, to leave room for expansion",
"buffer", "dangers-c", {}),
"strtrns":
(normal, 3,
"This function does not protect against buffer overflows (CWE-120)",
"Ensure that destination is at least as long as the source",
"buffer", "dangers-c", {}),
"realpath":
(normal, 3,
"This function does not protect against buffer overflows, "
"and some implementations can overflow internally (CWE-120/CWE-785!)",
"Ensure that the destination buffer is at least of size MAXPATHLEN, and"
"to protect against implementation problems, the input argument "
"should also be checked to ensure it is no larger than MAXPATHLEN",
"buffer", "dangers-c", {}),
"getopt|getopt_long":
(normal, 3,
"Some older implementations do not protect against internal buffer overflows (CWE-120, CWE-20)",
"Check implementation on installation, or limit the size of all string inputs",
"buffer", "dangers-c", {'input': 1}),
"getwd":
(normal, 3,
"This does not protect against buffer overflows "
"by itself, so use with caution (CWE-120, CWE-20)",
"Use getcwd instead",
"buffer", "dangers-c", {'input': 1}),
# fread not included here; in practice I think it's rare to mistake it.
"getchar|fgetc|getc|read|_gettc":
(normal, 1,
"Check buffer boundaries if used in a loop including recursive loops (CWE-120, CWE-20)",
"",
"buffer", "dangers-c", {'input': 1}),
"access": # ???: TODO: analyze TOCTOU more carefully.
(normal, 4,
"This usually indicates a security flaw. If an "
"attacker can change anything along the path between the "
"call to access() and the file's actual use (e.g., by moving "
"files), the attacker can exploit the race condition (CWE-362/CWE-367!)",
"Set up the correct permissions (e.g., using setuid()) and "
"try to open the file directly",
"race",
"avoid-race#atomic-filesystem", {}),
"chown":
(normal, 5,
"This accepts filename arguments; if an attacker "
"can move those files, a race condition results. (CWE-362)",
"Use fchown( ) instead",
"race", "", {}),
"chgrp":
(normal, 5,
"This accepts filename arguments; if an attacker "
"can move those files, a race condition results. (CWE-362)",
"Use fchgrp( ) instead",
"race", "", {}),
"chmod":
(normal, 5,
"This accepts filename arguments; if an attacker "
"can move those files, a race condition results. (CWE-362)",
"Use fchmod( ) instead",
"race", "", {}),
"vfork":
(normal, 2,
"On some old systems, vfork() permits race conditions, and it's "
"very difficult to use correctly (CWE-362)",
"Use fork() instead",
"race", "", {}),
"readlink":
(normal, 5,
"This accepts filename arguments; if an attacker "
"can move those files or change the link content, "
"a race condition results. "
"Also, it does not terminate with ASCII NUL. (CWE-362, CWE-20)",
# This is often just a bad idea, and it's hard to suggest a
# simple alternative:
"Reconsider approach",
"race", "", {'input': 1}),
"tmpfile":
(normal, 2,
"Function tmpfile() has a security flaw on some systems (e.g., older System V systems) (CWE-377)",
"",
"tmpfile", "", {}),
"tmpnam|tempnam":
(normal, 3,
"Temporary file race condition (CWE-377)",
"",
"tmpfile", "avoid-race", {}),
# TODO: Detect GNOME approach to mktemp and ignore it.
"mktemp":
(normal, 4,
"Temporary file race condition (CWE-377)",
"",
"tmpfile", "avoid-race", {}),
"mkstemp":
(normal, 2,
"Potential for temporary file vulnerability in some circumstances. Some older Unix-like systems create temp files with permission to write by all by default, so be sure to set the umask to override this. Also, some older Unix systems might fail to use O_EXCL when opening the file, so make sure that O_EXCL is used by the library (CWE-377)",
"",
"tmpfile", "avoid-race", {}),
"fopen|open":
(normal, 2,
"Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents? (CWE-362)",
"",
"misc", "", {}),
"umask":
(normal, 1,
"Ensure that umask is given most restrictive possible setting (e.g., 066 or 077) (CWE-732)",
"",
"access", "", {}),
# Windows. TODO: Detect correct usage approaches and ignore it.
"GetTempFileName":
(normal, 3,
"Temporary file race condition in certain cases "
"(e.g., if run as SYSTEM in many versions of Windows) (CWE-377)",
"",
"tmpfile", "avoid-race", {}),
# TODO: Need to detect varying levels of danger.
"execl|execlp|execle|execv|execvp|system|popen|WinExec|ShellExecute":
(normal, 4,
"This causes a new program to execute and is difficult to use safely (CWE-78)",
"try using a library call that implements the same functionality "
"if available",
"shell", "", {}),
# TODO: Be more specific. The biggest problem involves "first" param NULL,
# second param with embedded space. Windows.
"CreateProcessAsUser|CreateProcessWithLogon":
(normal, 3,
"This causes a new process to execute and is difficult to use safely (CWE-78)",
"Especially watch out for embedded spaces",
"shell", "", {}),
# TODO: Be more specific. The biggest problem involves "first" param NULL,
# second param with embedded space. Windows.
"CreateProcess":
(c_hit_if_null, 3,
"This causes a new process to execute and is difficult to use safely (CWE-78)",
"Specify the application path in the first argument, NOT as part of the second, "
"or embedded spaces could allow an attacker to force a different program to run",
"shell", "", {'check_for_null': 1}),
"atoi|atol|_wtoi|_wtoi64":
(normal, 2,
"Unless checked, the resulting number can exceed the expected range "
"(CWE-190)",
"If source untrusted, check both minimum and maximum, even if the"
" input had no minus sign (large numbers can roll over into negative"
" number; consider saving to an unsigned value if that is intended)",
"integer", "dangers-c", {}),
# Random values. Don't trigger on "initstate", it's too common a term.
"drand48|erand48|jrand48|lcong48|lrand48|mrand48|nrand48|random|seed48|setstate|srand|strfry|srandom|g_rand_boolean|g_rand_int|g_rand_int_range|g_rand_double|g_rand_double_range|g_random_boolean|g_random_int|g_random_int_range|g_random_double|g_random_double_range":
(normal, 3,
"This function is not sufficiently random for security-related functions such as key and nonce creation (CWE-327)",
"Use a more secure technique for acquiring random values",
"random", "", {}),
"crypt|crypt_r":
(normal, 4,
"The crypt functions use a poor one-way hashing algorithm; "
"since they only accept passwords of 8 characters or fewer "
"and only a two-byte salt, they are excessively vulnerable to "
"dictionary attacks given today's faster computing equipment (CWE-327)",
"Use a different algorithm, such as SHA-256, with a larger, "
"non-repeating salt",
"crypto", "", {}),
# OpenSSL EVP calls to use DES.
"EVP_des_ecb|EVP_des_cbc|EVP_des_cfb|EVP_des_ofb|EVP_desx_cbc":