-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpatched-codes-semgrep-rules.yml
15608 lines (14634 loc) · 563 KB
/
patched-codes-semgrep-rules.yml
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
# Patched Semgrep Rules
# Source Repo: https://github.com/patched-codes/semgrep-rules
# License: MIT
# Version: 0.0.1
---
rules:
- id: go_crypto_rule-tlsversion
languages:
- go
pattern-either:
- patterns:
- pattern-either:
- patterns:
- pattern-inside: |
tls.Config{...}
- pattern: |
MinVersion: $VAL
- patterns:
- pattern-inside: |
$VAR = uint16($VAL)
...
- pattern-inside: |
tls.Config{...}
- pattern: |
MinVersion: $VAR
- metavariable-pattern:
metavariable: $VAL
pattern-either:
- pattern: tls.VersionTLS11
- pattern: tls.VersionTLS10
- patterns:
- pattern-inside: |
tls.Config{...}
- pattern: |
MaxVersion: $ANYVAL
- pattern-not-inside: |
tls.Config{..., MinVersion: ..., ...}
message: |
TLS versions 1.1 and 1.0 were deprecated by the IETF in June 2018 due to
a number of attacks against the vulnerable versions. Use of a deprecated
TLS version may result in the unauthorized retrieval of sensitive
information. It is strongly recommended that all TLS connections
use TLS 1.3 as Go will automatically choose the most secure cipher when
negotiating the TLS handshake with client or servers. TLS 1.3 cipher suites
are configured to require Perfect Forward Secrecy (PFS). PFS is an important
property as it will ensure that past encrypted transmissions could not be
decrypted if the TLS certificate was compromised.
Example using TLS 1.3 for a Go server:
```
cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil {
log.Fatal(err)
}
cfg := &tls.Config{Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS13}
srv := &http.Server{
Addr: ":8999",
TLSConfig: cfg,
ReadTimeout: time.Minute,
WriteTimeout: time.Minute,
}
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
```
metadata:
shortDescription: Use of deprecated TLS version
cwe: CWE-310
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
security-severity: Medium
category: security
severity: WARNING
- id: go_crypto_rule-badtlssettings
languages:
- go
patterns:
- pattern-either:
- pattern: |
tls.Config{..., CipherSuites: []$SLICE{..., $CIPHERS, ...}, ...}
- pattern: |
tls.CipherSuite{..., ID: $CIPHERS, ...}
- metavariable-regex:
metavariable: $CIPHERS
regex:
((?!tls.TLS_AES_128_GCM_SHA256)|(?!tls.TLS_AES_256_GCM_SHA384)|(?!tls.TLS_CHACHA20_POLY1305_SHA256)|
(?!tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)|(?!tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)|
(?!tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384)|(?!tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384)|
(?!tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305)|(?!tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256)|
(?!tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305)|(?!tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256)|
(?!tls.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)|(?!tls.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384))
message: |
Usage of a cryptographically insecure cipher suite has been detected. It is recommended that
alternative ciphers be used instead. It is strongly recommended that all TLS connections
use TLS 1.3 as Go will automatically choose the most secure cipher when negotiating the
TLS handshake with client or servers. TLS 1.3 cipher suites are configured to require Perfect
Forward Secrecy (PFS).
PFS is an important property as it will ensure that past encrypted transmissions could not be
decrypted
if the TLS certificate was compromised.
Example using TLS 1.3 for a Go server:
```
cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil {
log.Fatal(err)
}
cfg := &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13}
srv := &http.Server{
Addr: ":8999",
TLSConfig: cfg,
ReadTimeout: time.Minute,
WriteTimeout: time.Minute,
}
log.Fatal(srv.ListenAndServeTLS("", ""))
```
If TLS 1.0-1.2 must be used, then the following list of ciphers should be chosen as they
support
Perfect Forward Secrecy (PFS):
- TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
- TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
Example `tls.Config` using the recommended cipher suites:
```
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
},
}
```
For more information on cipher suites in Go see: https://go.dev/blog/tls-cipher-suites
metadata:
shortDescription: Use of a broken or risky cryptographic algorithm
cwe: CWE-327
category: security
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
security-severity: Medium
severity: WARNING
- id: go_crypto_rule-weakkeystrength
languages:
- go
patterns:
- pattern-either:
- pattern: |
rsa.GenerateKey(..., $ARG)
- metavariable-comparison:
metavariable: $ARG
comparison: $ARG < 2048
message: |
The application is generating an RSA key that is less than the recommended 2048 bits.
The National Institute of Standards and Technology (NIST) deprecated signing Digital
Certificates that contained RSA Public Keys of 1024 bits in December 2010. While
1024-bit RSA keys have not been factored yet, advances in compute may make it possible
in the near future.
To generate an RSA key of 2048 pass the number of bits as the second parameter to
the `rsa.GenerateKey` function:
```
import (
"crypto/rand"
"crypto/rsa"
)
func generate() {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal(err)
}
}
```
metadata:
shortDescription: Inadequate encryption strength
cwe: CWE-326
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
security-severity: Medium
category: security
severity: WARNING
- id: go_crypto_rule-weakrandsource
languages:
- go
patterns:
- patterns:
- pattern-inside: |
import $IMPORT "math/rand"
...
- pattern-not-inside: |
import "crypto/rand"
- pattern-either:
- pattern: $IMPORT.$METHOD(...)
- pattern: rand.$METHOD(...)
- metavariable-regex:
metavariable: $METHOD
regex: (Float32|Float64|Int31|Int31n|Int63|Int63n|NormalFloat64|Uint32|Uint64)
message: |
Go's `math/rand` is not meant for use in generating random numbers for any cryptographic or
security sensitive context. This includes generating random numbers that could be used in
user specific identifiers or where the random number that is generated is considered to
be secret.
Replace all imports of `math/rand` with `crypto/rand`.
metadata:
shortDescription: Use of cryptographically weak Pseudo-Random Number Generator
(PRNG)
cwe: CWE-338
owasp:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
security-severity: Medium
category: security
severity: WARNING
- id: go_crypto_rule-insecure-ignore-host-key
languages:
- go
patterns:
- pattern: ssh.InsecureIgnoreHostKey(...)
message: |
The application was found to ignore host keys. Host keys are important as
they provide assurance that the client can prove that the host is trusted.
By ignoring these host keys, it is impossible for the client to validate the
connection is to a trusted host.
For the `ssh.ClientConfig` `HostKeyCallback` property, consider using the
[knownhosts](https://pkg.go.dev/golang.org/x/crypto/ssh/knownhosts) package that
parses OpenSSH's `known_hosts` key database.
Example configuration connecting to a known, trusted host:
```
knownHostCallback, err := knownhosts.New("/home/user/.ssh/known_hosts")
if err != nil {
log.Fatal(err)
}
// Create client config using the knownHost callback function
config := &ssh.ClientConfig{
...
HostKeyCallback: knownHostCallback,
}
// Connect to ssh server
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatal("unable to connect: ", err)
}
defer conn.Close()
```
metadata:
shortDescription: Key exchange without entity authentication
cwe: CWE-322
owasp:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
security-severity: Medium
category: security
severity: WARNING
- id: go_memory_rule-integer-overflow
languages:
- go
patterns:
- pattern-either:
- patterns:
- pattern-inside: |
$X, ... := strconv.Atoi(...)
...
- pattern-either:
- pattern: int32($X)
- pattern: int16($X)
message: |
Golang's `int` type size depends on the architecture of where the application is running. For
32-bit systems, `int` is
32-bit, for 64-bit systems, `int` will be 64-bit. By calling `strconv.Atoi` with a large
number, the integer may overflow
if the `int` return value is type converted into a smaller type (`int32` or `int16`). This
could cause unexpected application
behavior depending on how the resultant value is used.
Prior to running any type conversion, check that the value returned from `strconv.Atoi` will
fit in the resulting integer.
Example of checking the return value before type conversion:
```
bigValue, _ := strconv.Atoi("32768")
if bigValue > math.MaxInt16 {
log.Fatal("value too large to fit in int16")
}
value := int16(bigValue)
fmt.Println(value)
```
For more information on integer min/max constants see: https://pkg.go.dev/math#pkg-constants
metadata:
shortDescription: Integer overflow or wraparound
cwe: CWE-190
owasp:
- A1:2017-Injection
- A03:2021-Injection
security-severity: Medium
category: security
severity: ERROR
- id: go_memory_rule-memoryaliasing
languages:
- go
patterns:
- pattern-either:
- pattern: |
for ..., $ARG := range $SLICE {
<... &($ARG) ...>
}
- pattern: |
for ..., $ARG := range $SLICE {
<... func() { <... &$ARG ...> } ...>
}
- pattern: |
for ..., $ARG := range $SLICE {
<... $X(..., <... &$ARG ...>, ...) ...>
}
- pattern-not: |
for ..., $ARG := range $SLICE {
<... *$ARG ...>
}
- pattern-not-inside: |-
for ..., $ARG := range $SLICE { return ... }
message: |
Go's `for ... range` statements create an iteration variable for each iteration of the loop.
By taking the address of this iteration variable, the value of the address will be re-used
and always point to the same location in memory. This can have unexpected behavior if the
address is stored or re-used.
This can be fixed by:
- Not referencing the address of the variable
- Re-assigning the iteration variable to a new variable
- Using the address of the indexed variable
Example not referencing the address:
```
type someStruct struct {
x int
}
for _, n := range []someStruct{{1}, {2}, {3}, {4}} {
fmt.Printf("%d\n", n.x)
}
```
Example reassigning the iteration variable to a new variable:
```
type someStruct struct {
x int
}
for _, n := range []someStruct{{1}, {2}, {3}, {4}} {
p := n
fmt.Printf("%p\n", &p)
}
```
Example using the address of the indexed variable:
```
type someStruct struct {
x int
}
structData := []someStruct{{1}, {2}, {3}, {4}}
for idx := range structData {
fmt.Printf("%p\n", &structData[idx])
}
```
For more information on how the `for ... range` statement works see:
https://go.dev/ref/spec#For_statements
metadata:
shortDescription: Incorrect access of indexable resource ('Range Error')
cwe: CWE-118
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
security-severity: Info
category: security
severity: WARNING
- id: go_network_rule-bind-to-all-interfaces
languages:
- go
patterns:
- pattern-either:
- pattern: net.Listen(..., "$ADDR")
- pattern: tls.Listen(..., "$ADDR", ...)
- metavariable-regex:
metavariable: $ADDR
regex: ^(0\.0\.0\.0|\[::\])?(:[0-9]*)?$
message: |
Binding to all network interfaces can potentially open up a service to
traffic on unintended interfaces, that may not be properly documented or
secured. By passing "0.0.0.0" as the address to the `Listen` family of functions,
the application will bind to all interfaces.
Consider passing in the interface ip address through an environment variable,
configuration file, or by determining the primary interface(s) IP address.
Example getting the IP address from an environment variable `IP_ADDRESS`:
```
addr := os.Getenv("IP_ADDRESS")
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
```
metadata:
shortDescription: Exposure of sensitive information to an unauthorized actor
cwe: CWE-200
owasp:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
security-severity: Low
category: security
severity: WARNING
- id: go_filesystem_rule-decompression-bomb
languages:
- go
mode: taint
pattern-sources:
- pattern: gzip.NewReader(...)
- pattern: zlib.NewReader(...)
- pattern: bzip2.NewReader(...)
- pattern: flate.NewReader(...)
- pattern: lzw.NewReader(...)
- pattern: tar.NewReader(...)
- pattern: zip.NewReader(...)
- pattern: zlib.NewReaderDict(...)
- pattern: flate.NewReaderDict(...)
- pattern: zip.OpenReader(...)
pattern-sanitizers:
- patterns:
- pattern: io.LimitReader($TAINTED, ...)
- focus-metavariable: $TAINTED
pattern-sinks:
- patterns:
- pattern: io.Copy($DST, $TAINTED)
- focus-metavariable: $TAINTED
- patterns:
- pattern: io.CopyBuffer($DST, $TAINTED, $BUF)
- focus-metavariable: $TAINTED
message: |
Directly decompressing files or buffers may lead to a potential Denial of Service (DoS)
due to a decompression bomb. Decompression bombs are maliciously compressed files
or data that decompresses to extremely large sizes. This can cause the process to run
out of memory, or the disk to fill up.
To protect against decompression bombs, an
[io.LimitReader(...)](https://pkg.go.dev/io#LimitReader)
should be used to limit how much can be read during the decompression routine.
Example using `io.LimitReader` to protect against a decompression bomb:
```
f, err := os.Open("some.gz")
if err != nil {
log.Fatal(err)
}
r, err := gzip.NewReader(f)
if err != nil {
log.Fatal(err)
}
const oneMegabyte = 1024 * 1024
limitedReader := io.LimitReader(r, oneMegabyte)
// use limitedReader to stop copying after 1 MB
if _, err := io.Copy(os.Stdout, limitedReader); err != nil {
log.Fatal(err)
}
```
metadata:
shortDescription: Improper handling of highly compressed data
cwe: CWE-409
owasp:
- A1:2017-Injection
- A03:2021-Injection
security-severity: Medium
category: security
severity: WARNING
- id: go_filesystem_rule-httprootdir
languages:
- go
patterns:
- pattern-either:
- pattern: |
import $NET "net/http"
...
$NET.Dir("/")
- pattern: |
import "net/http"
...
http.Dir("/")
message: |
The application is potentially exposing the entire filesystem by mounting the root
directory `/` to an HTTP handler function. Anyone who is able to access this HTTP
server may be able to access any file that the HTTP server has access to.
Restrict the `http.Dir` path to only a specific folder instead of the entire
filesystem.
Example server only allowing directory listing on a public directory:
```
const path = "/var/www/html/public"
fs := http.FileServer(http.Dir(path))
log.Fatal(http.ListenAndServe(":9000", fs))
```
metadata:
shortDescription: Files or directories accessible to external parties
cwe: CWE-552
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
security-severity: Medium
category: security
severity: WARNING
- id: go_filesystem_rule-tempfiles
languages:
- go
patterns:
- pattern-either:
- pattern: |
os.WriteFile("$ARG", ...)
- pattern: |
ioutil.WriteFile("$ARG", ...)
- pattern: |
os.OpenFile("$ARG", <... os.O_CREATE ...>, ...)
- pattern: |
os.Create("$ARG")
- metavariable-regex:
metavariable: $ARG
regex: (/tmp/.*|/var/tmp/.*)
message: |
The application was found creating files in shared system temporary directories
(`/tmp` or `/var/tmp`) without using the `os.CreateTemp` function. Depending
on how the application uses this temporary file, an attacker may be able to create
symlinks that point to other files prior to the application creating or writing
to the target file, leading to unintended files being created or overwritten.
Example using `os.CreateTemp` in an application restricted directory:
```
// assumes /opt/appdir/ is chown'd to the running application user
if err := os.MkdirAll("/opt/appdir/restricted", 0700); err != nil {
log.Fatal(err)
}
// create a temporary file in the restricted directory in the form of temp-952569059.txt
f, err := os.CreateTemp("/opt/appdir/restricted", "temp-*.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// clean up on exit
defer os.Remove(f.Name())
// work with file
```
metadata:
shortDescription: Creation of temporary file with insecure permissions
cwe: CWE-378
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
security-severity: Medium
category: security
severity: WARNING
- id: go_filesystem_rule-poorwritepermissions
languages:
- go
patterns:
- pattern-either:
- pattern: |
ioutil.WriteFile(..., ..., $ARG)
- metavariable-comparison:
metavariable: $ARG
comparison: $ARG > 0o600
base: 8
message: |
The application was found setting file permissions to overly permissive values. Consider
using the following values if the application user is the only process to access
the file:
- 0400 - read only access to the file
- 0200 - write only access to the file
- 0600 - read/write access to the file
Example writing file contents with read/write permissions for the application user:
```
dat := []byte("sensitive data")
if err := os.WriteFile("file.txt", dat, 0600); err != nil {
log.Fatal(err)
}
```
For all other values please see:
https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation
metadata:
shortDescription: Incorrect default permissions
cwe: CWE-276
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
security-severity: Medium
category: security
severity: WARNING
- id: go_filesystem_rule-fileread
languages:
- go
mode: taint
pattern-sources:
- pattern: os.Getenv(...)
- pattern: fmt.Sprintf(...)
- pattern: filepath.Join(...)
- pattern: path.Join(...)
- patterns:
- pattern-either:
- pattern: '... + $TAINTED'
- pattern: '... + $TAINTED + ...'
- pattern: $TAINTED + ...
- pattern-not: '"..." + $TAINTED'
- pattern-not: '"..." + $TAINTED + "..."'
- pattern-not: $TAINTED + "..."
- pattern-not: fmt.Sprintf("...", "...")
- patterns:
- pattern-either:
- pattern: |
($REQUEST : *http.Request).$SOURCE_METHOD
- pattern: |
($REQUEST : http.Request).$SOURCE_METHOD
- metavariable-regex:
metavariable: $SOURCE_METHOD
regex:
^(BasicAuth|Body|Cookie|Cookies|Form|FormValue|GetBody|Host|MultipartReader|ParseForm|ParseMultipartForm|PostForm|PostFormValue|Referer|RequestURI|Trailer|TransferEncoding|UserAgent|URL)$
pattern-sanitizers:
- patterns:
- pattern-either:
- pattern: |
$CLEAN := $PKG.Clean(...)
...
if !strings.HasPrefix($CLEAN, "...") {...}
- pattern: |
$CLEAN := $PKG.Clean(...)
...
if strings.HasPrefix($CLEAN, "...") {...}
- pattern: |
$CLEAN := $PKG.Clean(...)
...
if strings.HasPrefix($CLEAN, "...") == false {...}
- metavariable-regex:
metavariable: $PKG
regex: ^((file)?path)$
pattern-sinks:
- pattern: os.OpenFile(...)
- pattern: os.Open(...)
- pattern: os.ReadFile(...)
- pattern: ioutil.ReadFile(...)
message: |
The application dynamically constructs file or path information. If the path
information comes from user input, it could be abused to read sensitive files,
access other users data or aid in exploitation to gain further system access.
User input should never be used in constructing paths or files for interacting
with the filesystem. This includes filenames supplied by user uploads or downloads.
If possible, consider hashing user input or replacing it with unique values.
Additionally, use `filepath.Base` to only use the filename and not path information.
Always validate the full path prior to opening or writing to any file.
Example using `filepath.Base`, generating a unique filename without using
user input to construct filepath information:
```
type userData struct {
id string
userFilename string
}
func newUserData(userFilename string) userData {
return userData{
id: randomFileID(), // random id as the filename
userFilename: userFilename,
}
}
// randomFileID generates a random id, to be used as a filename
func randomFileID() string {
id := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
log.Fatal(err)
}
return hex.EncodeToString(id)
}
func main() {
// user input, saved only as a reference
data := newUserData("../../possibly/malicious")
// restrict all file access to this path
const basePath = "/tmp/"
// resolve the full path, but only use our random generated id
resolvedPath, err := filepath.Join(basePath, filepath.Base(data.id))
if err != nil {
log.Fatal(err)
}
// verify the path is prefixed with our basePath
if !strings.HasPrefix(resolvedPath, basePath) {
log.Fatal("path does not start with basePath")
}
// process / work with file
}
```
For more information on path traversal issues see OWASP:
https://owasp.org/www-community/attacks/Path_Traversal
metadata:
shortDescription: Improper limitation of a pathname to a restricted directory
('Path Traversal')
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
security-severity: Medium
category: security
severity: WARNING
- id: go_filesystem_rule-ziparchive
languages:
- go
mode: taint
pattern-sources:
- pattern: zip.OpenReader(...)
- pattern: tar.OpenReader(...)
pattern-sanitizers:
- patterns:
- pattern-either:
- pattern: |
$CLEAN := $PKG.Clean(...)
...
if !strings.HasPrefix($CLEAN, "...") {...}
- pattern: |
$CLEAN := $PKG.Clean(...)
...
if strings.HasPrefix($CLEAN, "...") {...}
- pattern: |
$CLEAN := $PKG.Clean(...)
...
if strings.HasPrefix($CLEAN, "...") == false {...}
- metavariable-regex:
metavariable: $PKG
regex: ^((file)?path)$
pattern-sinks:
- pattern: filepath.Join(...)
message: |
The application may be vulnerable to a path traversal if it extracts untrusted archive files.
This vulnerability is colloquially known as 'Zip Slip'. Archive files may contain folders
which,
when extracted, may write outside of the intended directory. This is exploited by including
path traversal characters such as `../../other/directory` to overwrite or place files in system
or application directories.
Extra care must be taken when extracting archive files as there are numerous concerns:
- Limit the size of the zip archive as it may contain "Zip Bombs", files that extract to
extremely
large sizes.
- If possible, generate unique filenames instead of using the archives file names, as it may be
possible for users to overwrite files if the filenames are the same.
- Validate file paths are written with a prefixed, known trusted directory.
- Only process regular files and not symbolic links, as some applications may attempt to
read/follow
the symbolic link, leading to arbitrary file read / write vulnerabilities.
Example of securely processing an archive file:
```
r, err := zip.OpenReader("trusted.zip")
if err != nil {
log.Fatal(err)
}
// Ensure archive contains only the expected number of files
const expectedFileCount = 10
if len(r.File) > expectedFileCount {
log.Fatalf("too many files in archive: %d\n", len(r.File))
}
// One approach is to sum up all files before attempting to process
// them.
const totalAllowedSize = 1024 * 1024 * 10 // 10MB
var totalSize uint64
for _, f := range r.File {
totalSize += f.UncompressedSize64
}
if totalSize > totalAllowedSize {
log.Fatalf("archive exceeds total allowed size: %d\n", totalSize)
}
// configure a max size per file allowed
const maxFileSize = 1024 * 1024 // 1 MB
// set restricted basePath
const basePath = "/var/restricted/"
// iterate over the files in the archive
for _, f := range r.File {
// Ensure uncompressed size does not exceed our allowed file size
if f.UncompressedSize64 > maxFileSize {
log.Printf("skipping file as it exceeds maxFileSize: %s\n", f.Name)
continue
}
// Ensure file is a regular file and not a symbolic link or has other mode type
// bits set
if !f.Mode().IsRegular() {
log.Printf("skipping non regular file: %s\n", f.Name)
continue
}
// if possible consider not using the name at all, but generating a random id instead.
// If the filename must be used, extract the base name and not folder path information
name := filepath.Base(f.Name)
// Join the file name to the basePath.
resolvedPath, err := filepath.Join(basePath, name)
if err != nil {
log.Fatal(err)
}
// Application must still verify the path is prefixed by the basePath
if !strings.HasPrefix(resolvedPath, basePath) {
log.Fatal("path does not start with basePath")
}
// process / work with file
}
```
If the application must process directory names as well, use the following code:
```
// Join the cleaned name to the basePath, note if 'name' starts with `../../` it
// will still allow for traversal, so you _must_ verify the path prefix below
resolvedPath := filepath.Join(basePath, filepath.Clean(name))
// Application must still verify the path is prefixed by the basePath
if !strings.HasPrefix(resolvedPath, basePath) {
log.Fatal("path does not start with basePath")
}
// process / work with file
```
metadata:
shortDescription: Improper limitation of a pathname to a restricted directory
('Path Traversal')
cwe: CWE-22
owasp:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
security-severity: Medium
category: security
severity: WARNING
- id: go_subproc_rule-subproc
languages:
- go
patterns:
- pattern-either:
- patterns:
- pattern: exec.CommandContext($CTX, $EXE, ...)
- pattern-not: exec.CommandContext($CTX, "...", ...)
- patterns:
- pattern: exec.Command($EXE, ...)
- pattern-not: exec.Command("...", ...)
- patterns:
- pattern: syscall.ForkExec($EXE, ...)
- pattern-not: syscall.ForkExec("...", ...)
- patterns:
- pattern: syscall.StartProcess($EXE, ...)
- pattern-not: syscall.StartProcess("...", ...)
message: |
OS command injection is a critical vulnerability that can lead to a full system
compromise as it may allow an adversary to pass in arbitrary commands or arguments
to be executed.
User input should never be used in constructing commands or command arguments
to functions which execute OS commands. This includes filenames supplied by
user uploads or downloads.
Ensure your application does not:
- Use user-supplied information in the process name to execute.
- Use user-supplied information in an OS command execution function which does
not escape shell meta-characters.
- Use user-supplied information in arguments to OS commands.
The application should have a hardcoded set of arguments that are to be passed
to OS commands. If filenames are being passed to these functions, it is
recommended that a hash of the filename be used instead, or some other unique
identifier. It is strongly recommended that a native library that implements
the same functionality be used instead of using OS system commands, due to the
risk of unknown attacks against third party commands.
If operating in Windows environments, when specifying the OS command, ensure
the application uses the full path
information, otherwise the OS may attempt to look up which process to execute
and could be vulnerable to untrusted search path vulnerabilities (CWE-426).
Example of safely executing an OS command:
```
userData := []byte("user data")
// create a temporary file in the application specific directory
f, err := ioutil.TempFile("/var/app/restricted", "temp-*.dat")
if err != nil {
log.Fatal(err)
}
if _, err := f.Write(userData); err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
// pass the full path to the binary and the name of the temporary file
// instead of any user supplied filename
out, err := exec.Command("/bin/cat", f.Name()).Output()
if err != nil {
log.Fatal(err)
}
```
For more information on OS command injection, see OWASP's guide:
https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html
metadata:
shortDescription: Improper neutralization of special elements used in an OS command
('OS Command Injection')
cwe: CWE-78
owasp:
- A1:2017-Injection
- A03:2021-Injection
security-severity: High
category: security
severity: WARNING
- id: go_blocklist_rule-blocklist-rc4
languages:
- go
patterns:
- pattern: |
import "crypto/rc4"
message: |
The RC4 stream-cipher has been cryptographically broken and is unsuitable
for use in production. It is recommended that ChaCha20 or Advanced Encryption
Standard (AES) be used instead. Consider using `XChaCha20Poly1305` or `AES-256-GCM`.
For older applications, `AES-256-GCM` is recommended, however it has many drawbacks:
- Slower than `XChaCha20Poly1305`
- Smaller nonce value size compared to `XChaCha20Poly1305`
- Catastrophic failure if nonce values are re-used
Example using
[XChaCha20Poly1305](https://pkg.go.dev/golang.org/x/crypto/chacha20poly1305#NewX):
```
key := make([]byte, chacha20poly1305.KeySize)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
log.Fatal(err)
}
// NewX is a variant that uses longer nonce values for better security
aead, err := chacha20poly1305.NewX(key)
if err != nil {
log.Fatal(err)
}
var encrypted = []byte{}
var nonce = []byte{}
// Encryption routine
{
msg := []byte("Some secret message")