-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathOutOfBounds.qll
More file actions
1364 lines (1248 loc) · 49.3 KB
/
OutOfBounds.qll
File metadata and controls
1364 lines (1248 loc) · 49.3 KB
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
/*
* This module is a copy of `c/common/src/codingstandards/c/OutOfBounds.qll`. It
* is copied here as a workaround of the problem where the common libraries for
* C is not available for C++ queries; only the other way around is true.
*/
/**
* This module provides classes and predicates for analyzing the size of buffers
* or objects from their base or a byte-offset, and identifying the potential for
* expressions accessing those buffers to overflow.
*/
import cpp
import codingstandards.cpp.types.Pointers
import codingstandards.cpp.Allocations
import codingstandards.cpp.Overflow
import codingstandards.cpp.PossiblyUnsafeStringOperation
import codingstandards.cpp.SimpleRangeAnalysisCustomizations
private import semmle.code.cpp.dataflow.DataFlow
import semmle.code.cpp.valuenumbering.GlobalValueNumbering
module OOB {
/**
* Holds if `result` is either `name` or a string matching a pattern such as
* `__builtin_*name*_chk` or similar. This predicate exists to model internal functions
* such as `__builtin___memcpy_chk` under a common `memcpy` name in the table.
*/
bindingset[name, result]
string getNameOrInternalName(string name) {
result.regexpMatch("^(?:__.*_+)?" + name + "(?:_[^s].*)?$")
}
/**
* MISRA-C Rule 21.17 function table of names and parameter indices
* which covers functions from <string.h> that rely on null-terminated strings.
*
* This table is a subset of `libraryFunctionNameParamTable`.
*
* Note: These functions do not share a common semantic pattern of source and destination
* parameters with the other functions explicitly defined in `libraryFunctionNameParamTable`,
* although they do share a common issue of parsing non-null-terminated strings.
* The `SimpleStringLibraryFunction` base class provides an appropriate
* interface for analyzing the functions in the below table.
*/
private Function libraryFunctionNameParamTableSimpleString(
string name, int dst, int src, int src_sz, int dst_sz
) {
result.getName() = getNameOrInternalName(name) and
src_sz = -1 and
dst_sz = -1 and
(
name = "strcat" and
dst = 0 and
src = 1
or
name = "strchr" and
dst = -1 and
src = 0
or
name = ["strcmp", "strcoll"] and
dst = -1 and
src = [0, 1]
or
name = "strcpy" and
dst = 0 and
src = 1
or
name = "strcspn" and
dst = -1 and
src = [0, 1]
or
name = "strlen" and
dst = -1 and
src = 0
or
name = "strpbrk" and
dst = -1 and
src = [0, 1]
or
name = "strrchr" and
dst = -1 and
src = 0
or
name = "strspn" and
dst = -1 and
src = [0, 1]
or
name = "strstr" and
dst = -1 and
src = [0, 1]
or
// do not specify a src and dst to avoid buffer size assumptions
name = ["strtok", "strtok_r"] and
dst = -1 and
src = [0, 1]
)
}
/**
* A relation of the indices of buffer and size parameters of standard library functions
* which are defined in rules CERT ARR38-C and MISRA-C rules 21.17 and 21.18.
*/
private Function libraryFunctionNameParamTable(
string name, int dst, int src, int src_sz, int dst_sz
) {
result = libraryFunctionNameParamTableSimpleString(name, dst, src, src_sz, dst_sz)
or
result.getName() = getNameOrInternalName(name) and
(
name = ["fgets", "fgetws"] and
dst = 0 and
src = -1 and
src_sz = -1 and
dst_sz = 1
or
name = ["mbstowcs", "wcstombs"] and
dst = 0 and
src = 1 and
src_sz = -1 and
dst_sz = 2
or
name = ["mbrtoc16", "mbrtoc32"] and
dst = 0 and
src = 1 and
src_sz = 2 and
dst_sz = -1
or
name = ["mbsrtowcs", "wcsrtombs"] and
dst = 0 and
src = 1 and
src_sz = -1 and
dst_sz = 2
or
name = ["mbtowc", "mbrtowc"] and
dst = 0 and
src = 1 and
src_sz = 2 and
dst_sz = -1
or
name = ["mblen", "mbrlen"] and
dst = -1 and
src = 0 and
src_sz = 1 and
dst_sz = -1
or
name = ["memchr", "wmemchr"] and
dst = -1 and
src = 0 and
src_sz = 2 and
dst_sz = -1
or
name = ["memset", "wmemset"] and
dst = 0 and
src = -1 and
src_sz = -1 and
dst_sz = 2
or
name = ["strftime", "wcsftime"] and
dst = 0 and
src = -1 and
src_sz = -1 and
dst_sz = 1
or
name = ["strxfrm", "wcsxfrm"] and
dst = 0 and
src = 1 and
src_sz = -1 and
dst_sz = 2
or
name = ["strncat", "wcsncat"] and
dst = 0 and
src = 1 and
src_sz = 2 and
dst_sz = -1
or
name = ["snprintf", "vsnprintf", "swprintf", "vswprintf"] and
dst = 0 and
src = -1 and
src_sz = -1 and
dst_sz = 1
or
name = "setvbuf" and
dst = -1 and
src = 1 and
src_sz = 3 and
dst_sz = -1
or
name = ["memcpy", "wmemcpy", "memmove", "wmemmove", "memcmp", "wmemcmp", "strncmp", "wcsncmp"] and
dst = 0 and
src = 1 and
src_sz = 2 and
dst_sz = 2
or
name = ["strncpy", "wcsncpy"] and
dst = 0 and
src = 1 and
src_sz = -1 and
dst_sz = 2
or
name = "qsort" and
dst = 0 and
src = -1 and
src_sz = -1 and
dst_sz = 1
or
name = "bsearch" and
dst = -1 and
src = 1 and
src_sz = -1 and
dst_sz = 2
or
name = "fread" and
dst = 0 and
src = -1 and
src_sz = -1 and
dst_sz = 2
or
name = "fwrite" and
dst = -1 and
src = 0 and
src_sz = 2 and
dst_sz = -1
)
}
/**
* A library function that accesses one or more buffers supplied via arguments.
*/
class BufferAccessLibraryFunction extends Function {
BufferAccessLibraryFunction() { this = libraryFunctionNameParamTable(_, _, _, _, _) }
/**
* Returns the indices of parameters that are a destination buffer.
*/
int getWriteParamIndex() {
this = libraryFunctionNameParamTable(_, result, _, _, _) and
result >= 0
}
/**
* Returns the indices of parameters that are a source buffer.
*/
int getReadParamIndex() {
this = libraryFunctionNameParamTable(_, _, result, _, _) and
result >= 0
}
/**
* Returns the index of the parameter that is the source buffer size.
*/
int getReadSizeParamIndex() {
this = libraryFunctionNameParamTable(_, _, _, result, _) and
result >= 0
}
/**
* Returns the index of the parameter that is the destination buffer size.
*/
int getWriteSizeParamIndex() {
this = libraryFunctionNameParamTable(_, _, _, _, result) and
result >= 0
}
/**
* Gets a parameter than is a source (read) buffer.
*/
Parameter getReadParam() { result = this.getParameter(this.getReadParamIndex()) }
/**
* Gets a parameter than is a destination (write) buffer.
*/
Parameter getWriteParam() { result = this.getParameter(this.getWriteParamIndex()) }
/**
* Gets a parameter than is a source (read) buffer size.
*/
Parameter getReadSizeParam() { result = this.getParameter(this.getReadSizeParamIndex()) }
/**
* Gets a parameter than is a destination (write) buffer size.
*/
Parameter getWriteSizeParam() { result = this.getParameter(this.getWriteSizeParamIndex()) }
/**
* Gets the size of an element in the destination buffer class
*/
int getWriteParamElementSize(Parameter p) {
p = this.getWriteParam() and
p.getType().getUnspecifiedType().(DerivedType).getBaseType().getSize().maximum(1) = result
}
/**
* Gets the size of an element in the source buffer class
*/
int getReadParamElementSize(Parameter p) {
p = this.getReadParam() and
p.getType().getUnspecifiedType().(DerivedType).getBaseType().getSize().maximum(1) = result
}
/**
* Holds if `i` is the index of a parameter of this function that requires arguments to be null-terminated.
* This predicate should be overriden by extending classes to specify null-terminated parameters, if necessary.
*/
predicate getANullTerminatedParameterIndex(int i) {
// by default, require null-terminated parameters for src but
// only if the type of src is a plain char pointer or wchar_t.
this.getReadParamIndex() = i and
exists(Type baseType |
baseType = this.getReadParam().getUnspecifiedType().(PointerType).getBaseType() and
(
baseType.getUnspecifiedType() instanceof PlainCharType or
baseType.getUnspecifiedType() instanceof Wchar_t
)
)
}
/**
* Holds if `i` is the index of a parameter of this function that is a size multiplier.
* This predicate should be overriden by extending classes to specify size multiplier parameters, if necessary.
*/
predicate getASizeMultParameterIndex(int i) {
// by default, there is no size multiplier parameter
// exceptions: fread, fwrite, bsearch, qsort
none()
}
/**
* Holds if `i` is the index of a parameter of this function that expects an element count rather than buffer size argument.
* This predicate should be overriden by extending classes to specify length parameters, if necessary.
*/
predicate getALengthParameterIndex(int i) {
// by default, size parameters do not exclude the size of a null terminator
none()
}
/**
* Holds if the read or write parameter at index `i` is allowed to be null.
* This predicate should be overriden by extending classes to specify permissibly null parameters, if necessary.
*/
predicate getAPermissiblyNullParameterIndex(int i) {
// by default, pointer parameters are not allowed to be null
none()
}
}
/**
* A library function that accesses one or more string buffers and has no
* additional parameters for specifying the size of the buffers.
*/
class SimpleStringLibraryFunction extends BufferAccessLibraryFunction {
SimpleStringLibraryFunction() {
this = libraryFunctionNameParamTableSimpleString(_, _, _, -1, -1)
}
override predicate getANullTerminatedParameterIndex(int i) {
// by default, require null-terminated parameters for src but
// only if the type of src is a plain char pointer.
this.getReadParamIndex() = i and
this.getReadParam().getUnspecifiedType().(PointerType).getBaseType().getUnspecifiedType()
instanceof PlainCharType
}
}
/**
* A `BufferAccessLibraryFunction` that performs string concatenation.
*/
abstract class StringConcatenationFunctionLibraryFunction extends BufferAccessLibraryFunction {
override predicate getANullTerminatedParameterIndex(int i) {
// `strcat` and variants require null-terminated params for both src and dst
i = [0, 1]
}
}
/**
* A `BufferAccessLibraryFunction` modelling `strcat`
*/
class StrcatLibraryFunction extends StringConcatenationFunctionLibraryFunction {
StrcatLibraryFunction() { this.getName() = getNameOrInternalName("strcat") }
}
/**
* A `BufferAccessLibraryFunction` modelling `strncat` or `wcsncat`
*/
class StrncatLibraryFunction extends StringConcatenationFunctionLibraryFunction {
StrncatLibraryFunction() { this.getName() = getNameOrInternalName(["strncat", "wcsncat"]) }
override predicate getALengthParameterIndex(int i) {
// `strncat` and `wcsncat` exclude the size of a null terminator, but
// both stops copying right after the null terminator is encountered.
// In fact, they don't care if the source buffer is null-terminated
// or not.
none()
}
override predicate getANullTerminatedParameterIndex(int i) {
// `strncat` does not require null-terminated parameters
none()
}
}
/**
* A `BufferAccessLibraryFunction` modelling `strncpy`
*/
class StrncpyLibraryFunction extends StringConcatenationFunctionLibraryFunction {
StrncpyLibraryFunction() { this.getName() = getNameOrInternalName("strncpy") }
override predicate getANullTerminatedParameterIndex(int i) {
// `strncpy` does not require null-terminated parameters
none()
}
}
/**
* A `BufferAccessLibraryFunction` modelling `strncmp`
*/
class StrncmpLibraryFunction extends BufferAccessLibraryFunction {
StrncmpLibraryFunction() { this.getName() = getNameOrInternalName("strncmp") }
override predicate getANullTerminatedParameterIndex(int i) {
// `strncmp` does not require null-terminated parameters
none()
}
}
/**
* A `BufferAccessLibraryFunction` modelling `mbtowc` and `mbrtowc`
*/
class MbtowcLibraryFunction extends BufferAccessLibraryFunction {
MbtowcLibraryFunction() { this.getName() = getNameOrInternalName(["mbtowc", "mbrtowc"]) }
override predicate getAPermissiblyNullParameterIndex(int i) {
// `mbtowc` requires null-terminated parameters for both src and dst
i = [0, 1]
}
}
/**
* A `BufferAccessLibraryFunction` modelling `mblen` and `mbrlen`
*/
class MblenLibraryFunction extends BufferAccessLibraryFunction {
MblenLibraryFunction() { this.getName() = getNameOrInternalName(["mblen", "mbrlen"]) }
override predicate getAPermissiblyNullParameterIndex(int i) { i = 0 }
}
/**
* A `BufferAccessLibraryFunction` modelling `setvbuf`
*/
class SetvbufLibraryFunction extends BufferAccessLibraryFunction {
SetvbufLibraryFunction() { this.getName() = getNameOrInternalName("setvbuf") }
override predicate getAPermissiblyNullParameterIndex(int i) { i = 1 }
override predicate getANullTerminatedParameterIndex(int i) {
// `setvbuf` does not require a null-terminated buffer
none()
}
}
/**
* A `BufferAccessLibraryFunction` modelling `snprintf`, `vsnprintf`, `swprintf`, and `vswprintf`.
* This class overrides the `getANullTerminatedParameterIndex` predicate to include the `format` parameter.
*/
class PrintfLibraryFunction extends BufferAccessLibraryFunction {
PrintfLibraryFunction() {
this.getName() = getNameOrInternalName(["snprintf", "vsnprintf", "swprintf", "vswprintf"])
}
override predicate getANullTerminatedParameterIndex(int i) {
// `snprintf` and variants require a null-terminated format string
i = 2
}
}
/**
* A `BufferAccessLibraryFunction` modelling `fread` and `fwrite`.
*/
class FreadFwriteLibraryFunction extends BufferAccessLibraryFunction {
FreadFwriteLibraryFunction() { this.getName() = getNameOrInternalName(["fread", "fwrite"]) }
override predicate getASizeMultParameterIndex(int i) {
// `fread` and `fwrite` have a size multiplier parameter
i = 1
}
}
/**
* A `BufferAccessLibraryFunction` modelling `bsearch`
*/
class BsearchLibraryFunction extends BufferAccessLibraryFunction {
BsearchLibraryFunction() { this.getName() = getNameOrInternalName("bsearch") }
override predicate getASizeMultParameterIndex(int i) {
// `bsearch` has a size multiplier parameter
i = 3
}
}
/**
* A `BufferAccessLibraryFunction` modelling `qsort`
*/
class QsortLibraryFunction extends BufferAccessLibraryFunction {
QsortLibraryFunction() { this.getName() = getNameOrInternalName("qsort") }
override predicate getASizeMultParameterIndex(int i) {
// `qsort` has a size multiplier parameter
i = 2
}
}
/**
* A `BufferAccessLibraryFunction` modelling `strtok`
*/
class StrtokLibraryFunction extends BufferAccessLibraryFunction {
StrtokLibraryFunction() { this.getName() = getNameOrInternalName(["strtok", "strtok_r"]) }
override predicate getAPermissiblyNullParameterIndex(int i) {
// `strtok` does not require a non-null `str` parameter
i = 0
}
}
/**
* An construction of a pointer to a buffer.
*/
abstract class BufferAccess extends Expr {
abstract predicate hasABuffer(Expr buffer, Expr size, int sizeMult);
Expr getARelevantExpr() {
hasABuffer(result, _, _)
or
hasABuffer(_, result, _)
}
}
class PointerArithmeticBufferAccess extends BufferAccess instanceof PointerArithmeticExpr {
override predicate hasABuffer(Expr buffer, Expr size, int sizeMult) {
buffer = this.(PointerArithmeticExpr).getPointer() and
size = this.(PointerArithmeticExpr).getOperand() and
sizeMult =
buffer.getType().getUnspecifiedType().(DerivedType).getBaseType().getSize().maximum(1)
}
}
class ArrayBufferAccess extends BufferAccess, ArrayExpr {
override predicate hasABuffer(Expr buffer, Expr size, int sizeMult) {
buffer = this.getArrayBase() and
size = this.getArrayOffset() and
sizeMult =
buffer.getType().getUnspecifiedType().(DerivedType).getBaseType().getSize().maximum(1)
}
}
/**
* A `FunctionCall` to a `BufferAccessLibraryFunction` that provides predicates for
* reasoning about buffer overflow and other buffer access violations.
*/
class BufferAccessLibraryFunctionCall extends FunctionCall, BufferAccess {
BufferAccessLibraryFunctionCall() { this.getTarget() instanceof BufferAccessLibraryFunction }
override predicate hasABuffer(Expr buffer, Expr size, int sizeMult) {
buffer = this.getWriteArg() and
size = this.getWriteSizeArg(sizeMult)
or
buffer = this.getReadArg() and
size = this.getReadSizeArg(sizeMult)
}
Expr getReadArg() {
result = this.getArgument(this.getTarget().(BufferAccessLibraryFunction).getReadParamIndex())
}
Expr getWriteArg() {
result = this.getArgument(this.getTarget().(BufferAccessLibraryFunction).getWriteParamIndex())
}
Expr getReadSizeArg(int mult) {
result =
this.getArgument(this.getTarget().(BufferAccessLibraryFunction).getReadSizeParamIndex()) and
getReadSizeArgMult() = mult
}
Expr getWriteSizeArg(int mult) {
result =
this.getArgument(this.getTarget().(BufferAccessLibraryFunction).getWriteSizeParamIndex()) and
getWriteSizeArgMult() = mult
}
int getReadSizeArgMult() {
result =
this.getTarget().(BufferAccessLibraryFunction).getReadParamElementSize(_) *
getSizeMultArgValue()
}
int getWriteSizeArgMult() {
result =
this.getTarget().(BufferAccessLibraryFunction).getWriteParamElementSize(_) *
getSizeMultArgValue()
}
int getSizeMultArgValue() {
// Note: This predicate currently expects the size multiplier argument to be a constant.
// This implementation could be improved with range-analysis or data-flow to determine the argument value.
exists(int i |
this.getTarget().(BufferAccessLibraryFunction).getASizeMultParameterIndex(i) and
result = this.getArgument(i).getValue().toInt()
)
or
not this.getTarget().(BufferAccessLibraryFunction).getASizeMultParameterIndex(_) and
result = 1
}
}
/**
* A `FunctionCall` to a `SimpleStringLibraryFunction`
*/
class SimpleStringLibraryFunctionCall extends BufferAccessLibraryFunctionCall {
SimpleStringLibraryFunctionCall() { this.getTarget() instanceof SimpleStringLibraryFunction }
}
bindingset[dest]
private Expr getSourceConstantExpr(Expr dest) {
exists(result.getValue().toInt()) and
DataFlow::localExprFlow(result, dest)
}
/**
* Gets the smallest of the upper bound of `e` or the largest source value (i.e. "stated value") that flows to `e`.
* Because range-analysis can over-widen bounds, take the minimum of range analysis and data-flow sources.
*
* If there is no source value that flows to `e`, this predicate does not hold.
*
* This predicate, if `e` is the size argument to malloc, would return `20` for the following example:
* ```
* size_t sz = condition ? 10 : 20;
* malloc(sz);
* ```
*/
private int getMaxStatedValue(Expr e) {
result = upperBound(e).minimum(max(getSourceConstantExpr(e).getValue().toInt()))
}
/**
* Gets the smallest of the upper bound of `e` or the smallest source value (i.e. "stated value") that flows to `e`.
* Because range-analysis can over-widen bounds, take the minimum of range analysis and data-flow sources.
*
* If there is no source value that flows to `e`, this predicate does not hold.
*
* This predicate, if `e` is the size argument to malloc, would return `10` for the following example:
* ```
* size_t sz = condition ? 10 : 20;
* malloc(sz);
* ```
*/
bindingset[e]
private int getMinStatedValue(Expr e) {
result = upperBound(e).minimum(min(getSourceConstantExpr(e).getValue().toInt()))
}
/**
* A class for reasoning about the offset of a variable from the original value flowing to it
* as a result of arithmetic or pointer arithmetic expressions.
*/
bindingset[expr]
private int getArithmeticOffsetValue(Expr expr, Expr base) {
result = getMinStatedValue(expr.(PointerArithmeticExpr).getOperand()) and
base = expr.(PointerArithmeticExpr).getPointer()
or
// &(array[index]) expressions
result =
getMinStatedValue(expr.(AddressOfExpr).getOperand().(PointerArithmeticExpr).getOperand()) and
base = expr.(AddressOfExpr).getOperand().(PointerArithmeticExpr).getPointer()
or
result = getMinStatedValue(expr.(AddExpr).getRightOperand()) and
base = expr.(AddExpr).getLeftOperand()
or
result = -getMinStatedValue(expr.(SubExpr).getRightOperand()) and
base = expr.(SubExpr).getLeftOperand()
or
expr instanceof IncrementOperation and
result = 1 and
base = expr.(IncrementOperation).getOperand()
or
expr instanceof DecrementOperation and
result = -1 and
base = expr.(DecrementOperation).getOperand()
or
// fall-back if `expr` is not an arithmetic or pointer arithmetic expression
not expr instanceof PointerArithmeticExpr and
not expr.(AddressOfExpr).getOperand() instanceof PointerArithmeticExpr and
not expr instanceof AddExpr and
not expr instanceof SubExpr and
not expr instanceof IncrementOperation and
not expr instanceof DecrementOperation and
base = expr and
result = 0
}
private int constOrZero(Expr e) {
result = e.getValue().toInt()
or
not exists(e.getValue().toInt()) and result = 0
}
abstract class PointerToObjectSource extends Expr {
/**
* Gets the expression that points to the object.
*/
abstract Expr getPointer();
/**
* Gets the expression, if any, that defines the size of the object.
*/
abstract Expr getSizeExpr();
/**
* Gets the size of the object, if it is statically known.
*/
abstract int getFixedSize();
/**
* Holds if the object is not null-terminated.
*/
abstract predicate isNotNullTerminated();
}
private class DynamicAllocationSource extends PointerToObjectSource instanceof AllocationExpr,
FunctionCall
{
DynamicAllocationSource() {
// exclude OperatorNewAllocationFunction to only deal with raw malloc-style calls,
// which do not apply a multiple to the size of the allocation passed to them.
not this.(FunctionCall).getTarget() instanceof OperatorNewAllocationFunction
}
override Expr getPointer() { result = this }
override Expr getSizeExpr() {
// AllocationExpr may sometimes return a subexpression of the size expression
// in order to separate the size from a sizeof expression in a MulExpr.
exists(AllocationFunction f |
f = this.(FunctionCall).getTarget() and
result = this.(FunctionCall).getArgument(f.getSizeArg())
)
}
/**
* Returns either `getSizeExpr()`, or, if a value assigned to a variable flows
* to `getSizeExpr()` or an `AddExpr` within it, the value assigned to that variable.
*
* If an `AddExpr` exists in the value assignment or `getSizeExpr()`, and that `AddExpr`
* has a constant right operand, then value of that operand is `offset`. Otherwise, `offset` is 0.
*
* If no `AddExpr` exists, `base = result`. Otherwise, `base` is the left operand of the `AddExpr`.
* If the left operand of the `AddExpr` comes from a variable assignment, `base` is assigned value.
*
* This predicate serves as a rough heuristic for cases such as the following:
* 1. `size_t sz = strlen(src) + 1; malloc(sz);`
* 2. `size_t sz = strlen(src); malloc(sz + 1);`
*/
Expr getSizeExprSource(Expr base, int offset) {
if this.getSizeExpr() instanceof AddExpr
then
exists(AddExpr ae |
exists(Variable v |
// case 1: variable access + const in the size expression
this.getSizeExpr() = ae and
result = v.getAnAssignedValue() and
base = ae.getLeftOperand() and
offset = constOrZero(ae.getRightOperand()) and
DataFlow::localExprFlow(result, base)
or
// case 2: expr + const in the variable assignment
v.getAnAssignedValue() = ae and
result = ae and
base = ae.getLeftOperand() and
offset = constOrZero(ae.getRightOperand()) and
DataFlow::localExprFlow(result, this.getSizeExpr())
)
or
// case 3: function call + const
result = ae and
this.getSizeExpr() = ae and
ae.getLeftOperand() = base and
ae.getLeftOperand() instanceof FunctionCall and
offset = constOrZero(ae.getRightOperand())
)
else (
offset = 0 and
// case 3: a variable is read in the size expression
// if the VariableAccess does not have a computable constant value,
// the source node could still be useful for data-flow and GVN comparisons
if this.getSizeExpr() instanceof VariableAccess
then
exists(Variable v |
v = this.getSizeExpr().(VariableAccess).getTarget() and
not v instanceof Field and
DataFlow::localExprFlow(v.getAnAssignedValue(), base) and
result = base
)
else (
// Case 4: no variable access in the size expression
// This case is equivalent to getSizeExpr.
base = this.getSizeExpr() and
result = base
)
)
}
override int getFixedSize() { result = getMaxStatedValue(getSizeExpr()) }
override predicate isNotNullTerminated() { none() }
}
/**
* A `PointerToObjectSource` which is an `AddressOfExpr` to a variable
* that is not a field or pointer type.
*/
private class AddressOfExprSource extends PointerToObjectSource instanceof AddressOfExpr {
AddressOfExprSource() {
exists(Variable v |
v = this.getOperand().(VariableAccess).getTarget() and
not v.getUnderlyingType() instanceof PointerType and
not v instanceof Field
)
}
override Expr getPointer() { result = this }
override Expr getSizeExpr() { none() }
override int getFixedSize() {
result = min(this.(AddressOfExpr).getOperand().getType().getSize())
}
override predicate isNotNullTerminated() { none() }
}
/**
* A `PointerToObjectSource` which is a `VariableAccess` to a static buffer
*/
private class StaticBufferAccessSource extends PointerToObjectSource instanceof VariableAccess {
StaticBufferAccessSource() {
not this.getTarget() instanceof Field and
not this.getTarget().getUnspecifiedType() instanceof PointerType and
this.getTarget().getUnderlyingType().(ArrayType).getSize() > 0
}
override Expr getPointer() { result = this }
override Expr getSizeExpr() { none() }
override int getFixedSize() {
result = this.(VariableAccess).getTarget().getUnderlyingType().(ArrayType).getSize()
}
override predicate isNotNullTerminated() {
// StringLiteral::getOriginalLength uses Expr::getValue, which implicitly truncates string literal
// values to the length fitting the buffer they are assigned to, thus breaking the 'obvious' check.
// Note: `CharArrayInitializedWithStringLiteral` falsely reports the string literal length in certain cases
// (e.g. when the string literal contains escape characters or on certain compilers), resulting in false-negatives
exists(CharArrayInitializedWithStringLiteral init |
init = this.(VariableAccess).getTarget().getInitializer().getExpr() and
init.getStringLiteralLength() + 1 > init.getContainerLength()
)
or
// if the buffer is not initialized and does not have any memset call zeroing it, it is not null-terminated.
// note that this heuristic does not evaluate the order of the memset calls made and whether they dominate
// any use of the buffer by functions requiring it to be null-terminated.
(
this.(VariableAccess).getTarget().getUnspecifiedType().(ArrayType).getBaseType() instanceof
PlainCharType
or
this.(VariableAccess).getTarget().getUnspecifiedType().(ArrayType).getBaseType() instanceof
Wchar_t
) and
not this.(VariableAccess).getTarget() instanceof GlobalVariable and
not exists(this.(VariableAccess).getTarget().getInitializer()) and
// exclude any BufferAccessLibraryFunction that writes to the buffer and does not require
// a null-terminated buffer argument for its write argument
not exists(
BufferAccessLibraryFunctionCall fc, BufferAccessLibraryFunction f, int writeParamIndex
|
f = fc.getTarget() and
writeParamIndex = f.getWriteParamIndex() and
not f.getANullTerminatedParameterIndex(writeParamIndex) and
fc.getArgument(writeParamIndex) = this.(VariableAccess).getTarget().getAnAccess()
) and
// exclude any buffers that have an assignment, deref, or array expr with a zero constant
// note: heuristically implemented using getAChild*()
not exists(AssignExpr assign |
assign.getRValue().getValue().toInt() = 0 and
assign.getLValue().getAChild*() = this.(VariableAccess).getTarget().getAnAccess()
)
// note: the case of initializers that are not string literals and non-zero constants is not handled here.
// e.g. char buf[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; (not null-terminated)
// char buf[10] = { 1 }; (not null-terminated)
}
}
/**
* A `PointerToObjectSource` which is a string literal that is not
* part of an variable initializer (to deduplicate `StaticBufferAccessSource`)
*/
private class StringLiteralSource extends PointerToObjectSource instanceof StringLiteral {
StringLiteralSource() { not this instanceof CharArrayInitializedWithStringLiteral }
override Expr getPointer() { result = this }
override Expr getSizeExpr() { none() }
override int getFixedSize() {
// (length of the string literal + null terminator) * (size of the base type)
result =
this.(StringLiteral).getOriginalLength() *
this.(StringLiteral).getUnderlyingType().(DerivedType).getBaseType().getSize()
}
override predicate isNotNullTerminated() { none() }
}
private module PointerToObjectSourceOrSizeToBufferAccessFunctionConfig implements
DataFlow::ConfigSig
{
predicate isSource(DataFlow::Node source) {
source.asExpr() instanceof PointerToObjectSource
or
exists(PointerToObjectSource ptr |
source.asExpr() = ptr.getSizeExpr() or
source.asExpr() = ptr.(DynamicAllocationSource).getSizeExprSource(_, _)
)
}
predicate isSink(DataFlow::Node sink) {
exists(BufferAccess ba, Expr arg |
(
arg = ba.(BufferAccessLibraryFunctionCall).getAnArgument() or
arg = ba.getARelevantExpr()
) and
(
sink.asExpr() = arg or
exists(getArithmeticOffsetValue(arg, sink.asExpr()))
)
)
}
predicate isBarrierOut(DataFlow::Node node) {
// the default interprocedural data-flow model flows through any array assignment expressions
// to the qualifier (array base or pointer dereferenced) instead of the individual element
// that the assignment modifies. this default behaviour causes false positives for any future
// access of the array base, so remove the assignment edge at the expense of false-negatives.
exists(AssignExpr a |
node.asExpr() = a.getRValue().getAChild*() and
(
a.getLValue() instanceof ArrayExpr or
a.getLValue() instanceof PointerDereferenceExpr
)
)
or
// remove flow from `src` to `dst` in a buffer access function call
// the standard library models such flow through functions such as memcpy, strcpy, etc.
exists(BufferAccessLibraryFunctionCall fc | node.asExpr() = fc.getReadArg().getAChild*())
or
node.asDefiningArgument() instanceof AddressOfExpr
}
}
private module PointerToObjectSourceOrSizeToBufferAccessFunctionFlow =
DataFlow::Global<PointerToObjectSourceOrSizeToBufferAccessFunctionConfig>;
private predicate hasFlowFromBufferOrSizeExprToUse(Expr source, Expr use) {
exists(Expr useOrChild |
exists(getArithmeticOffsetValue(use, useOrChild)) and
PointerToObjectSourceOrSizeToBufferAccessFunctionFlow::flow(DataFlow::exprNode(source),
DataFlow::exprNode(useOrChild))
)
}
private predicate bufferUseComputableBufferSize(
Expr bufferUse, PointerToObjectSource source, int size
) {
// flow from a PointerToObjectSource for which we can compute the exact size
size = source.getFixedSize() and
hasFlowFromBufferOrSizeExprToUse(source, bufferUse)
}
private predicate bufferUseNonComputableSize(Expr bufferUse, Expr source) {
not bufferUseComputableBufferSize(bufferUse, source, _) and
hasFlowFromBufferOrSizeExprToUse(source.(DynamicAllocationSource), bufferUse)
}
/**
* Relates `sizeExpr`, a buffer access size expresion, to `source`, which is either `sizeExpr`
* if `sizeExpr` has a stated value, or a `DynamicAllocationSource::getSizeExprSource` for which
* we can compute the exact size and that has flow to `sizeExpr`.
*/
private predicate sizeExprComputableSize(Expr sizeExpr, Expr source, int size) {
// computable direct value, e.g. array_base[10], where "10" is sizeExpr and source.
size = getMinStatedValue(sizeExpr) and
source = sizeExpr