-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathtasks.py
1795 lines (1716 loc) · 78.6 KB
/
tasks.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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time :2020/4/27 20:41
# @Author :r4v3zn
# @Site :
# @File :tasks.py
from __future__ import absolute_import, unicode_literals
from celery import shared_task, chain
import uuid
import time
import socket
import docker
import traceback
import json
import django.utils.timezone as timezone
import random
from django.db.models import Q
from layout_image.bridge import get_project
from vulfocus.settings import client, api_docker_client, DOCKER_CONTAINER_TIME, VUL_IP, REDIS_POOL, DOCKER_COMPOSE
from dockerapi.common import DEFAULT_CONFIG
from dockerapi.models import ContainerVul, ImageInfo
from user.models import UserProfile
from docker.errors import NotFound, ImageNotFound, BuildError
from .models import TaskInfo
from dockerapi.common import R, HTTP_ERR
from dockerapi.models import SysLog
import datetime
from dockerapi.serializers import ImageInfoSerializer, ContainerVulSerializer
import redis
import requests
import os
import yaml
from layout_image.models import LayoutData, LayoutServiceContainer, LayoutService,Layout
from dockerapi.common import get_setting_config
r = redis.Redis(connection_pool=REDIS_POOL)
from django.db import transaction
import shutil
from ruamel.yaml import YAML
def create_image_task(image_info, user_info, request_ip, image_file=None):
"""
创建镜像任务
"""
user_id = user_info.id
task_id = create_create_image_task(image_info=image_info, user_info=user_info)
if user_info.is_superuser:
image_name = image_info.image_name
image_desc = image_info.image_desc
image_vul_name = image_info.image_vul_name
image_rank = image_info.rank
task_info = TaskInfo.objects.filter(task_id=task_id).first()
if image_file:
task_msg = {}
try:
file_info = image_file.read()
images = client.images.load(file_info)
image = images[0]
repo_tags = image.attrs["RepoTags"]
if len(repo_tags) == 0:
# 移除本地镜像
try:
client.images.remove(image.id)
except Exception as e:
pass
task_msg = R.build(msg="文件镜像 Tag 不能为空")
else:
config = image.attrs["ContainerConfig"]
port_list = []
if "ExposedPorts" in config:
port_list = config["ExposedPorts"]
else:
port_list = image.attrs['Config']['ExposedPorts']
ports = []
for port in port_list:
port = port.replace("/", "").replace("tcp", "").replace("udp", "")
ports.append(port)
image_name = repo_tags[0]
image_port = ",".join(ports)
image_info = ImageInfo.objects.filter(image_name=image_name).first()
if not image_info:
image_info = ImageInfo()
image_info.image_name = image_name
image_info.image_port = image_port
# image_vul_name
image_info.image_vul_name = image_name.replace("vulfocus/","") if not image_vul_name else image_vul_name
# image_desc
image_info.image_desc = image_name.replace("vulfocus/","") if not image_desc else image_desc
# rank
image_info.rank = 2.5 if image_rank > 5 or image_rank < 0.5 else image_rank
image_info.is_ok = True
image_info.save()
task_info.task_name = "拉取镜像:"+image_name
task_info.task_status = 3
task_msg = R.ok(data="%s 添加成功" % (image_name, ))
except Exception as e:
traceback.print_exc()
task_msg = R.err()
try:
image_info.delete()
except:
pass
task_info.task_status = 4
finally:
task_info.task_msg = json.dumps(task_msg)
task_info.update_date = timezone.now()
task_info.save()
elif image_name:
# 创建任务
# create_image(task_id=task_id)
create_image.delay(task_id)
else:
R.build(msg="镜像文件或镜像名称不能为空")
operation_args = ImageInfoSerializer(image_info).data
sys_log = SysLog(user_id=user_id, operation_type="镜像", operation_name="创建", ip=request_ip,
operation_value=operation_args["image_vul_name"], operation_args=json.dumps(operation_args))
sys_log.save()
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="权限不足"))
task_info.task_status = 3
task_info.update_date = timezone.now()
task_info.save()
return task_id
def create_compose_task(user_info, image_info, tag, request_ip):
"""
创建docker-compose镜像任务
"""
image_list = []
local_images = [i.tags[0] for i in client.images.list() if i.tags]
user_id = user_info.id
task_id = create_create_image_task(image_info=image_info, user_info=user_info)
task_infos = TaskInfo.objects.filter(task_id=task_id).first()
if user_info.is_superuser:
new_yaml = YAML(typ='safe')
new_yaml.allow_duplicate_keys = True
args_yaml = new_yaml.load(json.loads(image_info.original_yml))
for services_name in args_yaml['services']:
if "image" in args_yaml['services'][services_name]:
image_name = args_yaml['services'][services_name]['image']
if ':' not in image_name:
image_name = image_name + ":latest"
all_arg = {"img_name": image_name, "images_name": image_info.image_name, 'args_yaml': json.dumps(args_yaml), 'tag':tag}
if image_name:
task_info = TaskInfo(task_name="docker-compose相关镜像:" + image_name,
user_id=user_id,
task_status=1,
task_msg=json.dumps({}),
task_start_date=timezone.now(),
operation_type=7,
operation_args=json.dumps(all_arg),
create_date=timezone.now(),
update_date=timezone.now())
task_info.save()
task_id = task_info.task_id
image_list.append(image_name)
compose.delay(task_id)
else:
task_infos = TaskInfo.objects.filter(task_id=task_id).first()
task_infos.task_msg = json.dumps(R.build(msg="权限不足"))
task_infos.task_status = 4
task_infos.update_date = timezone.now()
task_infos.save()
return image_list
def share_image_task(image_info, user_info, request_ip):
"""
共享镜像
:param image_info: 镜像信息
:param user_info: 用户信息
:param request_ip: 请求 IP
:return:
"""
task_id = create_share_image_task(image_info=image_info, user_info=user_info)
operation_args = ImageInfoSerializer(image_info).data
sys_log = SysLog(user_id=user_info.id, operation_type="镜像", operation_name="分享", ip=request_ip,
operation_value=operation_args["image_vul_name"], operation_args=json.dumps(operation_args))
sys_log.save()
share_image.delay(task_id)
return task_id
def create_container_task(container_vul, user_info, request_ip):
"""
创建漏洞容器
:param container_vul: container vul
:param user_info: user info
:param request_ip: request ip
:return:
"""
image_info = container_vul.image_id
user_id = user_info.id
task_id = create_run_container_task(container_vul, user_info)
if user_info.is_superuser or user_id == container_vul.user_id:
operation_args = ImageInfoSerializer(image_info).data
sys_log = SysLog(user_id=user_id, operation_type="容器", operation_name="启动", ip=request_ip,
operation_value=operation_args["image_vul_name"], operation_args=json.dumps(operation_args))
sys_log.save()
setting_config = get_setting_config()
try:
countdown = int(setting_config["time"])
except:
countdown = int(DEFAULT_CONFIG["time"])
if countdown == 0:
run_container.delay(container_vul.container_id, user_id, task_id, countdown)
elif countdown != 0 and countdown > 60:
# run_container(container_vul.container_id, user_id, task_id, countdown)
setting_config = get_setting_config()
if 'del_container' in setting_config:
del_container = setting_config['del_container']
if not del_container or del_container == 0 or del_container == '0':
add_chain_sig = chain(run_container.s(container_vul.container_id, user_id, task_id, countdown) |
stop_container.s().set(countdown=countdown))
else:
add_chain_sig = chain(run_container.s(container_vul.container_id, user_id, task_id, countdown) |
delete_container.s().set(countdown=countdown))
add_chain_sig.apply_async()
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="停止时间最小为 1 分钟"))
task_info.task_status = 4
task_info.update_date = timezone.now()
task_info.save()
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="权限不足"))
task_info.task_status = 3
task_info.update_date = timezone.now()
task_info.save()
return task_id
def start_docker_compose(request, image_id, container_vul, user_info, request_ip, time_model_id):
image_info = container_vul.image_id
user_id = user_info.id
task_id = create_run_container_task(container_vul, user_info)
if user_info.is_superuser or user_id == container_vul.user_id:
operation_args = ImageInfoSerializer(image_info).data
sys_log = SysLog(user_id=user_id, operation_type="容器", operation_name="启动", ip=request_ip,
operation_value=operation_args["image_vul_name"], operation_args=json.dumps(operation_args))
sys_log.save()
setting_config = get_setting_config()
try:
countdown = int(setting_config["time"])
except:
countdown = int(DEFAULT_CONFIG["time"])
if countdown == 0:
run_docker_compose(container_vul.container_id, user_id, time_model_id, task_id, countdown)
elif countdown != 0 and countdown > 60:
setting_config = get_setting_config()
if 'del_container' in setting_config:
del_container = setting_config['del_container']
if not del_container or del_container == 0 or del_container == '0':
add_chain_sig = chain(run_docker_compose.s(image_id, container_vul.container_id, user_id, time_model_id, task_id, countdown, ) |
stop_docker_compose.s().set(countdown=countdown))
else:
add_chain_sig = chain(run_docker_compose.s(image_id, container_vul.container_id, user_id, time_model_id, task_id, countdown, ) |
stop_docker_compose.s().set(countdown=countdown))
add_chain_sig.apply_async()
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="停止时间最小为 1 分钟"))
task_info.task_status = 4
task_info.update_date = timezone.now()
task_info.save()
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="权限不足"))
task_info.task_status = 3
task_info.update_date = timezone.now()
task_info.save()
return task_id
def stop_container_task(container_vul, user_info, request_ip):
"""
停止漏洞容器
:param container_vul: container vul
:param user_info: user info
:param request_ip: request ip
:return:
"""
user_id = user_info.id
task_id = create_stop_container_task(container_vul=container_vul, user_info=user_info)
if user_info.is_superuser or user_id == container_vul.user_id:
operation_args = ContainerVulSerializer(container_vul).data
img_info = ImageInfo.objects.filter(image_id=operation_args['image_id']).first()
sys_log = SysLog(user_id=user_id, operation_type="容器", operation_name="停止", ip=request_ip,
operation_value=operation_args["vul_name"], operation_args=json.dumps(operation_args))
sys_log.save()
# 下发停止容器任务
if img_info.is_docker_compose == True:
stop_docker_compose.delay(task_id)
else:
stop_container.delay(task_id)
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="权限不足"))
task_info.task_status = 3
task_info.update_date = timezone.now()
task_info.save()
return task_id
def delete_container_task(container_vul, user_info, request_ip):
"""
删除漏洞容器
:param container_vul: container vul
:param user_info: user info
:param request_ip: request ip
:return:
"""
user_id = user_info.id
task_id = create_delete_container_task(container_vul=container_vul, user_info=user_info)
if user_info.is_superuser or user_id == container_vul.user_id:
operation_args = ContainerVulSerializer(container_vul).data
img_info = ImageInfo.objects.filter(image_id=operation_args['image_id']).first()
sys_log = SysLog(user_id=user_id, operation_type="容器", operation_name="删除", ip=request_ip,
operation_value=operation_args["vul_name"], operation_args=json.dumps(operation_args))
sys_log.save()
# 下发停止容器任务
if img_info.is_docker_compose == True:
delete_docker_compose.delay(task_id)
else:
delete_container.delay(task_id)
else:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
task_info.task_msg = json.dumps(R.build(msg="权限不足"))
task_info.task_status = 3
task_info.update_date = timezone.now()
task_info.save()
return task_id
@shared_task(name="tasks.run_docker_compose")
def run_docker_compose(image_id, container_id, user_id, time_model_id, task_id, countdown):
img_info = ImageInfo.objects.filter(image_id=image_id).first()
user_info = UserProfile.objects.filter(id=user_id).first()
container_vul = ContainerVul.objects.filter(container_id=container_id).first()
net_list = []
net_name = 'docker-compose-dedicated'
network_list = client.networks.list()
for i in network_list:
net_list.append(i.attrs['Name'])
if net_name in net_list:
pass
else:
ipam_pool = docker.types.IPAMPool(
subnet='192.168.10.10/24',
gateway='192.168.10.10'
)
ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool]
)
net_work = client.networks.create(
net_name,
driver='bridge',
ipam=ipam_config,
scope='local',
)
net_work_client_id = str(net_work.id)
if img_info.is_docker_compose == True:
if container_vul.container_status == 'stop':
container_vul.container_status = "running"
task_info = TaskInfo.objects.filter(task_id=task_id).first()
compose_path = os.path.join(DOCKER_COMPOSE, str(container_vul.container_id))
container_list = get_project(compose_path).up()
try:
with transaction.atomic():
for container in container_list:
docker_container_id = container.id
docker_container = client.containers.get(container.id)
container_vul_img = ContainerVul.objects.filter(docker_container_id=docker_container_id).first()
container_vul_img.container_status = 'running'
container_vul_img.save()
args = {
"image_name": img_info.image_name,
"user_id": user_id,
"image_port": img_info.image_port
}
task_start_date = timezone.now()
if countdown != 0 and countdown >= 60:
task_end_date = task_start_date + datetime.timedelta(seconds=countdown)
elif countdown == 0:
task_end_date = None
else:
countdown = int(DEFAULT_CONFIG["time"])
task_end_date = task_start_date + datetime.timedelta(seconds=countdown)
if "running" == docker_container.status:
msg_data = R.ok(data={
"host": container_vul.vul_host,
"port": json.loads(container_vul.vul_port),
"id": str(container_vul.container_id),
"status": "running",
"start_date": int(task_start_date.timestamp()),
"end_date": 0 if not task_end_date else int(task_end_date.timestamp())
})
search_task = TaskInfo.objects.filter(user_id=user_id, task_msg=json.dumps(msg_data),
operation_type=2,
operation_args=json.dumps(args),
task_end_date=task_end_date,
task_name="运行容器:" + img_info.image_name).order_by(
"-create_date").first()
if not search_task:
task_info.task_status = 3
task_info.task_msg = json.dumps(msg_data)
task_info.update_date = timezone.now()
task_info.operation_args = json.dumps(args)
task_info.save()
task_id = str(task_info.task_id)
else:
task_info.delete()
search_task.task_id = task_id
search_task.task_status = 3
search_task.update_date = timezone.now()
search_task.save()
task_id = str(search_task.task_id)
container_vul.save()
except Exception as e:
traceback.print_exc()
else:
vulport = {}
yml_c = json.loads(img_info.docker_compose_yml)
yml_c['networks'] = {"default": {"external": {"name": "docker-compose-dedicated"}}}
yml_content = yaml.dump(yml_c)
env_content = json.loads(img_info.docker_compose_env)
random_list = []
result_port_list = []
container_flag = "flag-{bmh%s}" % (uuid.uuid4(),)
for _port in env_content:
random_port = ''
for i in range(20):
random_port = str(random.randint(8000, 65536))
if random_port in random_list or ContainerVul.objects.filter(container_port=random_port).first():
continue
break
if not random_port:
raise Exception("无可用端口")
random_list.append(random_port)
result_port_list.append("%s=%s" % (_port, random_port,))
for one_port in json.loads(img_info.compose_env_port):
split_port = one_port.split(':')
if _port in split_port[0]:
vulport[random_port] = split_port[1]
vulport = json.dumps(vulport)
original_port = ""
for port_str in random_list:
if random_list[-1] == port_str:
original_port = original_port + port_str
else:
original_port = original_port + port_str + ","
compose_path = os.path.join(DOCKER_COMPOSE, str(container_vul.container_id))
original_ip = get_local_ip()
original_container_vul = container_vul
original_container_vul.docker_compose_path = compose_path
original_container_vul.container_status = "running"
original_container_vul.container_port = original_port
original_container_vul.container_flag = container_flag
original_container_vul.vul_port = vulport
original_container_vul.vul_host = original_ip + ":" + original_port
original_container_vul.is_docker_compose_correlation = False
original_container_vul.save()
if not os.path.exists(compose_path):
os.makedirs(compose_path)
docker_compose_file = os.path.join(compose_path, "docker-compose.yml")
with open(docker_compose_file, "w", encoding="utf-8") as f:
f.write(yml_content)
env_file = os.path.join(compose_path, ".env")
with open(env_file, "w", encoding="utf-8") as f:
f.write("\n".join(result_port_list))
try:
task_info = TaskInfo.objects.filter(task_id=task_id).first()
container_list = get_project(compose_path).up()
with transaction.atomic():
for container in container_list:
docker_container_id = container.id
# service_id = container.service
container_host = ""
container_port = ""
docker_container = client.containers.get(container.id)
command = 'touch /tmp/%s' % (container_flag,)
execute_result = docker_container_run(docker_container, command)
if execute_result["status"] == 500:
raise Exception(execute_result["msg"])
container_ports = container.ports
if len(container_ports) == 0:
try:
container_ports = docker_container.attrs["NetworkSettings"]["Ports"]
except Exception as e:
pass
vul_host_list = []
vul_ip = get_local_ip()
port_dict = {
}
if len(container_ports) > 0:
for _tmp_port in container_ports:
source_port = str(_tmp_port).replace("/", "").replace("tcp", "").replace("udp", "")
if container_ports[_tmp_port]:
target_port = container_ports[_tmp_port][0]["HostPort"]
else:
target_port = source_port
port_dict[source_port] = target_port
vul_host_list.append(vul_ip + ":" + target_port)
if len(port_dict) > 0:
container_port = json.dumps(port_dict, ensure_ascii=False)
container_status = execute_result["data"]["status"]
if len(vul_host_list) > 0:
container_host = ",".join(vul_host_list)
container_vul_img = ContainerVul(image_id=img_info, user_id=user_info.id, vul_host=container_host,
container_status=container_status,
docker_container_id=docker_container_id,
vul_port=container_port,
container_port=container_port,
time_model_id=time_model_id,
create_date=timezone.now(),
container_flag=container_flag,
is_docker_compose_correlation=True)
container_vul_img.save()
args = {
"image_name": img_info.image_name,
"user_id": user_id,
"image_port": img_info.image_port
}
task_start_date = timezone.now()
if countdown != 0 and countdown >= 60:
task_end_date = task_start_date + datetime.timedelta(seconds=countdown)
elif countdown == 0:
task_end_date = None
else:
countdown = int(DEFAULT_CONFIG["time"])
task_end_date = task_start_date + datetime.timedelta(seconds=countdown)
if "running" == docker_container.status:
msg_data = R.ok(data={
"host": original_container_vul.vul_host,
"port": json.loads(original_container_vul.vul_port),
"id": str(original_container_vul.container_id),
"status": "running",
"start_date": int(task_start_date.timestamp()),
"end_date": 0 if not task_end_date else int(task_end_date.timestamp())
})
search_task = TaskInfo.objects.filter(user_id=user_id, task_msg=json.dumps(msg_data), operation_type=2,
operation_args=json.dumps(args), task_end_date=task_end_date,
task_name="运行容器:" + img_info.image_name).order_by("-create_date").first()
if not search_task:
task_info.task_status = 3
task_info.task_msg = json.dumps(msg_data)
task_info.update_date = timezone.now()
task_info.operation_args = json.dumps(args)
task_info.save()
task_id = str(task_info.task_id)
else:
task_info.delete()
search_task.task_id = task_id
search_task.task_status = 3
search_task.update_date = timezone.now()
search_task.save()
task_id = str(search_task.task_id)
except Exception as e:
traceback.print_exc()
return create_stop_container_task(container_vul,user_info)
@shared_task(name="tasks.stop_docker_compose")
def stop_docker_compose(task_id):
task_info = TaskInfo.objects.filter(task_id=task_id, task_status=1).first()
if not task_info:
return
operation_args = task_info.operation_args
args = json.loads(operation_args)
container_id = args["container_id"]
user_id = args["user_id"]
image_name = args["image_name"]
image_info = ImageInfo.objects.filter(image_name=image_name).first()
container_vul = ContainerVul.objects.filter(container_id=container_id).first()
compose_path = container_vul.docker_compose_path
try:
with transaction.atomic():
container_list = get_project(compose_path).stop()
if container_list:
for container in container_list:
container_id = container.id
container = ContainerVul.objects.filter(docker_container_id=container_id).update(
container_status="stop")
container.save()
all_container = ContainerVul.objects.filter(
Q(user_id=user_id) & Q(image_id=image_info.image_id) &
Q(container_status="running")).all()
if all_container:
for corrtlation_container in all_container:
corrtlation_container.container_status = 'stop'
corrtlation_container.save()
container_vul.container_status = 'stop'
container_vul.save()
msg = R.ok(msg="停止成功")
except Exception:
msg = R.ok(msg="停止成功")
task_info.task_status = 3
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
task_info.save()
print("停止漏洞容器成功,任务ID:%s" % (task_id,))
@shared_task(name="tasks.delete_docker_compose")
def delete_docker_compose(task_id):
task_info = TaskInfo.objects.filter(task_id=task_id, task_status=1).first()
if not task_info:
return
operation_args = task_info.operation_args
args = json.loads(operation_args)
user_id = args["user_id"]
container_id = args["container_id"]
image_name = args["image_name"]
user_info = UserProfile.objects.filter(id=user_id).first()
image_info = ImageInfo.objects.filter(image_name=image_name).first()
# 删除容器
container_vul = ContainerVul.objects.filter(Q(container_id=container_id)
& ~Q(docker_compose_path="") & ~Q(container_status='delete')).first()
con_user_id = container_vul.user_id
if container_vul.container_status == 'running':
compose_path = container_vul.docker_compose_path
try:
with transaction.atomic():
container_list = get_project(compose_path).stop()
if container_list:
for container in container_list:
container_id = container.id
container = ContainerVul.objects.filter(docker_container_id=container_id).update(
container_status="stop")
container.save()
all_container = ContainerVul.objects.filter(
Q(user_id=user_id) & Q(image_id=image_info.image_id) &
Q(container_status="running")).all()
if all_container:
for corrtlation_container in all_container:
corrtlation_container.container_status = 'stop'
corrtlation_container.save()
container_vul.container_status = 'stop'
container_vul.save()
except Exception:
msg = R.err(msg="删除失败,服务器内部错误")
all_stop_container = ContainerVul.objects.filter(Q(user_id=con_user_id) & Q(image_id=image_info.image_id) &
Q(container_status="stop") & Q(docker_compose_path="")).all()
if all_stop_container:
compose_path = container_vul.docker_compose_path
for corrtlation_container in all_stop_container:
docker_container_id = corrtlation_container.docker_container_id
try:
# 连接Docker容器
docker_container = client.containers.get(docker_container_id)
# 删除容器
docker_container.remove(force=True)
except Exception:
pass
finally:
corrtlation_container.container_status = "delete"
corrtlation_container.docker_container_id = ""
# 保存成功
corrtlation_container.save()
if os.path.exists(compose_path) == True:
shutil.rmtree(compose_path)
# container_vul.docker_compose_path = ""
container_vul.container_status = "delete"
container_vul.save()
msg = R.ok(msg="删除成功")
task_info.task_status = 3
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
task_info.save()
print("删除漏洞容器成功,任务ID:%s" % (task_id,))
@shared_task(name="tasks.run_container")
def run_container(container_id, user_id, tmp_task_id, countdown):
"""
运行 docker 容器
:param container_id: 漏洞容器数据库 id
:param user_id: 用户ID
:param tmp_task_id: 任务ID
:param countdown 定时
"""
container_vul = ContainerVul.objects.filter(container_id=container_id).first()
user_info = UserProfile.objects.filter(id=user_id).first()
container_id = container_vul.docker_container_id
image_info = container_vul.image_id
image_name = image_info.image_name
image_port = image_info.image_port
user_id = user_info.id
docker_container = None
msg = {}
"""
创建启动任务
"""
args = {
"image_name": image_name,
"user_id": user_id,
"image_port": image_port
}
task_id = ""
task_info = TaskInfo.objects.filter(task_id=tmp_task_id).first()
# run container execute command
command = ""
vul_flag = container_vul.container_flag
container_port = container_vul.container_port
vul_port = {}
if container_vul.vul_port:
vul_port = json.loads(container_vul.vul_port)
vul_host = container_vul.vul_host
if container_id:
# check container
check_rsp = check_container(container_id)
if check_rsp["flag"]:
docker_container = check_rsp["container"]
# set container_flag
vul_flag = container_vul.container_flag
# if container by delete , create a container
if not docker_container:
port_list = image_port.split(",")
port_dict = {}
random_list = []
for port in port_list:
random_port = ''
for i in range(20):
# random port
random_port = str(random.randint(8000, 65536))
if random_port in random_list or ContainerVul.objects.filter(container_port=random_port).first():
continue
break
if not random_port:
msg = R.err(msg="端口无效")
break
random_list.append(random_port)
port_dict['%s/tcp' % (port,)] = int(random_port)
# 端口重复,无法进行创建
if len(msg) > 0 or msg:
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
# except
task_info.task_status = 4
task_info.save()
return str(task_info.task_id)
container_port = ",".join(random_list)
"""
random port
"""
for tmp_port in port_dict:
tmp_random_port = port_dict[tmp_port]
tmp_port = tmp_port.replace("/tcp", "")
vul_port[tmp_port] = str(tmp_random_port)
try:
client.images.get(image_name)
except Exception as e:
msg = R.build(msg="镜像不存在")
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
# except
task_info.task_status = 4
task_info.save()
image_info.is_ok = False
image_info.save()
return str(task_info.task_id)
vul_flag = "flag-{bmh%s}" % (uuid.uuid4(),)
if container_vul.container_flag:
vul_flag = container_vul.container_flag
try:
docker_container = client.containers.run(image_name, ports=port_dict, detach=True, environment={"vul_flag": vul_flag})
except ImageNotFound:
msg = R.build(msg="镜像不存在")
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
# except
task_info.task_status = 4
task_info.save()
image_info.is_ok = False
image_info.save()
return str(task_info.task_id)
command = 'touch /tmp/%s' % (vul_flag,)
vul_host = get_local_ip() + ":" + container_port
task_start_date = timezone.now()
if countdown != 0 and countdown >= 60:
task_end_date = task_start_date + datetime.timedelta(seconds=countdown)
elif countdown == 0:
task_end_date = None
else:
countdown = int(DEFAULT_CONFIG["time"])
task_end_date = task_start_date + datetime.timedelta(seconds=countdown)
if "running" == docker_container.status:
msg_data = R.ok(data={
"host": container_vul.vul_host,
"port": container_vul.vul_port,
"id": str(container_vul.container_id),
"status": "running",
"start_date": int(task_start_date.timestamp()),
"end_date": 0 if not task_end_date else int(task_end_date.timestamp())
})
search_task = TaskInfo.objects.filter(user_id=user_id, task_msg=json.dumps(msg_data), operation_type=2,
operation_args=json.dumps(args), task_end_date=task_end_date,
task_name="运行容器:" + image_name).order_by("-create_date").first()
if not search_task:
task_info.task_status = 3
task_info.task_msg = json.dumps(msg_data)
task_info.update_date = timezone.now()
task_info.operation_args = json.dumps(args)
task_info.save()
task_id = str(task_info.task_id)
else:
task_info.delete()
search_task.task_id = tmp_task_id
search_task.task_status = 3
search_task.update_date = timezone.now()
search_task.save()
task_id = str(search_task.task_id)
else:
task_info.save()
docker_container.start()
msg = docker_container_run(docker_container, command=command)
if msg["status"] == HTTP_ERR:
try:
container_vul.delete()
except Exception:
pass
# except
task_info.task_status = 4
else:
container_status = msg["data"]["status"]
msg["data"]["host"] = vul_host
msg["data"]["port"] = vul_port
msg["data"]["id"] = str(container_vul.container_id)
msg["data"]["status"] = container_status
msg["data"]["start_date"] = int(task_start_date.timestamp())
msg["data"]["end_date"] = 0 if not task_end_date else int(task_end_date.timestamp())
# 容器状态
container_vul.container_status = container_status
# 容器 id
container_vul.docker_container_id = str(docker_container.id)
# 漏洞 HOST
container_vul.vul_host = vul_host
# 漏洞端口
container_vul.vul_port = json.dumps(vul_port)
# 容器端口映射关系
container_vul.container_port = container_port
# 验证 flag
container_vul.container_flag = vul_flag
container_vul.save()
task_start_date = timezone.now()
# start 时间
task_info.task_start_date = task_start_date
task_info.task_end_date = task_end_date
task_info.task_status = 3
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
task_info.save()
task_id = str(task_info.task_id)
print("启动漏洞容器成功,任务ID:%s" % (task_id, ))
return create_stop_container_task(container_vul,user_info)
@shared_task(name="tasks.stop_container")
def stop_container(task_id):
"""
停止 docker 容器
:param task_id: task id
"""
task_info = TaskInfo.objects.filter(task_id=task_id, task_status=1).first()
if not task_info:
return
operation_args = task_info.operation_args
args = json.loads(operation_args)
container_id = args["container_id"]
container_vul = ContainerVul.objects.filter(container_id=container_id).first()
msg = R.ok(msg="停止成功")
if container_vul:
docker_container_id = container_vul.docker_container_id
try:
# 连接 Docker 容器
if docker_container_id:
docker_container = client.containers.get(docker_container_id)
docker_container.stop()
container_vul.container_status = 'stop'
container_vul.save()
msg = R.ok(msg="停止成功")
except NotFound:
container_vul.delete()
msg = R.ok(msg="停止成功")
except Exception:
msg = R.err(msg="停止失败,服务器内部错误")
# execute finish
task_info.task_status = 3
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
task_info.save()
print("停止漏洞容器成功,任务ID:%s" % (task_id, ))
@shared_task(name="tasks.delete_container")
def delete_container(task_id):
"""
删除容器任务
:param task_id: 任务id
"""
task_info = TaskInfo.objects.filter(task_id=task_id, task_status=1).first()
if not task_info:
return
operation_args = task_info.operation_args
args = json.loads(operation_args)
container_id = args["container_id"]
# 删除容器
container_vul = ContainerVul.objects.filter(Q(docker_container_id__isnull=False), container_id=container_id).first()
msg = R.ok(msg="删除成功")
if container_vul:
# docker 连接容器ID
docker_container_id = container_vul.docker_container_id
try:
# 连接Docker容器
if docker_container_id:
docker_container = client.containers.get(docker_container_id)
# 停止容器运行
docker_container.stop()
# 删除容器
docker_container.remove(force=True)
except Exception:
pass
finally:
container_vul.container_status = "delete"
container_vul.docker_container_id = ""
# 保存成功
container_vul.save()
# container_vul.delete()
msg = R.ok(msg="删除成功")
task_info.task_status = 3
task_info.task_msg = json.dumps(msg)
task_info.update_date = timezone.now()
task_info.save()
print("删除漏洞容器成功,任务ID:%s" % (task_id, ))
@shared_task(name="tasks.create_image")
def create_image(task_id):
"""
创建镜像名称
"""
task_info = TaskInfo.objects.filter(task_id=task_id, task_status=1).first()
if not task_info:
return
operation_args = task_info.operation_args
args = json.loads(operation_args)
image_name = args["image_name"].strip()
image_info = ImageInfo.objects.filter(image_name=image_name).first()
if not image_info:
image_desc = image_name
image_rank = 2.5
image_vul_name = image_desc
image_info = ImageInfo(image_name=image_name, image_desc=image_desc, rank=image_rank, image_vul_name=image_vul_name)
image = None
msg = {}
try:
image = client.images.get(image_name)
except Exception as e:
image_info.is_ok = False
image_info.save()
try:
last_info = {}
progress_info = {
"total": 0,
"progress_count": 0,
"progress": round(0.0, 2),
}
black_list = ["total", "progress_count", "progress"]
for line in api_docker_client.pull(image_name, stream=True, decode=True):
if "status" in line and "progressDetail" in line and "id" in line:
id = line["id"]
status = line["status"]
if len(line["progressDetail"]) > 0:
try:
current = line["progressDetail"]["current"]
total = line["progressDetail"]["total"]
line["progress"] = round((current / total) * 100, 2)
if (current / total) > 1:
line["progress"] = round(0.99 * 100, 2)
except:
line["progress"] = round(1 * 100, 2)
else:
if (("Download" in status or "Pull" in status) and ("complete" in status)) or ("Verifying" in status) or \
("Layer" in status and "already" in status and "exists" in status):
line["progress"] = round(100.00, 2)
else:
line["progress"] = round(0.00, 2)
progress_info[id] = line
progress_info["total"] = len(progress_info) - len(black_list)
progress_count = 0
for key in progress_info: