forked from IBM/count-mvs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountMVS.py
executable file
·1638 lines (1346 loc) · 66.4 KB
/
countMVS.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 python3
"""
Copyright 2022 IBM Corporation All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
import argparse
import csv
import logging
import warnings
import getpass
import os
import time
import sys
import socket
from socket import gaierror
import subprocess
from json import JSONDecodeError
import six
import requests
from requests.exceptions import RequestException
import psycopg2
from psycopg2.extras import RealDictCursor
from psycopg2 import DatabaseError
# Disable insecure HTTPS warnings as most customers do not have
# certificate validation correctly configured for consoles
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
# This is a hard-coded list of log source type IDs that are considered "not MVS"
# Future versions will be more comprehensive in what to exclude but for now this list is all we need to remove
LOG_SOURCE_EXCLUDE = [331, 352, 359, 361, 382, 405]
# This is a hard-coded map of sensor protocol type ids to the name
# of the protocol parameter that can be used as a unique identifier
SENSOR_PROTOCOL_MAP = {
2: 'serverIp',
7: 'url',
8: 'databaseServerHostname',
9: 'deviceAddress',
15: 'remoteHost',
16: 'SERVER_ADDRESS',
17: 'SERVER_ADDRESS',
18: 'SERVER_ADDRESS',
19: 'serverAddress',
20: 'databaseServerHostname',
21: 'SERVER_ADDRESS',
32: 'SERVER_ADDRESS',
34: 'ESXIP',
37: 'databaseServerHostname',
42: 'databaseServerHostname',
43: 'vcloudURL',
54: 'loginUrl',
55: 'databaseServerHostname',
56: 'loginUrl',
60: 'remoteHost',
63: 'remoteHost',
65: 'server',
67: 'databaseServerHostname',
68: 'hostname',
69: 'server',
74: 'tenantUrl',
75: 'apiHostname',
77: 'authorizationServerUrl',
79: 'serverurl',
83: 'endpointURL',
84: 'hostname',
87: 'loginEndPoint',
90: 'authorizationEndPoint',
}
WINDOWS_SERVER_LOG_SOURCE_TYPES = {
13: 'Microsoft IIS', 97: 'Microsoft DHCP', 98: 'Microsoft IAS', 99: 'Microsoft Exchange',
101: 'Microsoft SQL Server', 191: 'Microsoft ISA'
}
MS_WINDOWS_SECURITY_EVENT_LOG_SOURCE_TYPE = 12
WINDOWS_SERVER_EVENT_IDS = [
4727, 4728, 4729, 4730, 4737, 4744, 4745, 4746, 4747, 4748, 4749, 4750, 4751, 4752, 4753, 4754, 4755, 4756, 4757,
4758, 4759, 4760, 4761, 4762, 4763, 4768, 4770, 4771, 4776, 4777
]
class RESTException(Exception):
def __init__(self, message, api_error=None):
self.message = message
self.api_error = api_error
super().__init__(message)
def __str__(self):
return str(self.message)
def get_api_error(self):
return self.api_error
class ValidatorException(Exception):
pass
class APIException(Exception):
pass
class TooManyResultsError(Exception):
pass
class LogSourceRetrievalException(Exception):
pass
class DomainRetrievalException(Exception):
pass
class WindowsWorkstationRetrievalException(Exception):
pass
class MyVerException(Exception):
pass
class QuitSelected(Exception):
pass
class CommandLineParser():
DEFAULT_LOG_FILE = '/var/log/countMVS.log'
DEFAULT_CSV_OUTPUT_FILE = 'mvsCount.csv'
def __init__(self):
self.csv_file = self.DEFAULT_CSV_OUTPUT_FILE
self.log_file = self.DEFAULT_LOG_FILE
self.debug = False
self.skip_windows_check = False
self.insecure = False
def parse_args(self, args):
self._parse_csv_file(args)
self._parse_log_file(args)
self._parse_debug(args)
self._parse_skip_windows_check(args)
self._parse_insecure(args)
def _parse_csv_file(self, args):
if args and 'o' in args and args['o']:
self.csv_file = args['o']
def _parse_log_file(self, args):
if args and 'l' in args and args['l']:
self.log_file = args['l']
def _parse_debug(self, args):
if args and 'debug' in args:
self.debug = args['debug']
def _parse_skip_windows_check(self, args):
if args and 'skip_workstation_check' in args:
self.skip_windows_check = args['skip_workstation_check']
def _parse_insecure(self, args):
if args and 'insecure' in args:
self.insecure = args['insecure']
def get_csv_file(self):
return self.csv_file
def get_log_file(self):
return self.log_file
def is_debug_enabled(self):
return self.debug
def is_insecure(self):
return self.insecure
def is_skip_windows_check(self):
return self.skip_windows_check
class LogSource():
# pylint: disable=too-many-arguments
def __init__(self,
device_id=None,
hostname=None,
domains=None,
devicename=None,
devicetypeid=None,
spconfig=None,
timestamp_last_seen=None):
self.sensor_device_id = device_id
self.hostname = hostname
self.device_name = devicename
if domains:
self.domains = domains
else:
self.domains = []
self.device_type_id = devicetypeid
self.sp_config = spconfig
self.timestamp_last_seen = timestamp_last_seen
def get_sensor_device_id(self):
return self.sensor_device_id
def set_sensor_device_id(self, sensor_device_id):
self.sensor_device_id = sensor_device_id
def get_hostname(self):
return self.hostname
def set_hostname(self, hostname):
self.hostname = hostname
def get_domains(self):
return self.domains
def add_domain(self, domain):
if not domain in self.domains:
self.domains.append(domain)
def set_domains(self, domains):
domains = list(dict.fromkeys(domains))
self.domains = domains
def get_first_domain(self):
if not self.domains:
return None
return self.domains[0]
def get_device_type_id(self):
return self.device_type_id
def set_device_type_id(self, device_type_id):
self.device_type_id = device_type_id
def get_sp_config(self):
return self.sp_config
def is_multi_domain(self):
if self.domains:
return len(self.domains) > 1
return False
@staticmethod
def load_from_db_row(row):
if row:
object_keys = [
'id', 'hostname', 'domains', 'devicename', 'devicetypeid', 'spconfig', 'timestamp_last_seen'
]
device_id = 0
for k in list(row.keys()):
if k == 'id':
device_id = row[k]
del row[k]
if not k in object_keys:
del row[k]
row['device_id'] = device_id
return LogSource(**row)
return LogSource()
class LogSourceToDomainMapping():
def __init__(self):
self.logsource_to_domain = {}
def add_mapping_from_json(self, response_json):
if response_json and 'logsourceid' in response_json and 'domainname_domainid' in response_json:
log_source_id = response_json['logsourceid']
domain_name = response_json['domainname_domainid']
if log_source_id in self.logsource_to_domain:
self.logsource_to_domain[log_source_id].append(str(domain_name))
else:
self.logsource_to_domain[log_source_id] = [str(domain_name)]
def get_logsource_to_domain(self):
return self.logsource_to_domain
def __str__(self):
mappings = []
for log_source_id, domains in self.logsource_to_domain.items():
mapping = '{} : {}'.format(log_source_id, str(domains))
mappings.append(mapping)
return '[{}]'.format('\n'.join(mappings))
class ArielSearch():
# pylint: disable=too-many-arguments
def __init__(self, search_id=None, status=None, progress=0, completed=False, record_count=0):
self.search_id = search_id
self.status = status
self.progress = progress
self.completed = completed
self.record_count = record_count
def get_search_id(self):
return self.search_id
def get_status(self):
return self.status
def set_status(self, status):
self.status = status
def get_progress(self):
return self.progress
def set_progress(self, progress):
self.progress = progress
def is_completed(self):
return self.completed
def set_completed(self, completed):
self.completed = completed
def get_record_count(self):
return self.record_count
@staticmethod
def from_json(response_json):
if response_json:
object_keys = ['search_id', 'status', 'progress', 'completed', 'record_count']
for k in list(response_json.keys()):
if not k in object_keys:
del response_json[k]
return ArielSearch(**response_json)
return None
class APIError():
def __init__(self, http_response=None, message=None):
self.http_response = http_response
self.detailed_error_message = message
def get_response_code(self):
if self.http_response and 'code' in self.http_response:
return self.http_response['code']
return None
def set_response_code(self, code):
if not self.http_response:
self.http_response = {}
self.http_response['code'] = code
def get_error_message(self):
if self.http_response and 'message' in self.http_response:
return self.http_response['message']
return None
def set_error_message(self, message):
if not self.http_response:
self.http_response = {}
self.http_response['message'] = message
def get_detailed_error_message(self):
return self.detailed_error_message
def set_detailed_error_message(self, message):
self.detailed_error_message = message
@staticmethod
def from_json(response_json):
if response_json:
object_keys = ['http_response', 'message']
for k in list(response_json.keys()):
if not k in object_keys:
del response_json[k]
return APIError(**response_json)
return APIError()
@staticmethod
def from_response_status_and_text(response_status, response_text):
return APIError({'code': response_status}, response_text)
class APIErrorGenerator():
LOCKED_OUT_ERROR = ('Your host has been locked out due to too many failed login attempts. '
'Please try again later.')
INCORRECT_PASSWORD = 'You have provided an incorrect password. '
INCORRECT_TOKEN = 'You have provided an incorrect token. '
INCORRECT_PERMISSIONS = 'The token provided has incorrect permissions. '
RE_RUN_MESSAGE = 'Please re-run the script and try again.'
LOCKED_OUT = 'locked out'
PASSWORD_AUTH_ERROR = INCORRECT_PASSWORD + RE_RUN_MESSAGE
TOKEN_AUTH_ERROR = INCORRECT_TOKEN + RE_RUN_MESSAGE
TOKEN_PERMISSIONS_ERROR = INCORRECT_PERMISSIONS + RE_RUN_MESSAGE
def __init__(self, client_auth, exception):
self.client_auth = client_auth
self.exception = exception
self.response_code = None
self.detailed_error_message = None
self._init()
def _init(self):
if self.exception:
if isinstance(self.exception, RESTException):
api_error = self.exception.get_api_error()
self.response_code = api_error.get_response_code()
self.detailed_error_message = api_error.get_detailed_error_message()
elif isinstance(self.exception, APIException):
self.detailed_error_message = str(self.exception)
def _generate_unauth_message(self):
unauth_error_message = self.detailed_error_message
if self.client_auth:
if self.LOCKED_OUT in self.detailed_error_message:
unauth_error_message = self.LOCKED_OUT_ERROR
elif self.client_auth.password_authentication():
unauth_error_message = self.PASSWORD_AUTH_ERROR
elif self.client_auth.token_authentication():
unauth_error_message = self.TOKEN_AUTH_ERROR
return unauth_error_message
def generate_error_message(self):
error_message = self.detailed_error_message
if self.response_code:
if self.response_code == 401:
error_message = self._generate_unauth_message()
elif self.response_code == 403 and self.client_auth and self.client_auth.token_authentication():
error_message = self.TOKEN_PERMISSIONS_ERROR
return error_message
class PermissionCheckResult():
def __init__(self, client_auth):
self.client_auth = client_auth
self.exception = None
self.response_json = None
def is_successful(self):
return self.exception is None
def set_exception(self, exception):
self.exception = exception
def get_response_json(self):
return self.response_json
def set_response_json(self, response_json):
self.response_json = response_json
def get_error_message(self):
api_error_generator = APIErrorGenerator(self.client_auth, self.exception)
return api_error_generator.generate_error_message()
class AQLClient():
API_URL = '/api'
ARIEL_API_URL = API_URL + '/ariel'
ARIEL_SEARCHES_ENDPOINT = ARIEL_API_URL + '/searches'
ARIEL_SEARCH_ENDPOINT = ARIEL_SEARCHES_ENDPOINT + '/{}'
ARIEL_SEARCH_RESULTS_ENDPOINT = ARIEL_SEARCH_ENDPOINT + '/results'
SYSTEM_ABOUT_TEST_ENDPOINT = API_URL + '/system/about'
def __init__(self, rest_client):
self.rest_client = rest_client
def perform_search(self, query):
params = {'query_expression': query}
response_json = self.rest_client.post(path=self.ARIEL_SEARCHES_ENDPOINT, success_code=201, params=params)
search = ArielSearch.from_json(response_json)
return search
def get_search(self, search_id):
response_json = self.rest_client.get(path=self.ARIEL_SEARCH_ENDPOINT.format(search_id))
search = ArielSearch.from_json(response_json)
return search
def get_search_result(self, search_id, headers=None):
response_json = self.rest_client.get(path=self.ARIEL_SEARCH_RESULTS_ENDPOINT.format(search_id),
headers=headers)
if response_json and 'events' in response_json:
return response_json['events']
return []
def check_api_permissions(self):
# We are using the system about REST API endpoint here because the
# ariel search endpoint returns an empty list when using an authorized service token
# that does not have the ADMIN capability
client_auth = self.rest_client.get_client_auth()
permission_check_result = PermissionCheckResult(client_auth)
try:
response_json = self.rest_client.get(path=self.SYSTEM_ABOUT_TEST_ENDPOINT)
permission_check_result.set_response_json(response_json)
except (APIException, RESTException) as err:
permission_check_result.set_exception(err)
return permission_check_result
class RESTClient():
SEC_HEADER = 'SEC'
def __init__(self, hostname, insecure=False):
self.hostname = hostname
self.client_auth = None
self.verify = not insecure
def set_client_auth(self, client_auth):
self.client_auth = client_auth
def get_client_auth(self):
return self.client_auth
def get(self, path, success_code=200, headers=None):
try:
rest_headers = self._build_headers(headers)
response = requests.get(self._build_url(path),
headers=rest_headers,
auth=self._build_auth(),
verify=self.verify)
except (RequestException, ValueError) as err:
raise APIException(err) from err
if response.status_code == 404:
return None
if response.status_code == success_code:
return response.json()
try:
api_error = APIError.from_json(response.json())
except JSONDecodeError:
api_error = APIError.from_response_status_and_text(response.status_code, response.text)
raise RESTException(api_error.get_error_message(), api_error)
def post(self, path, success_code=200, params=None, headers=None):
try:
rest_headers = self._build_headers(headers)
response = requests.post(self._build_url(path),
headers=rest_headers,
params=params,
auth=self._build_auth(),
verify=self.verify)
except (RequestException, ValueError) as err:
raise APIException(err) from err
if response.status_code == 404:
return None
if response.status_code == success_code:
return response.json()
try:
api_error = APIError.from_json(response.json())
except JSONDecodeError:
api_error = APIError.from_response_status_and_text(response.status_code, response.text)
raise RESTException(api_error.get_error_message(), api_error)
def _build_headers(self, headers):
if headers is None:
headers = {}
if self.client_auth and self.client_auth.get_auth_services_token():
headers[self.SEC_HEADER] = self.client_auth.get_auth_services_token()
return headers
def _build_auth(self):
if self.client_auth and self.client_auth.get_username() and self.client_auth.get_password():
return (self.client_auth.get_username(), self.client_auth.get_password())
return None
def _build_url(self, path):
return "https://{}{}".format(self.hostname, path)
class DatabaseClient():
TOO_MANY_ROWS_ERROR_MESSAGE = 'Too many rows returned'
def __init__(self, dbname=None, username=None):
self.dbname = dbname
self.username = username
self.conn = None
def connect(self):
self.conn = psycopg2.connect(database=self.dbname, user=self.username, cursor_factory=RealDictCursor)
def fetch_one(self, sql):
with self.conn.cursor() as cursor:
cursor.execute(sql)
if cursor.rowcount > 1:
raise TooManyResultsError(self.TOO_MANY_ROWS_ERROR_MESSAGE)
return cursor.fetchone()
def fetch_all(self, sql):
with self.conn.cursor() as cursor:
cursor.execute(sql)
return cursor.fetchall()
def close(self):
if self.conn:
self.conn.close()
class MachineIdentifierParser():
@staticmethod
def parse_machine_identifier(machine_id):
# If value is a url we need to retrieve the hostname/IP to use as identifier
if '//' in machine_id:
# remove substring before double slash
machine_id = machine_id.split('//', 1)[1]
# remove substring after next slash, if exists
machine_id = machine_id.split('/', 1)[0]
# remove substring after next colon, if exists
machine_id = machine_id.split(':', 1)[0]
return machine_id
class DatabaseService():
LOG_SOURCE_RETRIEVAL_QUERY = ('SELECT id, hostname, devicename, devicetypeid, spconfig, timestamp_last_seen '
'FROM sensordevice '
'WHERE timestamp_last_seen > {} and spconfig is not null')
SENSOR_PROTOCOL_ID_QUERY = ('SELECT spid FROM sensorprotocolconfig WHERE id = {}')
CONFIG_PARAM_VALUE_QUERY = ('SELECT value '
'FROM sensorprotocolconfigparameters '
'WHERE sensorprotocolconfigid = {} and name = \'{}\'')
DOMAIN_COUNT_QUERY = ('SELECT COUNT(id) FROM domains WHERE deleted=false')
WINDOWS_SERVER_QIDS_QUERY = ('SELECT qid '
'FROM qidmap '
'WHERE id IN (SELECT qidmapid '
'FROM dsmevent '
'WHERE devicetypeid = {} '
'AND deviceeventid in ({}))')
EXECUTING_QUERY_TEMPLATE = 'Executing query %s'
def __init__(self, db_client):
self.db_client = db_client
def _execute_log_source_query(self, time_period):
log_source_retrieval_query = self.LOG_SOURCE_RETRIEVAL_QUERY.format(time_period)
logging.debug(self.EXECUTING_QUERY_TEMPLATE, log_source_retrieval_query)
return self.db_client.fetch_all(log_source_retrieval_query)
@staticmethod
def _add_log_source_to_map(row, log_source_map):
log_source = LogSource.load_from_db_row(row)
log_source_id = log_source.get_sensor_device_id()
logging.info('Adding log source %d to log source map', int(log_source_id))
log_source_map[log_source_id] = log_source
def build_log_source_map(self, time_period):
logging.info('Attempting to build log source map from entries in the database')
error_message_template = 'Unable to retrieve log sources ' \
'from the database, Reason [{}]'
try:
log_source_map = {}
rows = self._execute_log_source_query(time_period)
logging.info('Query executed successfully, %d rows returned', len(rows))
for row in rows:
self._add_log_source_to_map(row, log_source_map)
return log_source_map
except (DatabaseError, TooManyResultsError) as err:
raise LogSourceRetrievalException(error_message_template.format(err)) from err
def _get_sensor_protocol_id(self, log_source):
sp_id = None
sp_id_query = self.SENSOR_PROTOCOL_ID_QUERY.format(log_source.get_sp_config())
logging.debug(self.EXECUTING_QUERY_TEMPLATE, sp_id_query)
sp_id_query_result = self.db_client.fetch_one(sp_id_query)
if sp_id_query_result and 'spid' in sp_id_query_result:
sp_id = sp_id_query_result['spid']
logging.debug('Query executed successfully. Retrieved spid=%s', sp_id)
else:
logging.debug('No results found for spid for id %s', log_source.get_sp_config())
return sp_id
def _get_sensor_config_param_value(self, param_name, log_source):
value = None
# This log source uses a protocol parameter as its identifier, retrieve name of
# parameter from SENSOR_PROTOCOL_MAP then retrieve value from postgres
config_param_query = self.CONFIG_PARAM_VALUE_QUERY.format(log_source.get_sp_config(), param_name)
logging.debug(self.EXECUTING_QUERY_TEMPLATE, config_param_query)
config_param_query_result = self.db_client.fetch_one(config_param_query)
if config_param_query_result and 'value' in config_param_query_result:
value = config_param_query_result['value']
logging.debug("Query executed successfully. Retrieved value = %s", value)
else:
logging.debug('No results found for parameter name %s', param_name)
return value
def _parse_machine_identifier(self, sp_id, log_source, machine_id):
if sp_id in SENSOR_PROTOCOL_MAP:
param_name = SENSOR_PROTOCOL_MAP[sp_id]
if param_name:
param_value = self._get_sensor_config_param_value(param_name, log_source)
if param_value:
machine_id = MachineIdentifierParser.parse_machine_identifier(param_value)
return machine_id
# Determine a unique identifier for this log source
def get_machine_identifier(self, log_source):
error_message = 'Unable to retrieve machine identifier'
# If machine is not a special case then the
# default identifier is the hostname
machine_id = log_source.get_hostname()
try:
sp_id = self._get_sensor_protocol_id(log_source)
if sp_id and sp_id in SENSOR_PROTOCOL_MAP:
machine_id = self._parse_machine_identifier(sp_id, log_source, machine_id)
except (DatabaseError, TooManyResultsError) as err:
logging.error('%s using hostname instead, '\
'Reason [%s]', error_message, err)
return machine_id
def get_domain_count(self):
error_message_template = 'Unable to retrieve domain count from the database, {}'
try:
domain_count_query_result = self.db_client.fetch_one(self.DOMAIN_COUNT_QUERY)
if domain_count_query_result:
return int(domain_count_query_result['count'])
domain_query_failure = 'No result returned when executing query {}'.format(self.DOMAIN_COUNT_QUERY)
raise DomainRetrievalException(error_message_template.format(domain_query_failure))
except (DatabaseError, TooManyResultsError) as err:
raise DomainRetrievalException(error_message_template.format(err)) from err
def get_windows_server_qids(self):
qids = []
event_ids = ','.join("'{}'".format(event_id) for event_id in WINDOWS_SERVER_EVENT_IDS)
windows_server_qids_query = self.WINDOWS_SERVER_QIDS_QUERY.format(MS_WINDOWS_SECURITY_EVENT_LOG_SOURCE_TYPE,
event_ids)
logging.debug(self.EXECUTING_QUERY_TEMPLATE, windows_server_qids_query)
rows = self.db_client.fetch_all(windows_server_qids_query)
for row in rows:
qids.append(row['qid'])
return qids
class Auth():
def __init__(self):
self.username = 'admin'
self.password = None
self.auth_services_token = None
self.password_auth = False
self.token_auth = False
def get_username(self):
return self.username
def get_password(self):
return self.password
def set_password(self, password):
self.password = password
self.password_auth = True
def get_auth_services_token(self):
return self.auth_services_token
def set_auth_services_token(self, token):
self.auth_services_token = token
self.token_auth = True
def password_authentication(self):
return self.password_auth
def token_authentication(self):
return self.token_auth
class TextFormatter():
BOLD_ANSI_ESCAPE_CODE = '\033[1m'
NORMAL_ANSI_ESCAPE_CODE = '\033[0m'
@staticmethod
def bold(text_to_format):
return '{}{}{}'.format(TextFormatter.BOLD_ANSI_ESCAPE_CODE, text_to_format,
TextFormatter.NORMAL_ANSI_ESCAPE_CODE)
class TimePeriodReader():
@staticmethod
def _print_description_header(default_period_in_days):
formatter = TextFormatter()
print('\nThis script calculates an estimated count of the MVS (Managed Virtual Servers) for the deployment.')
print(
'It uses log source data in order to calculate the count over a given time period. By default the script')
print(('will use {} days worth of log source data however you can select to increase this below.\n'.format(
default_period_in_days)))
print(
(formatter.bold('Note') +
': By increasing the value from the default {} day(s) this will increase the execution time of the script'
.format(default_period_in_days)))
print('especially in multi-domain deployments as it will have to perform a search for log source data over a ')
print('longer period of time.\n')
print('How many days worth of log source data would you like to use for the calculation.\n')
@staticmethod
def prompt_for_time_period(default_period_in_days, max_period_in_days):
TimePeriodReader._print_description_header(default_period_in_days)
period_in_days = default_period_in_days
while True:
try:
response = six.moves.input('Please enter your choice in days (default {} [Enter], max {}): '.format(
default_period_in_days, max_period_in_days))
if not response:
break
period_in_days = int(response)
if 1 <= period_in_days <= max_period_in_days:
break
if period_in_days < 1:
print('Invalid selection. You can only select a minimum of 1 day')
if period_in_days > max_period_in_days:
print(
('Invalid selection. You can only select up to a maximum of {} days'.format(max_period_in_days)
))
except ValueError:
print('Invalid selection. You must enter a numeric value')
return period_in_days
class AuthReader():
@staticmethod
def prompt_for_auth_method():
client_auth = Auth()
print('\nThis script needs to call the Ariel API to calculate the MVS count from the deployment.\n\n'
'Which authentication would you like to use:\n1: Admin User\n2: Authorized Service\n'
'(q to quit)\n')
while True:
auth_choice = str(six.moves.input('Please enter your choice: '))
if auth_choice == '1':
client_auth.set_password(getpass.getpass('Please input the admin user password: '))
break
if auth_choice == '2':
client_auth.set_auth_services_token(
getpass.getpass('Please input the security token for your authorized service: '))
break
if auth_choice in ('q', 'Q'):
client_auth = None
break
print('\nInvalid selection. Please choose from the following options:'
'\n1. Admin User\n2. Authorized Service\n(q to quit)\n')
return client_auth
class ProgressUtils():
@staticmethod
def _resolve_invalid_progress_range(progress):
if progress is None or progress < 0:
progress = 0
elif progress > 100:
progress = 100
return progress
@staticmethod
def print_progress_bar(progress):
progress = ProgressUtils._resolve_invalid_progress_range(progress)
progress_bar_length = int(progress / 2)
search_status = '{}%'.format(progress)
sys.stdout.write('\rProcessing... |' + '#' * progress_bar_length + '-' * (50 - progress_bar_length) + '| ' +
search_status)
sys.stdout.flush()
if progress == 100:
complete_msg = '100% ...done\n\n'
sys.stdout.write('\rProcessing... |' + '#' * progress_bar_length + '-' * (50 - progress_bar_length) +
'| ' + complete_msg)
sys.stdout.flush()
class DomainAppender():
DEFAULT_DOMAIN = 'Default Domain'
DOMAIN_AQL_QUERY_TEMPLATE = ('SELECT logsourceid,DOMAINNAME(domainid) '
'FROM events GROUP BY logsourceid,domainid '
'ORDER BY logsourceid LAST {} DAYS')
MAX_SEARCH_RESULTS_PER_REQUEST = 49
def __init__(self, multi_domain, aql_client=None, period_in_days=1):
self.multi_domain = multi_domain
self.aql_client = aql_client
self.period_in_days = period_in_days
self.ariel_search = None
self.range_start = 0
self.range_end = self.MAX_SEARCH_RESULTS_PER_REQUEST
def _add_default_domain(self, log_source_map):
for log_source in list(log_source_map.values()):
log_source.add_domain(self.DEFAULT_DOMAIN)
def _perform_aql_query(self):
print('\nPerforming AQL query to retrieve log source domain information, '
'Please wait...')
domain_aql_query = self.DOMAIN_AQL_QUERY_TEMPLATE.format(self.period_in_days)
logging.debug('Attempting to execute AQL query %s', domain_aql_query)
return self.aql_client.perform_search(domain_aql_query)
def _poll_query_for_completion(self):
logging.info('Polling for completion of ariel search with id %s', self.ariel_search.get_search_id())
while not self.ariel_search.is_completed():
current_ariel_search = self.aql_client.get_search(self.ariel_search.get_search_id())
if current_ariel_search:
self.ariel_search = current_ariel_search
logging.info('Ariel search with id %s has status %s', self.ariel_search.get_search_id(),
self.ariel_search.get_status())
ProgressUtils.print_progress_bar(self.ariel_search.get_progress())
time.sleep(1)
logging.info('Ariel search with id %s completed', self.ariel_search.get_search_id())
def _build_mapping_from_results(self):
# Retrieve results for the AQL query
mapping = LogSourceToDomainMapping()
range_headers = self._build_range_header()
while range_headers:
search_results = self.aql_client.get_search_result(self.ariel_search.get_search_id(), range_headers)
if search_results is not None:
for search_result in search_results:
mapping.add_mapping_from_json(search_result)
self.range_start = self.range_end + 1
self.range_end = self.range_start + self.MAX_SEARCH_RESULTS_PER_REQUEST
range_headers = self._build_range_header()
else:
logging.debug('No search results returned from Ariel API search')
logging.debug('Mapping result %s', str(mapping))
return mapping.get_logsource_to_domain()
def _build_range_header(self):
if self.range_start > self.ariel_search.get_record_count():
return None
headers = {}
last_item = self.range_end
if self.range_end >= self.ariel_search.get_record_count():
last_item = self.ariel_search.get_record_count() - 1
headers['Range'] = 'items={}-{}'.format(str(self.range_start), str(last_item))
return headers
def _build_logsource_to_domain_map(self):
error_message_template = 'Unable to retrieve domain information. ERROR {}'
try:
# Call API to perform an AQL search for log sources with
# associated domain names for the specified time period (1 day by default)
self.ariel_search = self._perform_aql_query()
if not self.ariel_search:
error_message = 'POST to ariel API returned a 404'
raise DomainRetrievalException(error_message_template.format(error_message))
# Poll for completion of the AQL search using the API
self._poll_query_for_completion()
if self.ariel_search.get_status() in ['ERROR', 'CANCELED']:
status_failure = 'Ariel search did not complete ' \
'successfully, status is {}'.format(self.ariel_search.get_status())
raise DomainRetrievalException(error_message_template.format(status_failure))
return self._build_mapping_from_results()
except (APIException, RESTException) as err:
raise DomainRetrievalException(error_message_template.format(err)) from err
def add_domains(self, log_source_map):
if self.multi_domain:
logsource_to_domain_mapping = self._build_logsource_to_domain_map()
for logsource_id, domains in logsource_to_domain_mapping.items():
if logsource_id in log_source_map:
logging.info('Appending domain information for log source id %d', logsource_id)
log_source = log_source_map[logsource_id]
log_source.set_domains(domains)
else:
logging.info('Appending default domain to all log sources')
self._add_default_domain(log_source_map)
logging.info('Completed adding domain information to log sources')
class WindowsDeviceProcessor():
WINDOWS_SERVER_QUERY_TEMPLATE = ('SELECT qid '
'FROM events '
'WHERE logsourceid IN ({}) '
'AND qid IN ({}) LIMIT 1 LAST {} DAYS')
WINDOWS_WORKSTATION_CACHE_FILE = '.windows_workstations'
def __init__(self, aql_client, db_service, mvs_results, period_in_days=1):
self.aql_client = aql_client
self.db_service = db_service
self.mvs_results = mvs_results
self.period_in_days = period_in_days
self.cached_windows_workstations = []
self.windows_workstations = []
self.ariel_search = None
def _perform_aql_query(self, machine_identifier, log_source_ids):
print(('\nPerforming AQL query to check if {} is a windows server or workstation, '
'Please wait...'.format(machine_identifier)))
windows_server_qids = self.db_service.get_windows_server_qids()
ls_ids = ','.join("{}".format(ls_id) for ls_id in log_source_ids)
qids = ','.join("{}".format(qid) for qid in windows_server_qids)