-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathswapi.py
executable file
·13126 lines (12765 loc) · 617 KB
/
swapi.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 python2.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
try:
from pip import main as pipmain
except:
from pip._internal import main as pipmain
'''
Copyright 2019. Aurelio Somarriba Lucas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import os, getopt, select, re, errno, copy, signal
import sys, time, random, string, socket, struct, os.path, datetime
from datetime import timedelta
from optparse import OptionParser
from optparse import OptionGroup
from urlparse import urljoin
from collections import OrderedDict
from time import sleep
import subprocess
import json #as simplejson
import getpass
import csv
from os.path import expanduser
import pprint
import calendar
import urllib
import base64
import locale
import time
import curses
import random
from collections import namedtuple
from HTMLParser import HTMLParser
class bcolors:
HEADER = '\033[95m'
TURQUO = '\033[96m'
WHITEGREY = '\033[100m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
WHITE = '\033[97m'
BROWN = '\033[33m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
BIG = '\033#3'
BLINK = '\033[5m'
BLINKF = '\033[6m'
CLEAR = '\033[2J'
ALIGN = '\033#8'
BACKWHITE = '\033[37m'
autoInstall = False
try:
reqFile = open('requirements.txt', 'r')
contents = reqFile.readlines()
#print contents[0]
reqReDo = False
if '==' in contents[0]:
#print contents[0].split('==')[1].strip()
if contents[0].split('==')[1].strip() == '3.2':
pass
else:
reqReDo = True
else:
reqReDo = True
if reqReDo == True:
f = open('requirements.txt', 'w+')
libraries = '''# version==3.2
nose==1.3.7
xlrd==1.2.0
pandas==0.24.2
requests==2.18.4
texttable==0.8.7
pyopenssl==17.2.0
dnspython==1.15.0
Pygments==2.2.0
paramiko==2.3.1
edgegrid-python==1.0.10
XlsxWriter==1.1.1
beautifulsoup4==4.6.0
pyfiglet==0.8.post1
#
'''
f.write(libraries)
f.close()
except:
f = open('requirements.txt', 'w+')
libraries = '''# version==3.2
nose==1.3.7
xlrd==1.2.0
pandas==0.24.2
requests==2.18.4
texttable==0.8.7
pyopenssl==17.2.0
dnspython==1.15.0
Pygments==2.2.0
paramiko==2.3.1
edgegrid-python==1.0.10
XlsxWriter==1.1.1
beautifulsoup4==4.6.0
pyfiglet==0.8.post1
#
'''
f.write(libraries)
f.close()
try:
import pandas
import xlsxwriter
import texttable as tt
from requests import Request, Session
import requests
from pygments import highlight, lexers, formatters
from akamai.edgegrid import EdgeGridAuth, EdgeRc
from bs4 import BeautifulSoup
from pyfiglet import Figlet
except:
print bcolors.TURQUO+"[Auto Install]"+bcolors.WARNING+" Required libraries not found. Auto Install initiated... "+bcolors.ENDC
failed = pipmain(['install','--user','-q','-r','requirements.txt'])
if failed == True:
print bcolors.TURQUO+"[Auto Install]"+bcolors.WARNING+" Auto Install failed. Please try to install manually. "+bcolors.ENDC
sys.exit()
else:
print bcolors.TURQUO+"[Auto Install]"+bcolors.WARNING+" Auto Install completed successfully. "+bcolors.ENDC
print bcolors.TURQUO+"[Auto Install]"+bcolors.WARNING+" How far down the whiteRabbit hole are you willing to go? "+bcolors.ENDC
sys.exit()
import xlsxwriter
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import texttable as tt
from requests import Request, Session
import requests
from bs4 import BeautifulSoup
from pygments import highlight, lexers, formatters
try:
from akamai.edgegrid import EdgeGridAuth, EdgeRc
except:
pass
PYTHON2 = sys.version_info.major < 3
locale.setlocale(locale.LC_ALL, '')
encoding = locale.getpreferredencoding()
VERSION = '3.1.7'
'''
Created by: Aurelio Somarriba Lucas
Name: SWaPI
CodeName: whiteRabbit
Version: RC3.1.7 - Aug 31, 2019
New in 3.x.x:
- Dockerize!!
docker pull ausomarr/swapi:v1
docker run -it --name swapi 303c8febd7c8
- Configuration Peer Review
- Auto Install Feature
- API Client File support
- Fast DNS
- PLX Analytics
- Application Security Clone Feature
- Patch command support on PAPI
- Alerts API
- Network Lists V2
- Contracts APIs
* Audit report included
- Minor bugs fixed
- SWaPI Links:
Main Blog:
https://collaborate.akamai.com/confluence/pages/viewpage.action?pageId=115908115
GIT:
https://stash.akamai.com/projects/GSS/repos/swapi/browse
Installation:
SWaPI should auto-install all necessary libraries.
'''
########################################################################
# TUNABLES
DROPPING_CHARS = 50
MIN_SPEED = 1
MAX_SPEED = 7
RANDOM_CLEANUP = 100
WINDOW_CHANCE = 50
WINDOW_SIZE = 25
WINDOW_ANIMATION_SPEED = 3
FPS = 25
SLEEP_MILLIS = 1.0/FPS
USE_COLORS = False
SCREENSAVER_MODE = True
MATRIX_CODE_CHARS = "{}[]\|';/>?<.,SWaPI=whiteRbcodn!@#$%^&*+-~ɀɁɂŧϢϣϤϥϦϧϨϫϬϭϮϯϰϱϢϣϤϥϦϧϨϩϪϫϬϭϮϯϰ߃߄༣༤༥༦༧༩༪༫༬༭༮༯༰༱༲༳༶"
########################################################################
# CODE
COLOR_CHAR_NORMAL = 1
COLOR_CHAR_HIGHLIGHT = 2
COLOR_WINDOW = 3
class FallingChar(object):
matrixchr = list(MATRIX_CODE_CHARS)
normal_attr = curses.A_NORMAL
highlight_attr = curses.A_REVERSE
def __init__(self, width, MIN_SPEED, MAX_SPEED):
self.x = 0
self.y = 0
self.speed = 1
self.char = ' '
self.reset(width, MIN_SPEED, MAX_SPEED)
def reset(self, width, MIN_SPEED, MAX_SPEED):
self.char = random.choice(FallingChar.matrixchr).encode(encoding)
self.x = randint(1, width - 1)
self.y = 0
self.speed = randint(MIN_SPEED, MAX_SPEED)
# offset makes sure that chars with same speed don't move all in same frame
self.offset = randint(0, self.speed)
def tick(self, scr, steps):
height, width = scr.getmaxyx()
if self.advances(steps):
# if window was resized and char is out of bounds, reset
self.out_of_bounds_reset(width, height)
# make previous char curses.A_NORMAL
if USE_COLORS:
scr.addstr(self.y, self.x, self.char, curses.color_pair(COLOR_CHAR_NORMAL))
else:
scr.addstr(self.y, self.x, self.char, curses.A_NORMAL)
# choose new char and draw it A_REVERSE if not out of bounds
self.char = random.choice(FallingChar.matrixchr).encode(encoding)
self.y += 1
if not self.out_of_bounds_reset(width, height):
if USE_COLORS:
scr.addstr(self.y, self.x, self.char, curses.color_pair(COLOR_CHAR_HIGHLIGHT))
else:
scr.addstr(self.y, self.x, self.char, curses.A_REVERSE)
def out_of_bounds_reset(self, width, height):
if self.x > width-2:
self.reset(width, MIN_SPEED, MAX_SPEED)
return True
if self.y > height-2:
self.reset(width, MIN_SPEED, MAX_SPEED)
return True
return False
def advances(self, steps):
if steps % (self.speed + self.offset) == 0:
return True
return False
def step(self, steps, scr):
return -1, -1, None
class WindowAnimation(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.step = 0
def tick(self, scr, steps):
if self.step > WINDOW_SIZE:
#stop window animation after some steps
self.draw_frame(scr, self.x - self.step, self.y - self.step,
self.x + self.step, self.y + self.step,
curses.A_NORMAL)
return False
# clear all characters covered by the window frame
for i in range(WINDOW_ANIMATION_SPEED):
anistep = self.step + i
self.draw_frame(scr, self.x - anistep, self.y - anistep,
self.x + anistep, self.y + anistep,
curses.A_NORMAL, ' ')
#cancel last animation
self.draw_frame(scr, self.x - self.step, self.y - self.step,
self.x + self.step, self.y + self.step,
curses.A_NORMAL)
#next step
self.step += WINDOW_ANIMATION_SPEED
#draw outer frame
self.draw_frame(scr, self.x - self.step, self.y - self.step,
self.x + self.step, self.y + self.step,
curses.A_REVERSE)
return True
def draw_frame(self, scr, x1, y1, x2, y2, attrs, clear_char=None):
if USE_COLORS:
if attrs == curses.A_REVERSE:
attrs = curses.color_pair(COLOR_WINDOW)
h, w = scr.getmaxyx()
for y in (y1, y2):
for x in range(x1, x2+1):
if x < 0 or x > w-1 or y < 0 or y > h-2:
continue
if clear_char is None:
scr.chgat(y, x, 1, attrs)
else:
scr.addstr(y, x, clear_char, attrs)
for x in (x1, x2):
for y in range(y1, y2+1):
if x < 0 or x > w-1 or y < 0 or y > h-2:
continue
if clear_char is None:
scr.chgat(y, x, 1, attrs)
else:
scr.addstr(y, x, clear_char, attrs)
# we don't need a good PRNG, just something that looks a bit random.
def rand():
# ~ 2 x as fast as random.randint
a = 9328475634
while True:
a ^= (a << 21) & 0xffffffffffffffff;
a ^= (a >> 35);
a ^= (a << 4) & 0xffffffffffffffff;
yield a
r = rand()
def randint(_min, _max):
if PYTHON2:
n = r.next()
else:
n = r.__next__()
return (n % (_max - _min)) + _min
def codeRain():
steps = 0
scr = curses.initscr()
scr.nodelay(1)
curses.curs_set(0)
curses.noecho()
if USE_COLORS:
curses.start_color()
curses.use_default_colors()
curses.init_pair(COLOR_CHAR_NORMAL, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(COLOR_CHAR_HIGHLIGHT, curses.COLOR_WHITE, curses.COLOR_GREEN)
curses.init_pair(COLOR_WINDOW, curses.COLOR_GREEN, curses.COLOR_GREEN)
height, width = scr.getmaxyx()
window_animation = None
lines = []
for i in range(DROPPING_CHARS):
l = FallingChar(width, MIN_SPEED, MAX_SPEED)
l.y = randint(0, height-2)
lines.append(l)
scr.refresh()
while True:
height, width = scr.getmaxyx()
for line in lines:
line.tick(scr, steps)
for i in range(RANDOM_CLEANUP):
x = randint(0, width-1)
y = randint(0, height-1)
scr.addstr(y, x, ' ')
#if randint(0, WINDOW_CHANCE) == 1:
# if window_animation is None:
#start window animation
# line = random.choice(lines)
# window_animation = WindowAnimation(line.x, line.y)
#if not window_animation is None:
# still_active = window_animation.tick(scr, steps)
# if not still_active:
# window_animation = None
scr.refresh()
time.sleep(SLEEP_MILLIS)
if SCREENSAVER_MODE:
key_pressed = scr.getch() != -1
if key_pressed:
raise KeyboardInterrupt()
steps += 1
def errorHandling(respjson,errorJson):
if respjson:
print errorJson.content
sys.exit()
print bcolors.TURQUO+"[ERROR]"+bcolors.WARNING+" There was a problem processing your request: "+bcolors.ENDC
print bcolors.TURQUO+"[ERROR]"+bcolors.WARNING+" Status Code: "+bcolors.FAIL+str(errorJson['status'])+bcolors.ENDC
print bcolors.TURQUO+"[ERROR]"+bcolors.WARNING+" Title: "+bcolors.FAIL+errorJson['title']+bcolors.ENDC
print bcolors.TURQUO+"[ERROR]"+bcolors.WARNING+" Detail: "+bcolors.FAIL+errorJson['detail']+bcolors.ENDC
try:
print bcolors.TURQUO+"[ERROR]"+bcolors.ENDC+bcolors.WARNING+" Object Type: "+bcolors.FAIL+errorJson['objectType']+bcolors.ENDC
print bcolors.TURQUO+"[ERROR]"+bcolors.ENDC+bcolors.WARNING+" Zone: "+bcolors.FAIL+errorJson['zone']+bcolors.ENDC
except:
pass
#formatted_json = json.dumps(errorJson, indent=4, sort_keys=True)
#colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
#print colorful_json
#pprint.pprint(result.json())
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
def setUp():
home = expanduser("~")
filename = home+'/.edgercNew'
#print filename
try:
open(filename, 'r')
except IOError:
createEdge = raw_input(bcolors.TURQUO+'[SETUP]'+bcolors.ENDC+' EdgeGrid Authentication file, .edgerc, has not been found. Do you want to create it with a default section? [y/N] ')
if createEdge == 'y':
credentials = raw_input(bcolors.TURQUO+'[SETUP]'+bcolors.ENDC+' Please enter credentials down below: \n')
print "please copy and paste your charge discharge data.\n"
"To end recording Press Ctrl+d on Linux/Mac on Crtl+z on Windows"
lines = ['default']
try:
while True:
lines.append(raw_input())
except EOFError:
pass
lines = "\n".join(lines)
outputfile = open(filename, 'w+')
#entry = "[default]\n"+credentials+"\n"
try:
outputfile.writelines(lines)
#print outputfile
outputfile.close()
print bcolors.TURQUO+"[SETUP]"+bcolors.ENDC+bcolors.WARNING+" Successfully created edgerc file. "+bcolors.ENDC
except:
print bcolors.TURQUO+"[SETUP]"+bcolors.ENDC+bcolors.WARNING+" There was a problem creating the edgerc file"+bcolors.ENDC
print bcolors.WHITE+'\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
'''
edgerc = EdgeRc(filename)
section = creds
try:
baseurl = 'https://%s' % edgerc.get(section, 'host')
except:
print bcolors.WARNING+'[IAM] SWaPI was unable to find any valid section in your EdgeRC file called: '+section+bcolors.ENDC
print bcolors.WARNING+'[IAM] Please check your EdgeRC file and fix.'+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
pass'''
def SIEMModule(automation,AccountSwitch,propertyName,creds,configId,offset,limit,start,end,respjson):
def convert_to_epoch(date_time):
"""
:param date_time:
:return:
"""
pattern = '%m/%d/%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
return utc_epoch
def epoch_to_datetime(epoch_time):
"""
:param epoch_time:
:return:
"""
pattern = '%Y-%m-%d %H:%M:%S'
return datetime.datetime.fromtimestamp(epoch_time).strftime(pattern)
def get_local_time_gmt():
"""
:return:
"""
ts = calendar.timegm(time.gmtime())
return ts
def decode_attack_data_payload(payload_string):
"""
:param payload_string:
:return:
"""
decode_payload_string = urllib.unquote(payload_string).decode('utf-8')
chunks = decode_payload_string.split(";")
decoded_chunks = []
for _i in chunks:
b64_decoded_chunk = base64.b64decode(_i)
decoded_chunks.append(b64_decoded_chunk.decode('utf-8'))
return ";".join(decoded_chunks)
def decode_headers(payload_string):
"""
:param payload_string:
:return:
"""
decode_payload_string = urllib.unquote(payload_string).decode('utf-8')
headers = decode_payload_string.split("\n")
return headers
def map_rules(payload):
"""
:param payload:
:return:
"""
list_rule_actions = payload['attackData']['ruleActions'].split(";")[:-1]
list_rule_data = payload['attackData']['ruleData'].split(";")[:-1]
list_rule_messages = payload['attackData']['ruleMessages'].split(";")[:-1]
list_rule_selectors = payload['attackData']['ruleSelectors'].split(";")
if len(list_rule_selectors) != 1:
list_rule_selectors = payload['attackData']['ruleSelectors'].split(";")[:-1]
list_rule_tags = payload['attackData']['ruleTags'].split(";")[:-1]
list_rule_versions = payload['attackData']['ruleVersions'].split(";")[:-1]
list_rules = payload['attackData']['rules'].split(";")[:-1]
dict_rules = []
for j in list_rules:
item_index = list_rules.index(j)
dict_rules.append(
{
"action": list_rule_actions[item_index],
"data": list_rule_data[item_index],
"message": list_rule_messages[item_index],
"selector": list_rule_selectors[item_index],
"tag": list_rule_tags[item_index],
"version": list_rule_versions[item_index],
"id": list_rules[item_index],
}
)
return dict_rules
def dictionary_rules(payload):
"""
:param payload:
:return:
"""
list_rule_actions = payload['attackData']['ruleActions'].split(";")[:-1]
list_rule_data = payload['attackData']['ruleData'].split(";")[:-1]
list_rule_messages = payload['attackData']['ruleMessages'].split(";")[:-1]
list_rule_selectors = payload['attackData']['ruleSelectors'].split(";")
if len(list_rule_selectors) != 1:
list_rule_selectors = payload['attackData']['ruleSelectors'].split(";")[:-1]
list_rule_tags = payload['attackData']['ruleTags'].split(";")[:-1]
list_rule_versions = payload['attackData']['ruleVersions'].split(";")[:-1]
list_rules = payload['attackData']['rules'].split(";")[:-1]
dict_rules = {}
for j in list_rules:
item_index = list_rules.index(j)
dict_rules[list_rules[item_index]] = {
"action": list_rule_actions[item_index],
"data": list_rule_data[item_index],
"message": list_rule_messages[item_index],
"selector": list_rule_selectors[item_index],
"tag": list_rule_tags[item_index],
"version": list_rule_versions[item_index],
"id": list_rule_versions[item_index]
}
return dict_rules
if not respjson and not automation:
print bcolors.WHITE+'<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
home = expanduser("~")
#print creds
#print os.getenv("USER")
#print os.getenv("SUDO_USER")
#print os.getenv("HOME")
filename = home+'/.edgerc'
#print filename
try:
outputfile = open(filename, 'r')
except IOError:
print '[IAM] Unable to open "EdgeRC" file. Does this file exists in your user directory? Location: '+home+bcolors.ENDC
print bcolors.WHITE+'\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
edgerc = EdgeRc(filename)
section = creds
try:
baseurl = 'https://%s' % edgerc.get(section, 'host')
except:
print bcolors.WARNING+'[IAM] SWaPI was unable to find any valid section in your EdgeRC file called: '+section+bcolors.ENDC
print bcolors.WARNING+'[IAM] Please check your EdgeRC file and fix.'+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
s = requests.Session()
s.auth = EdgeGridAuth.from_edgerc(edgerc, section)
if configId:
query = {'offset':offset,'limit':limit,'from':start,'to':end}
url = "/siem/v1/configs/"+configId
result = s.get(urljoin(baseurl, url),params=query)
if result.status_code == 200 or result.status_code == 201:
if not respjson and not automation:
#print result.content
#sys.exit()
print bcolors.TURQUO+"[SIEM]"+bcolors.ENDC+bcolors.WARNING+" SIEM Logs "+bcolors.ENDC
#print result.content
logs = result.text.split("\n")[:-2]
#print logs
offset_line = result.text.split("\n")[-2]
if logs:
for i in logs:
ParentTable = tt.Texttable()
ParentTable.set_cols_width([20,135])
ParentTable.set_cols_align(['c','l'])
ParentTable.set_cols_valign(['m','m'])
#HostnameTable.set_deco(tt.Texttable.HEADER)
Parentheader = ['Field','Value']
ParentTable.header(Parentheader)
event = json.loads(i)
Parentrow = [ 'Policy ID',event['attackData']['policyId'] ]
ParentTable.add_row(Parentrow)
Parentrow = [ 'Method',event['httpMessage']['method'] ]
ParentTable.add_row(Parentrow)
Parentrow = [ 'Host',event['httpMessage']['host'] ]
ParentTable.add_row(Parentrow)
Parentrow = [ 'Path',event['httpMessage']['path'] ]
ParentTable.add_row(Parentrow)
try:
event['httpMessage']['query']
Parentrow = [ 'Query',event['httpMessage']['query'] ]
ParentTable.add_row(Parentrow)
except:
pass
Parentrow = [ 'Request ID',event['httpMessage']['requestId'] ]
ParentTable.add_row(Parentrow)
Parentrow = [ 'Client IP',event['attackData']['clientIP'] ]
ParentTable.add_row(Parentrow)
Parentrow = [ 'GEO',event['geo'] ]
ParentTable.add_row(Parentrow)
event['attackData']['ruleActions'] = decode_attack_data_payload(event['attackData']['ruleActions'])
Parentrow = [ 'Rule Actions',event['attackData']['ruleActions'] ]
ParentTable.add_row(Parentrow)
event['attackData']['ruleData'] = decode_attack_data_payload(event['attackData']['ruleData'])
Parentrow = [ 'Rule Data',event['attackData']['ruleData'] ]
ParentTable.add_row(Parentrow)
event['attackData']['ruleMessages'] = decode_attack_data_payload(event['attackData']['ruleMessages'])
Parentrow = [ 'Rule Messages',event['attackData']['ruleMessages'] ]
ParentTable.add_row(Parentrow)
event['attackData']['ruleSelectors'] = decode_attack_data_payload(event['attackData']['ruleSelectors'])
Parentrow = [ 'Rule Selector',event['attackData']['ruleSelectors'] ]
ParentTable.add_row(Parentrow)
event['attackData']['ruleTags'] = decode_attack_data_payload(event['attackData']['ruleTags'])
Parentrow = [ 'Rule Tags',event['attackData']['ruleTags'] ]
ParentTable.add_row(Parentrow)
event['attackData']['ruleVersions'] = decode_attack_data_payload(event['attackData']['ruleVersions'])
Parentrow = [ 'Rule Versions',event['attackData']['ruleVersions'] ]
ParentTable.add_row(Parentrow)
event['attackData']['rules'] = decode_attack_data_payload(event['attackData']['rules'])
Parentrow = [ 'Rules',event['attackData']['rules'] ]
ParentTable.add_row(Parentrow)
event['httpMessage']['requestHeaders'] = decode_headers(event['httpMessage']['requestHeaders'])
Parentrow = [ 'Requests Headers',event['httpMessage']['requestHeaders'] ]
ParentTable.add_row(Parentrow)
event['httpMessage']['responseHeaders'] = decode_headers(event['httpMessage']['responseHeaders'])
Parentrow = [ 'Response Headers',event['httpMessage']['responseHeaders'] ]
ParentTable.add_row(Parentrow)
event['timestamp'] = int(event['httpMessage']['start'])
event['httpMessage']['start'] = epoch_to_datetime(int(event['httpMessage']['start']))
Parentrow = [ 'Time',event['httpMessage']['start'] ]
ParentTable.add_row(Parentrow)
if not respjson and not automation:
#print event
MainParentTable = ParentTable.draw()
print MainParentTable
print bcolors.TURQUO+bcolors.BOLD+"\n\t\t\t\t\t\t\t ------------------------Log Separator------------------------\n"+bcolors.ENDC
else:
print json.dumps(event)
else:
if respjson or automation:
print result.content
sys.exit()
print bcolors.TURQUO+"[SIEM] "+bcolors.ENDC+bcolors.WARNING+result.content+bcolors.ENDC
if respjson or automation:
sys.exit()
print bcolors.WHITE+'\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
else:
print bcolors.WHITE+"This module allows you fetch logs from your Akamai SIEM Collector\n"+bcolors.ENDC
print bcolors.WARNING+"Security Information and Event Management\n"+bcolors.ENDC
print "--creds - Use this option to specify your SIEM credentials section of your EdgeRC file"
print "--configId - Unique identifier for each security configuration (semicolon separated)"
print "--offset - Fetch only security events that have occurred from offset"
print "--limit - Maximum number of security events each fetch returns"
print "--start - The start of a specified time range, expressed in Unix epoch seconds"
print "--end - The end of a specified time range, expressed in Unix epoch seconds"
print bcolors.TURQUO+"\nMain Blog: https://ac.akamai.com/people/[email protected]/blog/2018/08/20/swapi-siem"+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
def IAMModule(sqa,automation,host,AccountSwitch,propertyName,creds,groupId,apiObject,respjson,propertyId,userId,sendEmail,passwd):
if not respjson and not automation:
print bcolors.WHITE+'<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
home = expanduser("~")
#print creds
#print os.getenv("USER")
#print os.getenv("SUDO_USER")
#print os.getenv("HOME")
filename = home+'/.edgerc'
#print filename
try:
outputfile = open(filename, 'r')
except IOError:
print '[IAM] Unable to open "EdgeRC" file. Does this file exists in your user directory? Location: '+home+bcolors.ENDC
print bcolors.WHITE+'\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
edgerc = EdgeRc(filename)
section = creds
try:
baseurl = 'https://%s' % edgerc.get(section, 'host')
except:
print bcolors.WARNING+'[IAM] SWaPI was unable to find any valid section in your EdgeRC file called: '+section+bcolors.ENDC
print bcolors.WARNING+'[IAM] Please check your EdgeRC file and fix.'+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
if AccountSwitch:
filename = '.map'
readfile = open(filename, 'r')
contents = readfile.readlines()
for item in contents:
if "[" and "]" in item:
accountCheck = item[1:-2]
if accountCheck == AccountSwitch:
AccountSwitch = contents[contents.index(item)+1].strip()
if not respjson:
print bcolors.TURQUO+"[APPSEC]"+bcolors.ENDC+bcolors.WARNING+" Friendly Name found and mapped to Account: "+contents[contents.index(item)+1].strip()+bcolors.ENDC
#print AccountSwitch
params = {'accountSwitchKey':AccountSwitch}
s = requests.Session()
s.auth = EdgeGridAuth.from_edgerc(edgerc, section)
if apiObject == 'groups':
params.update({'actions':True})
if groupId:
url = "/identity-management/v2/user-admin/groups/"+groupId
else:
url = "/identity-management/v2/user-admin/groups/"
result = s.get(urljoin(baseurl, url),params=params)
if result.status_code == 200:
if respjson:
json_data = result.json()
formatted_json = json.dumps(json_data, indent=4, sort_keys=True)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
#print colorful_json
print result.content
sys.exit()
#print result.json()
if groupId:
print bcolors.WARNING+'[IAM] Parent Group '+bcolors.ENDC
ParentTable = tt.Texttable()
ParentTable.set_cols_width([35,10,25,30,25,30])
ParentTable.set_cols_align(['c','c','c','c','c','c'])
ParentTable.set_cols_valign(['m','m','m','m','m','m'])
#HostnameTable.set_deco(tt.Texttable.HEADER)
Parentheader = ['Group Name','Group ID','Created By','Created Date','Modified By','Modified Date']
ParentTable.header(Parentheader)
Parentrow = [ result.json()['groupName'],result.json()['groupId'],result.json()['createdBy'],result.json()['createdDate'],result.json()['modifiedBy'],result.json()['modifiedDate'] ]
ParentTable.add_row(Parentrow)
MainParentTable = ParentTable.draw()
print MainParentTable
for subgroup in result.json()['subGroups']:
SubGroupTable = tt.Texttable()
SubGroupTable.set_cols_width([35,10,25,30,25,30])
SubGroupTable.set_cols_align(['c','c','c','c','c','c'])
SubGroupTable.set_cols_valign(['m','m','m','m','m','m'])
#HostnameTable.set_deco(tt.Texttable.HEADER)
SubGroupheader = ['Group Name','Group ID','Created By','Created Date','Modified By','Modified Date']
SubGroupTable.header(SubGroupheader)
SubGrouprow = [ subgroup['groupName'],subgroup['groupId'],subgroup['createdBy'],subgroup['createdDate'],subgroup['modifiedBy'],subgroup['modifiedDate'] ]
SubGroupTable.add_row(SubGrouprow)
if len(result.json()['subGroups']) > 0:
print bcolors.WARNING+'[IAM] Sub Groups '+bcolors.ENDC
MainSubGroupTable = SubGroupTable.draw()
print MainSubGroupTable
if len(result.json()['subGroups']) > 1:
print bcolors.TURQUO+'\n\n----------- Group Separator -----------\n\n'+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
for item in result.json():
print bcolors.WARNING+'[IAM] Parent Group '+bcolors.ENDC
ParentTable = tt.Texttable()
ParentTable.set_cols_width([35,10,25,30,25,30])
ParentTable.set_cols_align(['c','c','c','c','c','c'])
ParentTable.set_cols_valign(['m','m','m','m','m','m'])
#HostnameTable.set_deco(tt.Texttable.HEADER)
Parentheader = ['Group Name','Group ID','Created By','Created Date','Modified By','Modified Date']
ParentTable.header(Parentheader)
Parentrow = [ item['groupName'],item['groupId'],item['createdBy'],item['createdDate'],item['modifiedBy'],item['modifiedDate'] ]
ParentTable.add_row(Parentrow)
MainParentTable = ParentTable.draw()
print MainParentTable
if item['subGroups']:
SubGroupTable = tt.Texttable()
SubGroupTable.set_cols_width([35,10,25,30,25,30])
SubGroupTable.set_cols_align(['c','c','c','c','c','c'])
SubGroupTable.set_cols_valign(['m','m','m','m','m','m'])
#HostnameTable.set_deco(tt.Texttable.HEADER)
SubGroupheader = ['Group Name','Group ID','Created By','Created Date','Modified By','Modified Date']
SubGroupTable.header(SubGroupheader)
for subgroup in item['subGroups']:
SubGrouprow = [ subgroup['groupName'],subgroup['groupId'],subgroup['createdBy'],subgroup['createdDate'],subgroup['modifiedBy'],subgroup['modifiedDate'] ]
SubGroupTable.add_row(SubGrouprow)
print bcolors.WARNING+'[IAM] Sub Groups '+bcolors.ENDC
MainSubGroupTable = SubGroupTable.draw()
print MainSubGroupTable
else:
pass
if len(result.json()) > 1:
print bcolors.TURQUO+'\n\n----------- Group Separator -----------\n\n'+bcolors.ENDC
else:
print bcolors.TURQUO+"[IAM]"+bcolors.ENDC+bcolors.WARNING+" StatusCode: "+str(result.status_code)+bcolors.ENDC
print bcolors.TURQUO+"[IAM]"+bcolors.ENDC+bcolors.WARNING+" There was a problem processing your request: "+bcolors.ENDC
json_data = result.json()
formatted_json = json.dumps(json_data, indent=4, sort_keys=True)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
print colorful_json
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
elif apiObject == 'roles':
url = "/identity-management/v2/user-admin/roles"
params.update({'actions':True,'users':True})
if groupId:
params.update({'groupId':groupId})
result = s.get(urljoin(baseurl, url),params=params)
if result.status_code == 201 or result.status_code == 200:
if respjson:
json_data = result.json()
formatted_json = json.dumps(json_data, indent=4, sort_keys=True)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
#print colorful_json
print result.content
sys.exit()
RolesTable = tt.Texttable()
RolesTable.set_cols_width([8,40,20,40,50])
RolesTable.set_cols_align(['c','c','c','c','c'])
RolesTable.set_cols_valign(['m','m','m','m','m'])
Rolesheader = ['Role ID','Role Name','Created By','3rd Party Access','Role Description']
RolesTable.header(Rolesheader)
for item in result.json():
userinfo = []
try:
item['users']
for users in item['users']:
userinfo.append(users['uiIdentityId']+": "+users['firstName']+" "+users['lastName'])
except:
pass
Rolesrow = [ item['roleId'],item['roleName'],item['createdBy'],userinfo,item['roleDescription'] ]
RolesTable.add_row(Rolesrow)
MainRolesTable = RolesTable.draw()
print MainRolesTable
else:
print bcolors.TURQUO+"[IAM]"+bcolors.WARNING+" StatusCode: "+str(result.status_code)+bcolors.ENDC
print bcolors.TURQUO+"[IAM]"+bcolors.WARNING+" There was a problem retrieving roles information. "+bcolors.ENDC
json_data = result.json()
formatted_json = json.dumps(json_data, indent=4, sort_keys=True)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
print colorful_json
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
elif apiObject == 'apiclient':
filename = '.apiclient'
readfile = open(filename, 'r')
contents = readfile.readlines()
if not userId:
print bcolors.TURQUO+"[IAM]"+bcolors.WARNING+" You need to provide your API Client ID: "+bcolors.ENDC+"--userId ml5u5oman7w4d"
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
else:
if sqa:
for item in contents:
if 'SQA:' in item:
index = contents.index(item)
entry = "SQA: "+userId+"\n"
else:
for item in contents:
if 'PROD:' in item:
index = contents.index(item)
entry = "PROD: "+userId+"\n"
try:
index
del contents[index]
except:
pass
contents.append(entry)
try:
with open(filename, 'w') as f:
for item in contents:
f.write(item)
#outputfile = open(filename, 'w')
#outputfile.writelines(contents)
print bcolors.TURQUO+"[IAM]"+bcolors.ENDC+bcolors.WARNING+" Successfully added your API Client ID to .apiclient file."+bcolors.ENDC
except:
print bcolors.TURQUO+"[IAM]"+bcolors.ENDC+bcolors.WARNING+" There was a problem adding your API Client ID to the .apiclient file"+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
elif apiObject == 'search':
filename = '.apiclient'
readfile = open(filename, 'r')
contents = readfile.readlines()
for item in contents:
if sqa:
if 'SQA:' in item:
userId = item.split(':')[1].strip()
else:
if 'PROD:' in item:
userId = item.split(':')[1].strip()
if not host:
print bcolors.TURQUO+"[IAM]"+bcolors.WARNING+" You need to provide a target to search: -t 'IBM Bluemix'"+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
else:
try:
url = "/identity-management/v1/open-identities/"+userId+"/account-switch-keys"
except:
print bcolors.TURQUO+"[IAM]"+bcolors.WARNING+" You need to provide a userId to search account: swapi.py iam apiclient --userId hkbaskhb12723"+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
params.update({'search':host})
result = s.get(urljoin(baseurl, url),params=params)
if result.status_code == 404 or result.status_code == 403:
if result.json()['title'].strip() == 'invalid open identity':
print bcolors.TURQUO+'[IAM] '+bcolors.WARNING+'You need to enter your API Client ID: '+bcolors.ENDC+' python swapi.py iam apiclient --userId <ID>'
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
if result.status_code == 201 or result.status_code == 200:
if respjson:
json_data = result.json()
formatted_json = json.dumps(json_data, indent=4, sort_keys=True)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
#print colorful_json
print result.content
sys.exit()
print bcolors.TURQUO+"[IAM]"+bcolors.WARNING+" Account Search Result"+bcolors.ENDC
AccountsTable = tt.Texttable()
AccountsTable.set_cols_width([60,30])
AccountsTable.set_cols_align(['c','c'])
AccountsTable.set_cols_valign(['m','m'])
#HostnameTable.set_deco(tt.Texttable.HEADER)
Accountsheader = ['Account Name','Account Switch Key']
AccountsTable.header(Accountsheader)
for accountdata in result.json():
Accountsrow = [ accountdata['accountName'],accountdata['accountSwitchKey'] ]
AccountsTable.add_row(Accountsrow)
AllAccountsTable = AccountsTable.draw()
print AllAccountsTable
else:
print bcolors.TURQUO+"[IAM]"+bcolors.ENDC+bcolors.WARNING+" StatusCode: "+str(result.status_code)+bcolors.ENDC
print bcolors.TURQUO+"[IAM]"+bcolors.ENDC+bcolors.WARNING+" There was a problem retrieving account information. "+bcolors.ENDC
json_data = result.json()
formatted_json = json.dumps(json_data, indent=4, sort_keys=True)
colorful_json = highlight(unicode(formatted_json, 'UTF-8'), lexers.JsonLexer(), formatters.Terminal256Formatter())
print colorful_json
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
elif apiObject == 'reset':
if not userId:
print bcolors.WARNING+'[IAM] You need to provide a uiIdentity ID: --userId 19807'+section+bcolors.ENDC
print bcolors.WHITE+'\n\n<!----------- SWaPI -----------!>\n\n'+bcolors.ENDC
sys.exit()
if not passwd:
url = "/identity-management/v2/user-admin/ui-identities/"+userId+"/reset-password"
else:
url = "/identity-management/v2/user-admin/ui-identities/"+userId+"/restricted/set-password"
body = {'newPassword':passwd}
headers = {'Content-Type':'application/json'}