File size: 6,411 Bytes
ced8fd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Task 2 (Medium): Security Vulnerability Review in a Flask Web Endpoint.

The agent reviews a Flask user-authentication endpoint containing:
  1. SQL injection vulnerability (string formatting into query)
  2. Plaintext password storage (no hashing)
  3. Missing rate limiting / brute-force protection
  4. Sensitive data leakage in error response
  5. Hardcoded secret key
"""
from __future__ import annotations
from typing import Any, Dict

TASK_ID = "task_2_medium_security"
MAX_STEPS = 12

BUGGY_CODE = '''\
import sqlite3
from flask import Flask, request, jsonify

app = Flask(__name__)
app.secret_key = "supersecret123"   # VULN 5: hardcoded secret key

DB_PATH = "users.db"


def get_db():
    return sqlite3.connect(DB_PATH)


@app.route("/login", methods=["POST"])
def login():
    username = request.json.get("username")
    password = request.json.get("password")

    db = get_db()
    cursor = db.cursor()

    # VULN 1: SQL injection — user input directly interpolated into query
    query = f"SELECT * FROM users WHERE username = \'{username}\' AND password = \'{password}\'"
    cursor.execute(query)
    user = cursor.fetchone()

    if user:
        return jsonify({"status": "ok", "user_id": user[0], "email": user[2]})
    else:
        # VULN 4: leaks whether username exists or password is wrong
        cursor.execute(f"SELECT id FROM users WHERE username = \'{username}\'")
        exists = cursor.fetchone()
        if exists:
            return jsonify({"error": f"Wrong password for user {username}"}), 401
        return jsonify({"error": f"User {username} does not exist"}), 404


@app.route("/register", methods=["POST"])
def register():
    username = request.json.get("username")
    password = request.json.get("password")   # VULN 2: stored in plaintext
    email = request.json.get("email")

    db = get_db()
    cursor = db.cursor()
    # VULN 1 again: SQL injection in insert
    cursor.execute(
        f"INSERT INTO users (username, password, email) VALUES (\'{username}\', \'{password}\', \'{email}\')"
    )
    db.commit()
    return jsonify({"status": "registered"})


# VULN 3: No rate limiting on login endpoint (brute-force possible)

if __name__ == "__main__":
    app.run(debug=True)
'''

FIXED_CODE = '''\
import os
import sqlite3
from flask import Flask, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
app.secret_key = os.environ.get("SECRET_KEY")  # read from env, never hardcode

limiter = Limiter(get_remote_address, app=app, default_limits=["200 per day", "50 per hour"])

DB_PATH = "users.db"


def get_db():
    return sqlite3.connect(DB_PATH)


@app.route("/login", methods=["POST"])
@limiter.limit("5 per minute")   # brute-force protection
def login():
    username = request.json.get("username")
    password = request.json.get("password")

    db = get_db()
    cursor = db.cursor()

    # Parameterised query — prevents SQL injection
    cursor.execute("SELECT id, password_hash FROM users WHERE username = ?", (username,))
    user = cursor.fetchone()

    if user and check_password_hash(user[1], password):
        return jsonify({"status": "ok", "user_id": user[0]})
    # Generic error — does not reveal whether user exists
    return jsonify({"error": "Invalid credentials"}), 401


@app.route("/register", methods=["POST"])
def register():
    username = request.json.get("username")
    password = request.json.get("password")
    email = request.json.get("email")

    db = get_db()
    cursor = db.cursor()
    password_hash = generate_password_hash(password)
    cursor.execute(
        "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)",
        (username, password_hash, email),
    )
    db.commit()
    return jsonify({"status": "registered"})


if __name__ == "__main__":
    app.run(debug=False)
'''

KNOWN_VULNERABILITIES = {
    "sql_injection_login": {
        "line": 23,
        "description_keywords": ["sql injection", "parameterized", "f-string", "format", "interpolat", "query"],
        "severity": "critical",
        "issue_type": "security",
    },
    "sql_injection_register": {
        "line": 44,
        "description_keywords": ["sql injection", "parameterized", "f-string", "format", "interpolat", "insert"],
        "severity": "critical",
        "issue_type": "security",
    },
    "plaintext_password": {
        "line": 39,
        "description_keywords": ["plaintext", "hash", "bcrypt", "werkzeug", "password", "store"],
        "severity": "critical",
        "issue_type": "security",
    },
    "no_rate_limiting": {
        "line": None,
        "description_keywords": ["rate limit", "brute force", "throttl", "limiter"],
        "severity": "major",
        "issue_type": "security",
    },
    "sensitive_data_leak": {
        "line": 30,
        "description_keywords": ["leak", "enumerat", "username exist", "generic error", "information disclos"],
        "severity": "major",
        "issue_type": "security",
    },
    "hardcoded_secret": {
        "line": 5,
        "description_keywords": ["hardcode", "secret", "env", "environment variable", "secret_key"],
        "severity": "major",
        "issue_type": "security",
    },
}

PULL_REQUEST = {
    "pull_request_title": "Implement user login and registration API endpoints",
    "author": "backend-dev",
    "description": (
        "Adds /login and /register REST endpoints backed by SQLite. "
        "Ready for production review."
    ),
    "files_changed": [
        {
            "filename": "auth.py",
            "language": "python",
            "content": BUGGY_CODE,
            "line_count": BUGGY_CODE.count("\n") + 1,
        }
    ],
    "test_results": "Manual testing passed on happy path.",
    "linter_output": "No linter warnings.",
}


def get_task_config() -> Dict[str, Any]:
    return {
        "task_id": TASK_ID,
        "max_steps": MAX_STEPS,
        "pull_request": PULL_REQUEST,
        "known_vulnerabilities": KNOWN_VULNERABILITIES,
        "fixed_code": FIXED_CODE,
        "difficulty": "medium",
        "description": (
            "Review a Flask authentication endpoint for security vulnerabilities. "
            "Identify all issues by category and severity, then provide a secure patched version."
        ),
    }