-
Notifications
You must be signed in to change notification settings - Fork 81
/
flawfinder.py
executable file
·2551 lines (2267 loc) · 102 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-2019 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.
from __future__ import division
from __future__ import print_function
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
import time
import csv # To support generating CSV format
import hashlib
import json
version = "2.0.18"
# 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 = 0
showheading = 1 # --dataonly turns this off
output_format = 0 # 0 = normal, 1 = html.
single_line = 0 # 1 = singleline (can 't be 0 if html)
csv_output = 0 # 1 = Generate CSV
csv_writer = None
sarif_output = 0 # 1 = Generate SARIF report
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
starttime = time.time() # Used to determine analyzed lines/second.
# 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()
def to_json(o):
return json.dumps(o, default=lambda o: o.__dict__, sort_keys=False, indent=2)
# The following implements the SarifLogger.
# We intentionally merge all of flawfinder's functionality into 1 file
# so it's trivial to copy & use elsewhere.
class SarifLogger(object):
_hitlist = None
TOOL_NAME = "Flawfinder"
TOOL_URL = "https://dwheeler.com/flawfinder/"
TOOL_VERSION = version
URI_BASE_ID = "SRCROOT"
SARIF_SCHEMA = "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json"
SARIF_SCHEMA_VERSION = "2.1.0"
CWE_TAXONOMY_NAME = "CWE"
CWE_TAXONOMY_URI = "https://raw.githubusercontent.com/sarif-standard/taxonomies/main/CWE_v4.4.sarif"
CWE_TAXONOMY_GUID = "FFC64C90-42B6-44CE-8BEB-F6B7DAE649E5"
def __init__ (self, hits):
self._hitlist = hits
def output_sarif(self):
tool = {
"driver": {
"name": self.TOOL_NAME,
"version": self.TOOL_VERSION,
"informationUri": self.TOOL_URL,
"rules": self._extract_rules(self._hitlist),
"supportedTaxonomies": [{
"name": self.CWE_TAXONOMY_NAME,
"guid": self.CWE_TAXONOMY_GUID,
}],
}
}
runs = [{
"tool": tool,
"columnKind": "utf16CodeUnits",
"results": self._extract_results(self._hitlist),
"externalPropertyFileReferences": {
"taxonomies": [{
"location": {
"uri": self.CWE_TAXONOMY_URI,
},
"guid": self.CWE_TAXONOMY_GUID,
}],
},
}]
report = {
"$schema": self.SARIF_SCHEMA,
"version": self.SARIF_SCHEMA_VERSION,
"runs": runs,
}
jsonstr = to_json(report)
return jsonstr
def _extract_rules(self, hitlist):
rules = {}
for hit in hitlist:
if not hit.ruleid in rules:
rules[hit.ruleid] = self._to_sarif_rule(hit)
return list(rules.values())
def _extract_results(self, hitlist):
results = []
for hit in hitlist:
results.append(self._to_sarif_result(hit))
return results
def _to_sarif_rule(self, hit):
return {
"id": hit.ruleid,
"name": "{0}/{1}".format(hit.category, hit.name),
"shortDescription": {
"text": self._append_period(hit.warning),
},
"defaultConfiguration": {
"level": self._to_sarif_level(hit.defaultlevel),
},
"helpUri": hit.helpuri(),
"relationships": self._extract_relationships(hit.cwes()),
}
def _to_sarif_result(self, hit):
return {
"ruleId": hit.ruleid,
"level": self._to_sarif_level(hit.level),
"message": {
"text": self._append_period("{0}/{1}:{2}".format(hit.category, hit.name, hit.warning)),
},
"locations": [{
"physicalLocation": {
"artifactLocation": {
"uri": self._to_uri_path(hit.filename),
"uriBaseId": self.URI_BASE_ID,
},
"region": {
"startLine": hit.line,
"startColumn": hit.column,
"endColumn": len(hit.context_text) + 1,
"snippet": {
"text": hit.context_text,
}
}
}
}],
"fingerprints": {
"contextHash/v1": hit.fingerprint()
},
"rank": self._to_sarif_rank(hit.level),
}
def _extract_relationships(self, cwestring):
# example cwe string "CWE-119!/ CWE-120", "CWE-829, CWE-20"
relationships = []
for cwe in re.split(',|/',cwestring):
cwestr = cwe.strip()
if cwestr:
relationship = {
"target": {
"id": cwestr.replace("!", ""),
"toolComponent": {
"name": self.CWE_TAXONOMY_NAME,
"guid": self.CWE_TAXONOMY_GUID,
},
},
"kinds": [
"relevant" if cwestr[-1] != '!' else "incomparable"
],
}
relationships.append(relationship)
return relationships
@staticmethod
def _to_sarif_level(level):
# level 4 & 5
if level >= 4:
return "error"
# level 3
if level == 3:
return "warning"
# level 0 1 2
return "note"
@staticmethod
def _to_sarif_rank(level):
#SARIF rank FF Level SARIF level Default Viewer Action
#0.0 0 note Does not display by default
#0.2 1 note Does not display by default
#0.4 2 note Does not display by default
#0.6 3 warning Displays by default, does not break build / other processes
#0.8 4 error Displays by default, breaks build/ other processes
#1.0 5 error Displays by default, breaks build/ other processes
return level * 0.2
@staticmethod
def _to_uri_path(path):
return path.replace("\\", "/")
@staticmethod
def _append_period(text):
return text if text[-1] == '.' else text + "."
# The following code accepts unified diff format from both subversion (svn)
# and GNU diff, which aren't well-documented. It gets filenames from
# "Index:" if exists, else from the "+++ FILENAME ..." entry.
# Note that this is different than some tools (which will use "+++" in
# preference to "Index:"), but subversion's nonstandard format is easier
# to handle this way.
# Since they aren't well-documented, here's some info on the diff formats:
# GNU diff format:
# --- OLDFILENAME OLDTIMESTAMP
# +++ NEWFILENAME NEWTIMESTAMP
# @@ -OLDSTART,OLDLENGTH +NEWSTART,NEWLENGTH @@
# ... Changes where preceeding "+" is add, "-" is remove, " " is unchanged.
#
# ",OLDLENGTH" and ",NEWLENGTH" are optional (they default to 1).
# GNU unified diff format doesn't normally output "Index:"; you use
# the "+++/---" to find them (presuming the diff user hasn't used --label
# to mess it up).
#
# Subversion format:
# Index: FILENAME
# --- OLDFILENAME (comment)
# +++ NEWFILENAME (comment)
# @@ -OLDSTART,OLDLENGTH +NEWSTART,NEWLENGTH @@
#
# In subversion, the "Index:" always occurs, and note that paren'ed
# comments are in the oldfilename/newfilename, NOT timestamps like
# everyone else.
#
# Git format:
# diff --git a/junk.c b/junk.c
# index 03d668d..5b005a1 100644
# --- a/junk.c
# +++ b/junk.c
# @@ -6,4 +6,5 @@ main() {
#
# Single Unix Spec version 3 (http://www.unix.org/single_unix_specification/)
# does not specify unified format at all; it only defines the older
# (obsolete) context diff format. That format DOES use "Index:", but
# only when the filename isn't specified otherwise.
# We're only supporting unified format directly; if you have an older diff
# format, use "patch" to apply it, and then use "diff -u" to create a
# unified format.
#
diff_index_filename = re.compile(r'^Index:\s+(?P<filename>.*)')
diff_git_filename = re.compile(r'^diff --git a/.* b/(?P<filename>.*)$')
diff_newfile = re.compile(r'^\+\+\+\s(?P<filename>.*)$')
diff_hunk = re.compile(r'^@@ -\d+(,\d+)?\s+\+(?P<linenumber>\d+)[, ].*@@')
diff_line_added = re.compile(r'^\+[^+].*')
diff_line_del = re.compile(r'^-[^-].*')
# The "+++" newfile entries have the filename, followed by a timestamp
# or " (comment)" postpended.
# Timestamps can be of these forms:
# 2005-04-24 14:21:39.000000000 -0400
# Mon Mar 10 15:13:12 1997
# Also, "newfile" can have " (comment)" postpended. Find and eliminate this.
# Note that the expression below is Y10K (and Y100K) ready. :-).
diff_findjunk = re.compile(
r'^(?P<filename>.*)('
r'(\s\d\d\d\d+-\d\d-\d\d\s+\d\d:\d[0-9:.]+Z?(\s+[\-\+0-9A-Z]+)?)|'
r'(\s[A-Za-z][a-z]+\s[A-za-z][a-z]+\s\d+\s\d+:\d[0-9:.]+Z?'
r'(\s[\-\+0-9]*)?\s\d\d\d\d+)|'
r'(\s\(.*\)))\s*$'
)
def is_svn_diff(sLine):
if sLine.find('Index:') != -1:
return True
return False
def is_gnu_diff(sLine):
if sLine.startswith('--- '):
return True
return False
def is_git_diff(sLine):
if sLine.startswith('diff --git a'):
return True
return False
def svn_diff_get_filename(sLine):
return diff_index_filename.match(sLine)
def gnu_diff_get_filename(sLine):
newfile_match = diff_newfile.match(sLine)
if newfile_match:
patched_filename = newfile_match.group('filename').strip()
# Clean up filename - remove trailing timestamp and/or (comment).
return diff_findjunk.match(patched_filename)
return None
def git_diff_get_filename(sLine):
return diff_git_filename.match(sLine)
# 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 load_patch_info(input_patch_file):
patch = {}
line_counter = 0
initial_number = 0
try:
hPatch = open(input_patch_file, 'r')
except BaseException:
print("Error: failed to open", h(input_patch_file))
sys.exit(10)
patched_filename = "" # Name of new file patched by current hunk.
sLine = hPatch.readline()
# Heuristic to determine if it's a svn diff, git diff, or a GNU diff.
if is_svn_diff(sLine):
fn_get_filename = svn_diff_get_filename
elif is_git_diff(sLine):
fn_get_filename = git_diff_get_filename
elif is_gnu_diff(sLine):
fn_get_filename = gnu_diff_get_filename
else:
print("Error: Unrecognized patch format")
sys.exit(11)
while True: # Loop-and-half construct. Read a line, end loop when no more
# This is really a sequence of if ... elsif ... elsif..., but
# because Python forbids '=' in conditions, we do it this way.
filename_match = fn_get_filename(sLine)
if filename_match:
patched_filename = filename_match.group('filename').strip()
if patched_filename in patch:
error("filename occurs more than once in the patch: %s" %
patched_filename)
sys.exit(12)
else:
patch[patched_filename] = {}
else:
hunk_match = diff_hunk.match(sLine)
if hunk_match:
if patched_filename == "":
error(
"wrong type of patch file : "
"we have a line number without having seen a filename"
)
sys.exit(13)
initial_number = hunk_match.group('linenumber')
line_counter = 0
else:
line_added_match = diff_line_added.match(sLine)
if line_added_match:
line_added = line_counter + int(initial_number)
patch[patched_filename][line_added] = True
# Let's also warn about the lines above and below this one,
# so that errors that "leak" into adjacent lines are caught.
# Besides, if you're creating a patch, you had to at
# least look at adjacent lines,
# so you're in a position to fix them.
patch[patched_filename][line_added - 1] = True
patch[patched_filename][line_added + 1] = True
line_counter += 1
else:
line_del_match = diff_line_del.match(sLine)
if line_del_match is None:
line_counter += 1
sLine = hPatch.readline()
if sLine == '':
break # Done reading.
return patch
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, ruleid = data
self.hook, self.level, self.defaultlevel = hook, level, level
self.warning, self.suggestion = warning, suggestion
self.category, self.url = category, url
self.ruleid = ruleid
# 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)
def __eq__(self, other):
return (self.filename == other.filename
and self.line == other.line
and self.column == other.column
and self.level == other.level
and self.name == other.name)
def __ne__(self, other):
return not self == other
# Return CWEs
def cwes(self):
result = find_cwe_pattern.search(self.warning)
return result.group()[1:-1] if result else ''
def fingerprint(self):
"""Return fingerprint of stripped context."""
m = hashlib.sha256()
m.update(self.context_text.strip().encode('utf-8'))
return m.hexdigest()
# Help uri for each defined rule. e.g. "https://dwheeler.com/flawfinder#FF1002"
# return first CWE link for now
def helpuri(self):
cwe = re.split(',|!', self.cwes())[0] + ")"
return link_cwe_pattern.sub(
r'https://cwe.mitre.org/data/definitions/\2.html',
cwe)
# Show as CSV format
def show_csv(self):
csv_writer.writerow([
self.filename, self.line, self.column, self.defaultlevel, self.level, self.category,
self.name, self.warning + ".", self.suggestion + "." if self.suggestion else "", self.note,
self.cwes(), self.context_text, self.fingerprint(),
version, self.ruleid, self.helpuri()
])
def show(self):
if csv_output:
self.show_csv()
return
if sarif_output:
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):
print(h(message), file=sys.stderr)
# 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
curlylevel = 0
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 == '{':
curlylevel += 1
elif c == '}':
curlylevel -= 1
elif c == ';' and curlylevel < 1:
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) *$')