File size: 33,844 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
#!/usr/bin/env python3
"""SecureCodePairs v1.2.0 extension records (part 7): cross-language deepen (SCP-000241+).

Deepens Ruby/C/C++/Scala/Go/JS/TS/C#/PHP/Rust/Kotlin/Swift/YAML with more
classes and domains. Built with json-safe helpers.
"""
import json
from typing import List, Dict

L: List[Dict] = []


def rec(**kw):
    L.append(kw)


# ---------------- Ruby (SCP-000241 - 000255) ----------------
rec(id="SCP-000241", language="Ruby", framework="Rails",
    title="Mass assignment via update_attributes",
    description="A Rails controller updates all params including admin flag.",
    owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
    cwe="CWE-915", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="High", difficulty="Beginner",
    vulnerable_code='def update\n  @user.update_attributes(params[:user])  # Vulnerable: binds admin\nend',
    secure_code='def update\n  @user.update_attributes(params.require(:user).permit(:name, :email))  # Secure\nend',
    patch='--- a/users_controller.rb\n+++ b/users_controller.rb\n@@ -1,3 +1,3 @@\n-def update\n  @user.update_attributes(params[:user])\n+  @user.update_attributes(params.require(:user).permit(:name, :email))\n end',
    root_cause="All params bound to model.",
    attack="POST user[admin]=1 escalates.", impact="Privilege escalation.",
    fix="Use strong parameters.", guideline="Always permit explicit params.",
    tags=["mass-assignment", "rails", "ruby", "auth"],
    metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True})

rec(id="SCP-000242", language="Ruby", framework="Rails",
    title="Command injection via backticks",
    description="A Rails task runs a shell command via backticks with user input.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-78", mitre_attack="T1059 - Command and Scripting Interpreter",
    severity="High", difficulty="Beginner",
    vulnerable_code='def ping(host)\n  `\u0060ping -c1 #{host}\u0060`  # Vulnerable: shell interpolation\nend',
    secure_code='def ping(host)\n  raise "bad host" unless host.match?(/\\A[\\w.-]+\\z/)\n  system("ping", "-c1", host)  # Secure: arg array\nend',
    patch='--- a/ping.rb\n+++ b/ping.rb\n@@ -1,3 +1,4 @@\n-def ping(host)\n  `\u0060ping -c1 #{host}\u0060`\n+  raise "bad host" unless host.match?(/\\A[\\w.-]+\\z/)\n+  system("ping", "-c1", host)',
    root_cause="Shell interpolation of user input.",
    attack="host=;cat /etc/passwd executes.", impact="Command injection.",
    fix="Use system() with arg array.",
    guideline="Avoid shell interpolation in Ruby.",
    tags=["command-injection", "rails", "ruby", "rce"],
    metadata={"domain": "IoT", "input_source": "query_param", "auth_required": False})

rec(id="SCP-000243", language="Ruby", framework="Rails",
    title="Insecure comparison of session token",
    description="A Rails app compares tokens with == allowing timing attacks.",
    owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
    cwe="CWE-208", mitre_attack="T1600 - Weaken Encryption",
    severity="Low", difficulty="Intermediate",
    vulnerable_code='def valid?(t); t == session[:token]; end  # Vulnerable: timing',
    secure_code='def valid?(t)\n  ActiveSupport::SecurityUtils.secure_compare(t, session[:token])  # Secure\nend',
    patch='--- a/session.rb\n+++ b/session.rb\n@@ -1,2 +1,3 @@\n-def valid?(t); t == session[:token]; end\n+def valid?(t)\n+  ActiveSupport::SecurityUtils.secure_compare(t, session[:token])\n+end',
    root_cause="Non-constant-time comparison.",
    attack="Brute-force token via timing.", impact="Token recovery.",
    fix="Use secure_compare.", guideline="Use constant-time comparison.",
    tags=["crypto", "rails", "ruby", "timing"],
    metadata={"domain": "Authentication systems", "input_source": "cookie", "auth_required": False})

