-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic_rules.go
More file actions
1060 lines (1043 loc) · 42.6 KB
/
static_rules.go
File metadata and controls
1060 lines (1043 loc) · 42.6 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
package sight
import (
"fmt"
"regexp"
"strings"
)
// StaticRule defines a pattern-based static analysis rule that can catch common
// issues without invoking an LLM. Rules are matched against diff content or full
// file content before the LLM review pass, saving tokens on obvious issues.
type StaticRule struct {
ID string // unique identifier, e.g. "SEC-GO-001"
Name string // short human-readable name
Description string // detailed explanation
Language string // "go", "python", "typescript", "javascript", "any"
Pattern *regexp.Regexp // primary detection pattern
Antipattern *regexp.Regexp // if this also matches the same line, suppress the finding
Severity string // "critical", "high", "medium", "low"
Category string // "security", "correctness", "performance"
CWE string // e.g., "CWE-89"
Fix string // suggested fix description
}
// StaticAnalyzer runs pattern-based rules against code before the LLM review.
type StaticAnalyzer struct {
Rules []StaticRule
}
// NewStaticAnalyzer creates a StaticAnalyzer preloaded with the default rule set.
func NewStaticAnalyzer() *StaticAnalyzer {
return &StaticAnalyzer{
Rules: defaultRules(),
}
}
// Analyze runs all matching rules against a unified diff string and returns findings.
// Only added lines (starting with "+") are checked. The language parameter filters
// rules to those matching the language or "any".
func (sa *StaticAnalyzer) Analyze(diff string, language string) []Finding {
var findings []Finding
// Parse diff to extract added lines with file and line info
type diffLine struct {
file string
lineNum int
text string
}
var lines []diffLine
var currentFile string
var lineNum int
for _, raw := range strings.Split(diff, "\n") {
if strings.HasPrefix(raw, "+++ b/") {
currentFile = strings.TrimPrefix(raw, "+++ b/")
lineNum = 0
continue
}
if strings.HasPrefix(raw, "+++ ") {
currentFile = strings.TrimPrefix(raw, "+++ ")
lineNum = 0
continue
}
if strings.HasPrefix(raw, "@@ ") {
// Parse hunk header for line number: @@ -a,b +c,d @@
lineNum = parseHunkNewStart(raw) - 1
continue
}
if strings.HasPrefix(raw, "+") && !strings.HasPrefix(raw, "+++") {
lineNum++
lines = append(lines, diffLine{
file: currentFile,
lineNum: lineNum,
text: raw[1:], // strip leading "+"
})
} else if !strings.HasPrefix(raw, "-") {
lineNum++
}
}
lang := strings.ToLower(language)
for _, rule := range sa.Rules {
if rule.Language != "any" && rule.Language != lang {
continue
}
for _, dl := range lines {
if rule.Pattern.MatchString(dl.text) {
// Check antipattern — if it matches, this is a false positive
if rule.Antipattern != nil && rule.Antipattern.MatchString(dl.text) {
continue
}
findings = append(findings, Finding{
Concern: "static:" + rule.Category,
Severity: ParseSeverity(rule.Severity),
File: dl.file,
Line: dl.lineNum,
Message: fmt.Sprintf("[%s] %s: %s", rule.ID, rule.Name, rule.Description),
Fix: rule.Fix,
CWE: rule.CWE,
})
}
}
}
return findings
}
// AnalyzeFile runs all matching rules against a full file's content.
// Each line is checked independently. The language parameter filters rules.
func (sa *StaticAnalyzer) AnalyzeFile(content string, language string) []Finding {
var findings []Finding
lang := strings.ToLower(language)
lines := strings.Split(content, "\n")
for _, rule := range sa.Rules {
if rule.Language != "any" && rule.Language != lang {
continue
}
for i, line := range lines {
if rule.Pattern.MatchString(line) {
if rule.Antipattern != nil && rule.Antipattern.MatchString(line) {
continue
}
findings = append(findings, Finding{
Concern: "static:" + rule.Category,
Severity: ParseSeverity(rule.Severity),
File: "",
Line: i + 1,
Message: fmt.Sprintf("[%s] %s: %s", rule.ID, rule.Name, rule.Description),
Fix: rule.Fix,
CWE: rule.CWE,
})
}
}
}
return findings
}
// AnalyzeFileWithPath is like AnalyzeFile but sets the File field on findings.
func (sa *StaticAnalyzer) AnalyzeFileWithPath(content string, language string, path string) []Finding {
findings := sa.AnalyzeFile(content, language)
for i := range findings {
findings[i].File = path
}
return findings
}
// DetectLanguage guesses the language from a file path extension.
func DetectLanguage(path string) string {
lower := strings.ToLower(path)
switch {
case strings.HasSuffix(lower, ".go"):
return "go"
case strings.HasSuffix(lower, ".py"):
return "python"
case strings.HasSuffix(lower, ".ts"):
return "typescript"
case strings.HasSuffix(lower, ".tsx"):
return "typescript"
case strings.HasSuffix(lower, ".js"):
return "javascript"
case strings.HasSuffix(lower, ".jsx"):
return "javascript"
case strings.HasSuffix(lower, ".rs"):
return "rust"
case strings.HasSuffix(lower, ".java"):
return "java"
case strings.HasSuffix(lower, ".c") || strings.HasSuffix(lower, ".h"):
return "c"
case strings.HasSuffix(lower, ".cpp") || strings.HasSuffix(lower, ".hpp") || strings.HasSuffix(lower, ".cc") || strings.HasSuffix(lower, ".cxx"):
return "cpp"
case strings.HasSuffix(lower, ".rb"):
return "ruby"
case strings.HasSuffix(lower, ".sql"):
return "sql"
default:
return "any"
}
}
// parseHunkNewStart extracts the new-file start line from a hunk header.
// Format: @@ -old,count +new,count @@
func parseHunkNewStart(header string) int {
// Find "+N" after the first space
idx := strings.Index(header, "+")
if idx < 0 {
return 1
}
rest := header[idx+1:]
var n int
for _, ch := range rest {
if ch >= '0' && ch <= '9' {
n = n*10 + int(ch-'0')
} else {
break
}
}
if n == 0 {
return 1
}
return n
}
// defaultRules returns the built-in set of 30+ static analysis rules.
func defaultRules() []StaticRule {
return []StaticRule{
// =====================================================================
// SECURITY - Go
// =====================================================================
{
ID: "SEC-GO-001",
Name: "SQL Injection",
Description: "String formatting used in SQL query construction; use parameterized queries instead",
Language: "go",
Pattern: regexp.MustCompile(`fmt\.Sprintf\s*\(\s*"[^"]*(?:SELECT|INSERT|UPDATE|DELETE|DROP)[^"]*%[sv]`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-89",
Fix: "Use parameterized queries with ? or $1 placeholders instead of fmt.Sprintf for SQL",
},
{
ID: "SEC-GO-002",
Name: "Command Injection",
Description: "Potentially unsanitized input passed to exec.Command",
Language: "go",
Pattern: regexp.MustCompile(`exec\.Command\s*\([^"` + "`" + `][^,)]*\)`),
Antipattern: regexp.MustCompile(`exec\.Command\s*\(\s*"[^"]+"\s*\)`),
Severity: "critical",
Category: "security",
CWE: "CWE-78",
Fix: "Validate and sanitize all input passed to exec.Command; use an allowlist of permitted commands",
},
{
ID: "SEC-GO-003",
Name: "Path Traversal",
Description: "User-controlled path used in file operations without filepath.Clean or validation",
Language: "go",
Pattern: regexp.MustCompile(`(?:os\.(?:Open|ReadFile|Create|WriteFile)|filepath\.Join)\s*\(.*(?:req\.|r\.|input|param|query|user)`),
Antipattern: regexp.MustCompile(`filepath\.Clean`),
Severity: "high",
Category: "security",
CWE: "CWE-22",
Fix: "Use filepath.Clean() and validate the resolved path is within the expected directory",
},
{
ID: "SEC-GO-004",
Name: "Hardcoded Secret",
Description: "Hardcoded password or secret string detected",
Language: "go",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*(?::?=|=)\s*"[^"]{4,}`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secrets manager instead of hardcoded credentials",
},
{
ID: "SEC-GO-005",
Name: "Insecure TLS",
Description: "TLS certificate verification is disabled",
Language: "go",
Pattern: regexp.MustCompile(`InsecureSkipVerify\s*:\s*true`),
Antipattern: nil,
Severity: "high",
Category: "security",
CWE: "CWE-295",
Fix: "Remove InsecureSkipVerify: true; configure proper TLS certificate validation",
},
{
ID: "SEC-GO-006",
Name: "Weak Crypto (MD5)",
Description: "MD5 is cryptographically broken and should not be used for security purposes",
Language: "go",
Pattern: regexp.MustCompile(`md5\.(?:New|Sum)`),
Antipattern: regexp.MustCompile(`(?i)(?:checksum|fingerprint|cache|etag|non.?security)`),
Severity: "medium",
Category: "security",
CWE: "CWE-328",
Fix: "Use crypto/sha256 or crypto/sha512 instead of MD5 for security-sensitive operations",
},
{
ID: "SEC-GO-007",
Name: "Weak Crypto (SHA1)",
Description: "SHA-1 is deprecated for security use; collisions are practical",
Language: "go",
Pattern: regexp.MustCompile(`sha1\.(?:New|Sum)`),
Antipattern: regexp.MustCompile(`(?i)(?:git|fingerprint|cache|etag|non.?security)`),
Severity: "medium",
Category: "security",
CWE: "CWE-328",
Fix: "Use crypto/sha256 or crypto/sha512 instead of SHA-1 for security-sensitive operations",
},
{
ID: "SEC-GO-008",
Name: "Unvalidated Redirect",
Description: "HTTP redirect using user-controlled input without validation",
Language: "go",
Pattern: regexp.MustCompile(`http\.Redirect\s*\(.*(?:r\.(?:URL|Form|Query)|req\.|param|input)`),
Antipattern: nil,
Severity: "medium",
Category: "security",
CWE: "CWE-601",
Fix: "Validate redirect URLs against an allowlist of permitted destinations",
},
{
ID: "SEC-GO-009",
Name: "Sensitive Data in Log",
Description: "Potentially logging sensitive data (passwords, tokens, secrets)",
Language: "go",
Pattern: regexp.MustCompile(`(?:log\.|slog\.|logger\.)(?:Print|Info|Debug|Warn|Error|Fatal).*(?i)(?:password|token|secret|key|credential)`),
Antipattern: regexp.MustCompile(`(?i)(?:redact|mask|\*\*\*|<hidden>)`),
Severity: "medium",
Category: "security",
CWE: "CWE-532",
Fix: "Redact sensitive values before logging; never log passwords, tokens, or API keys",
},
{
ID: "SEC-GO-010",
Name: "Defer in Loop",
Description: "defer inside a loop can accumulate resources until the function returns",
Language: "go",
Pattern: regexp.MustCompile(`^\s*defer\s+`),
Antipattern: nil,
Severity: "medium",
Category: "correctness",
CWE: "",
Fix: "Move the deferred call into a helper function or handle resource cleanup explicitly in the loop",
},
// =====================================================================
// SECURITY - Python
// =====================================================================
{
ID: "SEC-PY-001",
Name: "SQL Injection (f-string)",
Description: "f-string used in SQL query construction; use parameterized queries",
Language: "python",
Pattern: regexp.MustCompile(`f["'](?:[^"']*(?:SELECT|INSERT|UPDATE|DELETE|DROP)[^"']*)\{`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-89",
Fix: "Use parameterized queries with %s or ? placeholders passed as a tuple",
},
{
ID: "SEC-PY-002",
Name: "eval() Usage",
Description: "eval() executes arbitrary code and is a common injection vector",
Language: "python",
Pattern: regexp.MustCompile(`\beval\s*\(`),
Antipattern: regexp.MustCompile(`(?i)(?:#.*safe|#.*trusted|ast\.literal_eval)`),
Severity: "critical",
Category: "security",
CWE: "CWE-95",
Fix: "Use ast.literal_eval() for data parsing or find a safer alternative to eval()",
},
{
ID: "SEC-PY-003",
Name: "exec() Usage",
Description: "exec() executes arbitrary code strings and is dangerous with user input",
Language: "python",
Pattern: regexp.MustCompile(`\bexec\s*\(`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-95",
Fix: "Avoid exec(); use structured approaches like importlib or predefined function dispatch",
},
{
ID: "SEC-PY-004",
Name: "Pickle Deserialization",
Description: "pickle.loads() can execute arbitrary code during deserialization",
Language: "python",
Pattern: regexp.MustCompile(`pickle\.loads?\s*\(`),
Antipattern: nil,
Severity: "high",
Category: "security",
CWE: "CWE-502",
Fix: "Use JSON or another safe serialization format; if pickle is required, only load from trusted sources",
},
{
ID: "SEC-PY-005",
Name: "Subprocess Shell Injection",
Description: "subprocess with shell=True is vulnerable to shell injection",
Language: "python",
Pattern: regexp.MustCompile(`subprocess\.(?:call|run|Popen|check_output|check_call)\s*\(.*shell\s*=\s*True`),
Antipattern: nil,
Severity: "high",
Category: "security",
CWE: "CWE-78",
Fix: "Use shell=False (default) and pass command as a list instead of a string",
},
{
ID: "SEC-PY-006",
Name: "Assert in Production",
Description: "assert statements are stripped with -O flag; do not use for validation",
Language: "python",
Pattern: regexp.MustCompile(`^\s*assert\s+`),
Antipattern: regexp.MustCompile(`(?i)(?:test_|_test\.py|conftest|pytest)`),
Severity: "low",
Category: "correctness",
CWE: "CWE-617",
Fix: "Replace assert with explicit validation that raises an appropriate exception",
},
{
ID: "SEC-PY-007",
Name: "Hardcoded Secret (Python)",
Description: "Hardcoded password or secret string detected",
Language: "python",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*=\s*["'][^"']{4,}["']`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|fake)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secrets manager instead of hardcoded credentials",
},
{
ID: "SEC-PY-008",
Name: "YAML Unsafe Load",
Description: "yaml.load() without SafeLoader can execute arbitrary Python objects",
Language: "python",
Pattern: regexp.MustCompile(`yaml\.load\s*\(`),
Antipattern: regexp.MustCompile(`Loader\s*=\s*(?:yaml\.)?SafeLoader`),
Severity: "high",
Category: "security",
CWE: "CWE-502",
Fix: "Use yaml.safe_load() or pass Loader=yaml.SafeLoader explicitly",
},
// =====================================================================
// SECURITY - TypeScript/JavaScript
// =====================================================================
{
ID: "SEC-TS-001",
Name: "innerHTML Assignment",
Description: "Direct innerHTML assignment enables XSS attacks",
Language: "typescript",
Pattern: regexp.MustCompile(`\.innerHTML\s*=`),
Antipattern: regexp.MustCompile(`(?i)(?:sanitize|DOMPurify|escape)`),
Severity: "high",
Category: "security",
CWE: "CWE-79",
Fix: "Use textContent for plain text or a sanitization library (DOMPurify) for HTML",
},
{
ID: "SEC-JS-001",
Name: "innerHTML Assignment",
Description: "Direct innerHTML assignment enables XSS attacks",
Language: "javascript",
Pattern: regexp.MustCompile(`\.innerHTML\s*=`),
Antipattern: regexp.MustCompile(`(?i)(?:sanitize|DOMPurify|escape)`),
Severity: "high",
Category: "security",
CWE: "CWE-79",
Fix: "Use textContent for plain text or a sanitization library (DOMPurify) for HTML",
},
{
ID: "SEC-TS-002",
Name: "eval() Usage",
Description: "eval() executes arbitrary code and is a common injection vector",
Language: "typescript",
Pattern: regexp.MustCompile(`\beval\s*\(`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-95",
Fix: "Use JSON.parse() for data or Function constructor with extreme caution",
},
{
ID: "SEC-JS-002",
Name: "eval() Usage",
Description: "eval() executes arbitrary code and is a common injection vector",
Language: "javascript",
Pattern: regexp.MustCompile(`\beval\s*\(`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-95",
Fix: "Use JSON.parse() for data or Function constructor with extreme caution",
},
{
ID: "SEC-TS-003",
Name: "Prototype Pollution",
Description: "__proto__ access can lead to prototype pollution attacks",
Language: "typescript",
Pattern: regexp.MustCompile(`__proto__`),
Antipattern: regexp.MustCompile(`(?i)(?:hasOwnProperty|Object\.create\(null\))`),
Severity: "high",
Category: "security",
CWE: "CWE-1321",
Fix: "Use Object.create(null) for lookup objects or validate keys against __proto__, constructor, prototype",
},
{
ID: "SEC-JS-003",
Name: "Prototype Pollution",
Description: "__proto__ access can lead to prototype pollution attacks",
Language: "javascript",
Pattern: regexp.MustCompile(`__proto__`),
Antipattern: regexp.MustCompile(`(?i)(?:hasOwnProperty|Object\.create\(null\))`),
Severity: "high",
Category: "security",
CWE: "CWE-1321",
Fix: "Use Object.create(null) for lookup objects or validate keys against __proto__, constructor, prototype",
},
{
ID: "SEC-TS-004",
Name: "Regex DoS",
Description: "Complex regex with nested quantifiers may be vulnerable to ReDoS",
Language: "typescript",
Pattern: regexp.MustCompile(`(?:new RegExp|/)\s*.*(?:\+\+|\*\*|\{\d+,\}.*\{\d+,\}|(?:\.\*){2,}|\([^)]*\+\)[^)]*\+)`),
Antipattern: nil,
Severity: "medium",
Category: "security",
CWE: "CWE-1333",
Fix: "Simplify regex; add bounds to quantifiers; consider using re2 or a timeout",
},
{
ID: "SEC-JS-004",
Name: "Regex DoS",
Description: "Complex regex with nested quantifiers may be vulnerable to ReDoS",
Language: "javascript",
Pattern: regexp.MustCompile(`(?:new RegExp|/)\s*.*(?:\+\+|\*\*|\{\d+,\}.*\{\d+,\}|(?:\.\*){2,}|\([^)]*\+\)[^)]*\+)`),
Antipattern: nil,
Severity: "medium",
Category: "security",
CWE: "CWE-1333",
Fix: "Simplify regex; add bounds to quantifiers; consider using re2 or a timeout",
},
{
ID: "SEC-TS-005",
Name: "Hardcoded Secret (TS)",
Description: "Hardcoded password or secret string detected",
Language: "typescript",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*[=:]\s*["'][^"']{4,}["']`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|process\.env|import)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secrets manager instead of hardcoded credentials",
},
{
ID: "SEC-JS-005",
Name: "Hardcoded Secret (JS)",
Description: "Hardcoded password or secret string detected",
Language: "javascript",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*[=:]\s*["'][^"']{4,}["']`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|process\.env|import)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secrets manager instead of hardcoded credentials",
},
// =====================================================================
// CORRECTNESS - Go
// =====================================================================
{
ID: "COR-GO-001",
Name: "Unchecked Error",
Description: "Function return value that likely includes an error is discarded",
Language: "go",
Pattern: regexp.MustCompile(`^\s*[a-zA-Z_][a-zA-Z0-9_.]*\s*\(.*\)\s*$`),
Antipattern: regexp.MustCompile(`(?:^//|^\s*//|defer|go\s+|fmt\.Print|log\.|println|print\()`),
Severity: "medium",
Category: "correctness",
CWE: "CWE-252",
Fix: "Capture and handle the returned error: if err != nil { return err }",
},
{
ID: "COR-GO-002",
Name: "Goroutine Leak Risk",
Description: "Goroutine launched without visible context cancellation or done channel",
Language: "go",
Pattern: regexp.MustCompile(`\bgo\s+func\s*\(`),
Antipattern: regexp.MustCompile(`(?:ctx|context|done|cancel|Done\(\)|quit|stop|timer|ticker)`),
Severity: "medium",
Category: "correctness",
CWE: "",
Fix: "Pass a context.Context or done channel to goroutines to enable graceful shutdown",
},
{
ID: "COR-GO-003",
Name: "Race Condition Risk",
Description: "Shared variable access in goroutine without synchronization",
Language: "go",
Pattern: regexp.MustCompile(`go\s+func\s*\([^)]*\)\s*\{[^}]*(?:[a-z]+\s*(?:\+\+|--|(?:\+|-|\*|/)=))`),
Antipattern: regexp.MustCompile(`(?:mutex|Mutex|sync\.|atomic\.|Lock\(\)|chan\s)`),
Severity: "high",
Category: "correctness",
CWE: "CWE-362",
Fix: "Use sync.Mutex, sync/atomic, or channels to synchronize shared state access",
},
{
ID: "COR-GO-004",
Name: "nil Map Write",
Description: "Writing to a potentially nil map causes a runtime panic",
Language: "go",
Pattern: regexp.MustCompile(`var\s+\w+\s+map\[`),
Antipattern: regexp.MustCompile(`=\s*(?:make|map\[)`),
Severity: "high",
Category: "correctness",
CWE: "",
Fix: "Initialize the map with make() before writing to it",
},
// =====================================================================
// PERFORMANCE
// =====================================================================
{
ID: "PERF-GO-001",
Name: "String Concat in Loop",
Description: "String concatenation with += in a loop causes quadratic allocation",
Language: "go",
Pattern: regexp.MustCompile(`\w+\s*\+=\s*(?:"|\w+)`),
Antipattern: regexp.MustCompile(`(?:int|float|byte|rune|uint|count|total|sum|num|idx|index|offset|i\s*\+)`),
Severity: "low",
Category: "performance",
CWE: "",
Fix: "Use strings.Builder for string concatenation in loops",
},
{
ID: "PERF-GO-002",
Name: "Unbounded Allocation",
Description: "Slice allocation with user-controlled size without bounds check",
Language: "go",
Pattern: regexp.MustCompile(`make\s*\(\s*\[\]\w+\s*,\s*(?:req\.|r\.|input|param|query|size|length|count|n\b)`),
Antipattern: regexp.MustCompile(`(?:maxSize|maxLen|cap|min\(|max\(|limit|<=|>=|<\s*\d|>\s*\d)`),
Severity: "medium",
Category: "performance",
CWE: "CWE-789",
Fix: "Validate and cap allocation sizes to prevent denial of service via memory exhaustion",
},
{
ID: "PERF-GO-003",
Name: "N+1 Query Pattern",
Description: "Database query inside a loop suggests N+1 query problem",
Language: "go",
Pattern: regexp.MustCompile(`(?:\.Query|\.Exec|\.Get|\.Find|\.First|\.Select|\.Where)\s*\(`),
Antipattern: regexp.MustCompile(`(?:batch|bulk|IN\s*\(|ids|Preload|Join)`),
Severity: "medium",
Category: "performance",
CWE: "",
Fix: "Batch database queries outside the loop; use IN clauses or JOINs",
},
{
ID: "PERF-PY-001",
Name: "N+1 Query Pattern (Python)",
Description: "Database query inside a loop suggests N+1 query problem",
Language: "python",
Pattern: regexp.MustCompile(`(?:\.execute|\.query|\.filter|\.get|session\.)\s*\(`),
Antipattern: regexp.MustCompile(`(?:bulk|batch|in_|prefetch|select_related|join)`),
Severity: "medium",
Category: "performance",
CWE: "",
Fix: "Use select_related/prefetch_related (Django) or eager loading (SQLAlchemy) to batch queries",
},
{
ID: "PERF-ANY-001",
Name: "Synchronous Sleep",
Description: "Hardcoded sleep/delay found; consider exponential backoff or event-driven approach",
Language: "any",
Pattern: regexp.MustCompile(`(?:time\.Sleep|sleep\(|setTimeout.*\d{4,}|Thread\.sleep)`),
Antipattern: regexp.MustCompile(`(?i)(?:test|spec|mock|backoff|retry)`),
Severity: "low",
Category: "performance",
CWE: "",
Fix: "Use exponential backoff for retries or event-driven signaling instead of fixed sleeps",
},
// =====================================================================
// SECURITY - Any Language
// =====================================================================
{
ID: "SEC-ANY-001",
Name: "TODO Security",
Description: "TODO/FIXME/HACK comment related to security found in code",
Language: "any",
Pattern: regexp.MustCompile(`(?i)(?://|#|/\*)\s*(?:TODO|FIXME|HACK|XXX).*(?:security|auth|crypt|password|token|vuln|inject|xss|csrf)`),
Antipattern: nil,
Severity: "medium",
Category: "security",
CWE: "",
Fix: "Address security-related TODOs before shipping; they indicate known unresolved issues",
},
{
ID: "SEC-ANY-002",
Name: "Private Key in Source",
Description: "Private key material appears to be embedded in source code",
Language: "any",
Pattern: regexp.MustCompile(`-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|sample|mock|fixture)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Remove private keys from source; load them from secure storage or environment at runtime",
},
{
ID: "SEC-ANY-003",
Name: "HTTP in Production",
Description: "Insecure HTTP URL used where HTTPS should be expected",
Language: "any",
Pattern: regexp.MustCompile(`http://[a-zA-Z][a-zA-Z0-9._-]*`),
Antipattern: regexp.MustCompile(`(?i)(?:http://localhost|http://127\.0\.0\.1|http://0\.0\.0\.0|http://\[?::1|http://example\.com|test|spec|mock|doc|xmlns|http://www\.w3\.org)`),
Severity: "low",
Category: "security",
CWE: "CWE-319",
Fix: "Use HTTPS for all production URLs to prevent man-in-the-middle attacks",
},
// =====================================================================
// SECURITY - Rust
// =====================================================================
{
ID: "SEC-RS-001",
Name: "Unsafe Block",
Description: "unsafe block bypasses Rust's memory safety guarantees; ensure the invariant is upheld",
Language: "rust",
Pattern: regexp.MustCompile(`\bunsafe\s*\{`),
Antipattern: nil,
Severity: "high",
Category: "security",
CWE: "CWE-242",
Fix: "Avoid unsafe blocks; use safe abstractions. If required, document the safety invariant in a comment",
},
{
ID: "SEC-RS-002",
Name: "unwrap() in Production",
Description: "unwrap() will panic at runtime if the value is None/Err; handle errors gracefully instead",
Language: "rust",
Pattern: regexp.MustCompile(`\.unwrap\(\)`),
Antipattern: regexp.MustCompile(`(?i)(?:test|#\[test|#\[cfg\(test|expect\()`),
Severity: "medium",
Category: "correctness",
CWE: "CWE-252",
Fix: "Use match, if let, or the ? operator to handle Option/Result properly",
},
{
ID: "SEC-RS-003",
Name: "Hardcoded Secret (Rust)",
Description: "Hardcoded password or secret string detected",
Language: "rust",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*(?:=>|:)\s*"[^"]{4,}`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|fake)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secrets manager instead of hardcoded credentials",
},
{
ID: "SEC-RS-004",
Name: "SQL Injection (Rust)",
Description: "format! macro used in SQL query construction; use parameterized queries",
Language: "rust",
Pattern: regexp.MustCompile(`format!\s*\(\s*"[^"]*(?:SELECT|INSERT|UPDATE|DELETE|DROP)[^"]*\{`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-89",
Fix: "Use parameterized queries with $1 placeholders (e.g., sqlx or diesel) instead of format!",
},
{
ID: "SEC-RS-005",
Name: "Command Injection (Rust)",
Description: "Command::new with user-controlled input may allow command injection",
Language: "rust",
Pattern: regexp.MustCompile(`Command::new\s*\([^"'][^)]*\)`),
Antipattern: regexp.MustCompile(`Command::new\s*\(\s*"[^"]+"\s*\)`),
Severity: "critical",
Category: "security",
CWE: "CWE-78",
Fix: "Validate and sanitize all input passed to Command::new; use an allowlist of permitted commands",
},
// =====================================================================
// SECURITY - Java
// =====================================================================
{
ID: "SEC-JV-001",
Name: "SQL Injection (Java)",
Description: "String concatenation used in SQL statement execution; use PreparedStatement instead",
Language: "java",
Pattern: regexp.MustCompile(`(?:(?:execute|executeQuery|executeUpdate)\s*\(.*\+)|(?:(?:Statement|createStatement).*\+)`),
Antipattern: regexp.MustCompile(`PreparedStatement|setParameter|bindValue`),
Severity: "critical",
Category: "security",
CWE: "CWE-89",
Fix: "Use PreparedStatement with parameter placeholders (?) instead of string concatenation",
},
{
ID: "SEC-JV-002",
Name: "Insecure Deserialization (Java)",
Description: "ObjectInputStream.readObject() can execute arbitrary code during deserialization",
Language: "java",
Pattern: regexp.MustCompile(`ObjectInputStream.*\.readObject\s*\(`),
Antipattern: regexp.MustCompile(`(?i)(?:ValidatingObjectInputStream|ObjectInputFilter|whiteList|allowList)`),
Severity: "critical",
Category: "security",
CWE: "CWE-502",
Fix: "Use ValidatingObjectInputStream or an ObjectInputFilter with a strict allowlist",
},
{
ID: "SEC-JV-003",
Name: "SSRF (Java)",
Description: "new URL() with user-controlled input may lead to Server-Side Request Forgery",
Language: "java",
Pattern: regexp.MustCompile(`new\s+URL\s*\(.*(?:req\.|request\.|param|input|query|user)`),
Antipattern: regexp.MustCompile(`(?i)(?:allowList|whitelist|validate.*url|UriUtils)`),
Severity: "high",
Category: "security",
CWE: "CWE-918",
Fix: "Validate URLs against an allowlist of permitted domains and schemes",
},
{
ID: "SEC-JV-004",
Name: "Hardcoded Secret (Java)",
Description: "Hardcoded password or secret string detected",
Language: "java",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*=\s*"[^"]{4,}"`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|fake|System\.getenv)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables, a secrets manager, or a vault instead of hardcoded credentials",
},
{
ID: "SEC-JV-005",
Name: "Path Traversal (Java)",
Description: "new File() with user-controlled input may allow path traversal attacks",
Language: "java",
Pattern: regexp.MustCompile(`new\s+File\s*\(.*(?:req\.|request\.|param|input|query|user|\+)`),
Antipattern: regexp.MustCompile(`(?i)(?:canonicalPath|normalize|sanitizePath|getCanonicalPath)`),
Severity: "high",
Category: "security",
CWE: "CWE-22",
Fix: "Validate and normalize paths; ensure the resolved path is within the expected directory",
},
// =====================================================================
// SECURITY - C/C++
// =====================================================================
{
ID: "SEC-C-001",
Name: "Buffer Overflow",
Description: "Unsafe string function (strcpy, strcat, sprintf, gets) used without bounds checking",
Language: "c",
Pattern: regexp.MustCompile(`\b(?:strcpy|strcat|sprintf|gets)\s*\(`),
Antipattern: regexp.MustCompile(`(?:strncpy|strncat|snprintf|fgets|safe)`),
Severity: "critical",
Category: "security",
CWE: "CWE-120",
Fix: "Use bounded variants: strncpy, strncat, snprintf, or fgets instead",
},
{
ID: "SEC-C-002",
Name: "Format String Vulnerability",
Description: "printf-family function called with non-literal format string; may enable format string attacks",
Language: "c",
Pattern: regexp.MustCompile(`\b(?:printf|fprintf|sprintf|snprintf)\s*\(\s*[a-zA-Z_][a-zA-Z0-9_]*\s*[,)]`),
Antipattern: nil,
Severity: "high",
Category: "security",
CWE: "CWE-134",
Fix: "Use a literal format string: printf(\"%s\", var) instead of printf(var)",
},
{
ID: "SEC-C-003",
Name: "Use-After-Free Risk",
Description: "Pointer used after free() call without being set to NULL",
Language: "c",
Pattern: regexp.MustCompile(`\bfree\s*\(\s*\w+\s*\)`),
Antipattern: regexp.MustCompile(`(?:(?:\w+)\s*=\s*NULL|=\s*0\b)`),
Severity: "high",
Category: "security",
CWE: "CWE-416",
Fix: "Set pointer to NULL after free() to prevent use-after-free and double-free",
},
{
ID: "SEC-C-004",
Name: "Hardcoded Secret (C/C++)",
Description: "Hardcoded password or secret string detected",
Language: "c",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*=\s*"[^"]{4,}"`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|fake)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secure configuration mechanism instead of hardcoded secrets",
},
{
ID: "SEC-C-005",
Name: "Command Injection (C)",
Description: "system() or popen() with user-controlled input may allow command injection",
Language: "c",
Pattern: regexp.MustCompile(`\b(?:system|popen)\s*\(\s*[a-zA-Z_]`),
Antipattern: regexp.MustCompile(`\b(?:system|popen)\s*\(\s*"[^"]*"\s*\)`),
Severity: "critical",
Category: "security",
CWE: "CWE-78",
Fix: "Use execve() with an explicit argument vector instead of system()/popen() with shell interpretation",
},
// Duplicate C/C++ rules for cpp language tag
{
ID: "SEC-CPP-001",
Name: "Buffer Overflow (C++)",
Description: "Unsafe string function (strcpy, strcat, sprintf, gets) used without bounds checking",
Language: "cpp",
Pattern: regexp.MustCompile(`\b(?:strcpy|strcat|sprintf|gets)\s*\(`),
Antipattern: regexp.MustCompile(`(?:strncpy|strncat|snprintf|fgets|std::string|safe)`),
Severity: "critical",
Category: "security",
CWE: "CWE-120",
Fix: "Use std::string or bounded variants: strncpy, strncat, snprintf, or fgets instead",
},
{
ID: "SEC-CPP-002",
Name: "Format String Vulnerability (C++)",
Description: "printf-family function called with non-literal format string",
Language: "cpp",
Pattern: regexp.MustCompile(`\b(?:printf|fprintf|sprintf|snprintf)\s*\(\s*[a-zA-Z_][a-zA-Z0-9_]*\s*[,)]`),
Antipattern: nil,
Severity: "high",
Category: "security",
CWE: "CWE-134",
Fix: "Use a literal format string or std::cout / fmt::format instead",
},
{
ID: "SEC-CPP-003",
Name: "Use-After-Free Risk (C++)",
Description: "Pointer used after free()/delete without being set to nullptr",
Language: "cpp",
Pattern: regexp.MustCompile(`\b(?:free\s*\(\s*\w+\s*\)|delete\s+\w+)`),
Antipattern: regexp.MustCompile(`(?:(?:\w+)\s*=\s*(?:NULL|nullptr)|=\s*0\b|unique_ptr|shared_ptr)`),
Severity: "high",
Category: "security",
CWE: "CWE-416",
Fix: "Use smart pointers (unique_ptr, shared_ptr); set raw pointers to nullptr after delete",
},
{
ID: "SEC-CPP-004",
Name: "Hardcoded Secret (C++)",
Description: "Hardcoded password or secret string detected",
Language: "cpp",
Pattern: regexp.MustCompile(`(?i)(?:password|secret|api_?key|token|private_?key)\s*=\s*"[^"]{4,}"`),
Antipattern: regexp.MustCompile(`(?i)(?:test|example|placeholder|TODO|CHANGE|xxx|dummy|fake)`),
Severity: "critical",
Category: "security",
CWE: "CWE-798",
Fix: "Use environment variables or a secure configuration mechanism instead of hardcoded secrets",
},
{
ID: "SEC-CPP-005",
Name: "Command Injection (C++)",
Description: "system() or popen() with user-controlled input may allow command injection",
Language: "cpp",
Pattern: regexp.MustCompile(`\b(?:system|popen)\s*\(\s*[a-zA-Z_]`),
Antipattern: regexp.MustCompile(`\b(?:system|popen)\s*\(\s*"[^"]*"\s*\)`),
Severity: "critical",
Category: "security",
CWE: "CWE-78",
Fix: "Use execve() or boost::process with an explicit argument vector instead of system()/popen()",
},
// =====================================================================
// SECURITY - Ruby
// =====================================================================
{
ID: "SEC-RB-001",
Name: "SQL Injection (Ruby)",
Description: "String interpolation in SQL query; use parameterized queries instead",
Language: "ruby",
Pattern: regexp.MustCompile(`(?:(?:\.where|\.find_by_sql|\.execute|\.query)\s*\(?\s*["'].*#\{)|(?:%[qQwWiI]?\{.*(?:SELECT|INSERT|UPDATE|DELETE).*#\{)`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-89",
Fix: "Use parameterized queries: Model.where('id = ?', id) or ActiveRecord::sanitize_sql",
},
{
ID: "SEC-RB-002",
Name: "Command Injection (Ruby)",
Description: "system(), exec(), or backtick command with user-controlled input",
Language: "ruby",
Pattern: regexp.MustCompile(`\b(?:system|exec|` + "`" + `)\s*[\(]?.*#\{`),
Antipattern: nil,
Severity: "critical",
Category: "security",
CWE: "CWE-78",
Fix: "Use Open3.capture2 or Kernel#system with separate arguments to avoid shell injection",
},
{
ID: "SEC-RB-003",
Name: "Mass Assignment",
Description: "permit! or unfiltered params usage allows arbitrary attribute assignment",
Language: "ruby",
Pattern: regexp.MustCompile(`\.permit!|params\s*\[|params\.require\(.*\)\.permit\s*[^(\w]`),
Antipattern: regexp.MustCompile(`\.permit\s*\(\s*[:\w]`),
Severity: "high",
Category: "security",
CWE: "CWE-915",
Fix: "Use strong parameters: params.require(:model).permit(:field1, :field2) with explicit allowlist",
},
{
ID: "SEC-RB-004",
Name: "Hardcoded Secret (Ruby)",
Description: "Hardcoded password or secret string detected",
Language: "ruby",