akaaafk commited on
Commit
a5d495e
·
verified ·
1 Parent(s): 58ba3af

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/admin.py +511 -0
  2. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/admin.pyc +0 -0
  3. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/auth.py +137 -0
  4. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/auth.pyc +0 -0
  5. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/challenges.py +128 -0
  6. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/challenges.pyc +0 -0
  7. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/config.py +19 -0
  8. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/config.pyc +0 -0
  9. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/ctfd.db +0 -0
  10. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/errors.py +14 -0
  11. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/errors.pyc +0 -0
  12. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/models.py +189 -0
  13. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/models.pyc +0 -0
  14. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/scoreboard.py +49 -0
  15. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/scoreboard.pyc +0 -0
  16. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/utils.py +183 -0
  17. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/README.md +15 -0
  18. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/prepare.sh +4 -0
  19. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/requirements.txt +12 -0
  20. benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/serve.py +3 -0
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/admin.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import render_template, request, redirect, abort, jsonify, url_for, session
2
+ from CTFd.utils import sha512, is_safe_url, authed, admins_only, is_admin, unix_time, unix_time_millis, get_config, set_config, get_digitalocean, sendmail, rmdir
3
+ from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking, Pages, Config
4
+ from itsdangerous import TimedSerializer, BadTimeSignature
5
+ from werkzeug.utils import secure_filename
6
+ from socket import inet_aton, inet_ntoa
7
+ from passlib.hash import bcrypt_sha256
8
+ from flask import current_app as app
9
+
10
+ import logging
11
+ import hashlib
12
+ import time
13
+ import re
14
+ import os
15
+ import json
16
+
17
+ def init_admin(app):
18
+ @app.route('/admin', methods=['GET', 'POST'])
19
+ def admin():
20
+ if request.method == 'POST':
21
+ username = request.form.get('name')
22
+ password = request.form.get('password')
23
+
24
+ admin = Teams.query.filter_by(name=request.form['name'], admin=True).first()
25
+ if admin and bcrypt_sha256.verify(request.form['password'], admin.password):
26
+ try:
27
+ session.regenerate() # NO SESSION FIXATION FOR YOU
28
+ except:
29
+ pass # TODO: Some session objects dont implement regenerate :(
30
+ session['username'] = admin.name
31
+ session['id'] = admin.id
32
+ session['admin'] = True
33
+ session['nonce'] = sha512(os.urandom(10))
34
+ db.session.close()
35
+ return redirect('/admin/graphs')
36
+
37
+ if is_admin():
38
+ return redirect('/admin/graphs')
39
+
40
+ return render_template('admin/login.html')
41
+
42
+ @app.route('/admin/graphs')
43
+ @admins_only
44
+ def admin_graphs():
45
+ return render_template('admin/graphs.html')
46
+
47
+ @app.route('/admin/config', methods=['GET', 'POST'])
48
+ @admins_only
49
+ def admin_config():
50
+ if request.method == "POST":
51
+ try:
52
+ start = int(request.form['start'])
53
+ end = int(request.form['end'])
54
+ except (ValueError, TypeError):
55
+ start = None
56
+ end = None
57
+
58
+ try:
59
+ view_challenges_unregistered = bool(request.form.get('view_challenges_unregistered', None))
60
+ prevent_registration = bool(request.form.get('prevent_registration', None))
61
+ except (ValueError, TypeError):
62
+ view_challenges_unregistered = None
63
+ prevent_registration = None
64
+
65
+ do_api_key = set_config("do_api_key", request.form.get('do_api_key', None))
66
+
67
+ db_start = Config.query.filter_by(key='start').first()
68
+ db_start.value = start
69
+
70
+ db_end = Config.query.filter_by(key='end').first()
71
+ db_end.value = end
72
+
73
+ db_view_challenges_unregistered = Config.query.filter_by(key='view_challenges_unregistered').first()
74
+ db_view_challenges_unregistered.value = view_challenges_unregistered
75
+
76
+ db_prevent_registration = Config.query.filter_by(key='prevent_registration').first()
77
+ db_prevent_registration.value = prevent_registration
78
+
79
+ db.session.add(db_start)
80
+ db.session.add(db_end)
81
+ db.session.add(db_view_challenges_unregistered)
82
+ db.session.add(db_prevent_registration)
83
+
84
+ db.session.commit()
85
+ return redirect('/admin/config')
86
+
87
+ do_api_key = get_config('do_api_key')
88
+ if not do_api_key:
89
+ set_config('do_api_key', None)
90
+
91
+ start = get_config('start')
92
+ if not start:
93
+ set_config('start', None)
94
+
95
+ end = get_config('end')
96
+ if not end:
97
+ set_config('end', None)
98
+
99
+ view_challenges_unregistered = get_config('view_challenges_unregistered') == '1'
100
+ if not view_challenges_unregistered:
101
+ set_config('view_challenges_unregistered', None)
102
+
103
+ prevent_registration = get_config('prevent_registration') == '1'
104
+ if not prevent_registration:
105
+ set_config('prevent_registration', None)
106
+
107
+ db.session.commit()
108
+ db.session.close()
109
+
110
+ return render_template('admin/config.html', start=start, end=end, view_challenges_unregistered=view_challenges_unregistered,
111
+ prevent_registration=prevent_registration, do_api_key=do_api_key)
112
+
113
+ @app.route('/admin/pages', defaults={'route': None}, methods=['GET', 'POST'])
114
+ @app.route('/admin/pages/<route>', methods=['GET', 'POST'])
115
+ @admins_only
116
+ def admin_pages(route):
117
+ if route and request.method == 'GET':
118
+ page = Pages.query.filter_by(route=route).first()
119
+ return render_template('admin/editor.html', page=page)
120
+ if route and request.method == 'POST':
121
+ page = Pages.query.filter_by(route=route).first()
122
+ errors = []
123
+ html = request.form['html']
124
+ route = request.form['route']
125
+ if not route:
126
+ errors.append('Missing URL route')
127
+ if errors:
128
+ page = Pages(html, "")
129
+ return render_template('/admin/editor.html', page=page)
130
+ if page:
131
+ page.route = route
132
+ page.html = html
133
+ db.session.commit()
134
+ return redirect('/admin/pages')
135
+ page = Pages(route, html)
136
+ db.session.add(page)
137
+ db.session.commit()
138
+ return redirect('/admin/pages')
139
+ if not route and request.method == 'POST':
140
+ return render_template('admin/editor.html')
141
+ pages = Pages.query.all()
142
+ return render_template('admin/pages.html', routes=pages)
143
+
144
+
145
+ @app.route('/admin/hosts', methods=['GET'])
146
+ @admins_only
147
+ def admin_hosts():
148
+ m = get_digitalocean()
149
+ errors = []
150
+ if not m:
151
+ errors.append("Your Digital Ocean API key is not set")
152
+ return render_template('admin/hosts.html', errors=errors)
153
+
154
+ hosts = m.get_all_droplets()
155
+ slugs = m.get_all_sizes()
156
+ images = m.get_all_images()
157
+ regions = m.get_all_regions()
158
+
159
+ return render_template('admin/hosts.html', hosts=hosts, slugs=slugs, images=images, regions=regions)
160
+
161
+ @app.route('/admin/chals', methods=['POST', 'GET'])
162
+ @admins_only
163
+ def admin_chals():
164
+ if request.method == 'POST':
165
+ chals = Challenges.query.add_columns('id', 'name', 'value', 'description', 'category').order_by(Challenges.value).all()
166
+
167
+ json = {'game':[]}
168
+ for x in chals:
169
+ json['game'].append({'id':x[1], 'name':x[2], 'value':x[3], 'description':x[4], 'category':x[5]})
170
+
171
+ db.session.close()
172
+ return jsonify(json)
173
+ else:
174
+ return render_template('admin/chals.html')
175
+
176
+ @app.route('/admin/keys/<chalid>', methods=['POST', 'GET'])
177
+ @admins_only
178
+ def admin_keys(chalid):
179
+ if request.method == 'GET':
180
+ keys = Keys.query.filter_by(chal=chalid).all()
181
+ json = {'keys':[]}
182
+ for x in keys:
183
+ json['keys'].append({'id':x.id, 'key':x.flag, 'type':x.key_type})
184
+ return jsonify(json)
185
+ elif request.method == 'POST':
186
+ keys = Keys.query.filter_by(chal=chalid).all()
187
+ for x in keys:
188
+ db.session.delete(x)
189
+
190
+ newkeys = request.form.getlist('keys[]')
191
+ newvals = request.form.getlist('vals[]')
192
+ for flag, val in zip(newkeys, newvals):
193
+ key = Keys(chalid, flag, val)
194
+ db.session.add(key)
195
+
196
+ db.session.commit()
197
+ db.session.close()
198
+ return '1'
199
+
200
+ @app.route('/admin/tags/<chalid>', methods=['GET', 'POST'])
201
+ @admins_only
202
+ def admin_tags(chalid):
203
+ if request.method == 'GET':
204
+ tags = Tags.query.filter_by(chal=chalid).all()
205
+ json = {'tags':[]}
206
+ for x in tags:
207
+ json['tags'].append({'id':x.id, 'chal':x.chal, 'tag':x.tag})
208
+ return jsonify(json)
209
+
210
+ elif request.method == 'POST':
211
+ newtags = request.form.getlist('tags[]')
212
+ for x in newtags:
213
+ tag = Tags(chalid, x)
214
+ db.session.add(tag)
215
+ db.session.commit()
216
+ db.session.close()
217
+ return '1'
218
+
219
+ @app.route('/admin/tags/<tagid>/delete', methods=['POST'])
220
+ @admins_only
221
+ def admin_delete_tags(tagid):
222
+ if request.method == 'POST':
223
+ tag = Tags.query.filter_by(id=tagid).first_or_404()
224
+ db.session.delete(tag)
225
+ db.session.commit()
226
+ db.session.close()
227
+ return "1"
228
+
229
+
230
+ @app.route('/admin/files/<chalid>', methods=['GET', 'POST'])
231
+ @admins_only
232
+ def admin_files(chalid):
233
+ if request.method == 'GET':
234
+ files = Files.query.filter_by(chal=chalid).all()
235
+ json = {'files':[]}
236
+ for x in files:
237
+ json['files'].append({'id':x.id, 'file':x.location})
238
+ return jsonify(json)
239
+ if request.method == 'POST':
240
+ if request.form['method'] == "delete":
241
+ f = Files.query.filter_by(id=request.form['file']).first_or_404()
242
+ if os.path.isfile(f.location):
243
+ os.unlink(f.location)
244
+ db.session.delete(f)
245
+ db.session.commit()
246
+ db.session.close()
247
+ return "1"
248
+ elif request.form['method'] == "upload":
249
+ files = request.files.getlist('files[]')
250
+
251
+ for f in files:
252
+ filename = secure_filename(f.filename)
253
+
254
+ if len(filename) <= 0:
255
+ continue
256
+
257
+ md5hash = hashlib.md5(os.urandom(64)).hexdigest()
258
+
259
+ # BUG NEEDS TO GO TO S3
260
+ if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], md5hash)):
261
+ os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], md5hash))
262
+
263
+ f.save(os.path.join(app.config['UPLOAD_FOLDER'], md5hash, filename))
264
+ db_f = Files(chalid, os.path.join(app.config['UPLOAD_FOLDER'], md5hash, filename))
265
+ db.session.add(db_f)
266
+
267
+ db.session.commit()
268
+ db.session.close()
269
+ return redirect('/admin/chals')
270
+
271
+ @app.route('/admin/teams')
272
+ @admins_only
273
+ def admin_teams():
274
+ teams = Teams.query.all()
275
+ return render_template('admin/teams.html', teams=teams)
276
+
277
+ @app.route('/admin/team/<teamid>', methods=['GET', 'POST'])
278
+ @admins_only
279
+ def admin_team(teamid):
280
+ user = Teams.query.filter_by(id=teamid).first()
281
+ solves = Solves.query.filter_by(teamid=teamid).all()
282
+ addrs = Tracking.query.filter_by(team=teamid).group_by(Tracking.ip).all()
283
+ score = user.score()
284
+ place = user.place()
285
+
286
+ if request.method == 'GET':
287
+ return render_template('admin/team.html', solves=solves, team=user, addrs=addrs, score=score, place=place)
288
+ elif request.method == 'POST':
289
+ name = request.form.get('name', None)
290
+ password = request.form.get('password', None)
291
+ email = request.form.get('email', None)
292
+ website = request.form.get('website', None)
293
+ affiliation = request.form.get('affiliation', None)
294
+ country = request.form.get('country', None)
295
+
296
+ errors = []
297
+
298
+ name_used = Teams.query.filter(Teams.name == name).first()
299
+ if name_used and int(name_used.id) != int(teamid):
300
+ errors.append('That name is taken')
301
+
302
+ email_used = Teams.query.filter(Teams.email == email).first()
303
+ if email_used and int(email_used.id) != int(teamid):
304
+ errors.append('That email is taken')
305
+
306
+ if errors:
307
+ db.session.close()
308
+ return jsonify({'data':errors})
309
+ else:
310
+ user.name = name
311
+ user.email = email
312
+ if password:
313
+ user.password = bcrypt_sha256(password)
314
+ user.website = website
315
+ user.affiliation = affiliation
316
+ user.country = country
317
+ db.session.commit()
318
+ db.session.close()
319
+ return jsonify({'data':['success']})
320
+
321
+ @app.route('/admin/team/<teamid>/mail', methods=['POST'])
322
+ @admins_only
323
+ def email_user(teamid):
324
+ message = request.form.get('msg', None)
325
+ team = Teams.query.filter(Teams.id == teamid).first()
326
+ if message and team:
327
+ if sendmail(team.email, message):
328
+ return "1"
329
+ return "0"
330
+
331
+
332
+ @app.route('/admin/team/<teamid>/ban', methods=['POST'])
333
+ @admins_only
334
+ def ban(teamid):
335
+ user = Teams.query.filter_by(id=teamid).first()
336
+ user.banned = 1
337
+ db.session.commit()
338
+ return redirect('/admin/scoreboard')
339
+
340
+ @app.route('/admin/team/<teamid>/unban', methods=['POST'])
341
+ @admins_only
342
+ def unban(teamid):
343
+ user = Teams.query.filter_by(id=teamid).first()
344
+ user.banned = None
345
+ db.session.commit()
346
+ return redirect('/admin/scoreboard')
347
+
348
+ @app.route('/admin/team/<teamid>/delete', methods=['POST'])
349
+ @admins_only
350
+ def delete_team(teamid):
351
+ user = Teams.query.filter_by(id=teamid).first()
352
+ db.session.delete(user)
353
+ db.session.commit()
354
+ return '1'
355
+
356
+
357
+ @app.route('/admin/graphs/<graph_type>')
358
+ @admins_only
359
+ def admin_graph(graph_type):
360
+ if graph_type == 'categories':
361
+ categories = db.session.query(Challenges.category, db.func.count(Challenges.category)).group_by(Challenges.category).all()
362
+ json = {'categories':[]}
363
+ for category, count in categories:
364
+ json['categories'].append({'category':category, 'count':count})
365
+ return jsonify(json)
366
+ elif graph_type == "solves":
367
+ solves = Solves.query.add_columns(db.func.count(Solves.chalid)).group_by(Solves.chalid).all()
368
+ json = {}
369
+ for chal, count in solves:
370
+ json[chal.chal.name] = count
371
+ return jsonify(json)
372
+
373
+ @app.route('/admin/scoreboard')
374
+ @admins_only
375
+ def admin_scoreboard():
376
+ score = db.func.sum(Challenges.value).label('score')
377
+ quickest = db.func.max(Solves.date).label('quickest')
378
+ teams = db.session.query(Solves.teamid, Teams.name, Teams.banned, score).join(Teams).join(Challenges).group_by(Solves.teamid).order_by(score.desc(), quickest)
379
+ db.session.close()
380
+ return render_template('admin/scoreboard.html', teams=teams)
381
+
382
+ @app.route('/admin/scores')
383
+ @admins_only
384
+ def admin_scores():
385
+ score = db.func.sum(Challenges.value).label('score')
386
+ quickest = db.func.max(Solves.date).label('quickest')
387
+ teams = db.session.query(Solves.teamid, Teams.name, score).join(Teams).join(Challenges).filter(Teams.banned == None).group_by(Solves.teamid).order_by(score.desc(), quickest)
388
+ db.session.close()
389
+ json = {'teams':[]}
390
+ for i, x in enumerate(teams):
391
+ json['teams'].append({'place':i+1, 'id':x.teamid, 'name':x.name,'score':int(x.score)})
392
+ return jsonify(json)
393
+
394
+ @app.route('/admin/solves/<teamid>', methods=['GET'])
395
+ @admins_only
396
+ def admin_solves(teamid="all"):
397
+ if teamid == "all":
398
+ solves = Solves.query.all()
399
+ else:
400
+ solves = Solves.query.filter_by(teamid=teamid).all()
401
+ db.session.close()
402
+ json = {'solves':[]}
403
+ for x in solves:
404
+ json['solves'].append({'id':x.id, 'chal':x.chal.name, 'chalid':x.chalid,'team':x.teamid, 'value': x.chal.value, 'category':x.chal.category, 'time':unix_time(x.date)})
405
+ return jsonify(json)
406
+
407
+ @app.route('/admin/statistics', methods=['GET'])
408
+ @admins_only
409
+ def admin_stats():
410
+ db.session.commit()
411
+
412
+ teams_registered = db.session.query(db.func.count(Teams.id)).first()[0]
413
+ wrong_count = db.session.query(db.func.count(WrongKeys.id)).first()[0]
414
+ solve_count = db.session.query(db.func.count(Solves.id)).first()[0]
415
+ challenge_count = db.session.query(db.func.count(Challenges.id)).first()[0]
416
+ most_solved_chal = Solves.query.add_columns(db.func.count(Solves.chalid).label('solves')).group_by(Solves.chalid).order_by('solves DESC').first()
417
+ least_solved_chal = Solves.query.add_columns(db.func.count(Solves.chalid).label('solves')).group_by(Solves.chalid).order_by('solves ASC').first()
418
+
419
+ db.session.close()
420
+
421
+ return render_template('admin/statistics.html', team_count=teams_registered,
422
+ wrong_count=wrong_count,
423
+ solve_count=solve_count,
424
+ challenge_count=challenge_count,
425
+ most_solved=most_solved_chal,
426
+ least_solved=least_solved_chal
427
+ )
428
+
429
+
430
+
431
+ @app.route('/admin/fails/<teamid>', methods=['GET'])
432
+ @admins_only
433
+ def admin_fails(teamid='all'):
434
+ if teamid == "all":
435
+ fails = WrongKeys.query.count()
436
+ solves = Solves.query.count()
437
+ db.session.close()
438
+ json = {'fails':str(fails), 'solves': str(solves)}
439
+ return jsonify(json)
440
+ else:
441
+ fails = WrongKeys.query.filter_by(team=teamid).count()
442
+ solves = Solves.query.filter_by(teamid=teamid).count()
443
+ db.session.close()
444
+ json = {'fails':str(fails), 'solves': str(solves)}
445
+ return jsonify(json)
446
+
447
+
448
+
449
+ @app.route('/admin/chal/new', methods=['POST'])
450
+ def admin_create_chal():
451
+ files = request.files.getlist('files[]')
452
+
453
+ # Create challenge
454
+ chal = Challenges(request.form['name'], request.form['desc'], request.form['value'], request.form['category'])
455
+ db.session.add(chal)
456
+ db.session.commit()
457
+
458
+ # Add keys
459
+ key = Keys(chal.id, request.form['key'], request.form['key_type[0]'])
460
+ db.session.add(key)
461
+ db.session.commit()
462
+
463
+ for f in files:
464
+ filename = secure_filename(f.filename)
465
+
466
+ if len(filename) <= 0:
467
+ continue
468
+
469
+ md5hash = hashlib.md5(filename).hexdigest()
470
+
471
+ if not os.path.exists(os.path.join(os.path.normpath(app.config['UPLOAD_FOLDER']), md5hash)):
472
+ os.makedirs(os.path.join(os.path.normpath(app.config['UPLOAD_FOLDER']), md5hash))
473
+
474
+ f.save(os.path.join(os.path.normpath(app.config['UPLOAD_FOLDER']), md5hash, filename))
475
+ db_f = Files(chal.id, os.path.join(os.path.normpath(app.config['UPLOAD_FOLDER']), md5hash, filename))
476
+ db.session.add(db_f)
477
+
478
+ db.session.commit()
479
+ db.session.close()
480
+ return redirect('/admin/chals')
481
+
482
+ @app.route('/admin/chal/delete', methods=['POST'])
483
+ def admin_delete_chal():
484
+ challenge = Challenges.query.filter_by(id=request.form['id']).first()
485
+ if challenge:
486
+ WrongKeys.query.filter_by(chal=challenge.id).delete()
487
+ Solves.query.filter_by(chalid=challenge.id).delete()
488
+ Keys.query.filter_by(chal=challenge.id).delete()
489
+ files = Files.query.filter_by(chal=challenge.id).all()
490
+ print files
491
+ Files.query.filter_by(chal=challenge.id).delete()
492
+ for file in files:
493
+ folder = os.path.dirname(file.location)
494
+ rmdir(folder)
495
+ Tags.query.filter_by(chal=challenge.id).delete()
496
+ Challenges.query.filter_by(id=challenge.id).delete()
497
+ db.session.commit()
498
+ db.session.close()
499
+ return "flag{at_least_it_isnt_php}"
500
+
501
+ @app.route('/admin/chal/update', methods=['POST'])
502
+ def admin_update_chal():
503
+ challenge = Challenges.query.filter_by(id=request.form['id']).first()
504
+ challenge.name = request.form['name']
505
+ challenge.description = request.form['desc']
506
+ challenge.value = request.form['value']
507
+ challenge.category = request.form['category']
508
+ db.session.add(challenge)
509
+ db.session.commit()
510
+ db.session.close()
511
+ return redirect('/admin/chals')
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/admin.pyc ADDED
Binary file (19.7 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/auth.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import render_template, request, redirect, abort, jsonify, url_for, session
2
+ from CTFd.utils import sha512, is_safe_url, authed, mailserver, sendmail, can_register
3
+ from CTFd.models import db, Teams
4
+
5
+ from itsdangerous import TimedSerializer, BadTimeSignature
6
+ from passlib.hash import bcrypt_sha256
7
+ from flask import current_app as app
8
+
9
+ import logging
10
+ import time
11
+ import re
12
+ import os
13
+
14
+ def init_auth(app):
15
+ @app.context_processor
16
+ def inject_user():
17
+ if authed():
18
+ return dict(session)
19
+ return dict()
20
+
21
+ @app.route('/reset_password', methods=['POST', 'GET'])
22
+ @app.route('/reset_password/<data>', methods=['POST', 'GET'])
23
+ def reset_password(data=None):
24
+ if data is not None and request.method == "GET":
25
+ return render_template('reset_password.html', mode='set')
26
+ if data is not None and request.method == "POST":
27
+ try:
28
+ s = TimedSerializer(app.config['SECRET_KEY'])
29
+ name = s.loads(data.decode('base64'), max_age=1800)
30
+ except BadTimeSignature:
31
+ return render_template('reset_password.html', errors=['Your link has expired'])
32
+ team = Teams.query.filter_by(name=name).first()
33
+ team.password = sha512(request.form['password'].strip())
34
+ db.session.commit()
35
+ db.session.close()
36
+ return redirect('/login')
37
+
38
+ if request.method == 'POST':
39
+ email = request.form['email'].strip()
40
+ team = Teams.query.filter_by(email=email).first()
41
+ if not team:
42
+ return render_template('reset_password.html', errors=['Check your email'])
43
+ s = TimedSerializer(app.config['SECRET_KEY'])
44
+ token = s.dumps(team.name)
45
+ text = """
46
+ Did you initiate a password reset?
47
+
48
+ {0}/reset_password/{1}
49
+
50
+ """.format(app.config['HOST'], token.encode('base64'))
51
+
52
+ sendmail(email, text)
53
+
54
+ return render_template('reset_password.html', errors=['Check your email'])
55
+ return render_template('reset_password.html')
56
+
57
+ @app.route('/register', methods=['POST', 'GET'])
58
+ def register():
59
+ if not can_register():
60
+ return redirect('/login')
61
+ if request.method == 'POST':
62
+ errors = []
63
+ name_len = len(request.form['name']) == 0
64
+ names = Teams.query.add_columns('name', 'id').filter_by(name=request.form['name']).first()
65
+ emails = Teams.query.add_columns('email', 'id').filter_by(email=request.form['email']).first()
66
+ pass_short = len(request.form['password']) == 0
67
+ pass_long = len(request.form['password']) > 128
68
+ valid_email = re.match("[^@]+@[^@]+\.[^@]+", request.form['email'])
69
+
70
+ if not valid_email:
71
+ errors.append("That email doesn't look right")
72
+ if names:
73
+ errors.append('That team name is already taken')
74
+ if emails:
75
+ errors.append('That email has already been used')
76
+ if pass_short:
77
+ errors.append('Pick a longer password')
78
+ if pass_long:
79
+ errors.append('Pick a shorter password')
80
+ if name_len:
81
+ errors.append('Pick a longer team name')
82
+
83
+ if len(errors) > 0:
84
+ return render_template('register.html', errors=errors, name=request.form['name'], email=request.form['email'], password=request.form['password'])
85
+ else:
86
+ with app.app_context():
87
+ team = Teams(request.form['name'], request.form['email'], request.form['password'])
88
+ db.session.add(team)
89
+ db.session.commit()
90
+ if mailserver():
91
+ sendmail(request.form['email'], "You've successfully registered for the CTF")
92
+
93
+ db.session.close()
94
+
95
+ logger = logging.getLogger('regs')
96
+ logger.warn("[{0}] {1} registered with {2}".format(time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'), request.form['email'].encode('utf-8')))
97
+ return redirect('/login')
98
+ else:
99
+ return render_template('register.html')
100
+
101
+ @app.route('/login', methods=['POST', 'GET'])
102
+ def login():
103
+ if request.method == 'POST':
104
+ errors = []
105
+ # team = Teams.query.filter_by(name=request.form['name'], password=sha512(request.form['password'])).first()
106
+ team = Teams.query.filter_by(name=request.form['name']).first()
107
+ if team and bcrypt_sha256.verify(request.form['password'], team.password):
108
+ try:
109
+ session.regenerate() # NO SESSION FIXATION FOR YOU
110
+ except:
111
+ pass # TODO: Some session objects don't implement regenerate :(
112
+ session['username'] = team.name
113
+ session['id'] = team.id
114
+ session['admin'] = team.admin
115
+ session['nonce'] = sha512(os.urandom(10))
116
+ db.session.close()
117
+
118
+ logger = logging.getLogger('logins')
119
+ logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8')))
120
+
121
+ # if request.args.get('next') and is_safe_url(request.args.get('next')):
122
+ # return redirect(request.args.get('next'))
123
+ return redirect('/team/{0}'.format(team.id))
124
+ else:
125
+ errors.append("That account doesn't seem to exist")
126
+ db.session.close()
127
+ return render_template('login.html', errors=errors)
128
+ else:
129
+ db.session.close()
130
+ return render_template('login.html')
131
+
132
+
133
+ @app.route('/logout')
134
+ def logout():
135
+ if authed():
136
+ session.clear()
137
+ return redirect('/')
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/auth.pyc ADDED
Binary file (5.66 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/challenges.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import current_app as app, render_template, request, redirect, abort, jsonify, json as json_mod, url_for, session
2
+
3
+ from CTFd.utils import ctftime, authed, unix_time, get_kpm, can_view_challenges
4
+ from CTFd.models import db, Challenges, Files, Solves, WrongKeys, Keys
5
+
6
+ import time
7
+ import re
8
+ import logging
9
+
10
+ def init_challenges(app):
11
+ @app.route('/challenges', methods=['GET'])
12
+ def challenges():
13
+ if not ctftime():
14
+ return redirect('/')
15
+ if can_view_challenges():
16
+ return render_template('chals.html')
17
+ else:
18
+ return redirect(url_for('login', next="challenges"))
19
+
20
+ @app.route('/chals', methods=['GET'])
21
+ def chals():
22
+ if not ctftime():
23
+ return redirect('/')
24
+ if can_view_challenges():
25
+ chals = Challenges.query.add_columns('id', 'name', 'value', 'description', 'category').order_by(Challenges.value).all()
26
+
27
+ json = {'game':[]}
28
+ for x in chals:
29
+ files = [ str(f.location) for f in Files.query.filter_by(chal=x.id).all() ]
30
+ json['game'].append({'id':x[1], 'name':x[2], 'value':x[3], 'description':x[4], 'category':x[5], 'files':files})
31
+
32
+ db.session.close()
33
+ return jsonify(json)
34
+ else:
35
+ db.session.close()
36
+ return redirect('/login')
37
+
38
+ @app.route('/chals/solves')
39
+ def chals_per_solves():
40
+ if can_view_challenges():
41
+ solves = Solves.query.add_columns(db.func.count(Solves.chalid)).group_by(Solves.chalid).all()
42
+ json = {}
43
+ for chal, count in solves:
44
+ json[chal.chal.name] = count
45
+ return jsonify(json)
46
+ return redirect(url_for('login', next="/chals/solves"))
47
+
48
+ @app.route('/solves')
49
+ @app.route('/solves/<teamid>')
50
+ def solves(teamid=None):
51
+ if teamid is None:
52
+ if authed():
53
+ solves = Solves.query.filter_by(teamid=session['id']).all()
54
+ else:
55
+ abort(401)
56
+ else:
57
+ solves = Solves.query.filter_by(teamid=teamid).all()
58
+ db.session.close()
59
+ json = {'solves':[]}
60
+ for x in solves:
61
+ json['solves'].append({'id':x.id, 'chal':x.chal.name, 'chalid':x.chalid,'team':x.teamid, 'value': x.chal.value, 'category':x.chal.category, 'time':unix_time(x.date)})
62
+ return jsonify(json)
63
+
64
+ @app.route('/fails/<teamid>', methods=['GET'])
65
+ def fails(teamid):
66
+ fails = WrongKeys.query.filter_by(team=teamid).count()
67
+ solves = Solves.query.filter_by(teamid=teamid).count()
68
+ db.session.close()
69
+ json = {'fails':str(fails), 'solves': str(solves)}
70
+ return jsonify(json)
71
+
72
+ @app.route('/chal/<chalid>/solves', methods=['GET'])
73
+ def who_solved(chalid):
74
+ solves = Solves.query.filter_by(chalid=chalid)
75
+ json = {'teams':[]}
76
+ for solve in solves:
77
+ json['teams'].append({'id':solve.team.id, 'name':solve.team.name, 'date':solve.date})
78
+ return jsonify(json)
79
+
80
+ @app.route('/chal/<chalid>', methods=['POST'])
81
+ def chal(chalid):
82
+ if not ctftime():
83
+ return redirect('/')
84
+ if authed():
85
+ logger = logging.getLogger('keys')
86
+ data = (time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'), request.form['key'].encode('utf-8'), get_kpm(session['id']))
87
+ print "[{0}] {1} submitted {2} with kpm {3}".format(*data)
88
+ if get_kpm(session['id']) > 10:
89
+ wrong = WrongKeys(session['id'], chalid, request.form['key'])
90
+ db.session.add(wrong)
91
+ db.session.commit()
92
+ db.session.close()
93
+ logger.warn("[{0}] {1} submitted {2} with kpm {3} [TOO FAST]".format(*data))
94
+ return "3" # Submitting too fast
95
+ solves = Solves.query.filter_by(teamid=session['id'], chalid=chalid).first()
96
+ if not solves:
97
+ keys = Keys.query.filter_by(chal=chalid).all()
98
+ key = request.form['key'].strip().lower()
99
+ for x in keys:
100
+ if x.key_type == 0: #static key
101
+ if x.flag.strip().lower() == key:
102
+ solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr)
103
+ db.session.add(solve)
104
+ db.session.commit()
105
+ db.session.close()
106
+ logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
107
+ return "1" # key was correct
108
+ elif x.key_type == 1: #regex
109
+ res = re.match(str(x), key, re.IGNORECASE)
110
+ if res and res.group() == key:
111
+ solve = Solves(chalid=chalid, teamid=session['id'], ip=request.remote_addr)
112
+ db.session.add(solve)
113
+ db.session.commit()
114
+ db.session.close()
115
+ logger.info("[{0}] {1} submitted {2} with kpm {3} [CORRECT]".format(*data))
116
+ return "1" # key was correct
117
+
118
+ wrong = WrongKeys(session['id'], chalid, request.form['key'])
119
+ db.session.add(wrong)
120
+ db.session.commit()
121
+ db.session.close()
122
+ logger.info("[{0}] {1} submitted {2} with kpm {3} [WRONG]".format(*data))
123
+ return '0' # key was wrong
124
+ else:
125
+ logger.info("{0} submitted {1} with kpm {2} [ALREADY SOLVED]".format(*data))
126
+ return "2" # challenge was already solved
127
+ else:
128
+ return "-1"
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/challenges.pyc ADDED
Binary file (6.2 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/config.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ ##### SERVER SETTINGS #####
3
+ SECRET_KEY = os.urandom(64)
4
+ SQLALCHEMY_DATABASE_URI = 'sqlite:///ctfd.db'
5
+ SESSION_TYPE = "filesystem"
6
+ SESSION_FILE_DIR = "/tmp/flask_session"
7
+ SESSION_COOKIE_HTTPONLY = True
8
+ HOST = ".ctfd.io"
9
+ UPLOAD_FOLDER = os.path.normpath('static/uploads')
10
+
11
+ ##### EMAIL #####
12
+ CTF_NAME = ''
13
+ MAIL_SERVER = ''
14
+ MAIL_PORT = 0
15
+ MAIL_USE_TLS = False
16
+ MAIL_USE_SSL = False
17
+ MAIL_USERNAME = ''
18
+ MAIL_PASSWORD = ''
19
+ ADMINS = []
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/config.pyc ADDED
Binary file (753 Bytes). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/ctfd.db ADDED
Binary file (18.4 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/errors.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import current_app as app, render_template
2
+
3
+ def init_errors(app):
4
+ @app.errorhandler(404)
5
+ def page_not_found(error):
6
+ return render_template('errors/404.html'), 404
7
+
8
+ @app.errorhandler(403)
9
+ def forbidden(error):
10
+ return render_template('errors/403.html'), 403
11
+
12
+ @app.errorhandler(500)
13
+ def forbidden(error):
14
+ return render_template('errors/500.html'), 500
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/errors.pyc ADDED
Binary file (1.2 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/models.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #from CTFd import db
2
+ from flask.ext.sqlalchemy import SQLAlchemy
3
+
4
+ from socket import inet_aton, inet_ntoa
5
+ from struct import unpack, pack
6
+ from passlib.hash import bcrypt_sha256
7
+
8
+ import datetime
9
+ import hashlib
10
+
11
+ def sha512(string):
12
+ return hashlib.sha512(string).hexdigest()
13
+
14
+ def ip2long(ip):
15
+ return unpack('!I', inet_aton(ip))[0]
16
+
17
+ def long2ip(ip_int):
18
+ return inet_ntoa(pack('!I', ip_int))
19
+
20
+ db = SQLAlchemy()
21
+
22
+
23
+ class Pages(db.Model):
24
+ id = db.Column(db.Integer, primary_key=True)
25
+ route = db.Column(db.String(80), unique=True)
26
+ html = db.Column(db.Text)
27
+
28
+ def __init__(self, route, html):
29
+ self.route = route
30
+ self.html = html
31
+
32
+ def __repr__(self):
33
+ return "<Tag {0} for challenge {1}>".format(self.tag, self.chal)
34
+
35
+ class Challenges(db.Model):
36
+ id = db.Column(db.Integer, primary_key=True)
37
+ name = db.Column(db.String(80))
38
+ description = db.Column(db.Text)
39
+ value = db.Column(db.Integer)
40
+ category = db.Column(db.String(80))
41
+ # add open category
42
+
43
+ def __init__(self, name, description, value, category):
44
+ self.name = name
45
+ self.description = description
46
+ self.value = value
47
+ self.category = category
48
+
49
+ def __repr__(self):
50
+ return '<chal %r>' % self.name
51
+
52
+ class Tags(db.Model):
53
+ id = db.Column(db.Integer, primary_key=True)
54
+ chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
55
+ tag = db.Column(db.String(80))
56
+
57
+ def __init__(self, chal, tag):
58
+ self.chal = chal
59
+ self.tag = tag
60
+
61
+ def __repr__(self):
62
+ return "<Tag {0} for challenge {1}>".format(self.tag, self.chal)
63
+
64
+ class Files(db.Model):
65
+ id = db.Column(db.Integer, primary_key=True)
66
+ chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
67
+ location = db.Column(db.Text)
68
+
69
+ def __init__(self, chal, location):
70
+ self.chal = chal
71
+ self.location = location
72
+
73
+ def __repr__(self):
74
+ return "<File {0} for challenge {1}>".format(self.location, self.chal)
75
+
76
+ class Keys(db.Model):
77
+ id = db.Column(db.Integer, primary_key=True)
78
+ chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
79
+ key_type = db.Column(db.Integer)
80
+ flag = db.Column(db.Text)
81
+
82
+
83
+ def __init__(self, chal, flag, key_type):
84
+ self.chal = chal
85
+ self.flag = flag
86
+ self.key_type = key_type
87
+
88
+ def __repr__(self):
89
+ return self.flag
90
+
91
+
92
+ class Teams(db.Model):
93
+ id = db.Column(db.Integer, primary_key=True)
94
+ name = db.Column(db.String(128), unique=True)
95
+ email = db.Column(db.String(128), unique=True)
96
+ password = db.Column(db.String(128))
97
+ website = db.Column(db.String(128))
98
+ affiliation = db.Column(db.String(128))
99
+ country = db.Column(db.String(32))
100
+ bracket = db.Column(db.String(32))
101
+ banned = db.Column(db.Boolean)
102
+ admin = db.Column(db.Boolean)
103
+
104
+ def __init__(self, name, email, password):
105
+ self.name = name
106
+ self.email = email
107
+ self.password = bcrypt_sha256.encrypt(password)
108
+
109
+ def __repr__(self):
110
+ return '<team %r>' % self.name
111
+
112
+ def score(self):
113
+ score = db.func.sum(Challenges.value).label('score')
114
+ team = db.session.query(Solves.teamid, score).join(Teams).join(Challenges).filter(Teams.banned == None, Teams.id==self.id).group_by(Solves.teamid).first()
115
+ if team:
116
+ return team.score
117
+ else:
118
+ return 0
119
+
120
+ def place(self):
121
+ score = db.func.sum(Challenges.value).label('score')
122
+ quickest = db.func.max(Solves.date).label('quickest')
123
+ teams = db.session.query(Solves.teamid).join(Teams).join(Challenges).filter(Teams.banned == None).group_by(Solves.teamid).order_by(score.desc(), quickest).all()
124
+ #http://codegolf.stackexchange.com/a/4712
125
+ try:
126
+ i = teams.index((self.id,)) + 1
127
+ k = i % 10
128
+ return "%d%s" % (i, "tsnrhtdd"[(i / 10 % 10 != 1) * (k < 4) * k::4])
129
+ except ValueError:
130
+ return 0
131
+
132
+ class Solves(db.Model):
133
+ __table_args__ = (db.UniqueConstraint('chalid', 'teamid'), {})
134
+ id = db.Column(db.Integer, primary_key=True)
135
+ chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))
136
+ teamid = db.Column(db.Integer, db.ForeignKey('teams.id'))
137
+ ip = db.Column(db.Integer)
138
+ date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
139
+ team = db.relationship('Teams', foreign_keys="Solves.teamid", lazy='joined')
140
+ chal = db.relationship('Challenges', foreign_keys="Solves.chalid", lazy='joined')
141
+ # value = db.Column(db.Integer)
142
+
143
+ def __init__(self, chalid, teamid, ip):
144
+ self.ip = ip2long(ip)
145
+ self.chalid = chalid
146
+ self.teamid = teamid
147
+ # self.value = value
148
+
149
+ def __repr__(self):
150
+ return '<solves %r>' % self.chal
151
+
152
+
153
+ class WrongKeys(db.Model):
154
+ id = db.Column(db.Integer, primary_key=True)
155
+ chal = db.Column(db.Integer, db.ForeignKey('challenges.id'))
156
+ team = db.Column(db.Integer, db.ForeignKey('teams.id'))
157
+ date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
158
+ flag = db.Column(db.Text)
159
+
160
+ def __init__(self, team, chal, flag):
161
+ self.team = team
162
+ self.chal = chal
163
+ self.flag = flag
164
+
165
+ def __repr__(self):
166
+ return '<wrong %r>' % self.flag
167
+
168
+
169
+ class Tracking(db.Model):
170
+ id = db.Column(db.Integer, primary_key=True)
171
+ ip = db.Column(db.BigInteger)
172
+ team = db.Column(db.Integer, db.ForeignKey('teams.id'))
173
+ date = db.Column(db.DateTime, default=datetime.datetime.utcnow)
174
+
175
+ def __init__(self, ip, team):
176
+ self.ip = ip2long(ip)
177
+ self.team = team
178
+
179
+ def __repr__(self):
180
+ return '<ip %r>' % self.team
181
+
182
+ class Config(db.Model):
183
+ id = db.Column(db.Integer, primary_key=True)
184
+ key = db.Column(db.Text)
185
+ value = db.Column(db.Text)
186
+
187
+ def __init__(self, key, value):
188
+ self.key = key
189
+ self.value = value
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/models.pyc ADDED
Binary file (11.2 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/scoreboard.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import current_app as app, session, render_template, jsonify
2
+ from CTFd.utils import unix_time
3
+ from CTFd.models import db, Teams, Solves, Challenges
4
+
5
+ def init_scoreboard(app):
6
+ @app.route('/scoreboard')
7
+ def scoreboard():
8
+ score = db.func.sum(Challenges.value).label('score')
9
+ quickest = db.func.max(Solves.date).label('quickest')
10
+ teams = db.session.query(Solves.teamid, Teams.name, score).join(Teams).join(Challenges).filter(Teams.banned == None).group_by(Solves.teamid).order_by(score.desc(), quickest)
11
+ #teams = db.engine.execute("SELECT solves.teamid, teams.id, teams.name, SUM(value) as score, MAX(solves.date) as quickest FROM solves JOIN teams ON solves.teamid=teams.id INNER JOIN challenges ON solves.chalid=challenges.id WHERE teams.banned IS NULL GROUP BY solves.teamid ORDER BY score DESC, quickest ASC;")
12
+ db.session.close()
13
+ return render_template('scoreboard.html', teams=teams)
14
+
15
+ @app.route('/scores')
16
+ def scores():
17
+ #teams = db.engine.execute("SELECT solves.teamid, teams.id, teams.name, SUM(value) as score, MAX(solves.date) as quickest FROM solves JOIN teams ON solves.teamid=teams.id INNER JOIN challenges ON solves.chalid=challenges.id WHERE teams.banned IS NULL GROUP BY solves.teamid ORDER BY score DESC, quickest ASC;")
18
+ score = db.func.sum(Challenges.value).label('score')
19
+ quickest = db.func.max(Solves.date).label('quickest')
20
+ teams = db.session.query(Solves.teamid, Teams.name, score).join(Teams).join(Challenges).filter(Teams.banned == None).group_by(Solves.teamid).order_by(score.desc(), quickest)
21
+ db.session.close()
22
+ json = {'teams':[]}
23
+ for i, x in enumerate(teams):
24
+ json['teams'].append({'place':i+1, 'id':x.teamid, 'name':x.name,'score':int(x.score)})
25
+ return jsonify(json)
26
+
27
+ @app.route('/top/<count>')
28
+ def topteams(count):
29
+ try:
30
+ count = int(count)
31
+ except:
32
+ count = 10
33
+ if count > 20 or count < 0:
34
+ count = 10
35
+
36
+ json = {'scores':{}}
37
+
38
+ #teams = db.engine.execute("SELECT solves.teamid, teams.id, teams.name, SUM(value) as score, MAX(solves.date) as quickest FROM solves JOIN teams ON solves.teamid=teams.id INNER JOIN challenges ON solves.chalid=challenges.id WHERE teams.banned IS NULL GROUP BY solves.teamid ORDER BY score DESC, quickest ASC LIMIT {0};".format(count))
39
+ score = db.func.sum(Challenges.value).label('score')
40
+ teams = db.session.query(Solves.teamid, Teams.name, score, db.func.max(Solves.date).label('quickest')).join(Teams).join(Challenges).filter(Teams.banned == None).group_by(Solves.teamid).order_by(score.desc(), Solves.date).limit(count)
41
+
42
+
43
+ for team in teams:
44
+ solves = Solves.query.filter_by(teamid=team.teamid).all()
45
+ json['scores'][team.name] = []
46
+ for x in solves:
47
+ json['scores'][team.name].append({'id':x.teamid, 'chal':x.chalid, 'team':x.teamid, 'value': x.chal.value, 'time':unix_time(x.date)})
48
+
49
+ return jsonify(json)
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/scoreboard.pyc ADDED
Binary file (3.04 kB). View file
 
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/CTFd/utils.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from CTFd.models import db, WrongKeys, Pages, Config
2
+ from CTFd import mail
3
+
4
+ from urlparse import urlparse, urljoin
5
+ from functools import wraps
6
+ from flask import current_app as app, g, request, redirect, url_for, session
7
+ from flask.ext.mail import Message
8
+ from socket import inet_aton, inet_ntoa
9
+ from struct import unpack, pack
10
+
11
+ import time
12
+ import datetime
13
+ import hashlib
14
+ import digitalocean
15
+ import shutil
16
+
17
+
18
+ def init_utils(app):
19
+ app.jinja_env.filters['unix_time'] = unix_time
20
+ app.jinja_env.filters['unix_time_millis'] = unix_time_millis
21
+ app.jinja_env.filters['long2ip'] = long2ip
22
+ app.jinja_env.globals.update(pages=pages)
23
+ app.jinja_env.globals.update(can_register=can_register)
24
+ app.jinja_env.globals.update(mailserver=mailserver)
25
+
26
+
27
+ def pages():
28
+ pages = Pages.query.filter(Pages.route!="index").all()
29
+ return pages
30
+
31
+
32
+ def authed():
33
+ return bool(session.get('id', False))
34
+
35
+
36
+ def is_setup():
37
+ setup = Config.query.filter_by(key='setup').first()
38
+ if setup:
39
+ return setup.value
40
+ else:
41
+ return False
42
+
43
+
44
+ def is_admin():
45
+ if authed():
46
+ return session['admin']
47
+ else:
48
+ return False
49
+
50
+
51
+ def can_register():
52
+ config = Config.query.filter_by(key='prevent_registration').first()
53
+ if config:
54
+ return config.value != '1'
55
+ else:
56
+ return True
57
+
58
+
59
+ def admins_only(f):
60
+ @wraps(f)
61
+ def decorated_function(*args, **kwargs):
62
+ if session.get('admin', None) is None:
63
+ return redirect(url_for('login', next=request.url))
64
+ return f(*args, **kwargs)
65
+ return decorated_function
66
+
67
+
68
+ def ctftime():
69
+ """ Checks whether it's CTF time or not. """
70
+
71
+ start = Config.query.filter_by(key="start").first().value
72
+ end = Config.query.filter_by(key="end").first().value
73
+
74
+ if start:
75
+ start = int(start)
76
+ if end:
77
+ end = int(end)
78
+
79
+ if start and end:
80
+ if start < time.time() and time.time() < end:
81
+ # Within the two time bounds
82
+ return True
83
+
84
+ if start < time.time() and end is None:
85
+ # CTF starts on a date but never ends
86
+ return True
87
+
88
+ if start is None and time.time() < end:
89
+ # CTF started but ends at a date
90
+ return True
91
+
92
+ if start is None and end is None:
93
+ # CTF has no time requirements
94
+ return True
95
+
96
+ return False
97
+
98
+
99
+ def can_view_challenges():
100
+ config = Config.query.filter_by(key="view_challenges_unregistered").first()
101
+ if config:
102
+ return authed() or config.value == '1'
103
+ else:
104
+ return authed()
105
+
106
+
107
+ def unix_time(dt):
108
+ epoch = datetime.datetime.utcfromtimestamp(0)
109
+ delta = dt - epoch
110
+ return int(delta.total_seconds())
111
+
112
+
113
+ def unix_time_millis(dt):
114
+ return unix_time(dt) * 1000
115
+
116
+
117
+ def long2ip(ip_int):
118
+ return inet_ntoa(pack('!I', ip_int))
119
+
120
+
121
+ def ip2long(ip):
122
+ return unpack('!I', inet_aton(ip))[0]
123
+
124
+
125
+ def get_kpm(teamid): # keys per minute
126
+ one_min_ago = datetime.datetime.utcnow() + datetime.timedelta(minutes=-1)
127
+ return len(db.session.query(WrongKeys).filter(WrongKeys.team == teamid, WrongKeys.date >= one_min_ago).all())
128
+
129
+
130
+ def get_config(key):
131
+ config = Config.query.filter_by(key=key).first()
132
+ if config:
133
+ return config.value
134
+ else:
135
+ return None
136
+
137
+
138
+ def set_config(key, value):
139
+ config = Config.query.filter_by(key=key).first()
140
+ if config:
141
+ config.value = value
142
+ else:
143
+ config = Config(key, value)
144
+ db.session.add(config)
145
+ db.session.commit()
146
+ return config
147
+
148
+
149
+ def mailserver():
150
+ if app.config['MAIL_SERVER'] and app.config['MAIL_PORT'] and app.config['ADMINS']:
151
+ return True
152
+ return False
153
+
154
+
155
+ def sendmail(addr, text):
156
+ try:
157
+ msg = Message("Message from {0}".format(app.config['CTF_NAME']), sender = app.config['ADMINS'][0], recipients = [addr])
158
+ msg.body = text
159
+ mail.send(msg)
160
+ return True
161
+ except:
162
+ return False
163
+
164
+
165
+ def rmdir(dir):
166
+ shutil.rmtree(dir, ignore_errors=True)
167
+
168
+ def is_safe_url(target):
169
+ ref_url = urlparse(request.host_url)
170
+ test_url = urlparse(urljoin(request.host_url, target))
171
+ return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
172
+
173
+
174
+ def sha512(string):
175
+ return hashlib.sha512(string).hexdigest()
176
+
177
+
178
+ def get_digitalocean():
179
+ token = get_config('do_api_key')
180
+ if token:
181
+ return digitalocean.Manager(token=token)
182
+ else:
183
+ return False
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![](https://github.com/isislab/CTFd/blob/master/static/img/logo.png)
2
+ ====
3
+
4
+ CTFd is a CTF in a can. Easily modifiable and has everything you need to run a jeopardy style CTF.
5
+
6
+ Install:
7
+ 1. `./prepare.sh` to install dependencies using apt.
8
+ 2. Modify [CTFd/config.py](https://github.com/isislab/CTFd/blob/master/CTFd/config.py) to your liking.
9
+ 3. Use `python serve.py` in a terminal to drop into debug mode.
10
+ 4. [Here](http://flask.pocoo.org/docs/0.10/deploying/) are some Flask deployment options
11
+
12
+ Live Demo:
13
+ [https://demo.ctfd.io/](https://demo.ctfd.io/)
14
+
15
+ Logo by [Laura Barbera](http://www.laurabb.com/)
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/prepare.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ apt-get install build-essential python-dev python-pip
4
+ pip install -r requirements.txt
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APScheduler==3.0.1
2
+ Flask==0.10.1
3
+ Flask-Mail==0.9.1
4
+ Flask-SQLAlchemy==2.0
5
+ Flask-Session==0.1.1
6
+ SQLAlchemy==0.9.8
7
+ passlib==1.6.2
8
+ bcrypt
9
+ six==1.8.0
10
+ itsdangerous
11
+ python-digitalocean
12
+ Werkzeug<1
benchmark/NYU_CTF_Bench/development/2015/CSAW-Quals/web/throwback/CTFd/serve.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from CTFd import create_app
2
+ app = create_app()
3
+ app.run(debug=True, host="0.0.0.0", port=4000)