rec(id="SCP-000244", language="Ruby", framework="Rails",
    title="Path traversal in send_file",
    description="A Rails controller serves a file from a user path.",
    owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
    cwe="CWE-22", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="High", difficulty="Intermediate",
    vulnerable_code='def download\n  send_file("/uploads/#{params[:name]}")  # Vulnerable: traversal\nend',
    secure_code='def download\n  name = File.basename(params[:name])\n  path = Rails.root.join("uploads", name)\n  raise "no" unless path.to_s.start_with?(Rails.root.join("uploads").to_s)\n  send_file(path)  # Secure\nend',
    patch='--- a/files_controller.rb\n+++ b/files_controller.rb\n@@ -1,3 +1,6 @@\n-def download\n  send_file("/uploads/#{params[:name]}")\n+  name = File.basename(params[:name])\n+  path = Rails.root.join("uploads", name)\n+  raise "no" unless path.to_s.start_with?(Rails.root.join("uploads").to_s)\n+  send_file(path)',
    root_cause="Unsanitized filename joined to path.",
    attack="name=../../config/secrets.yml reads secret.", impact="File disclosure.",
    fix="Basename + confine to base.", guideline="Confine file paths.",
    tags=["path-traversal", "rails", "ruby", "file-read"],
    metadata={"domain": "Backend", "input_source": "query_param", "auth_required": False})

rec(id="SCP-000245", language="Ruby", framework="Rails",
    title="SQL injection in find_by with raw SQL",
    description="A Rails model uses a raw SQL fragment with user input.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-89", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="High", difficulty="Intermediate",
    vulnerable_code='def self.search(q)\n  where("name LIKE \u0027%#{q}%\u0027")  # Vulnerable\nend',
    secure_code='def self.search(q)\n  where("name LIKE ?", "%#{q}%")  # Secure: bound\nend',
    patch='--- a/user.rb\n+++ b/user.rb\n@@ -1,3 +1,3 @@\n-def self.search(q)\n  where("name LIKE \u0027%#{q}%\u0027")\n+  where("name LIKE ?", "%#{q}%")',
    root_cause="String interpolation into SQL.",
    attack="q=%\u0027 OR 1=1 leaks rows.", impact="Data disclosure.",
    fix="Use bound params.", guideline="Bind all SQL params.",
    tags=["sqli", "rails", "ruby", "injection"],
    metadata={"domain": "E-commerce", "input_source": "query_param", "auth_required": False})

rec(id="SCP-000246", language="Ruby", framework="Rails",
    title="Open redirect in redirect_to",
    description="A Rails action redirects to a param without validation.",
    owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
    cwe="CWE-601", mitre_attack="T1566 - Phishing",
    severity="Medium", difficulty="Beginner",
    vulnerable_code='def go\n  redirect_to params[:url]  # Vulnerable\nend',
    secure_code='def go\n  url = params[:url]\n  redirect_to (url if url&.start_with?("/")) || root_path  # Secure\nend',
    patch='--- a/links_controller.rb\n+++ b/links_controller.rb\n@@ -1,3 +1,4 @@\n-def go\n  redirect_to params[:url]\n+  url = params[:url]\n+  redirect_to (url if url&.start_with?("/")) || root_path',
    root_cause="Unvalidated redirect target.",
    attack="url=//evil.com phishing.", impact="Phishing.",
    fix="Allowlist relative paths.", guideline="Validate redirects.",
    tags=["open-redirect", "rails", "ruby", "phishing"],
    metadata={"domain": "Authentication systems", "input_source": "query_param", "auth_required": False})

rec(id="SCP-000247", language="Ruby", framework="Rails",
    title="Weak secret token in secrets.yml",
    description="A Rails app commits a static secret_key_base.",
    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='production:\n  secret_key_base: "abc123static"  # Vulnerable',
    secure_code='production:\n  secret_key_base: "<%= ENV["SECRET_KEY_BASE"] %>"  # Secure: env',
    patch='--- a/config/secrets.yml\n+++ b/config/secrets.yml\n@@ -1,3 +1,3 @@\n-production:\n  secret_key_base: "abc123static"\n+production:\n  secret_key_base: "<%= ENV["SECRET_KEY_BASE"] %>"',
    root_cause="Static secret in repo.",
    attack="Forge signed cookies.", impact="Auth bypass.",
    fix="Load from env/secret.", guideline="Externalize secret_key_base.",
    tags=["secrets", "rails", "ruby", "config"],
    metadata={"domain": "Backend", "input_source": "source_code", "auth_required": False})

rec(id="SCP-000248", language="Ruby", framework="Rails",
    title="Cross-site scripting in raw HTML",
    description="A Rails view renders a param with raw().",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-79", mitre_attack="T1059.007 - Command and Scripting Interpreter: JavaScript",
    severity="Medium", difficulty="Beginner",
    vulnerable_code='<div><%= raw(@comment) %></div>  <!-- Vulnerable: unescaped -->',
    secure_code='<div><%= @comment %></div>  <!-- Secure: escaped -->',
    patch='--- a/show.html.erb\n+++ b/show.html.erb\n@@ -1,2 +1,2 @@\n-<div><%= raw(@comment) %></div>\n+<div><%= @comment %></div>',
    root_cause="raw() disables escaping.",
    attack="comment=<script>steal()</script> runs.", impact="XSS.",
    fix="Use default escaping.", guideline="Avoid raw() on user input.",
    tags=["xss", "rails", "ruby", "template"],
    metadata={"domain": "E-commerce", "input_source": "db", "auth_required": False})

rec(id="SCP-000249", language="Ruby", framework="Rails",
    title="IDOR on message read",
    description="A Rails action returns a message by id without owner check.",
    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="High", difficulty="Beginner",
    vulnerable_code='def show\n  @msg = Message.find(params[:id])  # Vulnerable: no owner\nend',
    secure_code='def show\n  @msg = current_user.messages.find(params[:id])  # Secure: scoped\nend',
    patch='--- a/messages_controller.rb\n+++ b/messages_controller.rb\n@@ -1,3 +1,3 @@\n-def show\n  @msg = Message.find(params[:id])\n+  @msg = current_user.messages.find(params[:id])',
    root_cause="No ownership scoping on read.",
    attack="Enumerator reads others messages.", impact="PII disclosure.",
    fix="Scope by owner.", guideline="Scope reads by owner.",
    tags=["idor", "rails", "ruby", "access-control"],
    metadata={"domain": "E-commerce", "input_source": "path_param", "auth_required": True})

rec(id="SCP-000250", language="Ruby", framework="Rails",
    title="No rate limit on password reset",
    description="A Rails reset has no throttle, enabling enumeration.",
    owasp="A07:2021 - Identification and Authentication Failures", owasp_api="API4:2023 - Unrestricted Resource Consumption", owasp_llm="",
    cwe="CWE-307", mitre_attack="T1110 - Brute Force",
    severity="Medium", difficulty="Beginner",
    vulnerable_code='def create\n  User.send_reset(params[:email])  # Vulnerable: no throttle\n  redirect_to root_path\nend',
    secure_code='def create\n  if rate_limited?("reset", request.ip); render status: 429; return; end\n  User.send_reset(params[:email])\n  redirect_to root_path\nend',
    patch='--- a/passwords_controller.rb\n+++ b/passwords_controller.rb\n@@ -1,4 +1,6 @@\n-def create\n  User.send_reset(params[:email])\n+  if rate_limited?("reset", request.ip); render status: 429; return; end\n+  User.send_reset(params[:email])\n  redirect_to root_path',
    root_cause="No throttle on reset.",
    attack="Mass reset emails; enumerate.", impact="Abuse, enumeration.",
    fix="Rate limit reset.", guideline="Throttle password reset.",
    tags=["rate-limiting", "rails", "ruby", "auth"],
    metadata={"domain": "Authentication systems", "input_source": "request_body", "auth_required": False})

rec(id="SCP-000251", language="Ruby", framework="Rails",
    title="CSRF protection disabled",
    description="A Rails controller skips CSRF for a state-changing action.",
    owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
    cwe="CWE-352", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="Medium", difficulty="Beginner",
    vulnerable_code='class ApiController < ApplicationController\n  skip_before_action :verify_authenticity_token  # Vulnerable\nend',
    secure_code='class ApiController < ApplicationController\n  protect_from_forgery with: :exception  # Secure\nend',
    patch='--- a/api_controller.rb\n+++ b/api_controller.rb\n@@ -1,3 +1,3 @@\n-class ApiController < ApplicationController\n  skip_before_action :verify_authenticity_token\n+  protect_from_forgery with: :exception',
    root_cause="CSRF skipping on mutating action.",
    attack="Cross-site POST forges change.", impact="Unauthorized action.",
    fix="Keep CSRF protection.", guideline="Don't skip CSRF on state changes.",
    tags=["csrf", "rails", "ruby", "config"],
    metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})

rec(id="SCP-000252", language="Ruby", framework="Rails",
    title="Business logic: integer overflow in points",
    description="A Rails service adds loyalty points without overflow guard.",
    owasp="A04:2021 - Insecure Design", owasp_api="API3:2023 - Broken Object Property Level Authorization", owasp_llm="",
    cwe="CWE-190", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="Medium", difficulty="Intermediate",
    vulnerable_code='def add_points(u, n)\n  u.points += n  # Vulnerable: wraps at max\nend',
    secure_code='def add_points(u, n)\n  u.points = [u.points + n, MAX_POINTS].min  # Secure: cap\nend',
    patch='--- a/loyalty.rb\n+++ b/loyalty.rb\n@@ -1,3 +1,3 @@\n-def add_points(u, n)\n  u.points += n\n+  u.points = [u.points + n, MAX_POINTS].min',
    root_cause="Unbounded integer addition.",
    attack="Add huge n to overflow to small.", impact="Logic abuse.",
    fix="Cap accumulators.", guideline="Validate numeric bounds.",
    tags=["business-logic", "rails", "ruby", "overflow"],
    metadata={"domain": "E-commerce", "input_source": "request_body", "auth_required": True})

rec(id="SCP-000253", language="Ruby", framework="Rails",
    title="Insecure random with rand",
    description="A Rails token generator uses Kernel.rand.",
    owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
    cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
    severity="High", difficulty="Intermediate",
    vulnerable_code='def token\n  SecureRandom.base64(16)  # vulnerable if SecureRandom not loaded\nend',
    secure_code='require "securerandom"\ndef token\n  SecureRandom.urlsafe_base64(24)  # Secure: CSPRNG\nend',
    patch='--- a/token.rb\n+++ b/token.rb\n@@ -1,3 +1,4 @@\n-def token\n  SecureRandom.base64(16)\n+require "securerandom"\n+def token\n+  SecureRandom.urlsafe_base64(24)',
    root_cause="Non-CSPRNG token (or missing require).",
    attack="Predict token values.", impact="Token forgery.",
    fix="Use SecureRandom always.", guideline="Use CSPRNG for tokens.",
    tags=["crypto", "rails", "ruby", "tokens"],
    metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False})

rec(id="SCP-000254", language="Ruby", framework="Rails",
    title="File upload without type check",
    description="A Rails upload stores any content type.",
    owasp="A04:2021 - Insecure Design", owasp_api="", owasp_llm="",
    cwe="CWE-434", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="High", difficulty="Intermediate",
    vulnerable_code='def create\n  Upload.create!(file: params[:file])  # Vulnerable: any type\nend',
    secure_code='ALLOWED = %w[image/png image/jpeg].freeze\ndef create\n  raise "bad" unless ALLOWED.include?(params[:file].content_type)\n  Upload.create!(file: params[:file])  # Secure\nend',
    patch='--- a/uploads_controller.rb\n+++ b/uploads_controller.rb\n@@ -1,3 +1,5 @@\n-def create\n  Upload.create!(file: params[:file])\n+  raise "bad" unless ALLOWED.include?(params[:file].content_type)\n+  Upload.create!(file: params[:file])',
    root_cause="No content-type validation.",
    attack="Upload .rb webshell.", impact="RCE.",
    fix="Allowlist types; randomize name.", guideline="Validate upload types.",
    tags=["file-upload", "rails", "ruby", "rce"],
    metadata={"domain": "E-commerce", "input_source": "form_field", "auth_required": True})

rec(id="SCP-000255", language="Ruby", framework="Rails",
    title="Authorization missing on destroy",
    description="A Rails destroy action has no ownership or role check.",
    owasp="A01:2021 - Broken Access Control", owasp_api="API1:2023 - Broken Object Level Authorization", owasp_llm="",
    cwe="CWE-862", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="Critical", difficulty="Beginner",
    vulnerable_code='def destroy\n  Comment.find(params[:id]).destroy  # Vulnerable: anyone\nend',
    secure_code='def destroy\n  Comment.where(id: params[:id], user_id: current_user.id).destroy_all  # Secure\nend',
    patch='--- a/comments_controller.rb\n+++ b/comments_controller.rb\n@@ -1,3 +1,3 @@\n-def destroy\n  Comment.find(params[:id]).destroy\n+  Comment.where(id: params[:id], user_id: current_user.id).destroy_all',
    root_cause="No ownership on delete.",
    attack="Anyone deletes any comment.", impact="Data loss.",
    fix="Scope delete by owner.", guideline="Authorize deletions.",
    tags=["authorization", "rails", "ruby", "broken-access-control"],
    metadata={"domain": "E-commerce", "input_source": "path_param", "auth_required": True})

# ---------------- C (SCP-000256 - 000270) ----------------
rec(id="SCP-000256", language="C", framework="POSIX",
    title="Buffer overflow in strcpy",
    description="A C function copies input with strcpy into a fixed buffer.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-120", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="High", difficulty="Intermediate",
    vulnerable_code='void copy(char *in) {\n  char buf[32];\n  strcpy(buf, in);  // Vulnerable: no bounds\n}',
    secure_code='void copy(char *in) {\n  char buf[32];\n  strncpy(buf, in, sizeof(buf) - 1);  // Secure: bounded\n  buf[sizeof(buf)-1] = \u002700\u0027;\n}',
    patch='--- a/copy.c\n+++ b/copy.c\n@@ -1,4 +1,6 @@\n-  strcpy(buf, in);\n+  strncpy(buf, in, sizeof(buf) - 1);\n+  buf[sizeof(buf)-1] = \u002700\u0027;',
    root_cause="Unbounded copy into stack buffer.",
    attack="Long input overwrites return address.", impact="RCE.",
    fix="Use bounded copies.", guideline="Avoid strcpy; use strncpy/snprintf.",
    tags=["buffer-overflow", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "argv", "auth_required": False})

rec(id="SCP-000257", language="C", framework="POSIX",
    title="Format string vulnerability",
    description="A C program uses user input as a printf format.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-134", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="Medium", difficulty="Intermediate",
    vulnerable_code='void log_msg(char *m) {\n  printf(m);  // Vulnerable: format string\n}',
    secure_code='void log_msg(char *m) {\n  printf("%s", m);  // Secure: positional\n}',
    patch='--- a/log.c\n+++ b/log.c\n@@ -1,3 +1,3 @@\n-  printf(m);\n+  printf("%s", m);',
    root_cause="User input as format.",
    attack="%x.%x reads stack.", impact="Info leak.",
    fix="Use %s positional.", guideline="Never use user input as format.",
    tags=["format-string", "c", "logging"],
    metadata={"domain": "IoT", "input_source": "argv", "auth_required": False})

rec(id="SCP-000258", language="C", framework="POSIX",
    title="Use-after-free",
    description="A C program dereferences memory after free.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-416", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="High", difficulty="Advanced",
    vulnerable_code='void proc() {\n  int *p = malloc(8); *p = 1;\n  free(p);\n  *p = 2;  // Vulnerable: use-after-free\n}',
    secure_code='void proc() {\n  int *p = malloc(8); *p = 1;\n  free(p); p = NULL;  // Secure: null after free\n  if (p) *p = 2;\n}',
    patch='--- a/proc.c\n+++ b/proc.c\n@@ -1,5 +1,6 @@\n-  free(p);\n-  *p = 2;\n+  free(p); p = NULL;\n+  if (p) *p = 2;',
    root_cause="Deref after free.",
    attack="Heap spray / type confusion.", impact="Memory corruption.",
    fix="Null pointers after free.", guideline="Set freed pointers to NULL.",
    tags=["use-after-free", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "internal", "auth_required": False})

rec(id="SCP-000259", language="C", framework="POSIX",
    title="Integer overflow in allocation",
    description="A C function multiplies for allocation size without overflow check.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-190", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="High", difficulty="Advanced",
    vulnerable_code='void *make(size_t n, size_t sz) {\n  return malloc(n * sz);  // Vulnerable: overflow\n}',
    secure_code='void *make(size_t n, size_t sz) {\n  if (n > 0 && sz > 0 && n > SIZE_MAX / sz) return NULL;  // Secure\n  return malloc(n * sz);\n}',
    patch='--- a/make.c\n+++ b/make.c\n@@ -1,3 +1,4 @@\n-  return malloc(n * sz);\n+  if (n > 0 && sz > 0 && n > SIZE_MAX / sz) return NULL;\n+  return malloc(n * sz);',
    root_cause="Unchecked multiplication for size.",
    attack="Trigger small allocation, overflow.", impact="Memory corruption.",
    fix="Check overflow before alloc.", guideline="Validate allocation sizes.",
    tags=["integer-overflow", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "argv", "auth_required": False})

