DarkShadow0069 commited on
Commit
92eaf40
·
1 Parent(s): 2a53916

Upgrade all three tasks with enhanced security challenges

Browse files

TASK 1: Multi-File Secret Management (5 files, 2+ issues)
- Multiple API keys, DB passwords across files
- Realistic secrets scattered throughout codebase
- Red herring patterns for proper exclusions

TASK 2: SQL + NoSQL Injection (5 files, 3 issues)
- Flask app with vulnerable SQL queries
- MongoDB with NoSQL injection vulnerabilities
- Dual-injection type challenge

TASK 3: Cryptographic Weaknesses (5 files, 6 issues) - NEW
- MD5 hashing, weak RNG, hardcoded salts
- Realistic auth.py and database.py interaction
- Migration scenario with test patterns

Enhanced Simulator:
- Crypto weakness detection (MD5, weak RNG, hardcoded salt)
- Improved injection detection (SQL, NoSQL)
- Smart secret detection with proper exclusions

All tasks verified: scores (0,1), detection working, grading correct

Files changed (3) hide show
  1. cyber_env/simulator.py +37 -3
  2. cyber_env/tasks.py +421 -48
  3. inference.py +28 -9
cyber_env/simulator.py CHANGED
@@ -39,16 +39,50 @@ class SimulatedCodebase:
39
  # For simplicity, check for common issues
40
  output = ""
41
  passed = True
 
 
42
  for path, content in self.files.items():
43
- if "sk-" in content or "password" in content.lower():
44
- output += f"High: Hardcoded secret in {path}\n"
45
- passed = False
 
 
 
 
46
  if "subprocess.run" in content and "shell=True" in content:
47
  output += f"High: Command injection in {path}\n"
48
  passed = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  if "strcpy" in content and ".cpp" in path:
50
  output += f"High: Unsafe strcpy in {path}\n"
51
  passed = False
 
52
  self.security_scan = ScanResult(tool="bandit", output=output, passed=passed)
53
 
54
  def run_unit_tests(self):
 
39
  # For simplicity, check for common issues
40
  output = ""
41
  passed = True
42
+
43
+ # Check for hardcoded secrets (stricter)
44
  for path, content in self.files.items():
45
+ if "sk-" in content or "password" in content.lower() or "api_key" in content.lower():
46
+ # But allow if it's in tests or env files with proper pattern
47
+ if "test" not in path and ".env" not in path:
48
+ output += f"High: Hardcoded secret in {path}\n"
49
+ passed = False
50
+
51
+ # Command injection check
52
  if "subprocess.run" in content and "shell=True" in content:
53
  output += f"High: Command injection in {path}\n"
54
  passed = False
55
+
56
+ # SQL Injection check
57
+ if "f\"SELECT" in content or "f'SELECT" in content:
58
+ output += f"High: SQL injection vulnerability in {path}\n"
59
+ passed = False
60
+
61
+ # NoSQL Injection check
62
+ if "ObjectId(user_input)" in content or "{\"_id\": user_input}" in content:
63
+ output += f"High: NoSQL injection vulnerability in {path}\n"
64
+ passed = False
65
+
66
+ # Cryptographic weaknesses
67
+ if "hashlib.md5" in content or "MD5(" in content:
68
+ output += f"High: Weak cryptography (MD5) in {path}\n"
69
+ passed = False
70
+
71
+ if "random.randint" in content or "random.choice" in content:
72
+ output += f"High: Weak random number generation in {path}\n"
73
+ passed = False
74
+
75
+ if "salt = " in content and "\"" in content and ".py" in path:
76
+ # Check if salt is hardcoded, not if it's just a comment
77
+ if "salt = \"" in content or "salt = '" in content:
78
+ output += f"High: Hardcoded salt in {path}\n"
79
+ passed = False
80
+
81
+ # Buffer overflow check
82
  if "strcpy" in content and ".cpp" in path:
83
  output += f"High: Unsafe strcpy in {path}\n"
84
  passed = False
85
+
86
  self.security_scan = ScanResult(tool="bandit", output=output, passed=passed)
87
 
88
  def run_unit_tests(self):
cyber_env/tasks.py CHANGED
@@ -1,84 +1,457 @@
1
  from .simulator import SimulatedCodebase
2
 
