-
Notifications
You must be signed in to change notification settings - Fork 7
/
__init__.py
1506 lines (1218 loc) · 55.4 KB
/
__init__.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
# -*- coding: utf-8 -*-
"""# Welcome to the **msiempy** module documentation. The pythonic way to deal with McFee esm API.
### Classes listed in this module are used by other classes in sub-modules to build specialized objects and functions.
# If you with to see concrete example of code, **head to one of the sub-modules** !
This API offers two main types of objects to interact with the SIEM : `msiempy.NitroList`, `msiempy.NitroDict`.
`msiempy.NitroList`s have default behaviours related to parallel execution, string representation generation and search feature.
Whereas `msiempy.NitroDict` that doesn't have any specific behaviours. Both inheriths from `msiempy.NitroObject`.
`msiempy.NitroSession` is the point of convergence of every request to the McFee ESM It provides standard dialogue with the esm.
It uses `msiempy.NitroConfig` to setup authentication, other configuration like verbosity, logfile, general timeout, are offered throught the config file.
Class diagram : https://mfesiem.github.io/docs/msiempy/classes.png. Packages : https://mfesiem.github.io/docs/msiempy/packages.png
"""
import logging
import requests
import json
import ast
import re
import urllib.parse
import urllib3
import configparser
import os
import getpass
import abc
import collections
import tqdm
import copy
import csv
import concurrent.futures
import prettytable
from prettytable import MSWORD_FRIENDLY
import datetime
import functools
import textwrap
from .__utils__ import regex_match, tob64, format_esm_time, convert_to_time_obj, timerange_gettimes, parse_timedelta, divide_times
try :
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except : pass
logging.getLogger("urllib3").setLevel(logging.WARNING)
log = logging.getLogger('msiempy')
class NitroError(Exception):
"""
Base internal exception. It's used when the user/passwd is incorrect, or other specific ESM related errors.
"""
pass
class NitroConfig(configparser.ConfigParser):
"""Class that handles the configuration. Reads the config file where ever it is and make accessible it's values throught object properties.
If a `.msiem/` directory exists in your current directory, the program will assume the `conf.ini` file is there, if not, it will create it with default values.
Secondly, if no `.msiem/` directory exists in the current directory, it will be automatically placed in a appropriate place depending of your platform:
- For Windows: %APPDATA%\\
- For Mac : $HOME/
- For Linux : $XDG_CONFIG_HOME/ or : $HOME/
"""
CONFIG_FILE_NAME='.msiem/conf.ini'
"""`.msiem/conf.ini`"""
CONF_DIR='.msiem/'
"""`.msiem/`"""
DEFAULT_CONF_DICT={
'esm':{'host':'',
'user':'',
'passwd':''},
'general':{'verbose':False,
'quiet':False,
'logfile':'',
'timeout':30,
'ssl_verify':False,
'output':'text'}
}
"""Default configuration file should look like this. Authentication is left empty.
```
[esm]
host =
user =
passwd =
[general]
verbose = False
quiet = False
logfile =
timeout = 30
ssl_verify = False
output = text #Not used yet
```
"""
def __str__(self):
"""Custom str() method that lists all config fields.
"""
return('Configuration file : '+ self._path+'\n'+str({section: dict(self[section]) for section in self.sections()}))
def __init__(self, path=None, config=None, *arg, **kwarg):
"""Parameters:
- `path`: Config file special path, if path is left None, will automatically look for it.
- `config`: Manual config dict. ex: `{'general':{'verbose':True}}`.
- `*args, **kwargs` : Passed to `configparser.ConfigParser.__init__()` method.
"""
super().__init__(*arg, **kwarg)
self.read_dict(self.DEFAULT_CONF_DICT)
if not path :
self._path = self._find_ini_location()
else :
self._path = path
try :
files=self.read(self._path)
if len(files) == 0:
raise FileNotFoundError
except :
log.info("Config file inexistant or currupted, applying defaults")
if not os.path.exists(os.path.dirname(self._path)):
os.makedirs(os.path.dirname(self._path))
self.write()
if config is not None :
log.info("Reading config_dict : "+str(self))
self.read_dict(config)
def write(self):
"""Write the config file to the predetermined path.
"""
log.info("Write config file at "+self._path)
with open(self._path, 'w') as conf:
super().write(conf)
def _iset(self, section, option, secure=False):
"""Internal method to interactively set a option in a section.
"""
msg='Enter [{}]{}'
value = self.get(section, option)
newvalue=''
if option=='passwd':
secure=True
if secure :
newvalue = tob64(getpass.getpass(msg.format(section, option)+'. Press <Enter> to skip: '))
else:
newvalue = input(msg.format(section, option)+ '. Press <Enter> to keep '+ (value if (str(value) is not '') else 'empty') + ': ')
if newvalue != '' :
super().set(section, option, newvalue)
def iset(self, section, option=None, secure=False):
"""Interactively set the specified section/option by asking the user the input.
Parameters:
- `section`: Configuration's section. Exemple : 'esm' or 'general'.
- `option`: Configuraion's option. Leave to `None` to set the whole section one after another. Exemple : 'user', 'timeout'.
- `secure`: Will use getpass to retreive the configuration value and won't print old value.
"""
if option is None :
for key in self.options(section):
self._iset(section, key, secure)
else :
self._iset(section, option, secure)
@property
def user(self): return self.get('esm', 'user')
@property
def host(self): return self.get('esm', 'host')
@property
def passwd(self): return self.get('esm', 'passwd')
@property
def verbose(self): return self.getboolean('general', 'verbose')
@property
def quiet(self): return self.getboolean('general', 'quiet')
@property
def logfile(self): return self.get('general', 'logfile')
@property
def timeout(self): return self.getint('general', 'timeout')
@property
def ssl_verify(self): return self.getboolean('general', 'ssl_verify')
@property
def output(self): return self.get('general', 'output')
@staticmethod
def _find_ini_location():
'''
Returns the location of a supposed conf.ini file the conf.ini file,
If the file doesn't exist, will still return the location.
Do not create a file nor directory.
'''
conf_path_dir=None
if os.path.isdir('./'+NitroConfig.CONF_DIR):
conf_path_dir='./'
elif 'APPDATA' in os.environ:
conf_path_dir = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ:
conf_path_dir = os.environ['XDG_CONFIG_HOME']
elif 'HOME' in os.environ:
conf_path_dir = os.path.join(os.environ['HOME'])
else:
conf_path_dir='./'
#Join configuartion filename with supposed parent directory
conf_path=(os.path.join(conf_path_dir, NitroConfig.CONFIG_FILE_NAME))
return(conf_path)
class NitroSession():
'''NitroSession object represent the point of convergence of every request to the McFee ESM
It provides standard dialogue with the esm with agument interpolation with `msiempy.params`.
Internal `__dict__` refers to a unique instance of dict and thus, properties can be instanciated only once.
'''
BASE_URL = 'https://{}/rs/esm/'
"""API v2 base url.
"""
BASE_URL_PRIV = 'https://{}/ess/'
"""Private API base URL.
"""
__initiated__ = False
"""
Weither the session has been intaciated. It's supposed to be a singleton.
"""
__unique_state__ = {}
"""
The singleton unique state.
"""
config = None
"""
NitroConfig object.
"""
executor = None
"""
Executor object.
"""
PARAMS = {
"login": ("login",
"""{"username": "%(username)s",
"password" : "%(password)s",
"locale": "en_US",
"os": "Win32"}
"""),
"get_devtree": ("GRP_GETVIRTUALGROUPIPSLISTDATA",
"""{"ITEMS": "#{DC1 + DC2}",
"DID": "1",
"HD": "F",
"NS": "0"}
"""),
"get_zones_devtree": ("GRP_GETVIRTUALGROUPIPSLISTDATA",
"""{"ITEMS": "#{DC1 + DC2}",
"DID": "3",
"HD": "F",
"NS": "0"}
"""),
"req_client_str": ("DS_GETDSCLIENTLIST",
"""{"DSID": "%(_ds_id)s",
"SEARCH": ""}
"""),
"get_rfile": ("MISC_READFILE",
"""{"FNAME": "%(_ftoken)s",
"SPOS": "0",
"NBYTES": "0"}
"""),
"get_wfile": ("MISC_WRITEFILE",
"""{"DATA1": "%(_ds_id)s",
"""),
"map_dtree": ("map_dtree",
"""{"dev_type": "%(dev_type)s",
"name": "%(ds_name)s",
"ds_id": "%(ds_id)s",
"enabled": "%(enabled)s",
"ds_ip": "%(ds_ip)s",
"hostname" : "%(hostname)s",
"typeID": "%(type_id)s",
"vendor": "",
"model": "",
"tz_id": "",
"date_order": "",
"port": "",
"syslog_tls": "",
"client_groups": "%(client_groups)s"
}
"""),
"add_ds": ("dsAddDataSource",
"""{"datasource": {
"parentId": {"id": "%(parent_id)s"},
"name": "%(name)s",
"id": {"id": "%(ds_id)s"},
"typeId": {"id": "%(type_id)s"},
"childEnabled": "%(child_enabled)s",
"childCount": "%(child_count)s",
"childType": "%(child_type)s",
"ipAddress": "%(ds_ip)s",
"zoneId": "%(zone_id)s",
"url": "%(url)s",
"enabled": "%(enabled)s",
"idmId": "%(idm_id)s",
"parameters": %(parameters)s
}}"""),
"add_client": ("DS_ADDDSCLIENT",
"""{"PID": "%(parent_id)s",
"NAME": "%(name)s",
"ENABLED": "%(enabled)s",
"IP": "%(ds_ip)s",
"HOST": "%(hostname)s",
"TYPE": "%(type_id)s",
"TZID": "%(tz_id)s",
"DORDER": "%(dorder)s",
"MASKFLAG": "%(maskflag)s",
"PORT": "%(port)s",
"USETLS": "%(syslog_tls)s"
}"""),
"get_recs": ("devGetDeviceList?filterByRights=false",
"""{"types": ["RECEIVER"]}
"""),
"get_dstypes": ("dsGetDataSourceTypes",
"""{"receiverId": {"id": "%(rec_id)s"}
}
"""),
"del_ds": ("dsDeleteDataSource",
"""{"receiverId": {"id": "%(parent_id)s"},
"datasourceId": {"id": "%(ds_id)s"}}
"""),
"del_client": ("DS_DELETEDSCLIENTS",None
),
"ds_last_times": ("QRY%5FGETDEVICELASTALERTTIME","""{}"""),
"zonetree": ("zoneGetZoneTree",None),
"ds_by_type": ("QRY_GETDEVICECOUNTBYTYPE",None),
"_dev_types": ("dev_type_map",
"""{"1": "zone",
"2": "ERC",
"3": "datasource",
"4": "Database Event Monitor (DBM)",
"5": "DBM Database",
"7": "Policy Auditor",
"10": "Application Data Monitor (ADM)",
"12": "ELM",
"14": "Local ESM",
"15": "Advanced Correlation Engine (ACE)",
"16": "Asset datasource",
"17": "Score-based Correlation",
"19": "McAfee ePolicy Orchestrator (ePO)",
"20": "EPO",
"21": "McAfee Network Security Manager (NSM)",
"22": "McAfee Network Security Platform (NSP)",
"23": "NSP Port",
"24": "McAfee Vulnerability Manager (MVM)",
"25": "Enterprise Log Search (ELS)",
"254": "client_group",
"256": "client"}
"""),
"ds_details": ("dsGetDataSourceDetail",
"""{"datasourceId":
{"id": "%(ds_id)s"}}
"""),
"get_alarms_custom_time": ("""alarmGetTriggeredAlarms?triggeredTimeRange=%(time_range)s&customStart=%(start_time)s&customEnd=%(end_time)s&status=%(status)s&pageSize=%(page_size)s&pageNumber=%(page_number)s""",
None),
"get_alarms": ("""alarmGetTriggeredAlarms?triggeredTimeRange=%(time_range)s&status=%(status)s&pageSize=%(page_size)s&pageNumber=%(page_number)s""", None),
"get_alarm_details": ("""notifyGetTriggeredNotification""", """{"id":%(id)s}"""),
"ack_alarms": ("""alarmAcknowledgeTriggeredAlarm""", """{"triggeredIds":%(ids)s}"""),
"unack_alarms": ("""alarmUnacknowledgeTriggeredAlarm""", """{"triggeredIds":%(ids)s}"""),
"delete_alarms": ("""alarmDeleteTriggeredAlarm""", """{"triggeredIds":%(ids)s}"""),
"get_possible_filters" : ( """qryGetFilterFields""", None ),
"get_possible_fields" : ( """qryGetSelectFields?type=%(type)s&groupType=%(groupType)s""", None ),
"get_esm_time" : ( """essmgtGetESSTime""",None),
"logout" : ( """userLogout""", None ),
"get_user_locale" : ( """getUserLocale""", None ),
"event_query_custom_time" : ("""qryExecuteDetail?type=EVENT&reverse=false""", """{
"config": {
"timeRange": "%(time_range)s",
"customStart": "%(start_time)s",
"customEnd": "%(end_time)s",
"fields":%(fields)s,
"filters":%(filters)s,
"limit":%(limit)s,
"offset":%(offset)s
}
}"""),
"event_query" : ("""qryExecuteDetail?type=EVENT&reverse=false""", """{
"config": {
"timeRange":"%(time_range)s",
"fields":%(fields)s,
"filters":%(filters)s,
"limit":%(limit)s,
"offset":%(offset)s
}
}"""),
"query_status" : ("""qryGetStatus""", """{"resultID": %(resultID)s}"""),
"query_result" : ("""qryGetResults?startPos=%(startPos)s&numRows=%(numRows)s&reverse=false""", """{"resultID": %(resultID)s}"""),
"time_zones" : ("""userGetTimeZones""", None),
"logout" : ("""logout""", None),
"add_note_to_event" : ("""ipsAddAlertNote""", """{
"id": {"value": "%(id)s"},
"note": {"note": "%(note)s"}
}"""),
"get_watchlists_no_filters" : ("""sysGetWatchlists?hidden=%(hidden)s&dynamic=%(dynamic)s&writeOnly=%(writeOnly)s&indexedOnly=%(indexedOnly)s""",
None),
"get_watchlist_details": ("""sysGetWatchlistDetails""","""{"id": %(id)s}"""),
"add_watchlist_values": ("""sysAddWatchlistValues""","""{
"watchlist": %(watchlist)s,
"values": %(values)s,
}"""),
"get_watchlist_values": ("""sysGetWatchlistValues?pos=%(pos)s&count=%(count)s""", """{"file": {"id": "%(id)s"}}"""),
"get_alert_data": ("""ipsGetAlertData""", """{"id": "%(id)s"}"""),
"get_sys_info" : ("sysGetSysInfo",None),
"build_stamp" : ("essmgtGetBuildStamp",None)
}
"""
This structure provide a central place to aggregate API methods and parameters.
The parameters are stored as docstrings to support string replacement.
Args:
method (str): Dict key associated with desired function
Use normal dict access, PARAMS["method"], or PARAMS.get("method")
Returns:
tuple: (string, string)
The first string is the method name that is actually used as
the URI or passed to the ESM. The second string is the params
required for that method. Some params require variables be
interpolated as documented in the Attributes.
Example:
method, params = params["login"].format(username, password)
Important note : Do not use sigle quotes (') to delimit data into the interpolated strings !
"""
def __str__(self):
return repr(self.__unique_state__)
def __init__(self, conf_path=None, conf_dict=None):
"""
The init method is called every time you call NitroSession() constructor.
But the properties are actually initiated only once.
Use logout() to reinstanciate NitroSession.
Parameters:
- `conf_path` : Configuration file path.
- `conf_dict` : Manual config dict. ex: `{'general':{'verbose':True}}`. See `msiempy.NitroConfig` class to have full details.
"""
global log
self.__dict__ = NitroSession.__unique_state__
#Init properties only once
if not self.__initiated__ :
NitroSession.__initiated__ = True
log.info('New NitroSession instance')
#Private attributes
self._headers={'Content-Type': 'application/json'}
self._logged=False
#Config parsing
self.config = NitroConfig(path=conf_path, config=conf_dict)
NitroSession.config=self.config
#Set the logging configuration
self._init_log(verbose=self.config.verbose,
quiet=self.config.quiet,
logfile=self.config.logfile)
def _request(self, method, http, data=None, callback=None, raw=False, secure=False):
"""
Helper method that format the request, handle the basic parsing of the SIEM result
as well as other errors.
If method is all upper cases, it's a private API call.
Private API is under /ess/ and public api is under /rs/esm
Returns None if HTTP error, Timeout or TooManyRedirects if raw=False
"""
url=str()
privateApiCall=False
result=None
#Handling private API calls formatting
if method == method.upper():
privateApiCall=True
url = self.BASE_URL_PRIV
data = self._format_params(method, **data)
log.debug('Private API call : '+str(method)+' Formatted params : '+str(data))
#Normal API calls
else:
url = self.BASE_URL
if data:
data = json.dumps(data)
#Logging the data request if not secure | Logs anyway the method
log.debug('Requesting HTTP '+http+' '+ method +
(' with data '+str(data) if (data is not None and not secure) else '') )
try :
result = requests.request(
http,
urllib.parse.urljoin(url.format(self.config.host), method),
data=data,
headers=self._headers,
verify=self.config.ssl_verify,
timeout=self.config.timeout
)
if raw :
log.debug('Returning raw requests Response object :'+str(result))
return result
else:
try:
result.raise_for_status()
except requests.HTTPError as e :
log.error(str(e)+' '+str(result.text))
return result.text
"""
#TODO handle expired session error, result unavailable / other siem errors
# _InvalidFilter (228)
# _IndexNotTurnedOn (49)
# Status Code 500: Error processing request, see server logs for more details
# <Response [400]>
400 Client Error: 400 for url: https://207.179.200.58:4443/rs/esm/ipsGetAlertData Cannot construct instance of `com.mcafee.siem.api.data.alert.EsmAlertId`
# Input Validation Error
# By creating a new class
"""
else: #
result = self._unpack_resp(result)
if privateApiCall :
result = self._format_priv_resp(result)
if callback:
result = callback(result)
log.debug('Result '+str(result)[:100]+'[...]')
return result
#Soft errors
except requests.exceptions.Timeout as e:
log.error(e)
return None
except requests.exceptions.TooManyRedirects as e :
log.error(e)
return None
def _login(self):
"""
Internal method that will be called when the user is not logged yet.
Throws NitroError if login fails
"""
userb64 = tob64(self.config.user)
passb64 = self.config.passwd
resp = self.request('login', username=userb64, password=passb64, raw=True, secure=True)
if resp is not None :
if resp.status_code in [400, 401]:
raise NitroError('Invalid username or password for the ESM')
elif 402 <= resp.status_code <= 600:
raise NitroError('ESM Login Error:', resp.text)
self._headers['Cookie'] = resp.headers.get('Set-Cookie')
self._headers['X-Xsrf-Token'] = resp.headers.get('Xsrf-Token')
return True
else:
raise NitroError('ESM Login Error: Response empty')
def request(self, request, http='post', callback=None, raw=False, secure=False, **params):
"""
This method is the centralized interface of all requests going to the SIEM.
Parameters:
- `request`: Keyword corresponding to the request name in `msiempy.params` mapping.
- `http`: HTTP method.
- `callback`: A callable to execute on the returned object if needed.
- `raw`: If true will return the Response object from requests module.
- `secure`: If true will not log the content of the request.
- `**params`: Interpolation parameters that will be match to `msiempy.params` templates. Check the file to be sure of the keyword arguments.
Returns None if HTTP error, Timeout or TooManyRedirects if raw=False.
"""
log.debug("Calling nitro request : {} params={} http={} raw={} secure={} callback={}".format(
str(request), str(params) if not secure else '***', str(http), str(raw), str(secure), str(callback)
))
method, data = self.PARAMS.get(request)
if data is not None :
data = data % params
data = ast.literal_eval((data.replace('\n','').replace('\t','')))
if method is not None:
try :
method = method % params
except TypeError as err :
if ('must be real number, not dict' in str(err)):
log.warning("Interpolation failed probably because of the private API calls formatting... Unexpected behaviours can happend.")
if not self._logged and method != 'login':
self._logged=self._login()
try :
return self._request(method, http, data, callback, raw, secure)
except ConnectionError as e:
log.critical(e)
raise
except Exception as e:
log.error(e)
raise
def logout(self):
"""
This method will logout the session, clear headers and throw away the object,
a new session will be instanciated next time.
"""
self.request('logout', http='delete')
self._logged=False
NitroSession.__initiated__ = False
@staticmethod
def _init_log(verbose=False, quiet=False, logfile=None):
"""
Private method. Inits the session's logger settings based on params
All objects should be able to log stuff, so the logger is globaly accessible
"""
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
std = logging.StreamHandler()
std.setLevel(logging.DEBUG)
std.setFormatter(formatter)
if verbose :
std.setLevel(logging.DEBUG)
elif quiet :
std.setLevel(logging.CRITICAL)
else :
std.setLevel(logging.INFO)
log.handlers=[]
log.addHandler(std)
if logfile :
fh = logging.FileHandler(logfile)
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
log.addHandler(fh)
if verbose and quiet :
log.warning("Verbose and quiet values are both set to True. This is a very inconsistent state. By default, verbose value has priority.")
return (log)
@staticmethod
def _format_params(cmd, **params):
"""
Format private API call.
From mfe_saw project at https://github.com/andywalden/mfe_saw
"""
params = {k: v for k, v in params.items() if v is not None}
params = '%14'.join([k + '%13' + v + '%13' for (k, v) in params.items()])
if params:
params = 'Request=API%13' + cmd + '%13%14' + params + '%14'
else:
params = 'Request=API%13' + cmd + '%13%14'
return params
@staticmethod
def _format_priv_resp(resp):
"""
Format response from private API
From mfe_saw project at https://github.com/andywalden/mfe_saw
"""
resp = re.search('Response=(.*)', resp).group(1)
resp = resp.replace('%14', ' ')
pairs = resp.split()
formatted = {}
for pair in pairs:
pair = pair.replace('%13', ' ')
pair = pair.split()
key = pair[0]
if key == 'ITEMS':
value = pair[-1]
else:
value = urllib.parse.unquote(pair[-1])
formatted[key] = value
return formatted
@staticmethod
def _unpack_resp(response) :
"""Unpack data from response.
Args:
response: requests.Response response object
Returns a list, a dict or a string
"""
try :
data = response.json()
if isinstance(response.json(), dict):
try:
data = data['value']
except KeyError:
try:
data = data['return']
except KeyError:
pass
except json.decoder.JSONDecodeError:
data = response.text
return data
class NitroObject(abc.ABC):
"""
Base class for all nitro objects. All objects have a reference to the single `msiempy.NitroSession` object that handle the esm requests.
"""
class NitroJSONEncoder(json.JSONEncoder):
"""
Custom JSON encoder that will use the approprtiate propertie depending of the type of NitroObject.
TODO return meta info about the NitroList. Maybe create a section `manager` and `data`.
TODO support json json dumping of QueryFilers, may be by making them inherits from NitroDict.
"""
def default(self, obj): # pylint: disable=E0202
if isinstance(obj,(NitroDict, NitroList)):
return obj.data
#elif isinstance(obj, (QueryFilter)):
#return obj.config_dict
else:
return json.JSONEncoder.default(self, obj)
@abc.abstractmethod
def __init__(self):
"""Creates the object session.
"""
self.nitro=NitroSession()
def __str__(self):
"""str(obj) -> return text string.
Can be a table if the object is a NitroList.
"""
return self.text
def __repr__(self):
"""repr(obj) -> return json string.
"""
return self.json
@abc.abstractproperty
def text(self):
"""Returns printable string.
"""
pass
@abc.abstractproperty
def json(self):
"""Returns json string representation.
"""
pass
@abc.abstractmethod
def refresh(self):
"""Refresh the state of the object.
"""
pass
class NitroDict(collections.UserDict, NitroObject):
"""
Base class that represent any SIEM data that can be represented as a item of a list.
Exemple : Event, Alarm, etc...
Inherits from dict.
"""
def __init__(self, adict=None, id=None):
"""
Initiate the NitroObject and UserDict objects, load the data if id is specified, use adict agument
and update dict values accordingly.
Parameters:
- `adict`: dict object to wrap.
- `id`: ESM obejct unique identifier. Alert.IPSIDAlertID for exemple.
"""
NitroObject.__init__(self)
collections.UserDict.__init__(self, adict)
if id != None :
self.data=self.data_from_id(id)
if isinstance(adict, dict):
self.data=adict
for key in self.data :
if isinstance(self.data[key], list):
self.data[key]=NitroList(alist=self.data[key])
@property
def json(self):
"""JSON representation of a item. Basic dict.
"""
return(json.dumps(dict(self), indent=4, cls=NitroObject.NitroJSONEncoder))
@property
def text(self):
"""A list of values. Not titles.
"""
return(', '.join([str(val) for val in self.values()]))
def refresh(self):
"""Not implemented here
"""
log.debug('NOT Refreshing item :'+str(self)+' '+str(NotImplementedError()))
@abc.abstractmethod
def data_from_id(self, id):
"""This method figured out the way to retreive the item infos from an id.
"""
pass
class NitroList(collections.UserList, NitroObject):
"""
Base class for NitroList objects. It offers callable execution management, search and other data list actions.
TODO better polymorphism to cast every sub-NitroList class's item dynamcally in `__init__` method
"""
def __init__(self, alist=None):
"""
Parameters:
- `alist`: list object to wrap.
"""
NitroObject.__init__(self)
if alist is None:
collections.UserList.__init__(self, [])
elif isinstance(alist , (list, NitroList)):
collections.UserList.__init__(
self, alist #[NitroDict(adict=item) for item in alist if isinstance(item, (dict, NitroDict))]
#Can't instanciate NitroDict, so Concrete classes have to cast the items afterwards!
#TODO better polymorphism to cast every sub-NitroList class's item dynamcally !
)
else :
raise ValueError('NitroList can only be initiated based on a list')
@property
def table_colums(self):
"""Return the list of columns the table representation will have. This attribute is designed to overwritten.
"""
return []
def _norm_dicts(self):
"""
Internal method.
All dict should have the same set of keys.
Creating keys in dicts.
"""
for item in self.data :
if isinstance(item, (dict, NitroDict)):
for key in self.keys :
if key not in item :
item[key]=None
@property
def keys(self):
"""Set of keys for all dict
"""
#If new fields are added it won't show on text repr. Only json.
manager_keys=set()
for item in self.data:
if isinstance(item, (dict,NitroDict)):
manager_keys.update(item.keys())
return manager_keys
def get_text(self, compact=False, fields=None, max_column_width=120):
"""
Return a acsii table string representation of the manager list
Parameters:
- `compact`: Returns a nice string table made with prettytable, else an '|' separated list.
- `fields`: list of fields you want in the table is None : default fields are returned by .keys attribute and sorted.
- `max_column_width`: when using prettytable (not compact)
It's an expesive thing to do on big ammount of data !
"""
if not fields :
fields=sorted(self.keys)
if len(self) == 0 :
return('The list is empty')
if not compact : #Table
table = prettytable.PrettyTable()
table.set_style(MSWORD_FRIENDLY)
table.field_names=fields
self._norm_dicts()
for item in self.data:
if isinstance(item, (dict, NitroDict)):
table.add_row(['\n'.join(textwrap.wrap(str(item[field]), width=max_column_width))
if not isinstance(item[field], NitroList)
else item[field].get_text() for field in fields])
else : log.warning("Unnapropriate list element type, doesn't show on the list : {}".format(str(item)))
if len(self.table_colums) >0 :
try :
text =table.get_string(fields=self.table_colums)
except Exception as err :
if "Invalid field name" in str(err):
text=table.get_string()