-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCTF.py
293 lines (243 loc) · 11.4 KB
/
CTF.py
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
import os
import tempfile
import time
import psycopg2
from flask import (Flask, request, render_template_string, session, redirect,
url_for, make_response, send_from_directory)
from scapy.all import rdpcap
# Flask app instance
app = Flask(__name__)
# Configuration
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', "None")
if app.config['SECRET_KEY'] == "None":
print("WARNING: SECRET_KEY is not set. Please set it to a random value: Defaulting with None.")
# Flags and awards
FLAG_1 = "CTF{ROT-13-FLAG}"
FLAG_1_SCORE = 50
FLAG_2 = "CTF{SQLI_FLAG}"
FLAG_2_SCORE = 75
FLAG_3 = "CTF{REVERSE_ME}"
FLAG_3_SCORE = 125
FLAG_4 = "CTF{PCAP_FLAG}"
FLAG_4_SCORE = 150
FLAG_5 = "CTF{STEGANOGRAPHY_FLAG}"
FLAG_5_SCORE = 100
# Time awards
MAX_TIME = 2000 # Around 33 min and 20 seconds - Max 100 points bonus
# Update init_db for PostgreSQL
def init_db():
conn = psycopg2.connect(os.getenv('DATABASE_URL'))
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username TEXT NOT NULL,
password TEXT NOT NULL
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS teams (
id SERIAL PRIMARY KEY,
team_name TEXT NOT NULL,
score REAL DEFAULT 0,
ip_address TEXT,
flags_submitted TEXT
)
''')
# Insert admin user
cursor.execute('''
INSERT INTO users (username, password) VALUES (%s, %s)
ON CONFLICT (username) DO NOTHING
''', ('admin', 'password123'))
conn.commit()
conn.close()
# Favicon route
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico')
# Sign-in page
@app.route('/signin', methods=['GET', 'POST'])
def signin():
if request.method == 'POST':
team_name = request.form.get('team_name')
if not team_name:
return render_template_string(SIGNIN_TEMPLATE, error="Team name is required.")
session['team_name'] = team_name
ip_address = request.remote_addr
conn = psycopg2.connect(os.getenv('DATABASE_URL'))
cursor = conn.cursor()
cursor.execute('INSERT INTO teams (team_name, ip_address, flags_submitted) VALUES (%s, %s, %s)',
(team_name, ip_address, ''))
conn.commit()
conn.close()
resp = make_response(redirect(url_for('home')))
resp.set_cookie('team_name', team_name)
return resp
return render_template_string(SIGNIN_TEMPLATE)
# Submit page
@app.route('/submit', methods=['GET', 'POST'])
def submit():
points = 0
if request.method == 'POST':
flag = request.form.get('flag')
team_name = session.get('team_name')
if not team_name:
return redirect(url_for('signin'))
start_time = session.get('start_time', time.time())
end_time = time.time()
elapsed_time = end_time - start_time
if flag in [FLAG_1, FLAG_2, FLAG_3, FLAG_4, FLAG_5]:
flag_scores = {
FLAG_1: FLAG_1_SCORE,
FLAG_2: FLAG_2_SCORE,
FLAG_3: FLAG_3_SCORE,
FLAG_4: FLAG_4_SCORE,
FLAG_5: FLAG_5_SCORE
}
points = round(flag_scores[flag] + (MAX_TIME - elapsed_time) / 20, 2)
conn = psycopg2.connect(os.getenv('DATABASE_URL'))
cursor = conn.cursor()
cursor.execute('SELECT flags_submitted FROM teams WHERE team_name = %s', (team_name,))
flags_submitted = cursor.fetchone()[0].split(',')
if flag in flags_submitted:
return render_template_string(SUBMIT_TEMPLATE, error="Flag already submitted.")
if flag in [FLAG_1, FLAG_2, FLAG_3, FLAG_4, FLAG_5]:
flags_submitted.append(flag)
cursor.execute('UPDATE teams SET score = score + %s, flags_submitted = %s WHERE team_name = %s',
(round(points, 2), ','.join(flags_submitted), team_name))
conn.commit()
conn.close()
session['start_time'] = time.time() # Reset the timer
return render_template_string(SUBMIT_TEMPLATE, success=True, points=round(points, 2))
else:
return render_template_string(SUBMIT_TEMPLATE, error="Invalid flag.")
return render_template_string(SUBMIT_TEMPLATE)
# Leaderboard page
@app.route('/leaderboard')
def leaderboard():
conn = psycopg2.connect(os.getenv('DATABASE_URL'))
cursor = conn.cursor()
cursor.execute('SELECT team_name, score FROM teams ORDER BY score DESC')
teams = cursor.fetchall()
conn.close()
return render_template_string(LEADERBOARD_TEMPLATE, teams=teams)
# Challenge 1: Cryptography
@app.route('/cryptography', methods=['GET', 'POST'])
def cryptography():
description = "Decrypt a ROT13-encrypted message to uncover the flag."
encrypted_message = "GUVF_VF_GUR_SYNT"
if request.method == 'POST':
user_input = request.form.get('decrypted')
if user_input == "THIS_IS_THE_FLAG":
return render_template_string(COMP_TEMPLATE, challenge=1, success=True, flag=FLAG_1,
description=description, encrypted=encrypted_message)
else:
return render_template_string(COMP_TEMPLATE, challenge=1, error="Incorrect decryption.",
description=description, encrypted=encrypted_message)
return render_template_string(COMP_TEMPLATE, challenge=1, description=description, encrypted=encrypted_message)
# Challenge 2: Web Exploitation
@app.route('/weblogin', methods=['GET', 'POST'])
def weblogin():
description = "Bypass the login page using SQL Injection to discover the flag."
if request.method == 'POST':
username = request.form.get('username', '')
password = request.form.get('password', '')
conn = psycopg2.connect(os.getenv('DATABASE_URL'))
cursor = conn.cursor()
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
cursor.execute(query)
user = cursor.fetchone()
conn.close()
if user:
return render_template_string(COMP_TEMPLATE, challenge=2, success=True, flag=FLAG_2,
description=description)
else:
return render_template_string(COMP_TEMPLATE, challenge=2, error="Invalid credentials.",
description=description)
return render_template_string(COMP_TEMPLATE, challenge=2, description=description)
# Challenge 3: Reverse Engineering
@app.route('/reverse-engineering', methods=['GET', 'POST'])
def reverse_engineering():
description = "Analyze a binary file to find a hardcoded key (Format KEY{xxxx}). First you must find the correct BIN file, then the correct line number."
if request.method == 'POST':
uploaded_file = request.files['file']
if uploaded_file:
binary_data = uploaded_file.read()
if "KEY{i_tES_TYU564678IUY^&*(I_E%$rf}".encode() in binary_data and request.form.get('line',
'') == '136': # File C3_79.bin
return render_template_string(COMP_TEMPLATE, challenge=3, success=True, flag=FLAG_3,
description=description)
else:
return render_template_string(COMP_TEMPLATE, challenge=3,
error="Flag not found in the binary or Line number incorrect.",
description=description)
return render_template_string(COMP_TEMPLATE, challenge=3, description=description)
# Challenge 4: Forensics
@app.route('/forensics', methods=['GET', 'POST'])
def forensics():
description = "Analyze a PCAP file in [Wireshark] to find a hidden key (Format KEY{xxxx}). First you must find the correct PCAP file, then the correct line number."
if request.method == 'POST':
uploaded_file = request.files['file']
if uploaded_file:
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
packets = rdpcap(temp_file_path)
os.remove(temp_file_path) # Clean up the temporary file
for packet in packets:
if (packet.haslayer('Raw') and "KEY{i_tES_TYU564678IUY^&*(I_E%$rf}" in packet['Raw'].load.decode(
'utf-8', errors='ignore')
and request.form.get('line', '') == '452'): # File C4_68.pcap
return render_template_string(COMP_TEMPLATE, challenge=4, success=True, flag=FLAG_4,
description=description)
return render_template_string(COMP_TEMPLATE, challenge=4,
error="Flag not found in PCAP or Line number incorrect.",
description=description)
return render_template_string(COMP_TEMPLATE, challenge=4, description=description)
# Challenge 5: Steganography
@app.route('/steganography', methods=['GET', 'POST'])
def steganography():
description = "Extract hidden data (Format KEY{xxxx}) from an image file using a automated script. First you must find the correct JPEG file, then the correct line number."
if request.method == 'POST':
uploaded_file = request.files['file']
if uploaded_file:
try:
# Read the entire file content
file_content = uploaded_file.read()
flag = b"KEY{i_tES_TYU564678IUY^&*(I_E%$rf}"
if flag in file_content and request.form.get('line', '') == '206': # File C5_51.jpeg
return render_template_string(COMP_TEMPLATE, challenge=5, success=True, flag=FLAG_5,
description=description)
else:
return render_template_string(COMP_TEMPLATE, challenge=5,
error="Hidden flag not found or Line number incorrect.",
description=description)
except Exception as e:
return render_template_string(COMP_TEMPLATE, challenge=5, error=f"EXCEPTION: {e}",
description=description)
return render_template_string(COMP_TEMPLATE, challenge=5, description=description)
# Home Route
@app.route('/')
def home():
if 'team_name' not in session or request.cookies.get('team_name') != session['team_name']:
return redirect(url_for('signin'))
if 'start_time' not in session:
session['start_time'] = time.time()
return render_template_string(HOME_TEMPLATE)
# HTML template for home page
with open("src/html/home.html", "r") as f:
HOME_TEMPLATE = f.read()
# HTML template for challenges
with open("src/html/competition.html", "r") as f:
COMP_TEMPLATE = f.read()
# HTML templates for sign-in, submit and leaderboard pages
with open("src/html/signin.html", "r") as f:
SIGNIN_TEMPLATE = f.read()
with open("src/html/submit.html", "r") as f:
SUBMIT_TEMPLATE = f.read()
with open("src/html/leaderboard.html", "r") as f:
LEADERBOARD_TEMPLATE = f.read()
# Run the app
if __name__ == "__main__":
init_db()
app.run(debug=True)