-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdotnet.yml
More file actions
1026 lines (980 loc) · 40.8 KB
/
dotnet.yml
File metadata and controls
1026 lines (980 loc) · 40.8 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
rules:
# === Critical Severity Rules ===
# SQL injection - using taint mode for accurate detection
- id: dotnet-sql-injection
message: "SQL injection vulnerability detected. User-controlled data flows into SQL command without proper sanitization. Use parameterized queries with Parameters.Add() or Parameters.AddWithValue() to prevent SQL injection."
severity: CRITICAL
languages: [csharp]
mode: taint
pattern-sources:
- patterns:
- pattern: |
(string $X)
- pattern-not: |
"..."
pattern-propagators:
# StringBuilder propagation
- pattern: (StringBuilder $B).$ANY(...,(string $X),...)
from: $X
to: $B
# String.Format propagation
- pattern: String.Format($FMT, ..., (string $X), ...)
from: $X
to: $FMT
# String concatenation
- pattern: (string $A) + (string $B)
from: $B
to: $A
pattern-sinks:
- patterns:
- pattern-either:
# Command object instantiation
- patterns:
- pattern: |
new $PATTERN($CMD,...)
- focus-metavariable: $CMD
# CommandText property assignment
- patterns:
- pattern: |
$OBJ.$PATTERN = $VALUE;
- focus-metavariable: $VALUE
- metavariable-regex:
metavariable: $PATTERN
regex: ^(SqlCommand|CommandText|OleDbCommand|OdbcCommand|OracleCommand|MySqlCommand|NpgsqlCommand|SQLiteCommand|SqlCeCommand)$
pattern-sanitizers:
# Parameterized query usage
- pattern-either:
- pattern: |
$CMD.Parameters.Add(...)
- pattern: |
$CMD.Parameters.AddWithValue(...)
- pattern: |
$CMD.Parameters[$IDX] = ...
by-side-effect: true
metadata:
category: security
cwe: CWE-89
owasp:
- A03:2021 - Injection
confidence: high
subcategory: injection
vulnerability_class: "Injection Vulnerability"
fix: "Use parameterized queries with SqlCommand: cmd.Parameters.AddWithValue(\"@id\", userId); or use Entity Framework LINQ queries."
# Command injection
- id: dotnet-command-injection
message: "OS command injection vulnerability detected. User-controlled data flows into a system command without proper sanitization, allowing attackers to execute arbitrary commands. Use safe APIs with argument lists instead of shell execution."
severity: CRITICAL
languages: [csharp]
pattern-either:
# C#
- pattern: Process.Start($CMD + $USER_INPUT)
- pattern: new Process().StartInfo.FileName = $CMD + $USER_INPUT
- pattern: ProcessStartInfo($CMD + $USER_INPUT, ...)
metadata:
category: security
cwe: CWE-78
confidence: high
subcategory: injection
vulnerability_class: "Injection Vulnerability"
owasp: "A03:2021"
fix: "Use Process.Start() with Arguments set separately. Never concatenate user input into process arguments."
# Code injection via compilation
- id: dotnet-code-injection
message: "Code injection vulnerability detected. User-controlled input is passed to a code evaluation function, allowing arbitrary code execution. Avoid eval/exec with user input; use safe alternatives."
severity: CRITICAL
languages: [csharp]
pattern-either:
- pattern: CSharpCodeProvider().CompileAssemblyFromSource(..., $USER_INPUT)
- pattern: VBCodeProvider().CompileAssemblyFromSource(..., $USER_INPUT)
- pattern: CodeDomProvider.CreateProvider(...).CompileAssemblyFromSource(..., $USER_INPUT)
- pattern: Assembly.Load($USER_INPUT)
- pattern: Activator.CreateInstance($USER_INPUT, ...)
metadata:
category: security
cwe: CWE-94
confidence: high
subcategory: injection
vulnerability_class: "Injection Vulnerability"
owasp: "A03:2021"
fix: "Avoid CSharpScript.EvaluateAsync() or Roslyn compilation with user input. Use expression parsers or sandboxed environments."
# Deserialization vulnerabilities
- id: dotnet-unsafe-deserialization
message: "Unsafe deserialization detected. Deserializing untrusted data can lead to remote code execution or denial of service. Use safe serialization formats like JSON or validate data before deserializing."
severity: CRITICAL
languages: [csharp]
pattern-either:
- pattern: BinaryFormatter.Deserialize($STREAM)
- pattern: new BinaryFormatter().Deserialize($STREAM)
- pattern: NetDataContractSerializer.Deserialize($STREAM)
- pattern: JavaScriptSerializer.Deserialize($JSON)
- pattern: JsonConvert.DeserializeObject($JSON)
metadata:
category: security
cwe: CWE-502
confidence: high
subcategory: integrity
vulnerability_class: "Insecure Deserialization"
owasp: "A08:2021"
fix: "Use System.Text.Json or Newtonsoft.Json instead of BinaryFormatter/SoapFormatter. Set TypeNameHandling.None in Newtonsoft.Json."
# LDAP injection
- id: dotnet-ldap-injection
message: "LDAP injection vulnerability detected. User input in LDAP queries without sanitization allows attackers to modify query logic. Escape special characters in LDAP filters."
severity: CRITICAL
languages: [csharp]
pattern-either:
- pattern: new DirectorySearcher($FILTER + $USER_INPUT)
- pattern: $SEARCHER.Filter = $FILTER + $USER_INPUT
- pattern: DirectoryEntry.Path = $PATH + $USER_INPUT
metadata:
category: security
cwe: CWE-90
confidence: medium
subcategory: injection
vulnerability_class: "Injection Vulnerability"
owasp: "A03:2021"
fix: "Use System.DirectoryServices with parameterized searches. Escape special LDAP characters before inserting into filters."
# === High Severity Rules ===
# Hardcoded credentials - matches both variable-name patterns AND credential API usage
- id: dotnet-hardcoded-credentials
message: "Hard-coded credentials detected. Embedding secrets in source code makes them easily discoverable and impossible to rotate. Use environment variables or a secrets manager instead."
severity: HIGH
languages: [csharp]
pattern-either:
# Pattern 1: Variable name suggests credential AND value is a non-empty literal
- patterns:
- pattern-either:
- pattern: |
private const string $VAR = "$VALUE";
- pattern: |
public const string $VAR = "$VALUE";
- pattern: |
string $VAR = "$VALUE";
- metavariable-regex:
metavariable: $VAR
regex: (?i).*(password|passwd|pwd|secret|token|api_key|connection_string).*
- metavariable-regex:
metavariable: $VALUE
# Must look like an actual secret: 6+ chars, not a config path or empty
regex: ^(?!$).{6,}
- metavariable-regex:
metavariable: $VALUE
# Exclude config key paths and property names
regex: ^(?!.*\.\w+\.\w+)(?!.*\b(Use|Enable|Disable|Is|Has|Get|Set|On)\w+).*$
# Pattern 2: Credential APIs called with hardcoded string literals
- pattern: new NetworkCredential($USER, "...", ...)
- pattern: new NetworkCredential("...", "...", ...)
- pattern: new SqlConnection("...");
- pattern: new PasswordDeriveBytes("...", ...)
metadata:
category: security
cwe: CWE-798
confidence: medium
subcategory: authentication
vulnerability_class: "Authentication Weakness"
owasp: "A07:2021"
fix: "Store secrets in environment variables, Azure Key Vault, or user-secrets for development. Use IConfiguration to access secrets."
# Weak cryptography - MD5
- id: dotnet-weak-crypto-md5
message: "Weak cryptographic algorithm detected. Using broken or outdated algorithms may allow attackers to decrypt data or forge signatures. Use modern algorithms like AES-256, SHA-256, or Ed25519."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: MD5.Create()
- pattern: new MD5CryptoServiceProvider()
- pattern: MD5CryptoServiceProvider.ComputeHash(...)
- pattern: System.Security.Cryptography.MD5.Create()
metadata:
category: security
cwe: CWE-327
confidence: high
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
fix: "Use SHA256.Create() instead of MD5/SHA1. Use Aes.Create() with CipherMode.CBC or AesGcm for encryption."
# Weak cryptography - SHA1
- id: dotnet-weak-crypto-sha1
message: "Weak cryptographic algorithm detected. Using broken or outdated algorithms may allow attackers to decrypt data or forge signatures. Use modern algorithms like AES-256, SHA-256, or Ed25519."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: SHA1.Create()
- pattern: new SHA1CryptoServiceProvider()
- pattern: SHA1CryptoServiceProvider.ComputeHash(...)
- pattern: System.Security.Cryptography.SHA1.Create()
metadata:
category: security
cwe: CWE-327
confidence: high
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
fix: "Use SHA256.Create() instead of MD5/SHA1. Use Aes.Create() with CipherMode.CBC or AesGcm for encryption."
# SSL/TLS certificate bypass
- id: dotnet-ssl-bypass
message: "TLS/SSL certificate validation is disabled or bypassed. This allows man-in-the-middle attacks where attackers can intercept encrypted communications. Always validate certificates in production."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: ServicePointManager.ServerCertificateValidationCallback = ($SENDER, $CERT, $CHAIN, $ERRORS) => true
- pattern: ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }
- pattern: HttpClientHandler.ServerCertificateCustomValidationCallback = ($REQ, $CERT, $CHAIN, $ERRORS) => true
metadata:
category: security
cwe: CWE-295
confidence: high
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A07:2021"
fix: "Never return true from ServerCertificateCustomValidationCallback. Use the default certificate validation from ServicePointManager."
# XSS vulnerabilities - taint mode for accurate user-input tracking
- id: dotnet-xss-response-write
message: "Cross-site scripting (XSS) vulnerability detected. User input is rendered in HTML output without proper escaping, allowing attackers to inject malicious scripts. Sanitize or escape all user input before rendering."
severity: HIGH
languages: [csharp]
mode: taint
pattern-sources:
- pattern-either:
# ASP.NET request input sources
- pattern: Request.QueryString[...]
- pattern: Request.Form[...]
- pattern: Request.Params[...]
- pattern: Request.Cookies[...]
- pattern: Request[$KEY]
- pattern: Request.Headers[...]
- pattern: Request.UserAgent
- pattern: Request.RawUrl
- pattern: Request.Url
- pattern: Request.Path
- pattern: Request.PathInfo
- pattern: (HttpRequest $REQ).QueryString[...]
- pattern: (HttpRequest $REQ).Form[...]
- pattern: (HttpRequest $REQ).Params[...]
- pattern: (HttpRequest $REQ)[$KEY]
# ASP.NET Core model binding
- pattern: $REQ.Query[...]
- pattern: $REQ.Form[...]
- pattern: $REQ.Headers[...]
- pattern: $REQ.Cookies[...]
# ASP.NET Core controller parameter binding
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromQuery] $TYPE $PARAM, ...) { ... }
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromBody] $TYPE $PARAM, ...) { ... }
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromRoute] $TYPE $PARAM, ...) { ... }
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromForm] $TYPE $PARAM, ...) { ... }
# IFormFile upload sources
- pattern: (IFormFile $F).FileName
- pattern: (IFormFile $F).ContentType
# Network input sources (Juliet-style)
- pattern: (StreamReader $SR).ReadLine()
- pattern: (TextReader $TR).ReadLine()
- pattern: Console.ReadLine()
pattern-propagators:
- pattern: (string $A) + (string $B)
from: $B
to: $A
- pattern: String.Format($FMT, ..., (string $X), ...)
from: $X
to: $FMT
- pattern: String.Concat(..., (string $X), ...)
from: $X
to: String.Concat
pattern-sinks:
- pattern-either:
- pattern: Response.Write(...)
- pattern: Response.WriteAsync(...)
- pattern: HttpContext.Response.Write(...)
- pattern: HttpContext.Response.WriteAsync(...)
# HttpResponse parameter pattern (Juliet, ASP.NET handlers)
- pattern: $RESP.Write(...)
- pattern: $RESP.WriteAsync(...)
# Razor unencoded output
- pattern: Html.Raw(...)
pattern-sanitizers:
- pattern-either:
- pattern: HttpUtility.HtmlEncode(...)
- pattern: HtmlEncoder.Default.Encode(...)
- pattern: WebUtility.HtmlEncode(...)
- pattern: Server.HtmlEncode(...)
- pattern: AntiXssEncoder.HtmlEncode(...)
metadata:
category: security
cwe: CWE-79
confidence: high
subcategory: xss
vulnerability_class: "Cross-Site Scripting (XSS)"
owasp: "A03:2021"
fix: "Use Razor auto-encoding or HtmlEncoder.Default.Encode(). Never use Html.Raw() with user input. Validate input on both client and server."
# Path traversal - taint mode for accurate user-input tracking
- id: dotnet-path-traversal
message: "Path traversal vulnerability detected. User input is used in file paths without validation, allowing attackers to access files outside the intended directory. Validate and canonicalize paths before use."
severity: HIGH
languages: [csharp]
mode: taint
pattern-sources:
- pattern-either:
# ASP.NET request sources
- pattern: Request.QueryString[...]
- pattern: Request.Form[...]
- pattern: Request.Params[...]
- pattern: Request[$KEY]
- pattern: Request.Path
- pattern: Request.PathInfo
# ASP.NET Core
- pattern: $REQ.Query[...]
- pattern: $REQ.Form[...]
- pattern: $REQ.RouteValues[...]
# ASP.NET Core controller parameter binding
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromQuery] $TYPE $PARAM, ...) { ... }
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromBody] $TYPE $PARAM, ...) { ... }
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromRoute] $TYPE $PARAM, ...) { ... }
- patterns:
- pattern: $PARAM
- pattern-inside: |
public $RET $METHOD(..., [FromForm] $TYPE $PARAM, ...) { ... }
# IFormFile upload sources
- pattern: (IFormFile $F).FileName
# Network input sources (Juliet-style)
- pattern: (StreamReader $SR).ReadLine()
- pattern: (TextReader $TR).ReadLine()
- pattern: Console.ReadLine()
# Environment and system sources
- pattern: Environment.GetEnvironmentVariable(...)
pattern-propagators:
- pattern: (string $A) + (string $B)
from: $B
to: $A
- pattern: Path.Combine(..., (string $X), ...)
from: $X
to: Path.Combine
- pattern: String.Format($FMT, ..., (string $X), ...)
from: $X
to: $FMT
pattern-sinks:
- pattern-either:
- pattern: File.ReadAllText(...)
- pattern: File.ReadAllBytes(...)
- pattern: File.WriteAllText(...)
- pattern: File.WriteAllBytes(...)
- pattern: File.Open(...)
- pattern: File.OpenRead(...)
- pattern: File.OpenWrite(...)
- pattern: File.Exists(...)
- pattern: File.Delete(...)
# Fully-qualified System.IO variants (common in ASP.NET Core)
- pattern: System.IO.File.ReadAllText(...)
- pattern: System.IO.File.ReadAllBytes(...)
- pattern: System.IO.File.WriteAllText(...)
- pattern: System.IO.File.WriteAllBytes(...)
- pattern: System.IO.File.Exists(...)
- pattern: System.IO.File.Open(...)
- pattern: System.IO.File.Delete(...)
- pattern: new FileStream(...)
- pattern: new StreamReader(...)
- pattern: new StreamWriter(...)
- pattern: Directory.GetFiles(...)
- pattern: Directory.EnumerateFiles(...)
pattern-sanitizers:
- pattern-either:
- pattern: Path.GetFullPath(...)
- pattern: Path.GetFileName(...)
# Framework-provided base paths are safe sources, not sanitizers,
# but if the result is validated against a base we consider it sanitized
- pattern: $X.StartsWith($BASE)
metadata:
category: security
cwe: CWE-22
confidence: medium
subcategory: access-control
vulnerability_class: "Access Control Violation"
owasp: "A01:2021"
fix: "Use Path.GetFullPath() and verify the result starts with the allowed base directory. Use Path.Combine() instead of string concatenation."
# Insecure random
- id: dotnet-insecure-random
message: "Insecure random number generator used. Non-cryptographic PRNGs produce predictable values that attackers can guess. Use a cryptographically secure random generator for security-sensitive operations."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: new Random()
- pattern: new Random($SEED)
- pattern: Random.Next()
- pattern: Random.NextBytes(...)
metadata:
category: security
cwe: CWE-338
confidence: medium
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
fix: "Use System.Security.Cryptography.RandomNumberGenerator instead of System.Random for security-sensitive operations."
# XXE vulnerabilities
- id: dotnet-xxe-vulnerability
message: "XML External Entity (XXE) vulnerability. The XML parser processes external entity references that can read local files or make network requests. Disable external entity processing in XML parsers."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: XmlDocument.Load($XML)
- pattern: XmlDocument.LoadXml($XML)
- pattern: XmlReader.Create($XML)
- pattern: XDocument.Load($XML)
- pattern: XDocument.Parse($XML)
pattern-not-inside:
pattern: |
...
$XML_SETTINGS.DtdProcessing = DtdProcessing.Prohibit;
...
metadata:
category: security
cwe: CWE-611
confidence: medium
subcategory: injection
vulnerability_class: "Injection Vulnerability"
owasp: "A05:2021"
fix: "Set XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit and XmlReaderSettings.XmlResolver = null."
# === Medium Severity Rules ===
# Weak cipher algorithms
- id: dotnet-weak-cipher
message: "Weak cryptographic algorithm detected. Using broken or outdated algorithms may allow attackers to decrypt data or forge signatures. Use modern algorithms like AES-256, SHA-256, or Ed25519."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: DESCryptoServiceProvider()
- pattern: RC2CryptoServiceProvider()
- pattern: SymmetricAlgorithm.Create("DES")
- pattern: SymmetricAlgorithm.Create("RC2")
- pattern: SymmetricAlgorithm.Create("3DES")
metadata:
category: security
cwe: CWE-327
confidence: high
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
# HTTP instead of HTTPS
- id: dotnet-insecure-http
message: "Sensitive data transmitted over an unencrypted channel. Using HTTP instead of HTTPS allows network attackers to intercept data in transit. Use HTTPS for all communications containing sensitive data."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: 'new Uri("http://$URL")'
- pattern: '"http://$URL"'
- pattern: '"http://$URL"'
- pattern: 'HttpClient.GetAsync("http://$URL")'
- pattern: 'WebRequest.Create("http://$URL")'
metadata:
category: security
cwe: CWE-319
confidence: low
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
# Weak key sizes
- id: dotnet-weak-key-size
message: "Cryptographic weakness detected. Misuse of cryptographic primitives undermines data protection. Use well-tested crypto libraries with recommended configurations."
severity: MEDIUM
languages: [csharp]
patterns:
- pattern-either:
- pattern: RSACryptoServiceProvider(512)
- pattern: RSACryptoServiceProvider(1024)
- pattern: RSA.Create(512)
- pattern: RSA.Create(1024)
- pattern: DSACryptoServiceProvider(512)
- pattern: DSACryptoServiceProvider(1024)
metadata:
category: security
cwe: CWE-310
confidence: medium
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
# Cookie security issues
- id: dotnet-insecure-cookie
message: "Sensitive cookie missing the Secure flag. The cookie may be transmitted over unencrypted HTTP, allowing interception. Set the Secure flag on all sensitive cookies."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: |
new HttpCookie($NAME, $VALUE) {
Secure = false
}
- pattern: |
new HttpCookie($NAME, $VALUE) {
HttpOnly = false
}
- pattern: Response.Cookies.Add(new HttpCookie($NAME, $VALUE))
pattern-not-inside:
pattern: |
...
Secure = true
...
metadata:
category: security
cwe: CWE-614
confidence: low
subcategory: configuration
vulnerability_class: "Security Misconfiguration"
owasp: "A05:2021"
# Open redirect
- id: dotnet-open-redirect
message: "Open redirect vulnerability detected. The application redirects to a user-controlled URL without validation, enabling phishing attacks. Validate redirect targets against an allowlist."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: Response.Redirect($USER_INPUT)
- pattern: RedirectToAction($USER_INPUT)
- pattern: Redirect($USER_INPUT)
- pattern: LocalRedirect($USER_INPUT)
metadata:
category: security
cwe: CWE-601
confidence: low
subcategory: access-control
vulnerability_class: "Access Control Violation"
owasp: "A01:2021"
# === Low Severity Rules ===
# Debug information disclosure
- id: dotnet-debug-info-disclosure
message: "Sensitive information written to log files. Passwords, tokens, or personal data in logs can be exposed to unauthorized parties. Redact sensitive values before logging."
severity: LOW
languages: [csharp]
patterns:
- pattern-either:
- pattern: Console.WriteLine($USER_INPUT)
- pattern: Debug.WriteLine($USER_INPUT)
- pattern: Trace.WriteLine($USER_INPUT)
- pattern: System.Diagnostics.Debug.Write($USER_INPUT)
- metavariable-regex:
metavariable: $USER_INPUT
regex: (?i).*(password|token|secret|key|credential).*
metadata:
category: security
cwe: CWE-532
confidence: low
subcategory: logging
vulnerability_class: "Sensitive Data Exposure"
owasp: "A09:2021"
# Empty catch blocks
- id: dotnet-empty-catch-block
message: "Improper error handling detected. The application does not properly handle exceptions, which may cause crashes or information leaks. Catch specific exceptions and handle them gracefully."
severity: LOW
languages: [csharp]
pattern-either:
# C#
- pattern: |
try {
...
} catch ($EXCEPTION $VAR) {
}
- pattern: |
try {
...
} catch {
}
metadata:
category: security
cwe: CWE-703
confidence: high
subcategory: error-handling
vulnerability_class: "Improper Error Handling"
# Hardcoded IP addresses
- id: dotnet-hardcoded-ip
message: "Hard-coded credentials detected. Embedding secrets in source code makes them easily discoverable and impossible to rotate. Use environment variables or a secrets manager instead."
severity: LOW
languages: [csharp]
pattern-either:
- pattern: '"192.168.$IP"'
- pattern: '"10.$IP"'
- pattern: '"172.16.$IP"'
- pattern: '"127.0.0.1"'
- pattern: '"localhost"'
metadata:
category: security
cwe: CWE-798
confidence: low
subcategory: authentication
vulnerability_class: "Authentication Weakness"
owasp: "A07:2021"
# === Framework-specific Rules ===
# ASP.NET specific vulnerabilities
- id: dotnet-aspnet-validaterequest-false
message: "Cross-site scripting (XSS) vulnerability detected. User input is rendered in HTML output without proper escaping, allowing attackers to inject malicious scripts. Sanitize or escape all user input before rendering."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: ValidateRequest = false
- pattern: ValidateRequestMode.Disabled
- pattern: '[ValidateInput(false)]'
metadata:
category: security
framework: aspnet
cwe: CWE-79
confidence: medium
subcategory: xss
vulnerability_class: "Cross-Site Scripting (XSS)"
owasp: "A03:2021"
references:
- https://learn.microsoft.com/en-us/aspnet/core/security/
fix: "Use Razor auto-encoding or HtmlEncoder.Default.Encode(). Never use Html.Raw() with user input. Validate input on both client and server."
# ASP.NET viewstate MAC disabled
- id: dotnet-aspnet-viewstate-mac-disabled
message: "Insufficient data authenticity verification. Data is accepted without verifying its source. Validate data origin using signatures or MACs."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: EnableViewStateMac = false
- pattern: ViewStateEncryptionMode.Never
metadata:
category: security
framework: aspnet
cwe: CWE-345
confidence: high
subcategory: integrity
vulnerability_class: "Insecure Deserialization"
owasp: "A08:2021"
references:
- https://learn.microsoft.com/en-us/aspnet/core/security/
fix: "Validate data origin using cryptographic signatures or MACs."
# ASP.NET Core authorization bypass
- id: dotnet-aspnetcore-auth-bypass
message: "Missing authorization check. The application does not verify user permissions before granting access to resources. Add authorization checks to all protected endpoints."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: '[AllowAnonymous]'
- pattern: options.RequireAuthenticatedUser = false
- pattern: services.AddAuthorization(options => { })
metadata:
category: security
framework: aspnetcore
cwe: CWE-862
confidence: low
subcategory: access-control
vulnerability_class: "Access Control Violation"
owasp: "A01:2021"
references:
- https://learn.microsoft.com/en-us/aspnet/core/security/
fix: "Add [Authorize] attribute to controller actions. Configure authorization policies in Startup.cs. Use role-based or policy-based authorization."
# Entity Framework SQL injection
- id: dotnet-ef-sql-injection
message: "SQL injection vulnerability detected. User-supplied input is included in a SQL query without sanitization, potentially allowing attackers to read, modify, or delete database contents. Use parameterized queries or an ORM instead of string concatenation."
severity: CRITICAL
languages: [csharp]
pattern-either:
- pattern: context.Database.ExecuteSqlRaw($SQL + $USER_INPUT)
- pattern: context.Database.ExecuteSqlCommand($SQL + $USER_INPUT)
- pattern: FromSqlRaw($SQL + $USER_INPUT)
- pattern: FromSql($SQL + $USER_INPUT)
metadata:
category: security
framework: entityframework
cwe: CWE-89
confidence: high
subcategory: injection
vulnerability_class: "Injection Vulnerability"
owasp: "A03:2021"
fix: "Use parameterized queries with SqlCommand: cmd.Parameters.AddWithValue(\"@id\", userId); or use Entity Framework LINQ queries."
# WCF security issues
- id: dotnet-wcf-insecure-binding
message: "Sensitive data transmitted over an unencrypted channel. Using HTTP instead of HTTPS allows network attackers to intercept data in transit. Use HTTPS for all communications containing sensitive data."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: BasicHttpBinding()
- pattern: new NetTcpBinding(SecurityMode.None)
- pattern: new WSHttpBinding(SecurityMode.None)
metadata:
category: security
framework: wcf
cwe: CWE-319
confidence: medium
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
# JWT vulnerabilities
- id: dotnet-jwt-no-verification
message: "Cryptographic signature verification is missing or improper. Unverified signatures allow attackers to tamper with data. Always verify signatures before trusting signed data."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: JwtSecurityTokenHandler().ReadJwtToken($TOKEN)
- pattern: new JwtSecurityToken($TOKEN)
- pattern: new TokenValidationParameters { ValidateIssuer = false }
- pattern: new TokenValidationParameters { ValidateAudience = false }
metadata:
category: security
cwe: CWE-347
confidence: medium
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
owasp: "A02:2021"
# OWASP Top 10 related rules
# A01: Broken Access Control
- id: dotnet-broken-access-control
message: "Incorrect authorization implementation. Authorization checks exist but are flawed. Review and test authorization logic for bypass conditions."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: |
[HttpGet]
public ActionResult $METHOD() {
// No authorization check
...
}
- pattern: User.IsInRole($USER_INPUT)
metadata:
category: security
owasp: A01
cwe: CWE-863
confidence: low
subcategory: access-control
vulnerability_class: "Access Control Violation"
fix: "Review authorization logic for bypass conditions. Use policy-based authorization with IAuthorizationHandler. Test authorization with different user roles."
# A02: Cryptographic Failures - targets actual weak algorithm usage
- id: dotnet-crypto-failures
message: "Weak cryptographic algorithm detected. Using broken or outdated algorithms may allow attackers to decrypt data or forge signatures. Use modern algorithms like AES-256, SHA-256, or Ed25519."
severity: HIGH
languages: [csharp]
pattern-either:
# Weak symmetric ciphers
- pattern: new TripleDESCryptoServiceProvider()
- pattern: new DESCryptoServiceProvider()
- pattern: new RC2CryptoServiceProvider()
- pattern: TripleDES.Create()
- pattern: DES.Create()
- pattern: RC2.Create()
# Obsolete RijndaelManaged (use Aes.Create() instead)
- pattern: new RijndaelManaged()
# Using raw password bytes directly as crypto key (no KDF)
- pattern: new RijndaelManaged() { Key = Encoding.UTF8.GetBytes($KEY) }
- pattern: new AesCryptoServiceProvider() { Key = Encoding.UTF8.GetBytes($KEY) }
# Encoding password for storage without hashing (storing plaintext)
- pattern: Convert.ToBase64String(Encoding.UTF8.GetBytes($SECRET))
metadata:
category: security
owasp: A02
cwe: CWE-327
confidence: high
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
fix: "Use Aes.Create() instead of 3DES/DES/RC2. Use Rfc2898DeriveBytes or HKDF for key derivation from passwords. Never use raw Encoding.GetBytes() as a crypto key."
# A03: Injection (additional patterns)
- id: dotnet-xpath-injection
message: "XML/XPath injection detected. User input in XML queries can alter query logic. Use parameterized XPath queries."
severity: CRITICAL
languages: [csharp]
pattern-either:
- pattern: $XML.SelectNodes($XPATH + $USER_INPUT)
- pattern: $XML.SelectSingleNode($XPATH + $USER_INPUT)
- pattern: XPathExpression.Compile($XPATH + $USER_INPUT)
metadata:
category: security
owasp: A03
cwe: CWE-91
confidence: high
subcategory: injection
vulnerability_class: "Injection Vulnerability"
fix: "Use parameterized XPath queries with XPathNavigator.Compile(). Escape special characters in user input before XPath queries."
# A04: Insecure Design
- id: dotnet-insecure-design-session
message: "Credentials transmitted or stored with insufficient protection. Weak protection makes credentials recoverable. Use strong encryption and secure channels."
severity: MEDIUM
languages: [csharp]
patterns:
- pattern-either:
- pattern: Session[$KEY] = $SENSITIVE_DATA
- pattern: HttpContext.Session.SetString($KEY, $SENSITIVE_DATA)
- metavariable-regex:
metavariable: $SENSITIVE_DATA
regex: (?i).*(password|credit_card|ssn|social_security).*
metadata:
category: security
owasp: A04
cwe: CWE-522
confidence: low
subcategory: crypto
vulnerability_class: "Cryptographic Weakness"
# A05: Security Misconfiguration
- id: dotnet-security-misconfiguration
message: "Insecure configuration detected. A misconfigured setting weakens the application's security posture. Review and harden security-relevant configuration."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: app.UseDeveloperExceptionPage()
- pattern: services.AddAuthentication().AddCookie(options => { options.Cookie.SecurePolicy = CookieSecurePolicy.None; })
metadata:
category: security
owasp: A05
cwe: CWE-16
confidence: high
subcategory: configuration
vulnerability_class: "Security Misconfiguration"
# A06: Vulnerable and Outdated Components
- id: dotnet-vulnerable-components
message: "Use of unmaintained third-party component. Unpatched dependencies contain known vulnerabilities. Update to a maintained version or find an alternative."
severity: MEDIUM
languages: [csharp]
pattern-either:
- pattern: using Newtonsoft.Json;
- pattern: using System.Web.Script.Serialization;
- pattern: JavaScriptSerializer
metadata:
category: security
owasp: A06
cwe: CWE-1104
confidence: low
subcategory: configuration
vulnerability_class: "Security Misconfiguration"
# A07: Identification and Authentication Failures
- id: dotnet-auth-failures
message: "Improper authentication detected. The application does not properly verify user identity before granting access. Implement proper authentication mechanisms."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: FormsAuthentication.SetAuthCookie($USER, true)
- pattern: GenericPrincipal($IDENTITY, null)
- pattern: Thread.CurrentPrincipal = new GenericPrincipal($IDENTITY, $ROLES)
metadata:
category: security
owasp: A07
cwe: CWE-287
confidence: low
subcategory: authentication
vulnerability_class: "Authentication Weakness"
fix: "Use ASP.NET Core Identity or a proven authentication library. Implement multi-factor authentication. Use strong password hashing (BCrypt/Argon2)."
# A08: Software and Data Integrity Failures
- id: dotnet-integrity-failures
message: "Code downloaded without integrity verification. Executing unverified code allows supply chain attacks. Verify checksums or signatures before execution."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: Assembly.LoadFrom($USER_INPUT)
- pattern: Assembly.LoadFile($USER_INPUT)
- pattern: Assembly.UnsafeLoadFrom($USER_INPUT)
metadata:
category: security
owasp: A08
cwe: CWE-494
confidence: medium
subcategory: integrity
vulnerability_class: "Insecure Deserialization"
fix: "Verify assembly signatures using strong naming. Validate checksums of downloaded assemblies before loading."
# A09: Security Logging and Monitoring Failures
- id: dotnet-logging-failures
message: "Insufficient security logging. Critical events are not logged, hindering incident detection. Log authentication, authorization, and data access events."
severity: LOW
languages: [csharp]
pattern-either:
- pattern: |
try {
// Authentication logic
...
} catch {
// No logging of failed authentication
}
- pattern: |
if (!User.Identity.IsAuthenticated) {
// No security logging
return;
}
metadata:
category: security
owasp: A09
cwe: CWE-778
confidence: low
subcategory: logging
vulnerability_class: "Sensitive Data Exposure"
# A10: Server-Side Request Forgery (SSRF)
- id: dotnet-ssrf
message: "Server-side request forgery (SSRF) detected. The application fetches resources from user-controlled URLs, allowing attackers to access internal services. Validate and restrict URL targets."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: HttpClient.GetAsync($USER_INPUT)
- pattern: WebRequest.Create($USER_INPUT)
- pattern: new WebClient().DownloadString($USER_INPUT)
- pattern: RestClient.Get($USER_INPUT)
metadata:
category: security
owasp: A10
cwe: CWE-918
confidence: low
subcategory: ssrf
vulnerability_class: "Server-Side Request Forgery"
fix: "Validate URLs against an allowlist of permitted hosts. Block private IP ranges and localhost. Resolve DNS and check the IP before making requests."
# Additional .NET specific security issues
# Unsafe code usage
- id: dotnet-unsafe-code
message: "Memory buffer boundary violation. Operations read or write beyond buffer bounds, causing crashes or code execution. Use bounds-checked functions and validate sizes."
severity: HIGH
languages: [csharp]
pattern-either:
- pattern: |
unsafe {
...
}
- pattern: fixed ($TYPE* $VAR = $EXPR)
- pattern: Marshal.PtrToStringAnsi($PTR)
- pattern: Marshal.Copy($PTR, ...)
metadata:
category: security
cwe: CWE-119
confidence: medium
subcategory: deprecated
vulnerability_class: "Memory Safety Violation"
fix: "Use safe managed code. Avoid Marshal.Copy and unsafe fixed buffers. Use Span<T> with bounds checking for performance-critical buffer operations."
# Double check locking anti-pattern
- id: dotnet-double-check-locking
message: "Improper locking detected. Lock mismanagement may cause deadlocks or data corruption. Ensure locks are acquired and released in consistent order."
severity: MEDIUM
languages: [csharp]
pattern: |
if ($INSTANCE == null) {
lock ($LOCK) {
if ($INSTANCE == null) {
$INSTANCE = new $TYPE();
}