File size: 48,434 Bytes
2ef05ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
#!/usr/bin/env python3
"""SecureCodePairs v1.1.0 extension records (part 2): SCP-000087+.

Domains: fintech, FHIR/healthcare, Kubernetes, IoT.
Languages deepened: Python, Java, Go, TypeScript, C#, PHP, Kotlin, Swift, Rust.
"""
from typing import List, Dict

RECORDS_EXT2: List[Dict] = [
    # ================================================================== FINTECH (Python/FastAPI) ==================================================================
    {
        "id": "SCP-000087",
        "language": "Python",
        "framework": "FastAPI",
        "title": "Missing idempotency on payment endpoint",
        "description": "A payment endpoint processes the same request twice if retried, double-charging.",
        "owasp": "A04:2021 - Insecure Design",
        "owasp_api": "API3:2023 - Broken Object Property Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-840",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "@app.post('/pay')\n"
            "def pay(req: PaymentReq):\n"
            "    # Vulnerable: no idempotency key check\n"
            "    charge_card(req.user, req.amount)\n"
            "    return {'ok': True}\n"
        ),
        "secure_code": (
            "@app.post('/pay')\n"
            "def pay(req: PaymentReq, idem: str = Header(...)):\n"
            "    # Secure: dedupe by idempotency key\n"
            "    if redis.exists('idem:' + idem):\n"
            "        return {'ok': True, 'cached': True}\n"
            "    charge_card(req.user, req.amount)\n"
            "    redis.setex('idem:' + idem, 86400, '1')\n"
            "    return {'ok': True}\n"
        ),
        "patch": (
            "--- a/pay.py\n"
            "+++ b/pay.py\n"
            "@@ -1,5 +1,10 @@\n"
            "-def pay(req: PaymentReq):\n"
            "-    charge_card(req.user, req.amount)\n"
            "+def pay(req: PaymentReq, idem: str = Header(...)):\n"
            "+    if redis.exists('idem:' + idem):\n"
            "        return {'ok': True, 'cached': True}\n"
            "+    charge_card(req.user, req.amount)\n"
            "+    redis.setex('idem:' + idem, 86400, '1')\n"
        ),
        "root_cause": "No idempotency key, so client retries cause duplicate charges.",
        "attack": "Network retry or replay of the request double-charges the customer.",
        "impact": "Financial loss, customer trust damage.",
        "fix": "Require and dedupe on an idempotency key per mutating request.",
        "guideline": "Make payment endpoints idempotent via idempotency keys.",
        "tags": ["business-logic", "fintech", "fastapi", "idempotency"],
        "metadata": {"domain": "Banking", "input_source": "header", "auth_required": True},
    },
    {
        "id": "SCP-000088",
        "language": "Java",
        "framework": "Spring Boot",
        "title": "Rounding error in interest calculation",
        "description": "A Spring service uses binary floating point for money, causing rounding drift.",
        "owasp": "A04:2021 - Insecure Design",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-682",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Medium",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "public BigDecimal interest(double principal, double rate) {\n"
            "    // Vulnerable: double for currency\n"
            "    return BigDecimal.valueOf(principal * rate);\n"
            "}\n"
        ),
        "secure_code": (
            "public BigDecimal interest(BigDecimal principal, BigDecimal rate) {\n"
            "    // Secure: BigDecimal throughout, explicit rounding\n"
            "    return principal.multiply(rate)\n"
            "        .setScale(2, RoundingMode.HALF_UP);\n"
            "}\n"
        ),
        "patch": (
            "--- a/InterestService.java\n"
            "+++ b/InterestService.java\n"
            "@@ -1,4 +1,6 @@\n"
            "-    return BigDecimal.valueOf(principal * rate);\n"
            "+    return principal.multiply(rate)\n"
            "+        .setScale(2, RoundingMode.HALF_UP);\n"
        ),
        "root_cause": "Binary floating point cannot represent decimal currency exactly, introducing drift.",
        "attack": "Repeated calculations accumulate cents of error, enabling arbitrage or loss.",
        "impact": "Incorrect balances, financial discrepancy.",
        "fix": "Use BigDecimal (or integer minor units) with explicit rounding for all money.",
        "guideline": "Never use float/double for currency; use BigDecimal with scale.",
        "tags": ["fintech", "spring", "java", "rounding"],
        "metadata": {"domain": "Banking", "input_source": "server", "auth_required": False},
    },
    {
        "id": "SCP-000089",
        "language": "Go",
        "framework": "Gin",
        "title": "Missing signature verification on webhook",
        "description": "A Gin webhook handler trusts the body without verifying the provider's HMAC signature.",
        "owasp": "A08:2021 - Software and Data Integrity Failures",
        "owasp_api": "API2:2023 - Broken Authentication",
        "owasp_llm": "",
        "cwe": "CWE-345",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "func webhook(c *gin.Context) {\n"
            "    body, _ := c.GetRawData()\n"
            "    // Vulnerable: no signature check\n"
            "    processEvent(json.RawMessage(body))\n"
            "    c.Status(200)\n"
            "}\n"
        ),
        "secure_code": (
            "func webhook(c *gin.Context) {\n"
            "    body, _ := c.GetRawData()\n"
            "    sig := c.GetHeader(\"X-Signature\")\n"
            "    // Secure: verify HMAC\n"
            "    mac := hmac.New(sha256.New, []byte(os.Getenv(\"WEBHOOK_SECRET\")))\n"
            "    mac.Write(body)\n"
            "    if !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) {\n"
            "        c.Status(401); return\n"
            "    }\n"
            "    processEvent(json.RawMessage(body))\n"
            "    c.Status(200)\n"
            "}\n"
        ),
        "patch": (
            "--- a/webhook.go\n"
            "+++ b/webhook.go\n"
            "@@ -2,5 +2,12 @@\n"
            "-    processEvent(json.RawMessage(body))\n"
            "+    sig := c.GetHeader(\"X-Signature\")\n"
            "+    mac := hmac.New(sha256.New, []byte(os.Getenv(\"WEBHOOK_SECRET\")))\n"
            "+    mac.Write(body)\n"
            "+    if !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) {\n"
            "+        c.Status(401); return\n"
            "+    }\n"
            "+    processEvent(json.RawMessage(body))\n"
        ),
        "root_cause": "Webhook authenticity is not verified, so anyone can forge events.",
        "attack": "Attacker posts fake 'payment succeeded' events to grant themselves credit.",
        "impact": "Fraud, unauthorized state changes.",
        "fix": "Verify the provider HMAC signature on every webhook before processing.",
        "guideline": "Always verify webhook signatures (HMAC) before acting on events.",
        "tags": ["fintech", "gin", "go", "webhook"],
        "metadata": {"domain": "Banking", "input_source": "request_body", "auth_required": False},
    },
    {
        "id": "SCP-000090",
        "language": "TypeScript",
        "framework": "NestJS",
        "title": "Client-side amount manipulation in checkout",
        "description": "A NestJS checkout trusts the price sent from the client instead of the server catalog.",
        "owasp": "A04:2021 - Insecure Design",
        "owasp_api": "API3:2023 - Broken Object Property Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-602",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "@Post('checkout')\n"
            "checkout(@Body() b: { itemId: string; price: number }) {\n"
            "    // Vulnerable: trusts client price\n"
            "    return this.billing.charge(b.price);\n"
            "}\n"
        ),
        "secure_code": (
            "@Post('checkout')\n"
            "async checkout(@Body() b: { itemId: string }) {\n"
            "    // Secure: look up authoritative price server-side\n"
            "    const item = await this.catalog.get(b.itemId);\n"
            "    return this.billing.charge(item.price);\n"
            "}\n"
        ),
        "patch": (
            "--- a/checkout.controller.ts\n"
            "+++ b/checkout.controller.ts\n"
            "@@ -1,5 +1,6 @@\n"
            "-checkout(@Body() b: { itemId: string; price: number }) {\n"
            "-    return this.billing.charge(b.price);\n"
            "+async checkout(@Body() b: { itemId: string }) {\n"
            "+    const item = await this.catalog.get(b.itemId);\n"
            "+    return this.billing.charge(item.price);\n"
        ),
        "root_cause": "Price is taken from the client, so an attacker can set it to 0.01.",
        "attack": "Intercept the request and change price to 0.01 to buy at a discount.",
        "impact": "Revenue loss, fraud.",
        "fix": "Never trust client-supplied prices; derive totals server-side from the catalog.",
        "guideline": "Compute prices server-side from authoritative sources.",
        "tags": ["fintech", "nestjs", "typescript", "price-tampering"],
        "metadata": {"domain": "E-commerce", "input_source": "request_body", "auth_required": True},
    },
    {
        "id": "SCP-000091",
        "language": "Python",
        "framework": "Django",
        "title": "Reusable token (no expiry) for password reset",
        "description": "A Django reset token never expires and is stored in plaintext, enabling reuse.",
        "owasp": "A07:2021 - Identification and Authentication Failures",
        "owasp_api": "API2:2023 - Broken Authentication",
        "owasp_llm": "",
        "cwe": "CWE-640",
        "mitre_attack": "T1600 - Weaken Encryption",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "def issue_reset(user):\n"
            "    token = secrets.token_urlsafe(16)\n"
            "    # Vulnerable: no expiry, plaintext store\n"
            "    Cache.set('reset:' + user.id, token)\n"
            "    return token\n"
        ),
        "secure_code": (
            "def issue_reset(user):\n"
            "    token = secrets.token_urlsafe(32)\n"
            "    # Secure: hash + short TTL\n"
            "    Cache.set('reset:' + user.id, sha256(token), 900)\n"
            "    return token\n"
        ),
        "patch": (
            "--- a/auth.py\n"
            "+++ b/auth.py\n"
            "@@ -2,5 +2,6 @@\n"
            "-    token = secrets.token_urlsafe(16)\n"
            "-    Cache.set('reset:' + user.id, token)\n"
            "+    token = secrets.token_urlsafe(32)\n"
            "+    Cache.set('reset:' + user.id, sha256(token), 900)\n"
        ),
        "root_cause": "Reset tokens lack expiry and are stored reversibly, allowing indefinite reuse.",
        "attack": "Attacker who sees the token once can reset the password indefinitely.",
        "impact": "Persistent account takeover.",
        "fix": "Set short TTLs and store only token hashes; invalidate after use.",
        "guideline": "Reset tokens must expire and be single-use; store hashes only.",
        "tags": ["fintech", "django", "python", "auth"],
        "metadata": {"domain": "Authentication systems", "input_source": "server", "auth_required": False},
    },
    {
        "id": "SCP-000092",
        "language": "C#",
        "framework": "ASP.NET Core",
        "title": "Insecure direct object reference on bank account",
        "description": "An ASP.NET Core controller returns an account by id without verifying ownership.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "API1:2023 - Broken Object Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-639",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "[HttpGet(\"accounts/{id}\")]\n"
            "public Account Get(string id) => _repo.GetAccount(id);  // Vulnerable: no owner check\n"
        ),
        "secure_code": (
            "[HttpGet(\"accounts/{id}\")]\n"
            "public IActionResult Get(string id, [FromClaims] string userId)\n"
            "{\n"
            "    var acc = _repo.GetAccount(id);\n"
            "    if (acc == null || acc.OwnerId != userId) return NotFound();\n"
            "    return Ok(acc);\n"
            "}\n"
        ),
        "patch": (
            "--- a/AccountsController.cs\n"
            "+++ b/AccountsController.cs\n"
            "@@ -1,3 +1,7 @@\n"
            "-public Account Get(string id) => _repo.GetAccount(id);\n"
            "+public IActionResult Get(string id, [FromClaims] string userId) {\n"
            "+    var acc = _repo.GetAccount(id);\n"
            "+    if (acc == null || acc.OwnerId != userId) return NotFound();\n"
            "+    return Ok(acc); }\n"
        ),
        "root_cause": "Account lookup is keyed only by id, not by the authenticated owner.",
        "attack": "User enumerates account ids to read other customers' balances.",
        "impact": "Disclosure of financial data (PII).",
        "fix": "Scope lookups to the authenticated principal.",
        "guideline": "Enforce object-level authorization on financial records.",
        "tags": ["fintech", "aspnet", "csharp", "idor"],
        "metadata": {"domain": "Banking", "input_source": "path_param", "auth_required": True},
    },
    # ================================================================== FHIR / HEALTHCARE ==================================================================
    {
        "id": "SCP-000093",
        "language": "Java",
        "framework": "Spring Boot",
        "title": "FHIR resource IDOR across tenants",
        "description": "A Spring FHIR server returns a Patient resource by id without tenant scoping.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "API1:2023 - Broken Object Level Authorization",
        "owasp_llm": "",
        "cwe": "CWE-639",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Critical",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "@GetMapping(\"/fhir/Patient/{id}\")\n"
            "public Patient read(@PathVariable String id) {\n"
            "    // Vulnerable: no tenant filter\n"
            "    return fhirDao.read(Patient.class, id);\n"
            "}\n"
        ),
        "secure_code": (
            "@GetMapping(\"/fhir/Patient/{id}\")\n"
            "public Patient read(@PathVariable String id, @TenantId String tenant) {\n"
            "    // Secure: scope by tenant\n"
            "    Patient p = fhirDao.read(Patient.class, id);\n"
            "    if (!p.getTenant().equals(tenant)) throw new NotFoundException();\n"
            "    return p;\n"
            "}\n"
        ),
        "patch": (
            "--- a/FhirController.java\n"
            "+++ b/FhirController.java\n"
            "@@ -2,4 +2,7 @@\n"
            "-    return fhirDao.read(Patient.class, id);\n"
            "+    Patient p = fhirDao.read(Patient.class, id);\n"
            "+    if (!p.getTenant().equals(tenant)) throw new NotFoundException();\n"
            "+    return p;\n"
        ),
        "root_cause": "FHIR reads are not scoped by tenant, so one clinic reads another's patients.",
        "attack": "Intercept and change Patient id to scrape PHI across tenants.",
        "impact": "HIPAA violation, mass PHI disclosure.",
        "fix": "Apply tenant scoping on every FHIR read/write.",
        "guideline": "Tenant-isolate all PHI resources; verify on every access.",
        "tags": ["fhir", "spring", "java", "healthcare"],
        "metadata": {"domain": "Healthcare", "input_source": "path_param", "auth_required": True},
    },
    {
        "id": "SCP-000094",
        "language": "Python",
        "framework": "FastAPI",
        "title": "Unvalidated FHIR Observation value",
        "description": "A FastAPI endpoint stores a FHIR Observation value without validating type/range, enabling injection.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-20",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Medium",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "@app.post('/fhir/Observation')\n"
            "def obs(o: dict):\n"
            "    # Vulnerable: stores arbitrary value\n"
            "    db.observations.insert_one(o)\n"
            "    return {'ok': True}\n"
        ),
        "secure_code": (
            "@app.post('/fhir/Observation')\n"
            "def obs(o: ObservationModel):\n"
            "    # Secure: pydantic validation of code/value/unit\n"
            "    if not (0 <= o.valueQuantity.value <= 1000):\n"
            "        raise HTTPException(422, 'out of range')\n"
            "    db.observations.insert_one(o.dict())\n"
            "    return {'ok': True}\n"
        ),
        "patch": (
            "--- a/fhir_obs.py\n"
            "+++ b/fhir_obs.py\n"
            "@@ -1,5 +1,8 @@\n"
            "-def obs(o: dict):\n"
            "-    db.observations.insert_one(o)\n"
            "+def obs(o: ObservationModel):\n"
            "+    if not (0 <= o.valueQuantity.value <= 1000):\n"
            "+        raise HTTPException(422, 'out of range')\n"
            "+    db.observations.insert_one(o.dict())\n"
        ),
        "root_cause": "Observation payload is stored without schema/range validation, allowing malformed or hostile data.",
        "attack": "Post an Observation with a script payload later rendered in a clinician dashboard (stored XSS).",
        "impact": "Data integrity loss, stored XSS in viewers.",
        "fix": "Validate FHIR resources against the profile (type, range, required fields).",
        "guideline": "Validate all FHIR resources server-side before persistence.",
        "tags": ["fhir", "fastapi", "python", "input-validation"],
        "metadata": {"domain": "Healthcare", "input_source": "request_body", "auth_required": True},
    },
    {
        "id": "SCP-000095",
        "language": "C#",
        "framework": "ASP.NET Core",
        "title": "Missing audit log on PHI access",
        "description": "An ASP.NET Core healthcare API reads PHI without writing an audit trail.",
        "owasp": "A09:2021 - Security Logging and Monitoring Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-778",
        "mitre_attack": "T1562.001 - Impair Defenses: Disable or Modify Tools",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "[HttpGet(\"records/{id}\")]\n"
            "public Record Get(int id) {\n"
            "    // Vulnerable: no audit log\n"
            "    return _repo.Get(id);\n"
            "}\n"
        ),
        "secure_code": (
            "[HttpGet(\"records/{id}\")]\n"
            "public Record Get(int id, ClaimsPrincipal user)\n"
            "{\n"
            "    var r = _repo.Get(id);\n"
            "    _audit.Log(new PhiAccess { User = user.Identity.Name, RecordId = id, At = DateTime.UtcNow });\n"
            "    return r;\n"
            "}\n"
        ),
        "patch": (
            "--- a/RecordsController.cs\n"
            "+++ b/RecordsController.cs\n"
            "@@ -1,4 +1,7 @@\n"
            "-    return _repo.Get(id);\n"
            "+    var r = _repo.Get(id);\n"
            "+    _audit.Log(new PhiAccess { User = user.Identity.Name, RecordId = id, At = DateTime.UtcNow });\n"
            "+    return r;\n"
        ),
        "root_cause": "PHI access is not audited, failing compliance and incident response needs.",
        "attack": "An insider scrapes records with no trace, evading detection.",
        "impact": "Undetected PHI abuse; compliance failure (HIPAA).",
        "fix": "Emit immutable audit logs for every PHI read/write.",
        "guideline": "Audit all PHI access with user, record, and timestamp.",
        "tags": ["fhir", "aspnet", "csharp", "audit"],
        "metadata": {"domain": "Healthcare", "input_source": "path_param", "auth_required": True},
    },
    {
        "id": "SCP-000096",
        "language": "JavaScript",
        "framework": "Express",
        "title": "HL7v2 injection in message builder",
        "description": "An Express service builds HL7v2 messages by concatenating patient fields without escaping separators.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-93",
        "mitre_attack": "T1190 - Exploit Public-Facing Application",
        "severity": "Medium",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "function hl7(patient) {\n"
            "  // Vulnerable: unescaped field with pipe/newline\n"
            "  return `PID|1|${patient.name}|${patient.dob}`;\n"
            "}\n"
        ),
        "secure_code": (
            "function esc(s) { return String(s).replace(/[\\r\\n|]/g, ''); }\n"
            "function hl7(patient) {\n"
            "  // Secure: strip HL7 field/segment separators\n"
            "  return `PID|1|${esc(patient.name)}|${esc(patient.dob)}`;\n"
            "}\n"
        ),
        "patch": (
            "--- a/hl7.js\n"
            "+++ b/hl7.js\n"
            "@@ -1,4 +1,6 @@\n"
            "+function esc(s) { return String(s).replace(/[\\r\\n|]/g, ''); }\n"
            " function hl7(patient) {\n"
            "-  return `PID|1|${patient.name}|${patient.dob}`;\n"
            "+  return `PID|1|${esc(patient.name)}|${esc(patient.dob)}`;\n"
        ),
        "root_cause": "Patient fields containing HL7 separators corrupt the message or inject segments.",
        "attack": "name=EVN|1|admin sets a fake segment altering downstream routing.",
        "impact": "Message corruption, false data, misrouting.",
        "fix": "Escape HL7 separators and validate field contents.",
        "guideline": "Escape/encode structured-message separators before concatenation.",
        "tags": ["healthcare", "hl7", "express", "injection"],
        "metadata": {"domain": "Healthcare", "input_source": "request_body", "auth_required": False},
    },
    # ================================================================== KUBERNETES ==================================================================
    {
        "id": "SCP-000097",
        "language": "YAML",
        "framework": "Kubernetes",
        "title": "Container running as root with privileged",
        "description": "A Kubernetes Pod manifest runs as root with privileged: true, enabling host escape.",
        "owasp": "A05:2021 - Security Misconfiguration",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-250",
        "mitre_attack": "T1611 - Escape to Host",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "apiVersion: v1\n"
            "kind: Pod\n"
            "spec:\n"
            "  containers:\n"
            "  - name: app\n"
            "    image: app:1.0\n"
            "    securityContext:\n"
            "      privileged: true   # Vulnerable\n"
            "      runAsUser: 0       # Vulnerable: root\n"
        ),
        "secure_code": (
            "apiVersion: v1\n"
            "kind: Pod\n"
            "spec:\n"
            "  securityContext:\n"
            "    runAsNonRoot: true\n"
            "    runAsUser: 1000\n"
            "    seccompProfile:\n"
            "      type: RuntimeDefault\n"
            "  containers:\n"
            "  - name: app\n"
            "    image: app:1.0\n"
            "    securityContext:\n"
            "      allowPrivilegeEscalation: false\n"
            "      readOnlyRootFilesystem: true\n"
            "      capabilities:\n"
            "        drop: [\"ALL\"]\n"
        ),
        "patch": (
            "--- a/pod.yaml\n"
            "+++ b/pod.yaml\n"
            "@@ -3,7 +3,14 @@\n"
            "-    securityContext:\n"
            "-      privileged: true\n"
            "-      runAsUser: 0\n"
            "+  securityContext:\n"
            "+    runAsNonRoot: true\n"
            "+    runAsUser: 1000\n"
            "+    seccompProfile:\n"
            "+      type: RuntimeDefault\n"
            "+    securityContext:\n"
            "+      allowPrivilegeEscalation: false\n"
            "+      readOnlyRootFilesystem: true\n"
            "+      capabilities: { drop: [\"ALL\"] }\n"
        ),
        "root_cause": "Privileged root containers can escape to the node via the kernel.",
        "attack": "A compromised container mounts /host and reads node secrets or pivots.",
        "impact": "Full node/cluster compromise.",
        "fix": "Run as non-root, drop capabilities, disable privilege escalation, use seccomp.",
        "guideline": "Apply Pod Security Standards; never run privileged/root in prod.",
        "tags": ["kubernetes", "privilege", "yaml", "container"],
        "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False},
    },
    {
        "id": "SCP-000098",
        "language": "YAML",
        "framework": "Kubernetes",
        "title": "Missing NetworkPolicy allows lateral movement",
        "description": "A namespace has no NetworkPolicy, so any pod can reach any other pod (including the DB).",
        "owasp": "A05:2021 - Security Misconfiguration",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-923",
        "mitre_attack": "T1021 - Remote Services",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "# Vulnerable: no NetworkPolicy -> flat network\n"
            "apiVersion: v1\n"
            "kind: Service\n"
            "metadata:\n"
            "  name: db\n"
        ),
        "secure_code": (
            "apiVersion: networking.k8s.io/v1\n"
            "kind: NetworkPolicy\n"
            "metadata:\n"
            "  name: default-deny\n"
            "spec:\n"
            "  podSelector: {}\n"
            "  policyTypes: [Ingress, Egress]\n"
            "---\n"
            "apiVersion: networking.k8s.io/v1\n"
            "kind: NetworkPolicy\n"
            "metadata:\n"
            "  name: allow-app-to-db\n"
            "spec:\n"
            "  podSelector:\n"
            "    matchLabels: { app: db }\n"
            "  ingress:\n"
            "  - from:\n"
            "    - podSelector:\n"
            "        matchLabels: { app: api }\n"
        ),
        "patch": (
            "--- a/networkpolicy.yaml\n"
            "+++ b/networkpolicy.yaml\n"
            "@@ -1,5 +1,23 @@\n"
            "+apiVersion: networking.k8s.io/v1\n"
            "+kind: NetworkPolicy\n"
            "+metadata: { name: default-deny }\n"
            "+spec:\n"
            "+  podSelector: {}\n"
            "+  policyTypes: [Ingress, Egress]\n"
            "+---\n"
            "+kind: NetworkPolicy\n"
            "+metadata: { name: allow-app-to-db }\n"
            "+spec:\n"
            "+  podSelector: { matchLabels: { app: db } }\n"
            "+  ingress:\n"
            "+  - from:\n"
            "+    - podSelector: { matchLabels: { app: api } }\n"
        ),
        "root_cause": "Absence of NetworkPolicy leaves pod-to-pod traffic unrestricted.",
        "attack": "A compromised web pod connects directly to the database pod.",
        "impact": "Lateral movement, data access.",
        "fix": "Apply default-deny and explicit allow policies between tiers.",
        "guideline": "Use NetworkPolicies to segment pod traffic by tier.",
        "tags": ["kubernetes", "network", "yaml", "segmentation"],
        "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False},
    },
    {
        "id": "SCP-000099",
        "language": "YAML",
        "framework": "Kubernetes",
        "title": "Image pulled from unpinned tag (latest)",
        "description": "A Deployment references an image by mutable :latest tag, enabling supply-chain drift.",
        "owasp": "A08:2021 - Software and Data Integrity Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-494",
        "mitre_attack": "T1195.001 - Supply Chain Compromise: Compromise Software Dependencies",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "spec:\n"
            "  containers:\n"
            "  - name: app\n"
            "    image: registry/app:latest   # Vulnerable: mutable tag\n"
        ),
        "secure_code": (
            "spec:\n"
            "  containers:\n"
            "  - name: app\n"
            "    image: registry/app@sha256:9f86d0818...   # Secure: digest-pinned\n"
            "    imagePullPolicy: IfNotPresent\n"
        ),
        "patch": (
            "--- a/deploy.yaml\n"
            "+++ b/deploy.yaml\n"
            "@@ -3,4 +3,5 @@\n"
            "-    image: registry/app:latest\n"
            "+    image: registry/app@sha256:9f86d0818...\n"
            "+    imagePullPolicy: IfNotPresent\n"
        ),
        "root_cause": "Mutable image tags let an attacker-controlled rebuild run as the same deployment.",
        "attack": "Attacker pushes a malicious :latest; the next rollout runs it.",
        "impact": "Supply-chain compromise of workloads.",
        "fix": "Pin images by immutable digest and verify signatures (cosign).",
        "guideline": "Pin images by sha256 digest; sign and verify with cosign.",
        "tags": ["kubernetes", "supply-chain", "yaml", "image"],
        "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False},
    },
    {
        "id": "SCP-000100",
        "language": "Go",
        "framework": "Kubernetes Operator",
        "title": "Operator grants excessive RBAC",
        "description": "A Kubernetes operator's ClusterRole grants wildcard verbs/resources, violating least privilege.",
        "owasp": "A05:2021 - Security Misconfiguration",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-269",
        "mitre_attack": "T1078 - Valid Accounts",
        "severity": "High",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "rules:\n"
            "- apiGroups: [\"*\"]\n"
            "  resources: [\"*\"]      # Vulnerable: wildcard\n"
            "  verbs: [\"*\"]          # Vulnerable: all verbs\n"
        ),
        "secure_code": (
            "rules:\n"
            "- apiGroups: [\"app.example.com\"]\n"
            "  resources: [\"widgets\", \"widgets/status\"]\n"
            "  verbs: [\"get\", \"list\", \"watch\", \"update\", \"patch\"]\n"
        ),
        "patch": (
            "--- a/role.yaml\n"
            "+++ b/role.yaml\n"
            "@@ -1,5 +1,5 @@\n"
            "-  resources: [\"*\"]\n"
            "-  verbs: [\"*\"]\n"
            "+  resources: [\"widgets\", \"widgets/status\"]\n"
            "+  verbs: [\"get\", \"list\", \"watch\", \"update\", \"patch\"]\n"
        ),
        "root_cause": "Wildcard RBAC grants far more than the operator needs.",
        "attack": "A compromised operator can read secrets cluster-wide or delete workloads.",
        "impact": "Cluster-wide privilege escalation.",
        "fix": "Scope RBAC to specific API groups/resources/verbs; avoid wildcards.",
        "guideline": "Apply least-privilege RBAC; never use wildcard resources/verbs.",
        "tags": ["kubernetes", "rbac", "go", "least-privilege"],
        "metadata": {"domain": "Microservices", "input_source": "manifest", "auth_required": False},
    },
    {
        "id": "SCP-000101",
        "language": "Python",
        "framework": "Kubernetes Operator",
        "title": "Secret exposed in operator log",
        "description": "An operator logs the full resource spec including a Secret reference's literal value.",
        "owasp": "A09:2021 - Security Logging and Monitoring Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-532",
        "mitre_attack": "T1562.001 - Impair Defenses",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def reconcile(req):\n"
            "    # Vulnerable: logs secret contents\n"
            "    logging.info('spec=%s', req.obj['spec'])\n"
        ),
        "secure_code": (
            "SENSITIVE = {'password', 'token', 'secret'}\n"
            "def _redact(spec):\n"
            "    return {k: '***' if k.lower() in SENSITIVE else v for k, v in spec.items()}\n"
            "def reconcile(req):\n"
            "    logging.info('spec=%s', _redact(req.obj['spec']))\n"
        ),
        "patch": (
            "--- a/operator.py\n"
            "+++ b/operator.py\n"
            "@@ -1,3 +1,6 @@\n"
            "-    logging.info('spec=%s', req.obj['spec'])\n"
            "+    def _redact(spec):\n"
            "+        return {k: '***' if k.lower() in SENSITIVE else v for k, v in spec.items()}\n"
            "+    logging.info('spec=%s', _redact(req.obj['spec']))\n"
        ),
        "root_cause": "Full resource specs containing secrets are written to logs.",
        "attack": "Anyone with log access reads secret values.",
        "impact": "Secret disclosure.",
        "fix": "Redact sensitive fields before logging; never log secrets.",
        "guideline": "Redact secrets in all logs; scrub sensitive keys.",
        "tags": ["kubernetes", "logging", "python", "secrets"],
        "metadata": {"domain": "Microservices", "input_source": "request_body", "auth_required": False},
    },
    # ================================================================== IoT ==================================================================
    {
        "id": "SCP-000102",
        "language": "C",
        "framework": "Embedded",
        "title": "Hardcoded WiFi credentials in firmware",
        "description": "An embedded IoT firmware stores WiFi credentials as string literals in flash.",
        "owasp": "A02:2021 - Cryptographic Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-798",
        "mitre_attack": "T1552.001 - Unsecured Credentials: Credentials In Files",
        "severity": "High",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "const char *SSID = \"HomeNet\";\n"
            "const char *PSK = \"password123\";  // Vulnerable: hardcoded\n"
        ),
        "secure_code": (
            "char ssid[33], psk[64];\n"
            "// Secure: load from secure element / provisioning at first boot\n"
            "if (load_credentials(ssid, psk) != 0) {\n"
            "    enter_provisioning_mode();\n"
            "}\n"
        ),
        "patch": (
            "--- a/wifi.c\n"
            "+++ b/wifi.c\n"
            "@@ -1,3 +1,6 @@\n"
            "-const char *SSID = \"HomeNet\";\n"
            "-const char *PSK = \"password123\";\n"
            "+char ssid[33], psk[64];\n"
            "+if (load_credentials(ssid, psk) != 0) {\n"
            "+    enter_provisioning_mode();\n"
            "+}\n"
        ),
        "root_cause": "Credentials compiled into firmware are recoverable by dumping flash.",
        "attack": "Attacker extracts the firmware and reads the WiFi PSK for network access.",
        "impact": "Network compromise via recovered credentials.",
        "fix": "Store credentials in a secure element; provision at first boot.",
        "guideline": "Never store secrets in firmware; use secure provisioning.",
        "tags": ["iot", "c", "secrets", "firmware"],
        "metadata": {"domain": "IoT", "input_source": "source_code", "auth_required": False},
    },
    {
        "id": "SCP-000103",
        "language": "C",
        "framework": "Embedded",
        "title": "Unauthenticated MQTT control topic",
        "description": "An IoT device subscribes to a control topic without auth, allowing remote actuation.",
        "owasp": "A01:2021 - Broken Access Control",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-306",
        "mitre_attack": "T0883 - Internet Accessible Device",
        "severity": "Critical",
        "difficulty": "Intermediate",
        "vulnerable_code": (
            "void on_message(char *topic, char *payload) {\n"
            "    // Vulnerable: no auth on control topic\n"
            "    if (strcmp(topic, \"device/cmd\") == 0) actuate(payload);\n"
            "}\n"
        ),
        "secure_code": (
            "void on_message(char *topic, char *payload, mqtt_conn *c) {\n"
            "    // Secure: require authenticated client + signed command\n"
            "    if (!c->authenticated) return;\n"
            "    if (strcmp(topic, \"device/cmd\") == 0 && verify_sig(payload, c->pubkey))\n"
            "        actuate(payload);\n"
            "}\n"
        ),
        "patch": (
            "--- a/mqtt.c\n"
            "+++ b/mqtt.c\n"
            "@@ -1,4 +1,7 @@\n"
            "-    if (strcmp(topic, \"device/cmd\") == 0) actuate(payload);\n"
            "+    if (!c->authenticated) return;\n"
            "+    if (strcmp(topic, \"device/cmd\") == 0 && verify_sig(payload, c->pubkey))\n"
            "+        actuate(payload);\n"
        ),
        "root_cause": "Control commands are accepted from any client without authentication or integrity.",
        "attack": "Attacker publishes to device/cmd to unlock doors or change settings.",
        "impact": "Physical safety/security compromise.",
        "fix": "Require authenticated, signed commands over TLS MQTT.",
        "guideline": "Authenticate and sign IoT control commands; use MQTT over TLS.",
        "tags": ["iot", "c", "mqtt", "auth"],
        "metadata": {"domain": "IoT", "input_source": "network", "auth_required": True},
    },
    {
        "id": "SCP-000104",
        "language": "Python",
        "framework": "MicroPython",
        "title": "Telnet exposed without authentication on device",
        "description": "An IoT gateway starts a Telnet server with no auth, giving root shell access.",
        "owasp": "A07:2021 - Identification and Authentication Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-306",
        "mitre_attack": "T1021 - Remote Services",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "import utelnet\n"
            "# Vulnerable: telnet with no auth\n"
            "utelnet.start(port=23, login=None, password=None)\n"
        ),
        "secure_code": (
            "import ussl, socket\n"
            "# Secure: SSH/TLS with key auth only\n"
            "server = socket.socket()\n"
            "server = ussl.wrap_socket(server, keyfile='dev.key', certfile='dev.crt')\n"
            "server.bind(('', 22))\n"
            "server.listen(1)\n"
        ),
        "patch": (
            "--- a/shell.py\n"
            "+++ b/shell.py\n"
            "@@ -1,4 +1,8 @@\n"
            "-utelnet.start(port=23, login=None, password=None)\n"
            "+server = socket.socket()\n"
            "+server = ussl.wrap_socket(server, keyfile='dev.key', certfile='dev.crt')\n"
            "+server.bind(('', 22))\n"
            "+server.listen(1)\n"
        ),
        "root_cause": "An unauthenticated Telnet server exposes a root shell on the LAN.",
        "attack": "Anyone on the network connects and gains full device control.",
        "impact": "Complete device compromise.",
        "fix": "Disable Telnet; use SSH/TLS with key-based auth.",
        "guideline": "Never expose unauthenticated shells; use SSH/TLS with keys.",
        "tags": ["iot", "python", "telnet", "auth"],
        "metadata": {"domain": "IoT", "input_source": "network", "auth_required": True},
    },
    {
        "id": "SCP-000105",
        "language": "C",
        "framework": "Embedded",
        "title": "Lack of firmware signature verification",
        "description": "An IoT bootloader flashes any uploaded firmware without verifying a signature.",
        "owasp": "A08:2021 - Software and Data Integrity Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-494",
        "mitre_attack": "T1195.002 - Supply Chain Compromise: Compromise Software Supply Chain",
        "severity": "Critical",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "void flash(const uint8_t *img, size_t len) {\n"
            "    // Vulnerable: no signature check\n"
            "    write_to_flash(img, len);\n"
            "}\n"
        ),
        "secure_code": (
            "void flash(const uint8_t *img, size_t len) {\n"
            "    // Secure: verify ECDSA signature with root public key\n"
            "    if (!ecdsa_verify(ROOT_PUB, img, len - 64, img + len - 64))\n"
            "        return;\n"
            "    write_to_flash(img, len - 64);\n"
            "}\n"
        ),
        "patch": (
            "--- a/bootloader.c\n"
            "+++ b/bootloader.c\n"
            "@@ -1,4 +1,7 @@\n"
            "-    write_to_flash(img, len);\n"
            "+    if (!ecdsa_verify(ROOT_PUB, img, len - 64, img + len - 64))\n"
            "+        return;\n"
            "+    write_to_flash(img, len - 64);\n"
        ),
        "root_cause": "Firmware is flashed without verifying a trusted signature, enabling malicious images.",
        "attack": "Attacker uploads a trojaned firmware that persists on the device.",
        "impact": "Persistent device compromise, botnet recruitment.",
        "fix": "Verify firmware signatures (ECDSA) against a rooted public key before flashing.",
        "guideline": "Verify signed firmware; reject unsigned/modified images.",
        "tags": ["iot", "c", "firmware", "supply-chain"],
        "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False},
    },
    {
        "id": "SCP-000106",
        "language": "Python",
        "framework": "IoT Gateway",
        "title": "Default credentials on management API",
        "description": "An IoT gateway API accepts a hardcoded default admin password.",
        "owasp": "A07:2021 - Identification and Authentication Failures",
        "owasp_api": "API2:2023 - Broken Authentication",
        "owasp_llm": "",
        "cwe": "CWE-1392",
        "mitre_attack": "T1078.001 - Valid Accounts: Default Accounts",
        "severity": "Critical",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "def login(u, p):\n"
            "    # Vulnerable: default password\n"
            "    if u == 'admin' and p == 'admin':\n"
            "        return issue_token(u)\n"
        ),
        "secure_code": (
            "def login(u, p):\n"
            "    user = db.get_user(u)\n"
            "    if user and argon2.verify(p, user.pw_hash):\n"
            "        if not user.force_reset:\n"
            "            return issue_token(u)\n"
            "    return None\n"
        ),
        "patch": (
            "--- a/auth.py\n"
            "+++ b/auth.py\n"
            "@@ -1,5 +1,7 @@\n"
            "-    if u == 'admin' and p == 'admin':\n"
            "-        return issue_token(u)\n"
            "+    user = db.get_user(u)\n"
            "+    if user and argon2.verify(p, user.pw_hash):\n"
            "+        return issue_token(u)\n"
        ),
        "root_cause": "A static default credential grants trivial admin access.",
        "attack": "Attacker logs in as admin with 'admin'/'admin'.",
        "impact": "Full device/gateway takeover.",
        "fix": "Store hashed credentials; force password change on first login; no defaults.",
        "guideline": "No default credentials; use hashed passwords and forced reset.",
        "tags": ["iot", "python", "default-creds", "auth"],
        "metadata": {"domain": "IoT", "input_source": "form_field", "auth_required": False},
    },
    {
        "id": "SCP-000107",
        "language": "C",
        "framework": "Embedded",
        "title": "Stack-based buffer overflow in HTTP header parse",
        "description": "An embedded web server copies a header value into a fixed stack buffer without bounds.",
        "owasp": "A03:2021 - Injection",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-120",
        "mitre_attack": "T1203 - Exploitation for Client Execution",
        "severity": "Critical",
        "difficulty": "Advanced",
        "vulnerable_code": (
            "void parse_header(char *line) {\n"
            "    char val[64];\n"
            "    // Vulnerable: strcpy from attacker input\n"
            "    strcpy(val, strchr(line, ':') + 1);\n"
            "}\n"
        ),
        "secure_code": (
            "void parse_header(char *line) {\n"
            "    char val[64];\n"
            "    char *v = strchr(line, ':') + 1;\n"
            "    // Secure: bounded copy\n"
            "    strncpy(val, v, sizeof(val) - 1);\n"
            "    val[sizeof(val) - 1] = '\\0';\n"
            "}\n"
        ),
        "patch": (
            "--- a/httpd.c\n"
            "+++ b/httpd.c\n"
            "@@ -3,4 +3,6 @@\n"
            "-    strcpy(val, strchr(line, ':') + 1);\n"
            "+    char *v = strchr(line, ':') + 1;\n"
            "+    strncpy(val, v, sizeof(val) - 1);\n"
            "+    val[sizeof(val) - 1] = '\\0';\n"
        ),
        "root_cause": "strcpy into a fixed buffer allows overflow with a long header value.",
        "attack": "Send a huge header to overflow the stack and hijack execution.",
        "impact": "Remote code execution on the device.",
        "fix": "Use bounded copies (strncpy + NUL) or length-checked parsers.",
        "guideline": "Avoid strcpy; bound all copies; compile with stack protectors.",
        "tags": ["iot", "c", "buffer-overflow", "http"],
        "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False},
    },
    {
        "id": "SCP-000108",
        "language": "C++",
        "framework": "Embedded",
        "title": "Unencrypted telemetry transmission",
        "description": "An IoT device sends sensor telemetry over plain HTTP, exposing it to interception.",
        "owasp": "A02:2021 - Cryptographic Failures",
        "owasp_api": "",
        "owasp_llm": "",
        "cwe": "CWE-319",
        "mitre_attack": "T1557 - Adversary-in-the-Middle",
        "severity": "Medium",
        "difficulty": "Beginner",
        "vulnerable_code": (
            "void send_telemetry(const std::string& data) {\n"
            "    // Vulnerable: plain HTTP\n"
            "    http_post(\"http://collector/ingest\", data);\n"
            "}\n"
        ),
        "secure_code": (
            "void send_telemetry(const std::string& data) {\n"
            "    // Secure: HTTPS with cert pinning\n"
            "    https_post(\"https://collector/ingest\", data, COLLECTOR_PINNED_CERT);\n"
            "}\n"
        ),
        "patch": (
            "--- a/telemetry.cpp\n"
            "+++ b/telemetry.cpp\n"
            "@@ -2,4 +2,5 @@\n"
            "-    http_post(\"http://collector/ingest\", data);\n"
            "+    https_post(\"https://collector/ingest\", data, COLLECTOR_PINNED_CERT);\n"
        ),
        "root_cause": "Telemetry is transmitted without transport encryption, exposing data in transit.",
        "attack": "On-path attacker reads sensor data or injects false telemetry.",
        "impact": "Data interception/modification.",
        "fix": "Use TLS with certificate pinning for all device communication.",
        "guideline": "Encrypt all device telemetry with TLS + cert pinning.",
        "tags": ["iot", "cpp", "tls", "telemetry"],
        "metadata": {"domain": "IoT", "input_source": "network", "auth_required": False},
    },
]