-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathenhanced_api.py
More file actions
1522 lines (1237 loc) · 54.6 KB
/
Copy pathenhanced_api.py
File metadata and controls
1522 lines (1237 loc) · 54.6 KB
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
import os
import sys
import json
import docker
import threading
import time
import requests
import subprocess
import datetime
from pathlib import Path
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
load_dotenv()
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'cms'))
from cms.main import CentralManagementSystem
from cms.config_manager import ConfigManager
from cms.ids_manager import IDSManager
app = Flask(__name__, template_folder='templates', static_folder='static')
CORS(app)
cms = None
ids_manager = None
deployment_in_progress = False
deployment_status = "idle"
deployment_logs = []
def init_cms():
global cms, ids_manager
try:
cms = CentralManagementSystem()
print(" CMS initialized successfully")
ids_manager = IDSManager()
print(" IDS Manager initialized successfully")
return True
except Exception as e:
print(f" Warning: Error initializing CMS: {e}")
return False
def log_deployment(message):
global deployment_logs
deployment_logs.append(message)
print(message)
@app.route('/api/status', methods=['GET'])
def get_status():
global deployment_in_progress
try:
if cms is None:
return jsonify({'status': 'error', 'message': 'CMS not initialized'}), 500
containers = cms.docker_client.containers.list(all=True)
managed_containers = [c for c in containers if any(p in c.name for p in ['web-server-', 'db-server-', 'email-server-', 'client-pc-'])]
container_status = []
for container in managed_containers:
container_status.append({
'name': container.name,
'status': container.status,
'image': container.image.tags[0] if container.image.tags else 'unknown',
'id': container.id[:12]
})
return jsonify({
'status': 'ok',
'deployment_status': deployment_status,
'deployment_in_progress': deployment_in_progress,
'containers': container_status,
'container_count': len(container_status)
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/deployment/status', methods=['GET'])
def get_deployment_status():
return jsonify({
'status': deployment_status,
'in_progress': deployment_in_progress,
'logs': deployment_logs[-100:]
}), 200
@app.route('/api/deploy', methods=['POST'])
def deploy():
global deployment_in_progress, deployment_status
if deployment_in_progress:
return jsonify({'error': 'Deployment already in progress'}), 400
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 503
deployment_in_progress = True
deployment_logs.clear()
thread = threading.Thread(target=deploy_in_background)
thread.daemon = True
thread.start()
return jsonify({'message': 'Deployment started', 'status': 'deploying'}), 202
def deploy_in_background():
global deployment_in_progress, deployment_status
try:
deployment_status = "deploying"
log_deployment(" Starting infrastructure deployment...")
cms.deploy_infrastructure()
deployment_status = "completed"
log_deployment(" Infrastructure deployment completed!")
except Exception as e:
deployment_status = "failed"
log_deployment(f" Deployment failed: {str(e)}")
finally:
deployment_in_progress = False
deployment_status = "idle"
@app.route('/api/health', methods=['GET'])
def get_health():
try:
if cms is None:
return jsonify({'status': 'error', 'message': 'CMS not initialized'}), 500
health_stats = cms.get_system_health()
return jsonify(health_stats), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/health/check', methods=['POST'])
def check_health():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
health_report = cms.health_monitor.check_all_containers()
return jsonify(health_report), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/deployments', methods=['GET'])
def get_deployments():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
limit = request.args.get('limit', 10, type=int)
history = cms.get_deployment_history(limit)
return jsonify({
'deployments': history,
'count': len(history)
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/deployment/<deployment_id>', methods=['GET'])
def get_deployment(deployment_id):
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
deployment = cms.deployment_manager.get_deployment(deployment_id)
if not deployment:
return jsonify({'error': 'Deployment not found'}), 404
return jsonify(deployment), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/deployment/<deployment_id>/rollback', methods=['POST'])
def rollback_deployment(deployment_id):
global deployment_in_progress
if deployment_in_progress:
return jsonify({'error': 'Deployment operation in progress'}), 400
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 503
deployment_in_progress = True
deployment_logs.clear()
thread = threading.Thread(target=rollback_in_background, args=(deployment_id,))
thread.daemon = True
thread.start()
return jsonify({'message': 'Rollback started', 'deployment_id': deployment_id}), 202
def rollback_in_background(deployment_id):
global deployment_in_progress
try:
log_deployment(f" Starting rollback to {deployment_id}...")
cms.rollback_to_deployment(deployment_id)
log_deployment(" Rollback completed!")
except Exception as e:
log_deployment(f" Rollback failed: {str(e)}")
finally:
deployment_in_progress = False
@app.route('/api/configuration', methods=['GET'])
def get_configuration():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
config_export = cms.config_manager.export_config('json')
if config_export:
return json.loads(config_export), 200
return jsonify({'error': 'Failed to export config'}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/configuration/validate', methods=['POST'])
def validate_configuration():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
config_data = request.get_json()
is_valid = cms.config_manager.validate_config(config_data)
return jsonify({
'valid': is_valid,
'message': 'Configuration is valid' if is_valid else 'Configuration validation failed'
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/configuration/versions', methods=['GET'])
def get_configuration_versions():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
versions = cms.config_manager.list_versions()
return jsonify({'versions': versions}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/configuration/check-changes', methods=['GET'])
def check_config_changes():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
has_changes = cms.check_config_for_changes()
return jsonify({
'has_changes': has_changes,
'message': 'Configuration has changed' if has_changes else 'No changes detected'
}), 200
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/security/audit', methods=['POST'])
def security_audit():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
log_deployment(" Running security audit...")
audit_results = cms.security_audit()
log_deployment(" Security audit completed")
return jsonify({
'message': 'Security audit completed',
'audit_results': audit_results
}), 200
except Exception as e:
log_deployment(f" Audit failed: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/security/harden', methods=['POST'])
def harden_security():
global deployment_in_progress
if deployment_in_progress:
return jsonify({'error': 'Operation in progress'}), 400
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 503
deployment_in_progress = True
deployment_logs.clear()
thread = threading.Thread(target=harden_in_background)
thread.daemon = True
thread.start()
return jsonify({'message': 'Security hardening started'}), 202
def harden_in_background():
global deployment_in_progress
try:
log_deployment(" Starting security hardening...")
cms.enhanced_security.harden_all_containers()
log_deployment(" Security hardening completed!")
except Exception as e:
log_deployment(f" Hardening failed: {str(e)}")
finally:
deployment_in_progress = False
@app.route('/api/container/<container_name>/stop', methods=['POST'])
def stop_container(container_name):
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
container = cms.docker_client.containers.get(container_name)
container.stop(timeout=10)
log_deployment(f" Container {container_name} stopped")
return jsonify({'message': f'Container {container_name} stopped'}), 200
except docker.errors.NotFound:
return jsonify({'error': f'Container {container_name} not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/container/<container_name>/start', methods=['POST'])
def start_container(container_name):
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
container = cms.docker_client.containers.get(container_name)
container.start()
log_deployment(f" Container {container_name} started")
return jsonify({'message': f'Container {container_name} started'}), 200
except docker.errors.NotFound:
return jsonify({'error': f'Container {container_name} not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/container/<container_name>/remove', methods=['DELETE'])
def remove_container(container_name):
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
container = cms.docker_client.containers.get(container_name)
if container.status == 'running':
container.stop(timeout=10)
container.remove()
return jsonify({'message': f'Container {container_name} removed'}), 200
except docker.errors.NotFound:
return jsonify({'error': f'Container {container_name} not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/create-client', methods=['POST'])
def create_client():
try:
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 500
data = request.get_json()
client_name = data.get('name', 'client-pc-new') if data else 'client-pc-new'
try:
client_containers = cms.docker_client.containers.list(filters={'name': 'client-pc-'})
next_number = len(client_containers) + 1
final_name = f"client-pc-{next_number}"
except:
final_name = client_name
log_deployment(f" Creating new client: {final_name}")
container = cms.docker_client.containers.run(
"ubuntu:22.04",
name=final_name,
network="frontend_net",
detach=True,
command="tail -f /dev/null",
restart_policy={"Name": "unless-stopped"}
)
log_deployment(f" Client {final_name} created successfully")
return jsonify({
'message': f'Client {final_name} created successfully',
'container': {
'name': final_name,
'id': container.id[:12],
'status': container.status
}
}), 201
except Exception as e:
log_deployment(f" Failed to create client: {str(e)}")
return jsonify({'error': str(e)}), 500
@app.route('/api/cleanup', methods=['POST'])
def cleanup():
global deployment_in_progress, deployment_logs, deployment_status
if deployment_in_progress:
return jsonify({'error': 'Deployment in progress'}), 400
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 503
deployment_in_progress = True
deployment_status = "cleaning"
deployment_logs.clear()
thread = threading.Thread(target=cleanup_in_background)
thread.daemon = True
thread.start()
return jsonify({'message': 'Cleanup started'}), 202
def cleanup_in_background():
global deployment_in_progress, deployment_status
try:
log_deployment(" Starting cleanup...")
cms.destroy_infrastructure()
log_deployment(" Cleanup completed successfully!")
deployment_status = "idle"
except Exception as e:
log_deployment(f" Cleanup failed: {str(e)}")
deployment_status = "failed"
finally:
deployment_in_progress = False
deployment_status = "idle"
@app.route('/api/network/test', methods=['POST'])
def test_network_connectivity():
global deployment_in_progress, deployment_logs, deployment_status
if deployment_in_progress:
return jsonify({'error': 'Operation in progress'}), 400
if cms is None:
return jsonify({'error': 'CMS not initialized'}), 503
deployment_in_progress = True
deployment_status = "testing"
deployment_logs.clear()
thread = threading.Thread(target=test_connectivity_in_background)
thread.daemon = True
thread.start()
return jsonify({'message': 'Network connectivity test started'}), 202
def test_connectivity_in_background():
global deployment_in_progress, deployment_logs, deployment_status
try:
log_deployment(" Starting network connectivity tests...")
log_deployment("=" * 60)
log_deployment("\n Testing Container Connectivity:")
log_deployment("-" * 40)
containers = cms.docker_client.containers.list(filters={'status': 'running'})
if not containers:
log_deployment(" No running containers found")
else:
log_deployment(f"Found {len(containers)} running containers")
for container in containers:
container.reload()
networks = container.attrs['NetworkSettings']['Networks']
ip_addresses = []
for net_name, net_info in networks.items():
if net_info.get('IPAddress'):
ip_addresses.append(f"{net_name}: {net_info['IPAddress']}")
if ip_addresses:
log_deployment(f" {container.name}")
for ip_info in ip_addresses:
log_deployment(f" {ip_info}")
else:
log_deployment(f" {container.name} - No IP addresses")
log_deployment("\n Testing Inter-Container Communication:")
log_deployment("-" * 40)
web_servers = cms.docker_client.containers.list(filters={'name': 'web-server-', 'status': 'running'})
db_servers = cms.docker_client.containers.list(filters={'name': 'db-server-', 'status': 'running'})
email_servers = cms.docker_client.containers.list(filters={'name': 'email-server-', 'status': 'running'})
client_pcs = cms.docker_client.containers.list(filters={'name': 'client-pc-', 'status': 'running'})
if client_pcs and web_servers:
log_deployment(f"\n Client Connectivity:")
log_deployment(f"Found {len(client_pcs)} clients and {len(web_servers)} web servers")
for client in client_pcs[:1]:
client.reload()
client_networks = client.attrs['NetworkSettings']['Networks']
for web in web_servers:
web.reload()
web_networks = web.attrs['NetworkSettings']['Networks']
shared_networks = set(client_networks.keys()) & set(web_networks.keys())
if shared_networks:
for net in shared_networks:
web_ip = web_networks[net].get('IPAddress')
try:
result = client.exec_run(['/bin/sh', '-c', f'timeout 2 bash -c "</dev/tcp/{web_ip}/80" 2>/dev/null && echo connected || echo timeout'])
output = result.output.decode().strip() if result.output else ''
if 'connected' in output or result.exit_code == 0:
log_deployment(f" {client.name} → {web.name}: {web_ip}")
else:
log_deployment(f" {client.name} → {web.name}: {web_ip} (network accessible)")
except Exception as e:
log_deployment(f" {client.name} → {web.name}: {web_ip} (network accessible)")
else:
log_deployment(f" {client.name} and {web.name} not on same network")
for email in email_servers:
email.reload()
email_networks = email.attrs['NetworkSettings']['Networks']
shared_networks = set(client_networks.keys()) & set(email_networks.keys())
if shared_networks:
for net in shared_networks:
email_ip = email_networks[net].get('IPAddress')
try:
result = client.exec_run(['/bin/sh', '-c', f'timeout 2 bash -c "</dev/tcp/{email_ip}/25" 2>/dev/null && echo connected || echo timeout'])
output = result.output.decode().strip() if result.output else ''
if 'connected' in output or result.exit_code == 0:
log_deployment(f" {client.name} → {email.name}: {email_ip}")
else:
log_deployment(f" {client.name} → {email.name}: {email_ip} (network accessible)")
except Exception as e:
log_deployment(f" {client.name} → {email.name}: {email_ip} (network accessible)")
else:
log_deployment(f" {client.name} and {email.name} not on same network")
for db in db_servers:
db.reload()
db_networks = db.attrs['NetworkSettings']['Networks']
shared_networks = set(client_networks.keys()) & set(db_networks.keys())
if not shared_networks:
log_deployment(f" {client.name} ↛ {db.name}: Blocked (expected)")
else:
log_deployment(f" {client.name} can reach {db.name} (unexpected)")
if len(client_pcs) > 1:
log_deployment(f"\n Client Isolation:")
client1 = client_pcs[0]
client2 = client_pcs[1]
client1.reload()
client2.reload()
client1_networks = client1.attrs['NetworkSettings']['Networks']
client2_networks = client2.attrs['NetworkSettings']['Networks']
if 'client_net' in client1_networks and 'client_net' in client2_networks:
c2_ip = client2_networks['client_net'].get('IPAddress')
try:
result = client1.exec_run(['/bin/sh', '-c', f'ping -c 1 -W 2 {c2_ip}'])
if result.exit_code == 0:
log_deployment(f" {client1.name} ↔ {client2.name}: Connected (check isolation)")
else:
log_deployment(f" {client1.name} ↔ {client2.name}: Isolated (expected)")
except Exception as e:
log_deployment(f" {client1.name} ↔ {client2.name}: Isolated (expected)")
else:
log_deployment(f" {client1.name} ↔ {client2.name}: Not on same network (isolated)")
if web_servers and db_servers:
log_deployment(f"\n Web Server Connectivity:")
log_deployment(f"Found {len(web_servers)} web servers and {len(db_servers)} database servers")
for web in web_servers:
web.reload()
web_networks = web.attrs['NetworkSettings']['Networks']
for db in db_servers:
db.reload()
db_networks = db.attrs['NetworkSettings']['Networks']
shared_networks = set(web_networks.keys()) & set(db_networks.keys())
if shared_networks:
for net in shared_networks:
db_ip = db_networks[net].get('IPAddress')
try:
result = web.exec_run(['/bin/sh', '-c', f'timeout 2 bash -c "</dev/tcp/{db_ip}/3306" 2>/dev/null && echo connected || echo timeout'])
output = result.output.decode().strip() if result.output else ''
if 'connected' in output or result.exit_code == 0:
log_deployment(f" {web.name} → {db.name}: {db_ip} (port 3306 responding)")
else:
log_deployment(f" {web.name} → {db.name}: {db_ip} (network accessible)")
except Exception as e:
log_deployment(f" {web.name} → {db.name}: {db_ip} (network accessible)")
else:
log_deployment(f" {web.name} and {db.name} not on same network")
if email_servers and db_servers:
log_deployment(f"\n Email Server Connectivity:")
log_deployment(f"Found {len(email_servers)} email servers")
for email in email_servers:
email.reload()
email_networks = email.attrs['NetworkSettings']['Networks']
for db in db_servers:
db.reload()
db_networks = db.attrs['NetworkSettings']['Networks']
shared_networks = set(email_networks.keys()) & set(db_networks.keys())
if shared_networks:
for net in shared_networks:
db_ip = db_networks[net].get('IPAddress')
try:
result = email.exec_run(['/bin/sh', '-c', f'timeout 2 bash -c "</dev/tcp/{db_ip}/3306" 2>/dev/null && echo connected || echo timeout'])
output = result.output.decode().strip() if result.output else ''
if 'connected' in output or result.exit_code == 0:
log_deployment(f" {email.name} → {db.name}: {db_ip} (port 3306 responding)")
else:
log_deployment(f" {email.name} → {db.name}: {db_ip} (network accessible)")
except Exception as e:
log_deployment(f" {email.name} → {db.name}: {db_ip} (network accessible)")
else:
log_deployment(f" {email.name} and {db.name} not on same network")
log_deployment("\n" + "=" * 60)
log_deployment(" Network connectivity tests completed!")
deployment_status = "completed"
except Exception as e:
log_deployment(f" Network test failed: {str(e)}")
import traceback
log_deployment(f"Error details: {traceback.format_exc()}")
deployment_status = "failed"
finally:
deployment_in_progress = False
deployment_status = "idle"
@app.route('/api/connectivity-results', methods=['GET'])
def get_connectivity_results():
return jsonify({
'results': deployment_logs,
'completed': not deployment_in_progress,
'stats': {
'total': len([l for l in deployment_logs if 'Testing' in l or 'SUCCESS' in l or 'FAILED' in l]),
'passed': len([l for l in deployment_logs if 'SUCCESS' in l]),
'failed': len([l for l in deployment_logs if 'FAILED' in l])
},
'system_info': {
'containers_running': len([l for l in deployment_logs if 'deployed' in l.lower()]),
'networks': 3,
'duration': 'calculating...'
},
'issues': []
}), 200
@app.route('/api/virus-total-scan', methods=['POST'])
def virus_total_scan():
try:
data = request.json
scan_type = data.get('scan_type', 'url')
query = data.get('query', '')
if not query:
return jsonify({'success': False, 'error': 'Query parameter is required'}), 400
api_key = os.getenv('VIRUS_TOTAL_API_KEY')
if not api_key:
return jsonify({'success': False, 'error': 'VirusTotal API key not configured'}), 500
headers = {'x-apikey': api_key}
if scan_type == 'url':
url = 'https://www.virustotal.com/api/v3/urls'
files = {'url': (None, query)}
response = requests.post(url, files=files, headers=headers)
if response.status_code != 200:
return jsonify({'success': False, 'error': f'VirusTotal API error: {response.status_code}'}), 500
result_data = response.json()
analysis_id = result_data['data']['id']
analysis_url = f'https://www.virustotal.com/api/v3/analyses/{analysis_id}'
analysis_response = requests.get(analysis_url, headers=headers)
analysis_result = analysis_response.json()
stats = analysis_result['data']['attributes']['stats']
results = parse_virustotal_results(query, stats, analysis_result['data']['attributes'], scan_type)
else:
url = f'https://www.virustotal.com/api/v3/files/{query}'
response = requests.get(url, headers=headers)
if response.status_code == 404:
results = {
'query': query,
'detections': 0,
'total_vendors': 0,
'scan_date': 'Never scanned',
'categories': ['Not in database'],
'vendors': []
}
elif response.status_code != 200:
return jsonify({'success': False, 'error': f'VirusTotal API error: {response.status_code}'}), 500
else:
result_data = response.json()
stats = result_data['data']['attributes']['last_analysis_stats']
results = parse_virustotal_results(query, stats, result_data['data']['attributes'], scan_type)
return jsonify({
'success': True,
'results': results
}), 200
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
def parse_virustotal_results(query, stats, attributes, scan_type):
detections = stats.get('malicious', 0)
total = sum(stats.values()) if isinstance(stats, dict) else 0
vendors = []
last_analysis = attributes.get('last_analysis_results', {})
for vendor, result in last_analysis.items():
if result['category'] != 'undetected':
vendors.append({
'vendor': vendor,
'detection': result.get('result', 'Detected')
})
categories = []
if 'categories' in attributes:
categories = list(attributes['categories'].values()) if isinstance(attributes['categories'], dict) else []
return {
'query': query,
'detections': detections,
'total_vendors': total,
'scan_date': attributes.get('last_analysis_date', attributes.get('last_submission_date', 'N/A')),
'last_submission_date': attributes.get('last_submission_date'),
'categories': categories,
'vendors': vendors[:20],
'meaningful_name': attributes.get('meaningful_name'),
'size': attributes.get('size'),
'type': attributes.get('type_description')
}
@app.route('/api/abuseipdb-check', methods=['POST'])
def abuseipdb_check():
try:
data = request.json
ip_address = data.get('ip_address', '')
if not ip_address:
return jsonify({'success': False, 'error': 'IP address is required'}), 400
api_key = os.getenv('ABUSEIPDB_API_KEY')
if not api_key:
return jsonify({'success': False, 'error': 'AbuseIPDB API key not configured'}), 500
headers = {
'Key': api_key,
'Accept': 'application/json'
}
url = 'https://api.abuseipdb.com/api/v2/check'
params = {
'ipAddress': ip_address,
'maxAgeInDays': 90,
'verbose': ''
}
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
return jsonify({'success': False, 'error': f'AbuseIPDB API error: {response.status_code}'}), 500
result_data = response.json()
if 'data' not in result_data:
return jsonify({'success': False, 'error': 'Invalid API response'}), 500
results = parse_abuseipdb_results(result_data['data'])
return jsonify({
'success': True,
'results': results
}), 200
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
def parse_abuseipdb_results(data):
reports = []
if 'reports' in data and data['reports']:
for report in data['reports'][:20]:
reports.append({
'comment': report.get('comment', 'N/A'),
'reported_at': report.get('reportedAt', 'N/A'),
'reporter_id': report.get('reporterId', 'Anonymous'),
'category': report.get('category', 'Unknown')
})
return {
'ip_address': data.get('ipAddress', ''),
'abuse_score': data.get('abuseConfidenceScore', 0),
'total_reports': data.get('totalReports', 0),
'distinct_reporters': data.get('numDistinctUsers', 0),
'last_reported_at': data.get('lastReportedAt'),
'isp': data.get('isp', 'Unknown'),
'country_code': data.get('countryCode', 'Unknown'),
'country_name': data.get('countryName', 'Unknown'),
'hostname': data.get('hostnames', [None])[0] if data.get('hostnames') else None,
'usage_type': data.get('usageType', 'Unknown'),
'is_whitelisted': data.get('isWhitelisted', False),
'labels': data.get('labels', []),
'reports': reports
}
@app.route('/api/ssh-containers', methods=['GET'])
def get_ssh_containers():
try:
client = docker.from_env()
containers = []
ssh_ports = {
'web-server-1': 2201,
'web-server-2': 2202,
'db-server-1': 2203,
'email-server-1': 2204,
'client-pc-1': 2211,
'client-pc-2': 2212,
'client-pc-3': 2213
}
for container_name, ssh_port in ssh_ports.items():
try:
container = client.containers.get(container_name)
containers.append({
'name': container_name,
'status': container.status,
'ssh_port': ssh_port,
'host': 'localhost',
'service': container.labels.get('cms.service', 'unknown')
})
except:
pass
return jsonify({
'success': True,
'containers': containers
}), 200
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/ssh-test', methods=['POST'])
def ssh_test():
try:
data = request.json
container_name = data.get('container_name', '')
if not container_name:
return jsonify({'success': False, 'error': 'Container name required'}), 400
ssh_ports = {
'web-server-1': 2201,
'web-server-2': 2202,
'db-server-1': 2203,
'email-server-1': 2204,
'client-pc-1': 2211,
'client-pc-2': 2212,
'client-pc-3': 2213
}
if container_name not in ssh_ports:
return jsonify({'success': False, 'error': 'Container not found'}), 404
ssh_port = ssh_ports[container_name]
try:
key_path = os.path.join(os.path.dirname(__file__), 'keys', 'id_rsa')
result = subprocess.run(
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ConnectTimeout=5', '-i', key_path, '-p', str(ssh_port),
'root@localhost', 'echo "SSH Connection Successful"'],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
return jsonify({
'success': True,
'message': 'SSH connection successful',
'container': container_name,
'port': ssh_port
}), 200
else:
return jsonify({
'success': False,
'error': f'SSH connection failed: {result.stderr}'
}), 500
except subprocess.TimeoutExpired:
return jsonify({'success': False, 'error': 'SSH connection timeout'}), 500
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/ssh-command', methods=['POST'])
def ssh_command():
try:
data = request.json
container_name = data.get('container_name', '')
command = data.get('command', '')
if not container_name or not command:
return jsonify({'success': False, 'error': 'Container name and command required'}), 400
ssh_ports = {
'web-server-1': 2201,
'web-server-2': 2202,
'db-server-1': 2203,
'email-server-1': 2204,
'client-pc-1': 2211,
'client-pc-2': 2212,
'client-pc-3': 2213
}
if container_name not in ssh_ports:
return jsonify({'success': False, 'error': 'Container not found'}), 404
ssh_port = ssh_ports[container_name]
try:
key_path = os.path.join(os.path.dirname(__file__), 'keys', 'id_rsa')
result = subprocess.run(
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null',
'-i', key_path, '-p', str(ssh_port), 'root@localhost', command],
capture_output=True,
text=True,
timeout=30
)
return jsonify({
'success': True,
'output': result.stdout,
'error': result.stderr if result.returncode != 0 else '',
'exit_code': result.returncode,
'container': container_name
}), 200
except subprocess.TimeoutExpired:
return jsonify({'success': False, 'error': 'Command execution timeout'}), 500
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/logs/all', methods=['GET'])
def get_all_logs():
try:
all_logs = {
'deployment_logs': deployment_logs.copy(),
'container_logs': {},
'health_reports': {},
'system_logs': []
}
if cms is not None:
try:
containers = cms.docker_client.containers.list(all=True)
for container in containers:
try:
logs = container.logs(tail=100).decode('utf-8', errors='ignore')
if logs:
all_logs['container_logs'][container.name] = logs.split('\n')