rec(id="SCP-000260", language="C", framework="POSIX",
    title="Double free",
    description="A C program frees the same pointer twice.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-415", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="High", difficulty="Advanced",
    vulnerable_code='void run() {\n  char *p = malloc(16);\n  free(p); free(p);  // Vulnerable: double free\n}',
    secure_code='void run() {\n  char *p = malloc(16);\n  free(p); p = NULL;  // Secure: null after free\n}',
    patch='--- a/run.c\n+++ b/run.c\n@@ -1,4 +1,4 @@\n-  free(p); free(p);\n+  free(p); p = NULL;',
    root_cause="Freeing same pointer twice.",
    attack="Heap corruption / RCE.", impact="Memory corruption.",
    fix="Null after free.", guideline="Avoid double free.",
    tags=["double-free", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "internal", "auth_required": False})

rec(id="SCP-000261", language="C", framework="POSIX",
    title="Command injection via system()",
    description="A C program passes user input to system().",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-78", mitre_attack="T1059 - Command and Scripting Interpreter",
    severity="High", difficulty="Intermediate",
    vulnerable_code='void run(char *f) {\n  char cmd[128];\n  sprintf(cmd, "convert %s out.png", f);\n  system(cmd);  // Vulnerable\n}',
    secure_code='void run(char *f) {\n  if (strpbrk(f, ";|&$\u0027\"") != NULL) return;  // Secure: validate\n  char cmd[128];\n  snprintf(cmd, sizeof cmd, "convert %s out.png", f);\n  system(cmd);\n}',
    patch='--- a/run.c\n+++ b/run.c\n@@ -1,5 +1,7 @@\n-  sprintf(cmd, "convert %s out.png", f);\n-  system(cmd);\n+  if (strpbrk(f, ";|&$\u0027\"") != NULL) return;\n+  snprintf(cmd, sizeof cmd, "convert %s out.png", f);\n+  system(cmd);',
    root_cause="User input into shell command.",
    attack="f=img.png;cat /etc/passwd executes.", impact="Command injection.",
    fix="Validate + avoid system.", guideline="Avoid system() with input.",
    tags=["command-injection", "c", "rce"],
    metadata={"domain": "IoT", "input_source": "argv", "auth_required": False})

rec(id="SCP-000262", language="C", framework="POSIX",
    title="Insecure temporary file",
    description="A C program creates a temp file with a predictable name.",
    owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
    cwe="CWE-377", mitre_attack="T1190 - Exploit Public-Facing Application",
    severity="Medium", difficulty="Intermediate",
    vulnerable_code='void save(char *d) {\n  int fd = open("/tmp/data.txt", O_WRONLY|O_CREAT, 0644);  // Vulnerable: predictable\n  write(fd, d, strlen(d));\n}',
    secure_code='void save(char *d) {\n  char tmpl[] = "/tmp/dataXXXXXX";\n  int fd = mkstemp(tmpl);  // Secure: unpredictable\n  write(fd, d, strlen(d));\n}',
    patch='--- a/save.c\n+++ b/save.c\n@@ -1,4 +1,5 @@\n-  int fd = open("/tmp/data.txt", O_WRONLY|O_CREAT, 0644);\n+  char tmpl[] = "/tmp/dataXXXXXX";\n+  int fd = mkstemp(tmpl);\n  write(fd, d, strlen(d));',
    root_cause="Predictable temp file name.",
    attack="Symlink / pre-create the file.", impact="File tampering.",
    fix="Use mkstemp.", guideline="Use mkstemp for temp files.",
    tags=["temp-file", "c", "file-write"],
    metadata={"domain": "IoT", "input_source": "internal", "auth_required": False})

rec(id="SCP-000263", language="C", framework="POSIX",
    title="Off-by-one in loop copy",
    description="A C loop copies N+1 bytes into an N-byte buffer.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-193", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="Medium", difficulty="Intermediate",
    vulnerable_code='void cp(char *src, char *dst, int n) {\n  for (int i = 0; i <= n; i++) dst[i] = src[i];  // Vulnerable: <= off-by-one\n}',
    secure_code='void cp(char *src, char *dst, int n) {\n  for (int i = 0; i < n; i++) dst[i] = src[i];  // Secure: < not <=\n}',
    patch='--- a/cp.c\n+++ b/cp.c\n@@ -1,3 +1,3 @@\n-  for (int i = 0; i <= n; i++) dst[i] = src[i];\n+  for (int i = 0; i < n; i++) dst[i] = src[i];',
    root_cause="Loop bound off-by-one.",
    attack="Write one byte past buffer.", impact="Memory corruption.",
    fix="Correct loop bounds.", guideline="Audit loop bounds.",
    tags=["off-by-one", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "internal", "auth_required": False})

rec(id="SCP-000264", language="C", framework="POSIX",
    title="Null pointer dereference",
    description="A C function dereferences a pointer that may be NULL.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-476", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="Medium", difficulty="Beginner",
    vulnerable_code='void show(User *u) {\n  printf("%s\\n", u->name);  // Vulnerable: u may be NULL\n}',
    secure_code='void show(User *u) {\n  if (!u) return;  // Secure: NULL check\n  printf("%s\\n", u->name);\n}',
    patch='--- a/show.c\n+++ b/show.c\n@@ -1,3 +1,4 @@\n-  printf("%s\\n", u->name);\n+  if (!u) return;\n+  printf("%s\\n", u->name);',
    root_cause="Missing NULL check.",
    attack="Pass NULL to crash service.", impact="DoS.",
    fix="Check pointers before deref.", guideline="Null-check inputs.",
    tags=["null-deref", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "argv", "auth_required": False})

rec(id="SCP-000265", language="C", framework="POSIX",
    title="Hardcoded credentials in binary",
    description="A C client embeds a password string in source.",
    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 *PW = "admin123";  // Vulnerable: hardcoded',
    secure_code='char *get_pw() { return getenv("APP_PW"); }  // Secure: from env',
    patch='--- a/client.c\n+++ b/client.c\n@@ -1,2 +1,2 @@\n-const char *PW = "admin123";\n+char *get_pw() { return getenv("APP_PW"); }',
    root_cause="Credential in binary.",
    attack="Extract string from binary.", impact="Credential leak.",
    fix="Load from env/secret.", guideline="Externalize credentials.",
    tags=["secrets", "c", "config"],
    metadata={"domain": "IoT", "input_source": "source_code", "auth_required": False})

rec(id="SCP-000266", language="C", framework="POSIX",
    title="Stack buffer overflow via gets",
    description="A C program reads input with gets().",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-120", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="High", difficulty="Beginner",
    vulnerable_code='void read_line() {\n  char buf[64];\n  gets(buf);  // Vulnerable: no bound\n}',
    secure_code='void read_line() {\n  char buf[64];\n  if (fgets(buf, sizeof buf, stdin) == NULL) return;  // Secure: bounded\n}',
    patch='--- a/read.c\n+++ b/read.c\n@@ -1,4 +1,5 @@\n-  char buf[64];\n-  gets(buf);\n+  char buf[64];\n+  if (fgets(buf, sizeof buf, stdin) == NULL) return;',
    root_cause="gets() has no bounds.",
    attack="Overflow stack with long input.", impact="RCE.",
    fix="Use fgets with size.", guideline="Never use gets().",
    tags=["buffer-overflow", "c", "memory-safety"],
    metadata={"domain": "IoT", "input_source": "stdin", "auth_required": False})

