-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSecurity_Assistant_Bot.py
More file actions
1295 lines (1232 loc) · 81.1 KB
/
Security_Assistant_Bot.py
File metadata and controls
1295 lines (1232 loc) · 81.1 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: hao.ban@ehealthsask.ca//banhao@gmail.com
# Version:
# Issue Date: February 11, 2025
# Release Note: Disable EOP Phishing Simulation
from pyngrok import conf, ngrok
from datetime import datetime
import requests, json, sys, os, urllib3, paramiko, re, string, random, time, subprocess, csv, asyncio
import xml.etree.ElementTree as ET
from subprocess import PIPE
from lxml.etree import fromstring
from importlib import reload
#from import_file import import_file
from requests_toolbelt.multipart.encoder import MultipartEncoder
from dotenv import load_dotenv
import tempfile
import shutil
import zipfile
import glob
urllib3.disable_warnings()
script_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_path)
#variable = import_file('./config.py')
load_dotenv()
Qualys_username=os.getenv("Qualys_username")
Qualys_password=os.getenv("Qualys_password")
TAGNAME=os.getenv("TAGNAME")
activationKey=os.getenv("activationKey")
bearer=os.getenv("bearer")
sma_server=os.getenv("sma_server")
sma_token=os.getenv("sma_token")
sma_server_api=os.getenv("sma_server_api")
sma_uname=os.getenv("sma_uname")
headers = {
"Accept": "application/json",
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Bearer " + bearer
}
#clear registered webhooks
response = requests.get('https://webexapis.com/v1/webhooks', headers=headers)
if len(response.json()['items']) != 0:
for i in range(len(response.json()['items'])):
webhook_id = response.json()['items'][i]['id']
del_webhook_response = requests.delete('https://webexapis.com/v1/webhooks/'+webhook_id, headers=headers)
conf.get_default().region = "us"
ngrok.connect(5000).public_url #Start ngrok on port 5000
ngrok_response = requests.get('http://127.0.0.1:4040/api/tunnels')
webhook_url = ngrok_response.json()['tunnels'][0]['public_url']
#listener = ngrok.forward(5000, authtoken_from_env=True) #Start ngrok on port 5000
#for t in client.tunnels.list():
# print(t)
#for t in client.tunnel_sessions.list():
# print(t)
#webhook_url = listener.url()
print(webhook_url)
with open('webhook.txt', 'w') as file:
file.write(webhook_url)
#create new webhooks
response = requests.post('https://webexapis.com/v1/webhooks', json.dumps({"resource" : "messages","event" : "created","targetUrl" : webhook_url,"name" : "SecurityAssistantBot"}), headers=headers)
response = requests.post('https://webexapis.com/v1/webhooks', json.dumps({"resource" : "memberships","event" : "created","targetUrl" : webhook_url,"name" : "SecurityAssistantBot"}), headers=headers)
response = requests.post('https://webexapis.com/v1/webhooks', json.dumps({"resource" : "attachmentActions","event" : "created","targetUrl" : webhook_url,"name" : "SecurityAssistantBot"}), headers=headers)
#generate access list
if os.path.exists('accesslist.xml') :
root = ET.parse('accesslist.xml').getroot()
accesslist_ADMIN = []
accesslist_CERTIFICATES = []
accesslist_QUALYS = []
accesslist_RELEASEEMAIL = []
accesslist_SCRIPTSTATUS = []
# accesslist_REQUESTEDQUARANTINE = []
# accesslist_EOPPHISHSIM = []
if len(root.findall("ADMIN")[0]) != 0:
for i in range(len(root.findall("ADMIN")[0])):
accesslist_ADMIN.append(root.findall("ADMIN")[0][i-1].text.lower())
if len(root.findall("CERTIFICATES")[0]) != 0:
for i in range(len(root.findall("CERTIFICATES")[0])):
accesslist_CERTIFICATES.append(root.findall("CERTIFICATES")[0][i-1].text.lower())
if len(root.findall("QUALYS")[0]) != 0:
for i in range(len(root.findall("QUALYS")[0])):
accesslist_QUALYS.append(root.findall("QUALYS")[0][i-1].text.lower())
if len(root.findall("RELEASEEMAIL")[0]) != 0:
for i in range(len(root.findall("RELEASEEMAIL")[0])):
accesslist_RELEASEEMAIL.append(root.findall("RELEASEEMAIL")[0][i-1].text.lower())
if len(root.findall("SCRIPTSTATUS")[0]) != 0:
for i in range(len(root.findall("SCRIPTSTATUS")[0])):
accesslist_SCRIPTSTATUS.append(root.findall("SCRIPTSTATUS")[0][i-1].text.lower())
# if len(root.findall("REQUESTEDQUARANTINE")[0]) != 0:
# for i in range(len(root.findall("REQUESTEDQUARANTINE")[0])):
# accesslist_REQUESTEDQUARANTINE.append(root.findall("REQUESTEDQUARANTINE")[0][i-1].text.lower())
# if len(root.findall("EOPPHISHSIM")[0]) != 0:
# for i in range(len(root.findall("EOPPHISHSIM")[0])):
# accesslist_EOPPHISHSIM.append(root.findall("EOPPHISHSIM")[0][i-1].text.lower())
else:
accesslist_ADMIN = "ALL"
try:
from flask import Flask
from flask import request
except ImportError as e:
print(e)
print("Looks like 'flask' library is missing.\n"
"Type 'pip3 install flask' command to install the missing library.")
sys.exit()
def send_get(url, payload=None,js=True):
if payload == None:
request = requests.get(url, headers=headers)
else:
request = requests.get(url, headers=headers, params=payload)
if js == True:
request= request.json()
return request
def send_post(url, data):
request = requests.post(url, json.dumps(data), headers=headers).json()
return request
def send_put(url, data):
return requests.put(url, json.dumps(data), headers=headers).json()
def help_me():
return "Sure! I can help. Below are the commands that I understand:<br/>" \
"`Hello` - I will display my greeting message<br/>" \
"`Help` - I will display what I can do.<br/>" \
"`Release Emails` <br/>" \
"`Qualys Assets` <br/>" \
"`Client Certificates` <br/>" \
"`Script Status` <br/>" \
"<br/>" \
"If you need to report an email security incident, please forward the suspicious email as an attachement to emailsecurity@ehealthsask.ca <br/>" \
def greetings():
return "Hi, I am %s.<br/>" \
"Type `Help` to see what I can do.<br/>" \
"<br/>" \
"If you have any questions, please contact Hao.Ban@eHealthsask.ca <br/>" % bot_name
def releaseemails(result, webhook):
if result['inputs']['Question1'] == 'YES' and result['inputs']['Question2'] == 'YES' and result['inputs']['Question3'] == 'YES':
if result['inputs']['Environment'] == 'ESA':
MID = result['inputs']['MID']
PersonId = result['personId']
Created = result['created']
PersonName = send_get('https://webexapis.com/v1/people/{0}'.format(PersonId))['displayName']
PersonEmail = send_get('https://webexapis.com/v1/people/{0}'.format(PersonId))['emails']
with open("ReleaseEmail.log", "r") as file:
for line in file:
if MID in line and "successfully" in line:
msg = "Email was already released by: "+line
released = True
break
else:
released = False
if not released:
COMMAND = "grep "+MID+" mail_logs"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
k = paramiko.RSAKey.from_private_key_file(os.path.expanduser('.\\.ssh\\id_rsa_esa'))
ssh.connect(sma_server, username=sma_uname, pkey=k)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(COMMAND)
for line in ssh_stdout:
try:
found = re.search('MID .* \(', line.strip())
S_MID = found.group(0).split(" ")[1]
except AttributeError:
found = ''
ssh.close()
if not found:
msg = "Can't find Message MID#" + MID + " in Encrypted Message quarantine. Please check your input and try again."
else:
SMA_MID = []
SMA_MID.append(int(S_MID))
SMA_headers = {"Content-Type": "text/plain","Authorization": 'Basic ' + sma_token}
SMA_body = {"action": "release","mids": SMA_MID,"quarantineName": "Encrypted Message","quarantineType": "pvo"}
print(SMA_headers)
print(SMA_body)
SMA_response = requests.post(sma_server_api, data=json.dumps(SMA_body), headers=SMA_headers, verify=False)
print(SMA_response.json())
if SMA_response.status_code == 200 and SMA_response.json()['data']['totalCount'] == 1:
msg = "MID#"+MID+" is released successfully, please check your mailbox."
print(msg)
print(PersonName, PersonEmail, "submitted MID#", MID, "at", Created, "and is released successfully.", file=open("ReleaseEmail.log", "a"))
if SMA_response.status_code == 200 and SMA_response.json()['data']['totalCount'] == 0:
msg = "MID#"+MID+" was already released by the others but wasn't from this bot service."
print(msg)
if result['inputs']['Environment'] == 'O365':
MID = result['inputs']['MID']
RECIPIENT = result['inputs']['RECIPIENT']
#PersonId = result['personId']
#PersonEmail = send_get('https://webexapis.com/v1/people/{0}'.format(PersonId))['emails']
#RECIPIENT = PersonEmail[0].lower()
Release_Email = subprocess.Popen(['powershell.exe', './Release_O365.ps1', MID, RECIPIENT], stdout=subprocess.PIPE)
print(Release_Email.pid)
Release_Email.wait()
if Release_Email.returncode == 0:
msg = Release_Email.stdout.read().decode("utf-8")
else:
msg = "Invalid result: " + str(Release_Email.returncode) + " Please contact the developer to get more detail."
else:
msg = "You answered \"NO\" to any of the questions above, please delete the email or mark it as \"Junk\" in your mail client."
print(msg)
send_post("https://webexapis.com/v1/messages/", {"roomId": webhook['data']['roomId'], "markdown": msg})
def queryassets(result, webhook):
HOSTNAME = result['inputs']['HOSTNAME']
xml = """<ServiceRequest>
<filters>
<Criteria field="tagName" operator="EQUALS">{TAGNAME}</Criteria>
<Criteria field="name" operator="CONTAINS">{HOSTNAME}</Criteria>
</filters>
</ServiceRequest>""".format(HOSTNAME=HOSTNAME, TAGNAME="Cloud Agent")
headers = {'Content-Type': 'text/xml'}
response = requests.post('https://qualysapi.qg1.apps.qualys.ca/qps/rest/2.0/search/am/hostasset', data=xml, headers=headers, auth=(Qualys_username, Qualys_password))
root = ET.fromstring(response.text)
status = root[0].text
count = root[1].text
if status == 'SUCCESS' and count != '0':
try:
hostname = root[3][0].findall('name')[0].text
except IndexError:
hostname = "IndexError"
try:
AssetID = root[3][0].findall('id')[0].text
except IndexError:
AssetID = "IndexError"
try:
HostID = root[3][0].findall('qwebHostId')[0].text
except IndexError:
HostID = "IndexError"
try:
IPAddress = root[3][0].findall('address')[0].text
except IndexError:
IPAddress = "IndexError"
try:
OS = root[3][0].findall('os')[0].text
except IndexError:
OS = "IndexError"
try:
FQDN = root[3][0].findall('fqdn')[0].text
except IndexError:
FQDN = root[3][0].findall('name')[0].text
msg = status + " | " + count + " | " + hostname + " | Asset ID:" + AssetID + " | Host ID:" + HostID + " | IP Address:" + IPAddress + " | OS:" + OS
RoomID = webhook['data']['roomId']
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
filename = FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
path_filename = './vulnerabilities/' + FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
if os.path.exists(path_filename):
data = MultipartEncoder({'roomId': RoomID, "files": (filename, open(path_filename, 'rb'), 'text/csv')})
request = requests.post('https://webexapis.com/v1/messages', data=data, headers = {"Authorization": "Bearer " + bearer, 'Content-Type': data.content_type})
else:
if HostID != "IndexError" and AssetID != "IndexError":
msg = "Today's vulnerability file for " + HOSTNAME + " is not exist, bot is generating and will push the CSV file to you when it's done."
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
vuln_list(HostID,AssetID,RoomID,HOSTNAME, webhook)
else:
msg = "HostID or AssetID doesn't exist. Please contact the server administrator to have a check"
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
if status == 'SUCCESS' and count == '0':
HOSTNAME = HOSTNAME.lower()
xml = """<ServiceRequest>
<filters>
<Criteria field="tagName" operator="EQUALS">{TAGNAME}</Criteria>
<Criteria field="name" operator="CONTAINS">{HOSTNAME}</Criteria>
</filters>
</ServiceRequest>""".format(HOSTNAME=HOSTNAME, TAGNAME="Cloud Agent")
headers = {'Content-Type': 'text/xml'}
response = requests.post('https://qualysapi.qg1.apps.qualys.ca/qps/rest/2.0/search/am/hostasset', data=xml, headers=headers, auth=(Qualys_username, Qualys_password))
root = ET.fromstring(response.text)
status = root[0].text
count = root[1].text
if status == 'SUCCESS' and count != '0':
msg = status + " | " + count + " | " + root[3][0].findall('name')[0].text + " | Asset ID:" + root[3][0].findall('id')[0].text + " | Host ID:" + root[3][0].findall('qwebHostId')[0].text + " | IP Address:" + root[3][0].findall('address')[0].text + " | OS:" + root[3][0].findall('os')[0].text
HostID = root[3][0].findall('qwebHostId')[0].text
AssetID = root[3][0].findall('id')[0].text
try:
FQDN = root[3][0].findall('fqdn')[0].text
except IndexError:
FQDN = root[3][0].findall('name')[0].text
RoomID = webhook['data']['roomId']
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
filename = FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
path_filename = './vulnerabilities/' + FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
if os.path.exists(path_filename):
data = MultipartEncoder({'roomId': RoomID, "files": (filename, open(path_filename, 'rb'), 'text/csv')})
request = requests.post('https://webexapis.com/v1/messages', data=data, headers = {"Authorization": "Bearer " + bearer, 'Content-Type': data.content_type})
else:
msg = "Today's vulnerability file for " + HOSTNAME + " is not exist, bot is generating and will push the CSV file to you when it's done."
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
vuln_list(HostID,AssetID,RoomID,HOSTNAME)
if status == 'SUCCESS' and count == '0':
HOSTNAME = HOSTNAME.upper()
xml = """<ServiceRequest>
<filters>
<Criteria field="tagName" operator="EQUALS">{TAGNAME}</Criteria>
<Criteria field="name" operator="CONTAINS">{HOSTNAME}</Criteria>
</filters>
</ServiceRequest>""".format(HOSTNAME=HOSTNAME, TAGNAME="Cloud Agent")
headers = {'Content-Type': 'text/xml'}
response = requests.post('https://qualysapi.qg1.apps.qualys.ca/qps/rest/2.0/search/am/hostasset', data=xml, headers=headers, auth=(Qualys_username, Qualys_password))
root = ET.fromstring(response.text)
status = root[0].text
count = root[1].text
if status == 'SUCCESS' and count != '0':
msg = status + " | " + count + " | " + root[3][0].findall('name')[0].text + " | Asset ID:" + root[3][0].findall('id')[0].text + " | Host ID:" + root[3][0].findall('qwebHostId')[0].text + " | IP Address:" + root[3][0].findall('address')[0].text + " | OS:" + root[3][0].findall('os')[0].text
HostID = root[3][0].findall('qwebHostId')[0].text
AssetID = root[3][0].findall('id')[0].text
try:
FQDN = root[3][0].findall('fqdn')[0].text
except IndexError:
FQDN = root[3][0].findall('name')[0].text
RoomID = webhook['data']['roomId']
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
filename = FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
path_filename = './vulnerabilities/' + FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
if os.path.exists(path_filename):
data = MultipartEncoder({'roomId': RoomID, "files": (filename, open(path_filename, 'rb'), 'text/csv')})
request = requests.post('https://webexapis.com/v1/messages', data=data, headers = {"Authorization": "Bearer " + bearer, 'Content-Type': data.content_type})
else:
msg = "Today's vulnerability file for " + HOSTNAME + " is not exist, bot is generating and will push the CSV file to you when it's done."
send_post("https://webexapis.com/v1/messages/", {"roomId": RoomID, "markdown": msg})
vuln_list(HostID,AssetID,RoomID,HOSTNAME, webhook)
if status == 'SUCCESS' and count == '0':
msg = "Can't find " + HOSTNAME + " in Qualys. Host name is case-sensitive, please confirm the hostname and try again."
send_post("https://webexapis.com/v1/messages/", {"roomId": webhook['data']['roomId'], "markdown": msg})
def vuln_list(HostID,AssetID,RoomID,HOSTNAME, webhook):
global root_kb
ID = HostID
AssetID = AssetID
RoomID = RoomID
URL = 'https://qualysapi.qg1.apps.qualys.ca/api/2.0/fo/asset/host/vm/detection/?action=list&ids=' + ID
headers = {'X-Requested-With': 'Python'}
response = requests.post(URL, headers=headers, auth=(Qualys_username, Qualys_password), verify = False)
root = ET.fromstring(response.text)
try:
CODE = root[0].findall('CODE')[0].text
CODE_TEXT = root[0].findall('TEXT')[0].text
except IndexError:
CODE = 'NA'
CODE_TEXT ='NA'
if CODE == 'NA':
try:
HOSTLIST_TAG = root[0][1].tag
except IndexError:
HOSTLIST_TAG = 'NA'
if HOSTLIST_TAG != 'NA':
if os.path.exists('vulnerabilities'):
FQDN = root[0][1][0].findall('DNS')[0].text
filename = FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
path_filename = './vulnerabilities/' + FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
else:
os.mkdir('vulnerabilities')
filename = FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
path_filename = './vulnerabilities/' + FQDN + "_" + time.strftime('%Y-%m-%d', time.localtime()) + ".csv"
csvfile = open(path_filename, 'w', newline='', encoding="utf-8")
csvfile_writer = csv.writer(csvfile)
# ADD THE HEADER TO CSV FILE
csvfile_writer.writerow(['SEVERITY", "ASSET IP", "TITLE", "FIRST DETECTED", "STATUS", "QID", "CVSSv3 Base (nvd)", "TYPE DETECTED", "CVE", "SOLUTION", "CVE-Description", "ASSET ID", "LAST DETECTED", "ASSET NAME", "RESULTS'])
try:
ASSET_IP = root[0][1][0].findall('IP')[0].text
except IndexError:
ASSET_IP = 'NA'
try:
VulnNumber = len(root[0][1][0].findall('DETECTION_LIST')[0])
except IndexError:
VulnNumber = 0
if VulnNumber != 0:
try:
len(root_kb[0][1])
print(' *** There are ', len(root_kb[0][1]), 'QID records. *** ')
except NameError:
if os.path.isfile('Knowledge_Base.xml') and os.path.getsize('Knowledge_Base.xml') > 0 and ((datetime.fromtimestamp(os.stat('Knowledge_Base.xml').st_mtime)).strftime('%Y-%m') == time.strftime('%Y-%m', time.localtime())) :
tree = ET.parse('Knowledge_Base.xml')
root_kb = tree.getroot()
else:
headers = {'X-Requested-With': 'Python'}
URL = 'https://qualysapi.qg1.apps.qualys.ca/api/2.0/fo/knowledge_base/vuln/?action=list'
try:
response = requests.post(URL, headers=headers, auth=(Qualys_username, Qualys_password), verify = False)
if response.status_code == 200:
root_kb = ET.fromstring(response.text)
with open('Knowledge_Base.xml', 'w', encoding='utf-8-sig') as f:
f.write(response.text)
except BaseException as error:
print('An exception occurred: {}'.format(error))
print(' *** Qualys Knowledge Base Data has been loaded into memory. *** ')
for i in range(VulnNumber):
try:
QID = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('QID')[0].text
except IndexError:
QID = 'NA'
try:
STATUS = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('STATUS')[0].text
except IndexError:
STATUS = 'NA'
try:
SEVERITY = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('SEVERITY')[0].text
except IndexError:
SEVERITY = 'NA'
try:
TYPE_DETECTED = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('TYPE')[0].text
except IndexError:
TYPE_DETECTED = 'NA'
try:
RESULTS = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('RESULTS')[0].text
except IndexError:
RESULTS = 'NA'
try:
FIRST_DETECTED = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('FIRST_FOUND_DATETIME')[0].text
except IndexError:
FIRST_DETECTED = 'NA'
try:
LAST_DETECTED = root[0][1][0].findall('DETECTION_LIST')[0][i].findall('LAST_FOUND_DATETIME')[0].text
except IndexError:
LAST_DETECTED = 'NA'
CVE = []
if QID != 'NA':
for j in range(len(root_kb[0][1])):
if root_kb[0][1][j][0].text == QID:
try:
TITLE = root_kb[0][1][j].findall('TITLE')[0].text
except IndexError:
TITLE = 'NA'
try:
CVSS_V3 = root_kb[0][1][j].findall('CVSS_V3')[0].findall('BASE')[0].text
except IndexError:
CVSS_V3 = 'NA'
try:
SOLUTION = root_kb[0][1][j].findall('SOLUTION')[0].text
if SOLUTION is None:
SOLUTION = 'NA'
else:
SOLUTION = (SOLUTION.replace('\n', ' ')).replace('\t', ' ')
except IndexError:
SOLUTION = 'NA'
try:
CVE_Number = len(root_kb[0][1][j].findall('CVE_LIST')[0].findall('CVE'))
except IndexError:
CVE_Number = 0
if CVE_Number != 0:
for k in range(CVE_Number):
CVE.append(root_kb[0][1][j].findall('CVE_LIST')[0].findall('CVE')[k][0].text)
try:
CVE_Description = root_kb[0][1][j].findall('DIAGNOSIS')[0].text
except IndexError:
CVE_Description = 'NA'
# ADD A NEW ROW TO CSV FILE
csvfile_writer.writerow([SEVERITY, ASSET_IP, TITLE, FIRST_DETECTED, STATUS, QID, CVSS_V3, TYPE_DETECTED, CVE, SOLUTION, CVE_Description, AssetID, LAST_DETECTED, FQDN, RESULTS])
csvfile.close()
if os.path.exists(path_filename):
data = MultipartEncoder({'roomId': RoomID, "files": (filename, open(path_filename, 'rb'), 'text/csv')})
request = requests.post('https://webexapis.com/v1/messages', data=data, headers = {"Authorization": "Bearer " + bearer, 'Content-Type': data.content_type})
else:
msg = "There's no vulnerability for HOST " + HOSTNAME + ". If the host just registered, it would take a while to collect the vulnerabilities information, please try again later."
send_post("https://webexapis.com/v1/messages/", {"roomId": webhook['data']['roomId'], "markdown": msg})
else:
msg = CODE + CODE_TEXT
send_post("https://webexapis.com/v1/messages/", {"roomId": webhook['data']['roomId'], "markdown": msg})
def client_certificates(result, webhook):
PersonId = result['personId']
PersonEmail = send_get('https://webexapis.com/v1/people/{0}'.format(PersonId))['emails']
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " | " + str(PersonEmail[0]) + " | submit \"client certificates\" request.", file=open("Certificate_output.log", "a"))
CSR_content = """[Version]
Signature = "$Windows NT$"
[NewRequest]
Subject = "CN={CommonName}, O={Organization}, OU={Department}, L={City}, S={Province}, C={Country}, E={Email}"
Exportable = True
KeyLength = 4096
KeySpec = 1
KeyUsage = 0xA0
MachineKeySet = FALSE
ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"
RequestType = PKCS10
FriendlyName = {CommonName}_{CertificateTemplate}_{DateTime}
[Extensions]
[RequestAttributes]
CertificateTemplate = {CertificateTemplate}
""".format(CommonName=result['inputs']['CN'], Organization=result['inputs']['O'], Department=result['inputs']['OU'], City=result['inputs']['L'], Province=result['inputs']['S'], Country=result['inputs']['C'], Email=result['inputs']['Email'], CertificateTemplate=result['inputs']['CertificateType'], DateTime=time.strftime("%Y-%m-%d", time.localtime()) )
filename = ''.join(random.choice(string.ascii_letters) for i in range(20))
with open(filename, 'w') as CSRfile:
CSRfile.writelines(CSR_content)
CSRfile.close()
environment = result['inputs']['Environment'] # tells if PROD or NON-PROD
comment_file = filename + "_comment"
comments = result['inputs']['Comments']
with open(comment_file, 'w') as Commentfile:
Commentfile.writelines(comments)
Commentfile.close()
if os.path.isfile(filename):
Generate_Certificate = subprocess.Popen(['powershell.exe', './Generate_Certificate.ps1', filename, environment, comment_file]) # get file details, PROD or NON-PROD, write to comment_file if necessary
print(Generate_Certificate.pid)
Generate_Certificate.wait()
else:
print(filename, "doesn't exist")
if Generate_Certificate.returncode != 0:
msg = "Invalid result: " + str(Generate_Certificate.returncode) + " Please check the Certificate_output.log to get more detail."
else:
msg = "Email has been sent to " + result['inputs']['Email'] + " with the PFX file and password."
send_post("https://webexapis.com/v1/messages/", {"roomId": webhook['data']['roomId'], "markdown": msg})
"""
def zip_directory(directory, zip_name):
with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zip_file:
print(list(os.walk(f"BatchClientCertificate\\{directory}")))
for files in os.walk(f"BatchClientCertificate\\{directory}"):
if len(files[1]) == 1:
zip_directory(files[1][0], zip_name)
if len(files[2]) == 1:
zip_file.write(os.path.join(files[0], files[2][0]), os.path.relpath(files[2][0], directory))
"""
# def eop_phishsim(result):
# Remove = result['inputs']['Remove']
# if Remove == 'YES':
# EOP_PhishSim_result = subprocess.run(['powershell.exe', '-File', './EOPPhishSim.ps1', '-remove'], capture_output=True, text=True)
# msg = EOP_PhishSim_result.stdout
# print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " | submit \"Clean the current Phishing Simulation configuration\" request", file=open("Security_Assistant_Bot.log", "a"))
# else:
# Name = result['inputs']['Name'].replace(" ", "")
# Domain = result['inputs']['Domain'].split(',')
# IP = result['inputs']['IP'].split(',')
# if len(Domain) > 20:
# msg = "Domain entries can NOT be more than 20."
# elif len(IP) > 10:
# msg = "IP entries can NOT be more than 10."
# else:
# print(Name)
# Domain = ','.join(Domain)
# print(Domain)
# IP = ','.join(IP)
# print(IP)
# EOP_PhishSim_result = subprocess.run(['powershell.exe', '-File', './EOPPhishSim.ps1', Name, Domain, IP], capture_output=True, text=True)
# msg = EOP_PhishSim_result.stdout
# print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " | submit \"EOP Phish Simulation Configuration\" request with Domain " + Domain + " and with IP " + IP, file=open("Security_Assistant_Bot.log", "a"))
# if msg != None:
# send_post("https://webexapis.com/v1/messages/", {"roomId": webhook['data']['roomId'], "markdown": msg})
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def teams_webhook():
if request.method == 'POST':
webhook = request.get_json(silent=True)
if webhook['resource'] == "attachmentActions" and webhook['data']['type'] == "submit":
result = send_get('https://webexapis.com/v1/attachment/actions/{0}'.format(webhook['data']['id']))
#print(result)
if result['inputs']['id'] == "ReleaseEmails":
releaseemails(result, webhook)
if result['inputs']['id'] == "QualysAssets":
queryassets(result, webhook)
if result['inputs']['id'] == "ClientCertificates":
client_certificates(result, webhook)
if result['inputs']['id'] == "SingleOrBatch":
if result['inputs']['Batch'] == "True":
file_path = "./Client_Certificate_Information_Template.csv"
if os.path.exists(file_path):
with open(file_path, "rb") as file:
send_put("https://webexapis.com/v1/messages/" + result['messageId'],
{
"roomId": webhook['data']['roomId'],
"attachments":[
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{
"type": "TextBlock",
"size": "Large",
"weight": "Bolder",
"text": "Client Certificate Request",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"text": "To make a batch request, please download the file attached below:"
}]
}
}
],
"markdown": "Client Certificates"
}
)
parent_id = send_get("https://webexapis.com/v1/messages/" + result['messageId'])['parentId']
data = MultipartEncoder({'roomId': webhook['data']['roomId'], "parentId": parent_id, "files": (file_path, file, 'text/csv')})
requests.post("https://webexapis.com/v1/messages/", data=data, headers = {"Authorization": "Bearer " + bearer, 'Content-Type': data.content_type})
send_post("https://webexapis.com/v1/messages/",
{
"roomId": webhook['data']['roomId'],
"parentId": parent_id,
"attachments":[
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{
"type": "TextBlock",
"wrap": True,
"text": "Once you have finished filling out the entries in the CSV file, please REPLY to this message and upload the file TO THIS THREAD"
},
{
"type": "TextBlock",
"weight": "Bolder",
"text": "CertificateTemplate HAS ONLY 2 VALID OPTIONS:\r1. SLRR\r2. DrugPlan2.0",
"wrap": True
},
{
"type": "TextBlock",
"weight": "Bolder",
"text": "\nCA HAS ONLY 2 VALID OPTIONS:\r1. PROD\r2. NON-PROD",
"wrap": True
},
{
"type": "TextBlock",
"weight": "Bolder",
"text": "The CommonName field MUST BE NON-EMPTY",
"wrap": True
}]
}
}
],
"markdown": "Batch Client Certificates"
}
)
else:
send_put("https://webexapis.com/v1/messages/" + result['messageId'],
{
"roomId": webhook['data']['roomId'],
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{
"type": "TextBlock",
"size": "Large",
"weight": "Bolder",
"text": "Client Certificate Request",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"weight": "Bolder",
"text": "(Notice: comma is NOT allowed in all fields)",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"text": "Certificate Type"
},
{
"type": "Input.ChoiceSet",
"id": "CertificateType",
"choices": [
{
"title": "SLRR Certificate",
"value": "SLRR"
},
{
"title": "Drug Plan Certificate",
"value": "DrugPlan2.0"
},
{
"title": "Client Certificate",
"value": "ClientAuthenticationCNET-privatekeyexportable"
}
]
},
{
"type": "Input.ChoiceSet",
"id": "Environment",
"choices": [
{
"title": "PROD",
"value": "PROD"
},
{
"title": "NON-PROD",
"value": "NON-PROD"
}
]
},
{
"type": "Input.Text",
"placeholder": "Common Name",
"style": "text",
"maxLength": 0,
"id": "CN"
},
{
"type": "Input.Text",
"placeholder": "Organization",
"style": "text",
"maxLength": 0,
"id": "O"
},
{
"type": "Input.Text",
"placeholder": "Department",
"style": "text",
"maxLength": 0,
"id": "OU"
},
{
"type": "Input.Text",
"placeholder": "City",
"style": "text",
"maxLength": 0,
"id": "L"
},
{
"type": "Input.ChoiceSet",
"id": "S",
"choices": [
{
"title": "Alberta",
"value": "AB"
},
{
"title": "British Columbia",
"value": "BC"
},
{
"title": "Manitoba",
"value": "MB"
},
{
"title": "New Brunswick",
"value": "NB"
},
{
"title": "Newfoundland and Labrador",
"value": "NL"
},
{
"title": "Nova Scotia",
"value": "NS"
},
{
"title": "Northwest Territories",
"value": "NT"
},
{
"title": "Nunavut",
"value": "NU"
},
{
"title": "Ontario",
"value": "ON"
},
{
"title": "Prince Edward Island",
"value": "PE"
},
{
"title": "Quebec",
"value": "QC"
},
{
"title": "Saskatchewan",
"value": "SK"
},
{
"title": "Yukon",
"value": "YT"
}
]
},
{
"type": "Input.Text",
"placeholder": "Country",
"style": "text",
"maxLength": 0,
"value": "CA",
"id": "C"
},
{
"type": "Input.Text",
"placeholder": "Email",
"style": "text",
"maxLength": 0,
"id": "Email"
},
{
"type": "Input.Text",
"placeholder": "Comments(Optional)",
"isMultiline": True,
"id": "Comments"
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Submit",
"data": {
"cardType": "input",
"id": "ClientCertificates"
}
}
]
}
}
],
"markdown": "Client Certificates"
}
)
#client_certificates(result, webhook)
# if result['inputs']['id'] == "EOPPhishSim":
# eop_phishsim(result)
if webhook['resource']== "messages" and webhook['data']['personEmail']!= bot_email:
print(webhook)
msg = None
if "@webex.bot" not in webhook['data']['personEmail']:
result = send_get('https://webexapis.com/v1/messages/{0}'.format(webhook['data']['id']))
in_message = result.get('text', '').lower()
in_message = in_message.replace(bot_name.lower() + " ", '')
if in_message.startswith('help'):
msg = help_me()
elif in_message.startswith('hello'):
msg = greetings()
# elif in_message.startswith("eop phishsim"):
# if accesslist_ADMIN == "ALL" or webhook['data']['personEmail'].lower() in accesslist_ADMIN or webhook['data']['personEmail'].lower() in accesslist_EOPPHISHSIM:
# requester = webhook['data']['personEmail'].lower()
# send_post("https://webexapis.com/v1/messages/",
# {
# "roomId": webhook['data']['roomId'],
# "parentId": webhook['data']['id'],
# "attachments": [
# {
# "contentType": "application/vnd.microsoft.card.adaptive",
# "content": {
# "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
# "type": "AdaptiveCard",
# "version": "1.2",
# "body": [
# {
# "type": "TextBlock",
# "size": "Large",
# "weight": "Bolder",
# "text": "EOP Phish Simulation Configuration",
# "horizontalAlignment": "Center"
# },
# {
# "type": "TextBlock",
# "weight": "Bolder",
# "text": "(Notice: You can ONLY specify up to 20 Domain entries and 10 IP entries separated by commas.)",
# "horizontalAlignment": "Center"
# },
# {
# "type": "Input.Toggle",
# "title": "Clean the current Phishing Simulation configuration? (YES/NO)",
# "valueOn": "YES",
# "valueOff": "NO",
# "id": "Remove"
# },
# {
# "type": "Input.Text",
# "placeholder": "Name(No SPACE Allowed.)",
# "style": "text",
# "maxLength": 0,
# "value": "TerranovaPhishSim",
# "id": "Name"
# },
# {
# "type": "Input.Text",
# "placeholder": "Domain(ONLY up to 20 Domain entries separated by commas.)",
# "isMultiline": True,
# "id": "Domain"
# },
# {
# "type": "Input.Text",
# "placeholder": "IP(ONLY up to 10 IP entries separated by commas.)",
# "isMultiline": True,
# "id": "IP"
# }
# ],
# "actions": [
# {
# "type": "Action.Submit",
# "title": "Submit",
# "data": {
# "cardType": "input",
# "id": "EOPPhishSim"
# }
# }
# ]
# }
# }
# ],
# "markdown": "EOP PhishSim"
# }
# )
# print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " | " + requester + " | request Menu \"eop phishsim\"", file=open("Security_Assistant_Bot.log", "a"))
# else:
# msg = "Sorry, you (" + webhook['data']['personEmail'] + ") are NOT allowed to use this module. Please contact Hao.Ban@eHealthsask.ca for help."
# elif in_message.startswith("requested quarantine"):
# if accesslist_ADMIN == "ALL" or webhook['data']['personEmail'].lower() in accesslist_ADMIN or webhook['data']['personEmail'].lower() in accesslist_REQUESTEDQUARANTINE:
# Requested_Quarantine = subprocess.Popen(['powershell.exe', './Quarantined_Emails_Requested.ps1', webhook['data']['roomId']])
# print(Requested_Quarantine.pid)
# Requested_Quarantine.wait()
# else:
# msg = "Sorry, you (" + webhook['data']['personEmail'] + ") are NOT allowed to use this module. Please contact Hao.Ban@eHealthsask.ca for help."
elif in_message.startswith("script status"):
if accesslist_ADMIN == "ALL" or webhook['data']['personEmail'].lower() in accesslist_ADMIN or webhook['data']['personEmail'].lower() in accesslist_SCRIPTSTATUS:
Processor_Monitor = subprocess.Popen(['powershell.exe', './ProcessorMonitor.ps1', webhook['data']['roomId'], bearer])
print(Processor_Monitor.pid)
Processor_Monitor.wait()
else:
msg = "Sorry, you (" + webhook['data']['personEmail'] + ") are NOT allowed to use this module. Please contact Hao.Ban@eHealthsask.ca for help."
# elif in_message.startswith("block address"):
# msg = block_address()
elif in_message.startswith("release emails"):
if accesslist_ADMIN == "ALL" or webhook['data']['personEmail'].lower() in accesslist_ADMIN or webhook['data']['personEmail'].lower() in accesslist_RELEASEEMAIL:
send_post("https://webexapis.com/v1/messages/",
{
"roomId": webhook['data']['roomId'],
"parentId": webhook['data']['id'],
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
"body": [
{
"type": "TextBlock",
"size": "Large",
"weight": "Bolder",
"text": "Release Encrypted Emails",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"text": "Before proceeding:",
"size": "Medium",
"weight": "Bolder"
},
{
"type": "Input.Toggle",
"title": "Do you know the sender? (Select-YES/Empty-NO)",
"valueOn": "YES",
"valueOff": "NO",
"id": "Question1"
},
{
"type": "Input.Toggle",
"title": "Are you expecting this message? (Select-YES/Empty-NO)",
"valueOn": "YES",
"valueOff": "NO",
"id": "Question2"
},
{
"type": "Input.Toggle",