-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
2057 lines (1812 loc) · 75.2 KB
/
app.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, url_for, send_from_directory, render_template, abort, request, make_response, session, redirect, Response
from datetime import timedelta
import zipfile
import shutil
import sys
import logging
import jsonify
from werkzeug.utils import secure_filename
from flask_socketio import SocketIO, emit, join_room, leave_room, send
import redis
import datetime
from jjuctf.config import *
from jjuctf.Check import *
from jjuctf.Crypto import *
from jjuctf.Container import *
from jjuctf.functions import *
import random
import json
import threading
from flask_apscheduler import APScheduler # 引入APScheduler
app = Flask(__name__)
# start
# 任务配置类
class SchedulerConfig(object):
JOBS = [
{
'id': 'check_awd_status', # 任务id
'func': '__main__:check_awd', # 任务执行程序
'args': None, # 执行程序参数
'trigger': 'interval', # 任务执行类型,定时器
'seconds': 10, # 任务执行时间,单位秒
}
]
# 定义任务执行程序
def check_awd():
# print("I'm a scheduler!")
update_awd_flag()
def update_awd_flag():
mysql = Mysqld()
docker = Contain()
print('第',app.arrangement,'轮开始')
instance_list = mysql.select_awd_instance_id_list()
# ((972, '19f18de054c6'), (973, '149eaca40f72'), (974, 'cc8...
for i in instance_list:
id = i[0]
container_id = i[1]
falg = hashlib.md5((str(random.randint(1,1000))+str(random.randint(1,1000))).encode('utf8')).hexdigest()
#为实例化的flask引入定时任务配置
flag = 'flag{%s}'%(falg)
# print(flag)
docker.insert_awd_flag(container_id,flag,'/flag')
mysql.update_instance_id_list(id,flag,app.arrangement)
app.arrangement += 1
app.config.from_object(SchedulerConfig())
# end
# redis 连接
redis_instance = redis.Redis(host=redis_address, port=redis_port, decode_responses=True)
app.secret_key = '905008' # session 密钥
handler = logging.FileHandler('jjuctf.log')
app.logger.addHandler(handler)
socketio = SocketIO(app, cors_allowed_origins='*')
# 命名空间
name_space = '/test'
# 常量
app.config['UPLOAD_FOLDER'] = 'jjuctf/upload_file/'
app.config['UPLOAD_CTF_FILE'] = 'jjuctf/CTF_FILE/'
app.config['UPLOAD_CTF_CONTAINER'] = 'jjuctf/CTF_CONTAINER/'
app.config['UPLOAD_AWD_CONTAINER'] = 'jjuctf/AWD_CONTAINER/'
# 没啥用测试用的
@socketio.on('test')
def test123():
print('hello world')
@app.route("/test")
@app.route("/test", methods=["POST", "GET"])
def test():
return render_template("user/index_bak.html")
@app.route('/push')
def push():
event_name = 'test'
broadcast_data = "hello world!"
emit(event_name, broadcast_data, broadcast=True, namespace=name_space)
return "done!"
@socketio.on('connect', namespace=name_space)
def connected_msg():
print('client connected.')
@socketio.on('disconnect', namespace=name_space)
def disconnect_msg():
print('client disconnected.')
@app.route('/login', methods=['GET', 'POST'])
def login():
if session.get("user"):
return render_template("user/index.html")
if request.method == 'GET':
return render_template('user/login.html')
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if check_input(username) == 0 or check_input(password) == 0:
return render_template("user/login.html", message="请勿攻击靶场,违者做违规处理!")
if username == '' or password == '': # 检查用户名和密码是否为空
return render_template("user/login.html", message="用户名或密码不能为空")
mysql = Mysqld()
# 查一下是否拥有队伍
group_id = mysql.selectGroupidByusername(username)
# 防止重复注册
result = mysql.checkuser(username, password) # 对用户表进行操作,检查登录
# result为1表示该用户名未注册过
if result == 1:
session.permanent = False # 设置session为永久的
# app.permanent_session_lifetime = timedelta(minutes=20) # 设置session到期时间,单位分钟
session['user'] = request.form.get('username')
if group_id != 0:
resp = make_response(redirect(url_for('index')))
# print(group_id)/
message = str(group_id) + ':' + username
# print(message)
token = encrypt(message)
# print(token)
# 添加token信息
resp.set_cookie('token', token)
return resp
else:
return redirect(url_for('index'))
# return render_template('user/index.html', message="登陆成功")
else:
return render_template("user/login.html", message="帐号或密码错误")
else:
return redirect('/login')
# ctf解题模式
@app.route('/challenges')
def challenge():
app.logger.info("success")
user = session.get('user')
if user: # 如果登录成功
# 获取CTf实例列表
check = Check()
mysql = Mysqld()
challengeResult = mysql.selectChallengeListByUserName(user)
# print(challengeResult)
# 展示题目列表
challengeNum = mysql.showChallengeNum()
# challengeTypeNum = getChallengeListByType.selectCtfChallengeTypeNum(user) #用这个代替上面那个!今天不写了,难受,我写的垃圾代码。。。
# 查找队伍信息
groupInfo = mysql.selectGroupInfoByUsername(user)
#
UserTypeNum = mysql.selectCtfTypeNum()
# 如果该用户没有创建队伍,那么跳转让他创建队伍
if groupInfo == 0:
return redirect('/group')
challenge_list_rank = mysql.selectChallengeListRank()
# 分别得到排名,分数,解题数
rank, score, Challenge_Count = sortChallengeByGroupId(challenge_list_rank, groupInfo[0])
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
# 转换为js需要的格式
userChallengeinfo = mysql.selectUserChallengeListDesc()
startDateTime = str(competition_info[3])
endDateTime = str(competition_info[4])
end_time = str(competition_info[4]).replace('-', '/')
# 比赛状态码 如果比赛正在进行,则结果为1,已结束为2,未开始为0
competition_StatusCode = check.checkCompetition_start(startDateTime, endDateTime)
# 公告栏
userNotice = mysql.selectUserNotice()
# 解题动态 CTF_History_table
ctf_history_table = mysql.selectCtfHistoryTable()
# 0为web 以此类推
return render_template("user/challenge.html", username=user, headerType="challenges",
challengeResult=challengeResult, ctf_history_table=ctf_history_table,
examNum=challengeNum, groupInfo=groupInfo, userNotice=userNotice,
competition_info=competition_info, end_time=end_time,
competition_StatusCode=competition_StatusCode, UserTypeNum=UserTypeNum,
rank=rank, sum_score=score, Challenge_Count=Challenge_Count)
return render_template('user/login.html')
# 排序,找出带队伍的名次
def sortChallengeByGroupId(challenge_info, id):
# 当没有解题信息的时候,就返回这个
# rank,sls
# core,Challenge_Count
if challenge_info == ():
return None, 0, 0
rankid = 1
for i in challenge_info:
if id == i[0]:
return rankid, i[1], i[2]
else:
rankid += 1
return None, 0, 0
# index
# ctf解题模式
@app.route('/')
@app.route('/index')
def index():
user = session.get('user')
if user: # 如果登录成功
mysql = Mysqld()
# 比赛信息
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
return render_template("user/index.html", username=user, headerType="index", competition_info=competition_info)
return render_template('user/login.html')
@app.route('/ranks')
def ranks():
user = session.get('user')
type = request.args.get('type')
if user:
mysql = Mysqld()
# 这个函数貌似没啥用了,有时间的话就把这个删除
# GetChallengeList = mysql.select_user_challenge_list()
# GetGroupInfo = sqlcheck.
if type == 'ctf':
getUserCTFChallengeList = mysql.selectUserChallengeListDesc()
getUserCTFChallengeListNum = len(getUserCTFChallengeList)
GetUserNum = mysql.selectUserNum(user) # 查数据库将排行榜数据传到template中,目前是测试阶段,使用的是用户表
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
return render_template("user/ranks-ctf.html", username=user, headerType="rank", userNum=GetUserNum, a=1,
getUserCTFChallengeList=getUserCTFChallengeList,
getUserCTFChallengeListNum=getUserCTFChallengeListNum,
competition_info=competition_info)
if type == 'awd':
getUserAWDChallengeList = mysql.select_awd_rank_desc()
getUserAWDChallengeListNum = len(getUserAWDChallengeList)
GetUserNum = mysql.selectUserNum(user) # 查数据库将排行榜数据传到template中,目前是测试阶段,使用的是用户表
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
return render_template("user/ranks-awd.html", username=user, headerType="rank", userNum=GetUserNum, a=1,
getUserAWDChallengeList=getUserAWDChallengeList,
getUserAWDChallengeListNum=getUserAWDChallengeListNum,
competition_info=competition_info)
else:
return render_template("404.html")
else:
return render_template("user/login.html")
@app.route('/register', methods=['POST', 'GET'])
def userRegister():
if session.get('user'):
return redirect(url_for('index',message='您已经登录,无需注册!'))
if request.method != 'POST': # 用户不是使用
# =====start ====
# 等号里面的代码可以随时删除
# 思路:用于注册验证邮箱的,首先给注册者一个随机6位数,
# 然后给注册者一个sesson,用于跟踪用户,
# 然后注册者点击发送邮件,服务器就发送这个随机6位数给该邮箱
# 当验证成功之后,就执行其他步骤。
# 随机生产6位数字字符串
serialMail = ''
for i in range(6):
ch = chr(random.randrange(ord('0'), ord('9') + 1))
serialMail += ch
checkMailId = serialMail
session['checkid'] = checkMailId
print(checkMailId)
# =====end =====
return render_template("user/register.html")
else:
uid = request.form.get('uid')
username = request.form.get('username')
realname = request.form.get('realname')
email = request.form.get('email')
mobile = request.form.get('mobile')
class_id = request.form.get('classid')
passwd = request.form.get('passwd')
resultEmpty = 0
# result = checkstr.checkUserString(username=username,password=passwd,useremail=email,) #检查用户输入的字符串
if passwd == '' or username == '' or email == '' or mobile == '' or uid == '' or realname == '' or class_id == '':
resultEmpty = 1
if resultEmpty == 1:
return render_template("user/register.html", message="提交异常,请重新输入")
adduser = Mysqld()
if adduser.checkUserRegister(username=username) == 1:
return render_template("user/register.html", message="用户已经注册过!")
result1 = adduser.adduser(username, passwd, email)
if result1 == 1:
return render_template("user/login.html", message="注册成功,请到队伍管理添加队伍!")
@app.route("/logout")
def logout():
session.clear()
resp = Response()
if request.cookies.get('token'):
resp.delete_cookie('token')
resp.data = render_template("user/login.html", message="退出帐号成功,请重新登录")
return resp
# AWD模块
@app.route('/awd')
def awd():
user = session.get('user')
if user:
mysql = Mysqld()
groupInfo = mysql.selectGroupInfoByUsername(user)
# 如果该用户没有创建队伍,那么跳转让他创建队伍
#
if groupInfo == 0:
return redirect('/group')
# 比赛信息
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
# 公告栏
userNotice = mysql.selectUserNotice()
# 挑战列表信息
# (('test1234', 'awd_b4', '172.18.0.2', 0), ('admin', 'awd_b4', '172.18.0.3', 0))
awd_target_list = mysql.select_awd_target_list()
# awd挑战列表,最多有三个
awd_list = mysql.select_awd_target_by_groupname(groupInfo[1])
awd_rank_list = mysql.select_awd_rank_desc()
return render_template("user/awd.html", username=user, headerType="awd", groupInfo=groupInfo,
competition_info=competition_info, userNotice=userNotice,awd_target_list=awd_target_list
,awd_list=awd_list,awd_rank_list=awd_rank_list)
else:
return render_template("user/login.html")
# 用户个人设置
@app.route('/user', methods=['GET'])
def user():
user = session.get('user')
if user:
username = user
mysql = Mysqld()
userinfo = mysql.selectUserInfo(user)
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
# print(userinfo)
usergroupinfo = mysql.selectGroupInfoByUsername(user)
# print(usergroupinfo)
# print(usergroup)
return render_template('user/userinfo.html', username=username, headerType=username, userinfo=userinfo,
usergroupinfo=usergroupinfo, competition_info=competition_info)
# return render_template("user/user.html", username=username, headerType=username, userinfo=userinfo,usergroupinfo=usergroupinfo, competition_info=competition_info)
else:
return render_template("user/login.html")
@app.route('/user_setting', methods=['GET'])
def user_setting():
user = session.get('user')
if user:
mysql = Mysqld()
userinfo = mysql.selectUserInfo(user)
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
usergroupinfo = mysql.selectGroupInfoByUsername(user)
return render_template('user/user_setting.html', username=user, headerType=user,
competition_info=competition_info, userinfo=userinfo, usergroupinfo=usergroupinfo)
else:
return render_template('user/login.html')
# 队伍设置
@app.route('/group', methods=['GET'])
def groupSetting():
user = session.get('user')
if user:
# 获得用户名
username = user
mysql = Mysqld()
# 得到用户信息
userinfo = mysql.selectUserInfo(user)
# 得到用户队伍的id,如果没有则为0
group_id = mysql.selectGroupidByusername(user)
# print(groupinfo)
# 得到比赛信息
competition_info = mysql.selectCompetition_InfoByStatus(0)[0]
# 如果存在比赛id
if group_id != 0:
groupinfo = mysql.selectGroupInfoByUsername(user)
# 队伍成员信息
# 如果这个身份为队长,那么
if groupinfo[3] == mysql.selectUserIdByUserName(user):
# uid形式表示
applyList = mysql.selectUserGroupApplyByGroupId(group_id)
UserApplyList = []
# print(applyList)
for uid in applyList:
list = []
applyUsername = mysql.selectUserNameByUserId(uid[0])
list.append(uid[0])
# print(applyUsername)
list.append(applyUsername)
UserApplyList.append(list)
print(UserApplyList)
else:
UserApplyList = ()
userGroupList = mysql.selectUserGroupListByGroupId(group_id)
# 解题信息
userScoreList = mysql.selectUserScoreListByGroupId(group_id)
# print(userGroupList)
# print(userScoreList)
# (('hsm', 1),)
# (('web1', 0, 'hsm', 100, datetime.datetime(2021, 1, 5, 11, 5, 43)),)
# print(userinfo)
return render_template("user/groupinfo.html", username=username, headerType="userSetting", userinfo=userinfo,
group_id=group_id, groupinfo=groupinfo, userGroupList=userGroupList,
competition_info=competition_info, userScoreList=userScoreList,
UserApplyList=UserApplyList)
else:
return render_template("user/groupinfo.html", username=username, headerType="userSetting",
competition_info=competition_info, userinfo=userinfo, group_id=group_id)
else:
return render_template("user/login.html")
# 检查CTF答题模式flag是否正确
# 通过ajax验证
@app.route("/checkCtfFlag", methods=["POST"])
def checkCtfFlag():
# 检查flag需要ctf_id这个参数
user = session.get("user")
flag = request.form.get('flag')
challenge_id = int(request.form.get('ctf_id'))
if user:
if flag and challenge_id:
# ctf_id就是CTF靶场id
# 每创建一个题目都会创建一个或者多个ctf_id,静态flag只需要创建一个id即可
a = Mysqld()
result = a.checkFalg(flag, challenge_id)
# 如果result为1则正确,0为不正确
# print(result)
if result == 1: # 查到flag正确
mysql = Mysqld()
group_id = mysql.selectGroupInfoByUsername(user)[0]
groupname = mysql.selectGroupNameByGroupId(group_id)
# 检查队伍之前是否提交过这个flag
userPostFlag = mysql.checkUser_Post_Flag_OkByGroupIdAndCid(group_id, challenge_id)
# print(group_id)
# 如果返回值不为空,则表示之前已经提交过flag
if userPostFlag:
return "501"
# group_id!=0表示...
if group_id != 0:
# 获取ctf类型和分数
(ctfType, score) = mysql.selectCtfTypeAndScoreByChallenge_id(challenge_id)
# 解答时间
challenge_time = time.strftime("%H:%M:%S", time.localtime())
# 用户id
user_id = mysql.selectUserIdByUserName(user)
# 插入到得分表中
challengeinfo = mysql.selectChallengeInfoByChallengeId(challenge_id)
if challengeinfo:
data = {'name': groupname, "target": challengeinfo[0], "date": challenge_time,
"challenge_id": challenge_id, "score": str(score)}
# 广播战况
emit('challenge_list', data, broadcast=True, namespace='/challenges')
# 更新队伍答题记录
adduserscore_result = mysql.addUserScore(group_id, ctfType, challenge_id, user_id, score,
challenge_time)
ranknum = ctf_search_rank(groupname)
# print(ranknum)
data2 = {'name': groupname, "target": challengeinfo[0], "date": challenge_time,
"challenge_id": challenge_id, "score": str(score),"ranks":ranknum}
emit('group_message', data2, room=str(group_id), namespace='/challenges')
if adduserscore_result == 1:
return "1"
else:
return '0'
else:
return "0"
else:
return "0"
else:
return "503"
else:
return "502"
else:
return "0"
@app.route("/adminlogin")
def adminlogin():
if session.get("admin"):
return render_template("admin/login.html")
return render_template('admin/login.html')
@app.route("/admin_notice")
def admin_notice():
if session.get("admin"):
selectUserNotice = Mysqld()
userNotice = selectUserNotice.selectUserNotice()
return render_template("admin/admin_notice.html", userNotice=userNotice)
return render_template('admin/login.html')
# ajax实现
@app.route("/delUserNotice", methods=["POST"])
def delUserNotice():
if session.get('admin'):
if request.method == 'POST':
id = int(request.form.get('id'))
if id != 0:
mysql = Mysqld()
result = mysql.delUserNotice(id)
if result == 1:
return "1"
else:
return "0"
else:
return "0"
return "0"
# 检查admin登录情况
@app.route("/checkAdminLogin", methods=["POST"])
def checkAdminLogin():
if session.get("admin"):
return render_template("admin/index.html")
if request.method == 'GET':
# 如果是GET方法请求的,那么重新登录
return render_template('admin/login.html')
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username == '' or password == '': # 检查用户名和密码是否为空
return render_template("admin/login.html", message="用户名或密码不能为空")
checkuser = Mysqld()
result = checkuser.checkAdminLogin(username, password) # 对用户表进行操作,检查登录
if result == 1:
session.permanent = True # 设置session为永久的
app.permanent_session_lifetime = timedelta(minutes=20) # 设置session到期时间,单位分钟
session['admin'] = request.form.get('username')
return redirect('/admin')
else:
return render_template("admin/login.html", message="帐号或密码错误")
else:
return redirect('/login')
# ============================后台=================================
# 后台首页
@app.route("/admin")
def adminIndex():
admin = session.get('admin')
if admin:
mysql = Mysqld()
userNum = len(mysql.selectUserList())
groupNum = len(mysql.selectUserGroupList())
# 用户挑战数的
user_Challenge_List_Num = len(mysql.select_user_challenge_list())
return render_template("admin/index.html",userNum=userNum,groupNum=groupNum,user_Challenge_List_Num=user_Challenge_List_Num)
else:
return render_template("admin/login.html")
# ajax
# /admin 里面的echart数据更新
@app.route('/get_ctf_type')
def get_ctf_type():
admin = session.get('admin')
if admin:
typename = ['WEB', 'MISC', 'Crypto', 'Pwn', 'Reverse']
mysql = Mysqld()
ctf_type_num = mysql.select_ctf_type_num()
for i in ctf_type_num:
# web
if i[0] == 0:
web_num = i[1]
if i[0] == 1:
misc_num = i[1]
if i[0] == 2:
crypto_num = i[1]
if i[0] == 3:
reverse_num = i[1]
if i[0] == 4:
pwn_num = i[1]
type_num = [{'value': web_num, 'name': 'WEB'},{'value': misc_num, 'name': 'MISC'},{'value': crypto_num, 'name': 'Crypto'},{'value': pwn_num, 'name': 'Pwn'},{'value': reverse_num, 'name': 'Reverse'}]
return json.dumps({'typename':typename,'type_num':type_num},ensure_ascii=False)
else:
return ''
# 管理员系统设置
@app.route("/setting_info")
def setting_info():
admin = session.get("admin")
admin_ip = request.remote_addr
user_agent = request.user_agent
# 操作系统信息
system_info = {}
if os.name == 'nt':
system_info['system_os'] = 'Windows'
else:
system_info['system_os'] = 'Linux'
# python 版本
python_version = sys.version
system_info['python_version'] = python_version
# 数据库版本
mysql = Mysqld()
sql_version = mysql.select_sql_version()
system_info['sql_version'] = sql_version
# docker版本
docker = Contain()
docker_version = docker.show_docker_version()
system_info['docker_version'] = docker_version
if admin:
return render_template("admin/setting_info.html", admin_ip=admin_ip, adminname=admin, user_agent=user_agent,system_info=system_info)
else:
return render_template("admin/login.html")
# 添加管理员
@app.route("/add_admin")
@app.route("/add_admin", methods=['POST'])
def add_admin():
admin = session.get('admin')
if admin:
if request.method != 'POST':
return render_template("admin/addAdmin.html")
elif request.method == 'POST':
name = request.form.get('name')
passwd = request.form.get('passwd')
email = request.form.get('email')
mobile = request.form.get('mobile')
addAdmin = Mysqld()
result = addAdmin.addAdmin(name, email, mobile, passwd)
if result:
return redirect(url_for('man_admin', message="成功添加记录"))
return render_template("admin/addAdmin.html")
else:
return render_template("admin/login.html")
# CTF实例
@app.route("/man_ctf_instance")
def man_target_ctf():
admin = session.get('admin')
if admin:
connectsql = Mysqld()
ctfList = connectsql.selectCtfInstanceList()
# print(ctfList)
return render_template("admin/man_ctf_instance.html", ctfList=ctfList)
else:
return render_template("admin/login.html")
# man_target_awd
@app.route("/man_target_awd")
def man_target_awd():
return render_template("admin/man_target_awd.html")
# CTF题目列表
@app.route("/man_ctf_exam")
def man_ctf_exam():
admin = session.get('admin')
if admin:
mysql = Mysqld()
ctf_exam = mysql.selectctf_exam()
return render_template("admin/man_ctf_exam.html", ctf_exam=ctf_exam)
else:
return render_template("admin/login.html")
# CTF操作
# 添加CTF题目
# {#own_id,type,name,hint,base_score,status,flag_type,base_flag,file_flag,file_path,docker_flag,docker_path,info#}
@app.route("/man_ctf_add_exam", methods=["POST", "GET"])
def man_ctf_add_exam():
admin = session.get('admin')
if admin:
if request.method == 'POST':
try:
type = int(request.form.get('exam_type'))
flag_type = int(request.form.get('flag_type'))
score = int(request.form.get("base_score"))
except:
return render_template("admin/man_ctf_add_exam.html", message="添加失败,请按规范输入!")
name = request.form.get('exam_name')
hint = request.form.get('exam_hint')
flag = request.form.get('flag')
# 得到附件文件
file_path = request.files['file']
# file_path.save(os.path.join(app.config['UPLOAD_CTF_FILE'], secure_filename(file_path.filename)))
# 得到docker-compose文件
docker_image_id = request.form.get('docker_image_id')
# 题目备注
info = request.form.get('info')
createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if file_path.filename == '':
# 如果发现没有上传文件,则将flag标记为0,
file_flag = 0
else:
file_flag = 1
file_path.save(os.path.join(app.config['UPLOAD_CTF_FILE'], secure_filename(file_path.filename)))
# if docker_file.filename == '':
# docker_flag = 0
# else:
# # 上传docker zip包
# docker_flag = 1
# docker_file.save(
# os.path.join(app.config['UPLOAD_CTF_CONTAINER'], secure_filename(docker_file.filename)))
# # =======解压zip包=====
# # print(app.config['UPLOAD_CTF_CONTAINER']+docker_file.filename)
# zip = zipfile.ZipFile(app.config['UPLOAD_CTF_CONTAINER'] + docker_file.filename, 'r')
# try:
# zip.extractall(app.config['UPLOAD_CTF_CONTAINER'])
# except:
# return render_template("admin/man_ctf_add_exam.html", message="添加CTF题目失败,解压失败!")
# zip.close()
# # == 解压缩完成 ==
# # 删除上传的zip包
# os.remove(app.config['UPLOAD_CTF_CONTAINER'] + docker_file.filename)
docker_file = ''
if docker_image_id:
docker_flag = 1
else:
docker_flag = 0
mysql = Mysqld()
own_id = mysql.selectAdminIdByAdminName(admin)
result = mysql.addUserCtfExam(own_id, type, name, hint, score, 0, flag_type, flag, file_flag,
file_path.filename, docker_flag, docker_file, info,docker_image_id)
if result == 1:
return redirect(url_for('man_ctf_exam', message="添加成功")) # 页面跳转
else:
return render_template("admin/man_ctf_add_exam.html", message="添加失败")
else:
return render_template("admin/man_ctf_add_exam.html")
else:
return render_template("admin/login.html")
# 创建CTF实例
# 通过ajax实现,所以返回类型一定要是字符串
# 如果是静态flag的话,只需要创建一个实例为所有队伍使用就行
@app.route("/create_ctf_instance", methods=['POST'])
def create_ctf_instance():
admin = session.get('admin')
if admin:
ctf_exam_id = int(request.form.get('ctf_exam_id'))
mysql = Mysqld()
# 先检查是否已经创建过实例,实质是查challenge_list表是否存在数据
checkinsert = mysql.checkCtf_exam_insertById(ctf_exam_id)
# 查询这个实例之前是否创建过
if checkinsert == -1:
return "-1"
ctf_exam_info = mysql.selectctf_examByctf_exam_Id(ctf_exam_id)
# own_id = ctf_exam_info[1]
type = ctf_exam_info[2] # 题目类型 如web misc等
name = ctf_exam_info[3]
hint = ctf_exam_info[4]
score = ctf_exam_info[5]
flag = ctf_exam_info[7]
file_flag = ctf_exam_info[8]
file_info = ctf_exam_info[9]
docker_flag = ctf_exam_info[10]
docker_info = ctf_exam_info[11]
# info = ctf_exam_info[13]
# [6]为flag类型为静态flag
if ctf_exam_info[6] == 0:
# 如果docker_flag为1表示需要开启docker容器
if ctf_exam_info[10] == 1:
# 创建Docker虚拟机
docker_name = ctf_exam_info[11]
# print(docker_name)
docker = Contain()
# 打开虚拟机
docker.startContain(docker_name)
dockerid = docker.getDockerId(docker_name)
# print(dockerid)
docker_info = docker.geturl(dockerid)
else:
dockerid = [None]
result = mysql.insertChallenge_list(0, ctf_exam_id, name, hint, score, type, docker_flag, dockerid[0],
docker_info, file_flag, file_path=file_info, flag=flag)
# result = mysql.add_user_challenge_list(0, ctf_exam_id)
if result == 0:
# return "1"
print("create_ctf_instance函数插入错误!")
return "0"
# 动态flag:
return "1"
else:
return "0"
# ajax实现
# 用来删除CTF题目
@app.route('/delete_ctf_exam', methods=["POST"])
def delete_ctf_exam():
admin = session.get('admin')
if admin:
ctf_exam_id = int(request.form.get('ctf_exam_id'))
mysql = Mysqld()
# status[0],flag_type[1],file_flag[2],docker_flag[3],file_path[4],docker_path[5]
ctf_exam_info = mysql.selectCtf_exam_DeleteInfoByCtf_exam_Id(ctf_exam_id)
# 如果存在附件
if ctf_exam_info[2] == 1:
os.remove(app.config['UPLOAD_CTF_FILE'] + ctf_exam_info[4])
# 如果存在docker-compose文件
if ctf_exam_info[3] == 1:
shutil.rmtree(app.config['UPLOAD_CTF_CONTAINER'] + ctf_exam_info[5][:-4])
result = mysql.delUserCtfExam(ctf_exam_id)
if result == 1:
return "1"
else:
return "0"
else:
print("未授权访问/delete_ctf_exam!")
return "0"
# delete_ctf_instance
# ajax实现
# 用来删除CTF题目实例
@app.route('/delete_ctf_instance', methods=["POST"])
def delete_ctf_instance():
admin = session.get('admin')
if admin:
id = int(request.form.get('id'))
mysql = Mysqld()
ctfinstanceinfo = mysql.selectInstanceDockerStatusByChallengeId(id)
# group_id,docker_flag,ctf_exam_id
# group_id为0表示为静态flag,只需要关闭
if ctfinstanceinfo[0] == 0 and ctfinstanceinfo[1] == 1:
dockerID = ctfinstanceinfo[3]
# print(dockerID)
dockerServer = Contain()
dockerServer.stopContainByDockerID(dockerID)
result = mysql.delUserCtfInstanceById(id)
# result = 1
if result == 1:
return "1"
else:
return "0"
else:
print("未授权访问/delete_ctf_exam!")
return "0"
@app.route("/man_user")
def man_user():
admin = session.get('admin')
if admin:
# 消除意外弹框
# 启用之后,message参数将没用了
# if request.args.get('message'):
# return redirect(url_for('man_user'))
manAdmin = Mysqld()
userList = manAdmin.selectUserList()
if userList:
return render_template("admin/man_user.html", userList=userList)
else:
userList = ()
return render_template("admin/man_user.html", userList=userList)
else:
return render_template("admin/login.html")
@app.route("/man_admin", methods=["GET"])
def man_admin():
admin = session.get('admin')
if admin:
manAdmin = Mysqld()
adminList = manAdmin.selectAdminList()
if adminList:
return render_template("admin/man_admin.html", adminList=adminList)
return "404"
else:
return render_template('admin/login.html')
# 管理员登录退出
@app.route("/adminLogout")
def adminLogout():
session.clear()
return render_template("admin/login.html", message="退出帐号成功,请重新登录")
# 没啥用测试用的
@socketio.on('start_awd_exam')
def start_awd_exam_socket(group_list, images_id, name, ssh_port, other_port, ssh_user):
docker = Contain()
mysql = Mysqld()
now_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
print(now_time)
# 初始化当前任务索引
task_num = 0
# 总任务数
task_total = len(group_list)
print(task_total)
try:
# 初始化
data = {'status_code': '200', 'task_num': str(task_num), 'task_total': task_total, 'id': name}
emit('start_awd_exam', data, broadcast=True, namespace='/man_awd_exam')
task_num = 1
tmp_container_id_list = []
print('hello')
for i in group_list:
# 从ip池中获取一个ip
ip = docker_get_ip()
# print('image_id:',images_id)
container_id = docker.docker_start_by_imagesID('tag', images_id, ip)
print('ip:', ip)
if container_id == -1:
data = {'status_code': '500', 'id': container_id, 'task_num': str(task_num - 1),
'task_total': task_total, 'message': '启动镜像失败,image_id:' + images_id}
emit('start_awd_exam', data, broadcast=True, namespace='/man_awd_exam')
docker.docker_stop_container_by_list(tmp_container_id_list)
return -1
print('启动容器成功', container_id)
# 加入到临时列表中,当这个任务中断时,将之前开启的容器也一并关闭
tmp_container_id_list.append(container_id)
# 这里修改docker用户密码
passwd = get_random_password(ssh_user)
print('随机密码', passwd)
result = docker.docker_change_passwd(container_id, ssh_user, passwd)
if result == -1:
docker.docker_stop_container_by_list(tmp_container_id_list)
return -1
else:
status_code = mysql.insert_awd_instance(container_id, name, ssh_port, other_port, now_time, '', ip,
'tag', i[1], 1, ssh_user, passwd)
if status_code == 0:
data = {'status_code': '500', 'id': container_id, 'task_num': str(task_num - 1),
'task_total': task_total, 'message': '更新数据库错误'}
emit('start_awd_exam', data, broadcast=True, namespace='/man_awd_exam')
docker.docker_stop_container_by_list(tmp_container_id_list)
return -1
else:
print('progress:', task_num / task_total)
data = {'status_code': '200', 'task_num': task_num, 'task_total': task_total, 'id': name}
emit('start_awd_exam', data, broadcast=True, namespace='/man_awd_exam')
task_num += 1
print('status_code:', status_code)
# 修改awd开启状态
change_awd_exam_status_to_1_code = mysql.change_awd_exam_status_to_1_by_name(name)
if change_awd_exam_status_to_1_code == 1:
emit('start_awd_exam', data, broadcast=True, namespace='/man_awd_exam')
return 1
else:
docker.docker_stop_container_by_list(tmp_container_id_list)
return -1
except Exception as e:
# print('ddd')
print(e)
return -1