rec(id="SCP-000267", language="C", framework="POSIX",
    title="Insecure rand() for token",
    description="A C service generates a session token with rand().",
    owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
    cwe="CWE-338", mitre_attack="T1600 - Weaken Encryption",
    severity="High", difficulty="Intermediate",
    vulnerable_code='char *tok() {\n  static char t[17];\n  sprintf(t, "%ld", random());  // Vulnerable: weak\n  return t;\n}',
    secure_code='#include <openssl/rand.h>\nchar *tok() {\n  static unsigned char t[16];\n  RAND_bytes(t, 16);  // Secure: CSPRNG\n  return hex(t, 16);\n}',
    patch='--- a/tok.c\n+++ b/tok.c\n@@ -1,5 +1,6 @@\n-  sprintf(t, "%ld", random());\n+#include <openssl/rand.h>\n+  RAND_bytes(t, 16);',
    root_cause="Non-CSPRNG token.",
    attack="Predict token sequence.", impact="Session hijack.",
    fix="Use RAND_bytes / getrandom.", guideline="Use CSPRNG for tokens.",
    tags=["crypto", "c", "tokens"],
    metadata={"domain": "Authentication systems", "input_source": "server", "auth_required": False})

rec(id="SCP-000268", language="C", framework="POSIX",
    title="Unchecked return of malloc",
    description="A C program uses malloc result without NULL check.",
    owasp="A03:2021 - Injection", owasp_api="", owasp_llm="",
    cwe="CWE-252", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="Medium", difficulty="Beginner",
    vulnerable_code='void *p = malloc(n);\nmemcpy(p, src, n);  // Vulnerable: p may be NULL',
    secure_code='void *p = malloc(n);\nif (!p) return -1;  // Secure: check\nmemcpy(p, src, n);',
    patch='--- a/alloc.c\n+++ b/alloc.c\n@@ -1,3 +1,4 @@\n-void *p = malloc(n);\n-memcpy(p, src, n);\n+void *p = malloc(n);\n+if (!p) return -1;\n+memcpy(p, src, n);',
    root_cause="Unchecked allocation.",
    attack="Force OOM to get NULL then crash.", impact="DoS / corruption.",
    fix="Check malloc return.", guideline="Always check alloc returns.",
    tags=["memory-safety", "c", "error-handling"],
    metadata={"domain": "IoT", "input_source": "internal", "auth_required": False})

rec(id="SCP-000269", language="C", framework="POSIX",
    title="Race condition on shared file",
    description="A C program checks then opens a file (TOCTOU).",
    owasp="A01:2021 - Broken Access Control", owasp_api="", owasp_llm="",
    cwe="CWE-367", mitre_attack="T1203 - Exploitation for Client Execution",
    severity="High", difficulty="Advanced",
    vulnerable_code='if (access(path, R_OK) == 0) { fd = open(path, O_RDONLY); }  // Vulnerable: TOCTOU',
    secure_code='fd = open(path, O_RDONLY);\nif (fd >= 0) { struct stat st; fstat(fd, &st); }  // Secure: fd-based',
    patch='--- a/open.c\n+++ b/open.c\n@@ -1,3 +1,4 @@\n-if (access(path, R_OK) == 0) { fd = open(path, O_RDONLY); }\n+fd = open(path, O_RDONLY);\n+if (fd >= 0) { struct stat st; fstat(fd, &st); }',
    root_cause="Check-then-open race.",
    attack="Swap file between access and open.", impact="Arbitrary read.",
    fix="Operate on fd.", guideline="Avoid TOCTOU with fd.",
    tags=["toctou", "c", "race-condition"],
    metadata={"domain": "IoT", "input_source": "file", "auth_required": False})

rec(id="SCP-000270", language="C", framework="POSIX",
    title="Improper certificate validation (always true)",
    description="A C TLS client ignores certificate verification.",
    owasp="A02:2021 - Cryptographic Failures", owasp_api="", owasp_llm="",
    cwe="CWE-295", mitre_attack="T1557 - Adversary-in-the-Middle",
    severity="Critical", difficulty="Advanced",
    vulnerable_code='SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);  // Vulnerable: no verify',
    secure_code='SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);  // Secure: verify peer\nSSL_CTX_set_default_verify_paths(ctx);',
    patch='--- a/tls.c\n+++ b/tls.c\n@@ -1,2 +1,3 @@\n-SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n+SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);\n+SSL_CTX_set_default_verify_paths(ctx);',
    root_cause="Certificate verification disabled.",
    attack="MITM intercepts TLS.", impact="Credential/data theft.",
    fix="Enable peer verification.", guideline="Always verify TLS peers.",
    tags=["tls", "c", "mitm"],
    metadata={"domain": "Banking", "input_source": "network", "auth_required": False})

RECORDS_EXT7 = L