3
- # --- TASK 1: EASY (Python - The Leaked Secret) ---
 
 
 
 
 
4
  def setup_task_1(codebase: SimulatedCodebase):
5
- codebase.files["app.py"] = """
6
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- API_KEY = "sk-1234567890abcdef" # Hardcoded secret
9
- print("API Key:", API_KEY)
10
  """
11
- codebase.files["test_app.py"] = """
12
- import os
13
- os.environ['API_KEY'] = 'test_key'
14
- def test_app():
15
- import app
16
- assert app.API_KEY == 'test_key' # Should use env var
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
 
19
  def grade_task_1(codebase: SimulatedCodebase) -> float:
 
20
  score = 0.0
21
- if "app.py" in codebase.read_files:
22
- score += 0.2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  if codebase.security_scan and codebase.security_scan.passed:
24
- score += 0.3
 
 
25
  if codebase.unit_tests and codebase.unit_tests.passed:
26
- score += 0.5
 
27
  # Ensure score is strictly between 0 and 1 (exclusive)
28
- score = min(score, 0.99) # Cap at 0.99, not 1.0
29
- score = max(score, 0.01) # Floor at 0.01, not 0.0
30
  return score
31
 
32
- # --- TASK 2: MEDIUM (Python - Command Injection) ---
 
 
 
 
 
 
33
  def setup_task_2(codebase: SimulatedCodebase):
34
- codebase.files["utils.py"] = """
35
- import subprocess
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- def run_command(user_input):
38
- subprocess.run(user_input, shell=True) # Vulnerable
39
  """
40
- codebase.files["test_utils.py"] = """
41
- def test_run_command():
42
- from utils import run_command
43
- # Test safe input
44
- run_command(["echo", "hello"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  """
46
 
47
  def grade_task_2(codebase: SimulatedCodebase) -> float:
 
48
  score = 0.0
49
- if "utils.py" in codebase.read_files:
50
- score += 0.2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  if codebase.security_scan and codebase.security_scan.passed:
52
- score += 0.3
 
 
53
  if codebase.unit_tests and codebase.unit_tests.passed:
54
- score += 0.5
 
55
  # Ensure score is strictly between 0 and 1 (exclusive)
56
- score = min(score, 0.99) # Cap at 0.99, not 1.0
57
- score = max(score, 0.01) # Floor at 0.01, not 0.0
58
  return score
59
 
60
- # --- TASK 3: HARD (C++ - Memory Safety) ---
 
 
 
 
 
 
61
  def setup_task_3(codebase: SimulatedCodebase):
62
- codebase.files["main.cpp"] = """
63
- #include <cstring>
 
 
 
 
64
 
65
- void copy_string(char* dest, const char* src) {
66
- strcpy(dest, src); // Buffer overflow risk
67
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  """
69
- codebase.files["test_main.cpp"] = """
70
- // Assume compiled and tested
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  """
72
 
73
  def grade_task_3(codebase: SimulatedCodebase) -> float:
 
74
  score = 0.0
75
- if "main.cpp" in codebase.read_files:
76
- score += 0.2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  if codebase.security_scan and codebase.security_scan.passed:
78
- score += 0.3
 
 
79
  if codebase.unit_tests and codebase.unit_tests.passed:
80
- score += 0.5
 
81
  # Ensure score is strictly between 0 and 1 (exclusive)
82
- score = min(score, 0.99) # Cap at 0.99, not 1.0
83
- score = max(score, 0.01) # Floor at 0.01, not 0.0
84
- return score
 
1
  from .simulator import SimulatedCodebase
2
 
3
+ # ============================================================================
4
+ # TASK 1: EASY - Multi-File Secret Management
5
+ # ============================================================================
6
+ # Real-world scenario: Finding and replacing hardcoded secrets across codebase
7
+ # Difficulty: Agent must search multiple files and understand secret types
8
+
9
  def setup_task_1(codebase: SimulatedCodebase):
10
+ """Setup Task 1: Multiple hardcoded secrets across files."""
11
+
12
+ # File 1: Main application with API key
13
+ codebase.files["app.py"] = """import os
14
+ from config import DB_USER, DB_PASS
15
+
16
+ API_KEY_OPENAI = "sk-1234567890abcdef" # Hardcoded secret!
17
+ API_KEY_STRIPE = "sk_live_51234567890abcdef" # Another hardcoded secret!
18
+
19
+ def initialize_app():
20
+ # TODO: Use environment variables instead of hardcoding
21
+ print(f"Connecting with keys: {API_KEY_OPENAI}")
22
+ setup_database(DB_USER, DB_PASS)
23
+
24
+ if __name__ == "__main__":
25
+ initialize_app()
26
+ """
27
+
28
+ # File 2: Configuration with DB credentials
29
+ codebase.files["config.py"] = """# Database configuration
30
+ # TODO: Move sensitive data to .env file before production
31
+
32
+ DATABASE_CONFIG = {
33
+ "host": "localhost",
34
+ "port": 5432,
35
+ "username": "admin",
36
+ "password": "prod_password_abc123", # Hardcoded password!
37
+ "database": "production_db"
38
+ }
39
 
40
+ DB_USER = DATABASE_CONFIG["username"]
41
+ DB_PASS = DATABASE_CONFIG["password"]
42
  """
43
+
44
+ # File 3: Utility functions with another secret (red herring mix)
45
+ codebase.files["utils.py"] = """import requests
46
+
47
+ # API credentials hardcoded
48
+ GITHUB_TOKEN = "ghp_1234567890abcdefghijklmnop" # Hardcoded secret!
49
+ API_ENDPOINT = "https://api.github.com"
50
+
51
+ def fetch_repo_data(owner, repo):
52
+ headers = {
53
+ "Authorization": f"token {GITHUB_TOKEN}", # Using hardcoded token
54
+ "Accept": "application/vnd.github.v3+json"
55
+ }
56
+ return requests.get(f"{API_ENDPOINT}/repos/{owner}/{repo}", headers=headers)
57
+
58
+ def safe_log_info(data):
59
+ # This is OK - just logging, not a security issue (red herring check)
60
+ print(f"Processing data from: {data}")
61
+ return True
62
+ """
63
+
64
+ # File 4: Test file with proper environment usage (red herring)
65
+ codebase.files["test_app.py"] = """import os
66
+ import pytest
67
+
68
+ # Correct way - using environment variables in tests
69
+ @pytest.fixture
70
+ def setup_env(monkeypatch):
71
+ monkeypatch.setenv("API_KEY_OPENAI", "test_key_123")
72
+ monkeypatch.setenv("API_KEY_STRIPE", "test_stripe_key")
73
+ monkeypatch.setenv("DB_USER", "test_user")
74
+ monkeypatch.setenv("DB_PASS", "test_pass")
75
+
76
+ def test_app_initialization(setup_env):
77
+ from app import initialize_app
78
+ # Should work with env vars, not hardcoded values
79
+ initialize_app()
80
+
81
+ def test_config_from_env(setup_env):
82
+ os.environ["DB_USER"] = "test_admin"
83
+ os.environ["DB_PASS"] = "test_password"
84
+ # Once fixed, config should read from these
85
+ """
86
+
87
+ # File 5: .env.example (red herring - not a real issue)
88
+ codebase.files[".env.example"] = """# Environment variables - NEVER commit .env file with real secrets!
89
+ API_KEY_OPENAI=sk_test_xxxxxxxxxxxx
90
+ API_KEY_STRIPE=sk_test_xxxxxxxxxxxx
91
+ DB_USER=admin
92
+ DB_PASS=password_here
93
+ GITHUB_TOKEN=ghp_xxxxxxxxxxxx
94
  """
95
 
96
  def grade_task_1(codebase: SimulatedCodebase) -> float:
97
+ """Grade Task 1: Check if all secrets are properly removed."""
98
  score = 0.0
99
+
100
+ # 0.1: Read at least one file (discovery)
101
+ if len(codebase.read_files) >= 1:
102
+ score += 0.1
103
+
104
+ # 0.2: All secret files have been read
105
+ secret_files = {"app.py", "config.py", "utils.py"}
106
+ if secret_files.issubset(codebase.read_files):
107
+ score += 0.15
108
+
109
+ # 0.3: Check if all secrets have been removed
110
+ secrets_removed = 0
111
+ potential_secrets = [
112
+ ("app.py", "sk-"),
113
+ ("app.py", "sk_live"),
114
+ ("config.py", "prod_password"),
115
+ ("utils.py", "ghp_"),
116
+ ]
117
+
118
+ for filepath, secret_pattern in potential_secrets:
119
+ if filepath in codebase.files:
120
+ if secret_pattern not in codebase.files[filepath]:
121
+ secrets_removed += 1
122
+
123
+ if secrets_removed >= 3:
124
+ score += 0.25
125
+ elif secrets_removed == 2:
126
+ score += 0.12
127
+
128
+ # 0.15: Security scan passes (no more hardcoded secrets detected)
129
  if codebase.security_scan and codebase.security_scan.passed:
130
+ score += 0.15
131
+
132
+ # 0.2: Tests pass (configuration works with env vars)
133
  if codebase.unit_tests and codebase.unit_tests.passed:
134
+ score += 0.15
135
+
136
  # Ensure score is strictly between 0 and 1 (exclusive)
137
+ score = min(score, 0.99)
138
+ score = max(score, 0.01)
139
  return score
140
 
141
+
142
+ # ============================================================================
143
+ # TASK 2: MEDIUM - SQL Injection + NoSQL Injection
144
+ # ============================================================================
145
+ # Real-world scenario: Database queries vulnerable to injection attacks
146
+ # Difficulty: Agent must understand different database paradigms and safe practices
147
+
148
  def setup_task_2(codebase: SimulatedCodebase):
149
+ """Setup Task 2: SQL and NoSQL injection vulnerabilities."""
150
+
151
+ # File 1: Flask app with SQL injection
152
+ codebase.files["app.py"] = """from flask import Flask, request
153
+ import sqlite3
154
+
155
+ app = Flask(__name__)
156
+ db_connection = sqlite3.connect('users.db')
157
+
158
+ @app.route('/user')
159
+ def get_user():
160
+ # TODO: Use parameterized queries before production!
161
+ username = request.args.get('username')
162
+
163
+ # VULNERABLE: SQL Injection!
164
+ query = f"SELECT * FROM users WHERE username = '{username}'"
165
+ cursor = db_connection.execute(query)
166
+ return cursor.fetchall()
167
+
168
+ @app.route('/admin')
169
+ def admin_check():
170
+ user_id = request.args.get('user_id')
171
+
172
+ # VULNERABLE: Another SQL Injection!
173
+ query = f"SELECT role FROM user_roles WHERE id = {user_id}"
174
+ cursor = db_connection.execute(query)
175
+ return cursor.fetchone()
176
 
177
+ if __name__ == '__main__':
178
+ app.run(debug=False)
179
  """
180
+
181
+ # File 2: MongoDB handler with NoSQL injection
182
+ codebase.files["mongo_handler.py"] = """from pymongo import MongoClient
183
+ from bson.objectid import ObjectId
184
+
185
+ client = MongoClient('mongodb://localhost:27017/')
186
+ db = client['secure_app']
187
+ users_collection = db['users']
188
+
189
+ def find_user_by_id(user_input):
190
+ # TODO: Always validate and convert to ObjectId!
191
+ # VULNERABLE: NoSQL Injection!
192
+ try:
193
+ query = {"_id": ObjectId(user_input)}
194
+ except:
195
+ # Attacker could exploit this with: {"_id": {"$ne": null}}
196
+ query = user_input # Direct injection!
197
+
198
+ return users_collection.find_one(query)
199
+
200
+ def find_user_by_email(email_input):
201
+ # VULNERABLE: NoSQL Injection through string concatenation!
202
+ # {"email": email_input} where email_input = {"$regex": ".*password.*"}
203
+ query = {"email": email_input}
204
+ return users_collection.find_one(query)
205
+
206
+ def safe_logging_function(data):
207
+ # This looks like it might be vulnerable but it's NOT (red herring)
208
+ # Log data doesn't interact with database
209
+ print(f"User accessed: {data}")
210
+ return True
211
+ """
212
+
213
+ # File 3: Tests with security assertions
214
+ codebase.files["test_security.py"] = """import pytest
215
+ from app import app, db_connection
216
+ from mongo_handler import find_user_by_id, find_user_by_email
217
+
218
+ class TestSQLInjectionPrevention:
219
+ def test_username_with_sql_injection_payload(self):
220
+ # Payload: ' OR '1'='1
221
+ # Should NOT return all users
222
+ with app.test_client() as client:
223
+ response = client.get("/user?username=' OR '1'='1")
224
+ # Once fixed, should handle safely
225
+ assert len(response.get_json()) == 0 or response.status_code == 200
226
+
227
+ def test_user_id_with_injection(self):
228
+ # Payload: 1 OR 1=1
229
+ with app.test_client() as client:
230
+ response = client.get("/admin?user_id=1 OR 1=1")
231
+ # Should return empty or single result, not admin bypass
232
+ assert response.status_code == 200
233
+
234
+ class TestNoSQLInjectionPrevention:
235
+ def test_mongodb_regex_injection(self):
236
+ # Payload: {"$regex": ".*"}
237
+ # Should not return all users
238
+ result = find_user_by_email({"$regex": ".*"})
239
+ # Once fixed, should be safe
240
+ assert result is None or isinstance(result, dict)
241
+
242
+ def test_mongodb_ne_injection(self):
243
+ # Payload: {"$ne": null}
244
+ result = find_user_by_id({"$ne": null})
245
+ # Should not return all users
246
+ assert result is None or isinstance(result, dict)
247
+ """
248
+
249
+ # File 4: Configuration file (red herring)
250
+ codebase.files["config.py"] = """# Security configuration
251
+ # This is safe - just configuration, not executable
252
+ DB_TIMEOUT = 30
253
+ MAX_CONNECTIONS = 100
254
+ LOG_LEVEL = "INFO"
255
+ """
256
+
257
+ # File 5: Safe database wrapper (red herring - shows correct pattern)
258
+ codebase.files["safe_db.py"] = """import sqlite3
259
+
260
+ def get_user_safe(username):
261
+ # This is the CORRECT way - using parameterized queries
262
+ # Not a vulnerability - this is the solution pattern!
263
+ conn = sqlite3.connect('users.db')
264
+ query = "SELECT * FROM users WHERE username = ?"
265
+ cursor = conn.execute(query, (username,))
266
+ return cursor.fetchall()
267
  """
268
 
269
  def grade_task_2(codebase: SimulatedCodebase) -> float:
270
+ """Grade Task 2: Check if SQL and NoSQL injections are fixed."""
271
  score = 0.0
272
+
273
+ # 0.1: Read vulnerability files (discovery)
274
+ if "app.py" in codebase.read_files or "mongo_handler.py" in codebase.read_files:
275
+ score += 0.1
276
+
277
+ # 0.15: Read both file types that need fixing
278
+ if "app.py" in codebase.read_files and "mongo_handler.py" in codebase.read_files:
279
+ score += 0.1
280
+
281
+ # 0.2: SQL injection fixed (no f-strings with direct variables)
282
+ if "app.py" in codebase.files:
283
+ if 'f"SELECT' not in codebase.files["app.py"] and "f'SELECT" not in codebase.files["app.py"]:
284
+ score += 0.15
285
+
286
+ # 0.15: NoSQL injection fixed (proper ObjectId handling)
287
+ if "mongo_handler.py" in codebase.files:
288
+ if 'ObjectId(user_input)' not in codebase.files["mongo_handler.py"]:
289
+ score += 0.12
290
+
291
+ # 0.25: Security scan passes (no SQL or NoSQL injection detected)
292
  if codebase.security_scan and codebase.security_scan.passed:
293
+ score += 0.25
294
+
295
+ # 0.15: Tests pass (security assertions validate fixes)
296
  if codebase.unit_tests and codebase.unit_tests.passed:
297
+ score += 0.15
298
+
299
  # Ensure score is strictly between 0 and 1 (exclusive)
300
+ score = min(score, 0.99)
301
+ score = max(score, 0.01)
302
  return score
303
 
304
+
305
+ # ============================================================================
306
+ # TASK 3: HARD - Cryptographic Weaknesses & Safe Patterns
307
+ # ============================================================================
308
+ # Real-world scenario: Migrating from weak to strong cryptography
309
+ # Difficulty: Agent must understand crypto best practices and handle legacy code
310
+
311
  def setup_task_3(codebase: SimulatedCodebase):
312
+ """Setup Task 3: Multiple cryptographic vulnerabilities."""
313
+
314
+ # File 1: Authentication module with weak crypto
315
+ codebase.files["auth.py"] = """import hashlib
316
+ import random
317
+ import string
318
 
319
+ # TODO: Replace MD5 with bcrypt before production!
320
+ def hash_password(password):
321
+ # VULNERABLE: MD5 is cryptographically broken
322
+ return hashlib.md5(password.encode()).hexdigest()
323
+
324
+ # TODO: Use secrets module instead!
325
+ def generate_session_token():
326
+ # VULNERABLE: random is predictable
327
+ chars = string.ascii_letters + string.digits
328
+ token = ''.join(random.choice(chars) for _ in range(32))
329
+ return token
330
+
331
+ # VULNERABLE: Hardcoded salt
332
+ def hash_with_salt(password):
333
+ salt = "fixed_salt_12345" # Hardcoded!
334
+ return hashlib.md5((salt + password).encode()).hexdigest()
335
+
336
+ def verify_password(password, hashed):
337
+ return hash_password(password) == hashed
338
+ """
339
+
340
+ # File 2: User database with weak credentials
341
+ codebase.files["database.py"] = """import sqlite3
342
+ from auth import hash_password, hash_with_salt, generate_session_token
343
+
344
+ def create_user(username, password):
345
+ # Using weak hashing function
346
+ conn = sqlite3.connect('users.db')
347
+ hashed = hash_password(password) # MD5 - vulnerable!
348
+ conn.execute(
349
+ "INSERT INTO users (username, password_hash) VALUES (?, ?)",
350
+ (username, hashed)
351
+ )
352
+ conn.commit()
353
+
354
+ def create_session(user_id):
355
+ conn = sqlite3.connect('sessions.db')
356
+ token = generate_session_token() # Weak RNG - vulnerable!
357
+ conn.execute(
358
+ "INSERT INTO sessions (user_id, token) VALUES (?, ?)",
359
+ (user_id, token)
360
+ )
361
+ conn.commit()
362
+ return token
363
+
364
+ # Red herring: This is actually safe (parameterized query)
365
+ def get_user_safe(username):
366
+ conn = sqlite3.connect('users.db')
367
+ result = conn.execute(
368
+ "SELECT * FROM users WHERE username = ?",
369
+ (username,)
370
+ )
371
+ return result.fetchone()
372
  """
373
+
374
+ # File 3: Configuration with crypto settings (red herring)
375
+ codebase.files["config.py"] = """# Cryptography configuration
376
+ ENCRYPTION_ENABLED = False # Red herring: just config, not executable
377
+ ALGO_CHOICE = "md5" # Legacy choice
378
+ TOKEN_LENGTH = 32
379
+ HASH_ITERATIONS = 1
380
+ """
381
+
382
+ # File 4: Tests showing secure pattern (red herring)
383
+ codebase.files["test_crypto.py"] = """import pytest
384
+ from unittest.mock import patch
385
+ from auth import hash_password, verify_password, generate_session_token
386
+
387
+ def test_password_hashing():
388
+ # This test will fail until crypto is fixed
389
+ password = "secure_password_123"
390
+ hashed = hash_password(password)
391
+ assert verify_password(password, hashed), "Password verification failed"
392
+
393
+ def test_session_generation():
394
+ # This test will fail until RNG is fixed
395
+ token1 = generate_session_token()
396
+ token2 = generate_session_token()
397
+ assert token1 != token2, "Token generation is not unique"
398
+ assert len(token1) == 32, "Token length incorrect"
399
+
400
+ def test_password_salt():
401
+ # This test will fail until salt is made random
402
+ p1 = hash_password("test")
403
+ p2 = hash_password("test")
404
+ assert p1 == p2, "Should be same for MD5, but should be different with proper salting"
405
+ """
406
+
407
+ # File 5: Migration guide (red herring - not executable)
408
+ codebase.files["MIGRATION.md"] = """# Crypto Migration Guide
409
+
410
+ ## Libraries needed:
411
+ - bcrypt for password hashing
412
+ - secrets for token generation
413
+ - cryptography for encryption
414
+
415
+ These are just comments - not security issues.
416
  """
417
 
418
  def grade_task_3(codebase: SimulatedCodebase) -> float:
419
+ """Grade Task 3: Check if cryptographic weaknesses are fixed."""
420
  score = 0.0
421
+
422
+ # 0.1: Read vulnerability files
423
+ if "auth.py" in codebase.read_files or "database.py" in codebase.read_files:
424
+ score += 0.1
425
+
426
+ # 0.15: Read both key files
427
+ if "auth.py" in codebase.read_files and "database.py" in codebase.read_files:
428
+ score += 0.1
429
+
430
+ # 0.2: MD5 replaced with secure hash
431
+ if "auth.py" in codebase.files:
432
+ if "hashlib.md5" not in codebase.files["auth.py"] and "MD5(" not in codebase.files["auth.py"]:
433
+ score += 0.15
434
+
435
+ # 0.2: Weak RNG replaced with secrets
436
+ if "auth.py" in codebase.files:
437
+ if "random.choice" not in codebase.files["auth.py"] and "random.randint" not in codebase.files["auth.py"]:
438
+ score += 0.15
439
+
440
+ # 0.2: Hardcoded salt removed
441
+ if "auth.py" in codebase.files:
442
+ auth_content = codebase.files["auth.py"]
443
+ if 'salt = "fixed_salt' not in auth_content and 'salt = \'fixed_salt' not in auth_content:
444
+ score += 0.15
445
+
446
+ # 0.25: Security scan passes (all crypto issues fixed)
447
  if codebase.security_scan and codebase.security_scan.passed:
448
+ score += 0.25
449
+
450
+ # 0.15: Tests pass (crypto functions work securely)
451
  if codebase.unit_tests and codebase.unit_tests.passed:
452
+ score += 0.09
453
+
454
  # Ensure score is strictly between 0 and 1 (exclusive)
455
+ score = min(score, 0.99)
456
+ score = max(score, 0.01)
457
+ return score
inference.py CHANGED
@@ -55,18 +55,37 @@ def main():
55
  base_url=API_BASE_URL
56
  )
57
 
58
- # System prompt for agent
59
- system_prompt = """You are a DevSecOps engineer fixing security vulnerabilities.
60
 
61
- Actions available:
62
- - read_file (filepath)
63
- - search_and_replace (filepath, old_snippet, new_snippet)
64
- - run_security_scan ()
65
- - run_unit_tests ()
 
66
 
67
- Respond with JSON only: {"action_type": "...", ...}"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- max_steps_per_task = 10
 
70
 
71
  tasks_list = ["task_1", "task_2", "task_3"]
72
 
 
55
  base_url=API_BASE_URL
56
  )
57
 
58
+ # System prompt for agent (Enhanced for complex tasks)
59
+ system_prompt = """You are an expert DevSecOps engineer fixing security vulnerabilities.
60
 
61
+ Your approach:
62
+ 1. INVESTIGATE: Read files to understand the codebase structure
63
+ 2. IDENTIFY: Run security scan to find vulnerabilities
64
+ 3. REMEDIATE: Use search_and_replace to fix vulnerabilities
65
+ 4. VALIDATE: Run unit tests to ensure fixes work
66
+ 5. VERIFY: Run security scan again to confirm issues are resolved
67
 
68
+ Available actions:
69
+ - read_file (filepath): Read file contents to understand code
70
+ - search_and_replace (filepath, old_snippet, new_snippet): Fix vulnerabilities
71
+ - run_security_scan (): Scan for security issues
72
+ - run_unit_tests (): Validate fixes work correctly
73
+
74
+ Always respond with ONLY valid JSON: {"action_type": "...", "filepath": "...", ...}
75
+
76
+ For read_file: {"action_type": "read_file", "filepath": "filepath"}
77
+ For search_and_replace: {"action_type": "search_and_replace", "filepath": "filepath", "old_snippet": "...", "new_snippet": "..."}
78
+ For scans: {"action_type": "run_security_scan"} or {"action_type": "run_unit_tests"}
79
+
80
+ IMPORTANT:
81
+ - Read ALL files in the codebase first to understand dependencies
82
+ - Look for multiple vulnerabilities in different files
83
+ - Fix comprehensively, not just surface-level
84
+ - Use environment variables and safe patterns
85
+ - Test after every fix"""
86
 
87
+ # Allow more steps for complex tasks (Task 1 and 2 have multiple files)
88
+ max_steps_per_task = 20
89
 
90
  tasks_list = ["task_1", "task_2", "task_3"]
91