-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Gmail.py
2749 lines (2266 loc) · 99.8 KB
/
Gmail.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
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import base64
import concurrent.futures
import itertools as it
import json
import mimetypes
import random
import re
import string
import sys
import copy
from datetime import datetime, timedelta
from email.utils import parsedate_to_datetime, format_datetime
from distutils.util import strtobool
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from html.entities import name2codepoint
from html.parser import HTMLParser
from typing import *
from urllib.parse import urlparse
import google_auth_httplib2
import httplib2
from apiclient import discovery
from google.oauth2 import service_account
from googleapiclient.errors import HttpError
''' GLOBAL VARS '''
ADMIN_EMAIL = '' # set from params later on
PRIVATE_KEY_CONTENT = None
GAPPS_ID = None
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
PROXY = demisto.params().get('proxy')
DISABLE_SSL = demisto.params().get('insecure', False)
FETCH_TIME = demisto.params().get('fetch_time', '1 days')
SEND_AS_SMTP_FIELDS = ['host', 'port', 'username', 'password', 'securitymode']
DATE_FORMAT = '%Y-%m-%d' # sample - 2020-08-23
BATCH_DIVIDER = 5
MAX_USERS = 2500
MAX_WITHOUT_POLLING = 500
''' HELPER FUNCTIONS '''
class TextExtractHtmlParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self._texts = [] # type: list
self._ignore = False
def handle_starttag(self, tag, attrs): # noqa: F841
if tag in ('p', 'br') and not self._ignore: # ignore
self._texts.append('\n')
elif tag in ('script', 'style'):
self._ignore = True
def handle_startendtag(self, tag, attrs): # noqa: F841
if tag in ('br', 'tr') and not self._ignore:
self._texts.append('\n')
def handle_endtag(self, tag):
if tag in ('p', 'tr'):
self._texts.append('\n')
elif tag in ('script', 'style'):
self._ignore = False
def handle_data(self, data):
if data and not self._ignore:
stripped = data.strip()
if stripped:
self._texts.append(re.sub(r'\s+', ' ', stripped)) # pylint: disable=E1101
def handle_entityref(self, name):
if not self._ignore and name in name2codepoint:
self._texts.append(chr(name2codepoint[name]))
def handle_charref(self, name):
if not self._ignore:
if name.startswith('x'):
c = chr(int(name[1:], 16))
else:
c = chr(int(name))
self._texts.append(c)
def get_text(self):
return "".join(self._texts)
def html_to_text(html):
parser = TextExtractHtmlParser()
try:
parser.feed(html)
parser.close()
except Exception as e:
demisto.error(f'The following error occurred while parsing the HTML: {e}')
pass
return parser.get_text()
# disable-secrets-detection-start
def get_http_client_with_proxy(proxies):
proxy_info = None
if PROXY:
if not proxies or not proxies['https']:
raise Exception('https proxy value is empty. Check Demisto server configuration')
https_proxy = proxies['https']
if not https_proxy.startswith('https') and not https_proxy.startswith('http'):
https_proxy = 'https://' + https_proxy
parsed_proxy = urlparse(https_proxy)
proxy_info = httplib2.ProxyInfo(
proxy_type=httplib2.socks.PROXY_TYPE_HTTP, # disable-secrets-detection
proxy_host=parsed_proxy.hostname,
proxy_port=parsed_proxy.port,
proxy_user=parsed_proxy.username,
proxy_pass=parsed_proxy.password)
return httplib2.Http(proxy_info=proxy_info, disable_ssl_certificate_validation=DISABLE_SSL)
# disable-secrets-detection-end
def get_credentials(additional_scopes=None, delegated_user=None):
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
if not delegated_user or delegated_user == 'me':
delegated_user = ADMIN_EMAIL
scopes = SCOPES
if additional_scopes is not None:
scopes += additional_scopes
json_acct_info = json.loads(PRIVATE_KEY_CONTENT) # type: ignore
credentials = service_account.Credentials.from_service_account_info(json_acct_info)
scoped_credentials = credentials.with_scopes(scopes)
delegated_credentials = scoped_credentials.with_subject(delegated_user)
return delegated_credentials
def get_service(serviceName, version, additional_scopes=None, delegated_user=None):
credentials = get_credentials(additional_scopes=additional_scopes, delegated_user=delegated_user)
proxies = handle_proxy()
if PROXY or DISABLE_SSL:
http_client = google_auth_httplib2.AuthorizedHttp(credentials, http=get_http_client_with_proxy(proxies))
return discovery.build(serviceName, version, cache_discovery=False, http=http_client)
return discovery.build(serviceName, version, cache_discovery=False, credentials=credentials)
def parse_mail_parts(parts):
body = ''
html = ''
attachments = [] # type: list
for part in parts:
if 'multipart' in part['mimeType'] and part.get('parts'):
part_body, part_html, part_attachments = parse_mail_parts(
part['parts'])
body += part_body
html += part_html
attachments.extend(part_attachments)
elif len(part['filename']) == 0:
text = str(base64.urlsafe_b64decode(
part['body'].get('data', '').encode('ascii')), 'utf-8')
if 'text/html' in part['mimeType']:
html += text
else:
body += text
else:
if part['body'].get('attachmentId') is not None:
attachments.append({
'ID': part['body']['attachmentId'],
'Name': part['filename']
})
return body, html, attachments
def format_fields_argument(fields: list[str]) -> list[str] | None:
"""
Checks if the filter fields are valid, if so returns the valid fields,
otherwise returns `None`, when given an empty list returns `None`.
"""
all_valid_fields = (
"Type",
"Mailbox",
"ThreadId",
"Labels",
"Headers",
"Attachments",
"RawData",
"Format",
"Subject",
"From",
"To",
"Body",
"Cc",
"Bcc",
"Date",
"Html",
"Attachment Names",
)
lower_filter_fields = {field.lower() for field in fields}
if valid_fields := [field for field in all_valid_fields if field.lower() in lower_filter_fields]:
valid_fields.append('ID')
return valid_fields
return None
def filter_by_fields(full_mail: dict[str, Any], filter_fields: list[str]) -> dict:
return {field: full_mail.get(field) for field in filter_fields}
def parse_privileges(raw_privileges):
privileges = []
for p in raw_privileges:
privilege = assign_params(ServiceID=p.get('serviceId'), Name=p.get('privilegeName'))
if privilege:
privileges.append(privilege)
return privileges
def localization_extract(time_from_mail):
if time_from_mail is None or len(time_from_mail) < 5:
return '-0000', 0
utc = time_from_mail[-5:]
if utc[0] != '-' and utc[0] != '+':
return '-0000', 0
for ch in utc[1:]:
if not ch.isdigit():
return '-0000', 0
delta_in_seconds = int(utc[0] + utc[1:3]) * 3600 + int(utc[0] + utc[3:]) * 60
return utc, delta_in_seconds
def create_base_time(internal_date_timestamp, header_date):
"""
Args:
internal_date_timestamp: The timestamp from the Gmail API response.
header_date: The date string from the email payload.
Returns: A date string in the senders local time in the format of "Mon, 26 Aug 2019 14:40:04 +0300"
"""
# intenalDate timestamp has 13 digits, but epoch-timestamp counts the seconds since Jan 1st 1970
# (which is currently less than 13 digits) thus a need to cut the timestamp down to size.
timestamp_len = len(str(int(time.time())))
if len(str(internal_date_timestamp)) > timestamp_len:
internal_date_timestamp = int(str(internal_date_timestamp)[:timestamp_len])
utc, delta_in_seconds = localization_extract(header_date)
base_time = datetime.utcfromtimestamp(internal_date_timestamp) + timedelta(seconds=delta_in_seconds)
base_time = str(base_time.strftime('%a, %d %b %Y %H:%M:%S')) + " " + utc
return base_time
def get_occurred_date(email_data: dict) -> Tuple[datetime, bool]:
"""Get the occurred date of an email. The date gmail uses is actually the X-Received or the top Received
dates in the header. If fails finding these dates will fall back to internal date.
Args:
email_data (dict): email to extract from
Returns:
Tuple[datetime, bool]: occurred datetime, can be used for incrementing search date
"""
headers = demisto.get(email_data, 'payload.headers')
output = None
if not headers or not isinstance(headers, list):
demisto.error(f"couldn't get headers for msg (shouldn't happen): {email_data}")
else:
# use x-received or recvived. We want to use x-received first and fallback to received.
for name in ['x-received', 'received', ]:
header = next(filter(lambda ht: ht.get('name', '').lower() == name, headers), None)
if header:
val = header.get('value')
if val:
res = get_date_from_email_header(val)
if res:
output = datetime.fromtimestamp(res.timestamp(), tz=timezone.utc)
demisto.debug(f"The timing from header: {name} value: {val} the result: {res}, the UTC time is {output}")
break
internalDate = email_data.get('internalDate')
demisto.info(f"trying internalDate: {internalDate}")
if internalDate and internalDate != '0':
# intenalDate timestamp has 13 digits, but epoch-timestamp counts the seconds since Jan 1st 1970
# (which is currently less than 13 digits) thus a need to cut the timestamp down to size.
timestamp_len = len(str(int(time.time())))
if len(str(internalDate)) >= timestamp_len:
internalDate = (str(internalDate)[:timestamp_len])
internalDate_dt = datetime.fromtimestamp(int(internalDate), tz=timezone.utc)
demisto.debug(f"{internalDate=} {internalDate_dt=}")
if output and internalDate_dt:
# check which time is earlier, return it
output = internalDate_dt if internalDate_dt < output else output
elif internalDate_dt and not output:
output = internalDate_dt
if output:
demisto.debug(f"The final occurred time is {output}")
return output, True
# we didn't get a date from anywhere
demisto.info("Failed finding date from internal or headers. Using 'datetime.now()'")
return datetime.now(tz=timezone.utc), False
def get_date_from_email_header(header: str) -> Optional[datetime]:
"""Parse an email header such as Date or Received. The format is either just the date
or name value pairs followed by ; and the date specification. For example:
by 2002:a17:90a:77cb:0:0:0:0 with SMTP id e11csp4670216pjs; Mon, 21 Dec 2020 12:11:57 -0800 (PST)
Args:
header (str): header value to parse
Returns:
Optional[datetime]: parsed datetime
"""
if not header:
return None
try:
date_part = header.split(';')[-1].strip()
res = parsedate_to_datetime(date_part)
if res.tzinfo is None:
# some headers may contain a non TZ date so we assume utc
res = res.replace(tzinfo=timezone.utc)
return res
except Exception as ex:
demisto.debug(f'Failed parsing date from header value: [{header}]. Err: {ex}. Will ignore and continue.')
return None
def get_email_context(email_data, mailbox):
occurred, occurred_is_valid = get_occurred_date(email_data)
context_headers = email_data.get('payload', {}).get('headers', [])
context_headers = [{'Name': v['name'], 'Value': v['value']}
for v in context_headers]
headers = {h['Name'].lower(): h['Value'] for h in context_headers}
body = demisto.get(email_data, 'payload.body.data')
body = body.encode('ascii') if body is not None else ''
parsed_body = base64.urlsafe_b64decode(body)
demisto.debug(f"get_email_context {body=} {parsed_body=}")
context_gmail = {
'Type': 'Gmail',
'Mailbox': ADMIN_EMAIL if mailbox == 'me' else mailbox,
'ID': email_data.get('id'),
'ThreadId': email_data.get('threadId'),
'Labels': ', '.join(email_data.get('labelIds', [])),
'Headers': context_headers,
'Attachments': email_data.get('payload', {}).get('filename', ''),
# only for format 'raw'
'RawData': email_data.get('raw'),
# only for format 'full' and 'metadata'
'Format': headers.get('content-type', '').split(';')[0],
'Subject': headers.get('subject'),
'From': headers.get('from'),
'To': headers.get('to'),
# only for format 'full'
'Body': str(parsed_body, 'utf-8'),
# only for incident
'Cc': headers.get('cc', []),
'Bcc': headers.get('bcc', []),
'Date': format_datetime(occurred),
'Html': None,
}
context_email = {
'ID': email_data.get('id'),
'Headers': context_headers,
'Attachments': {'entryID': email_data.get('payload', {}).get('filename', '')},
# only for format 'raw'
'RawData': email_data.get('raw'),
# only for format 'full' and 'metadata'
'Format': headers.get('content-type', '').split(';')[0],
'Subject': headers.get('subject'),
'From': headers.get('from'),
'To': headers.get('to'),
# only for format 'full'
'Body/Text': str(parsed_body, 'utf-8'),
'CC': headers.get('cc', []),
'BCC': headers.get('bcc', []),
'Date': format_datetime(occurred),
'Body/HTML': None,
}
if 'text/html' in context_gmail['Format']: # type: ignore
context_gmail['Html'] = context_gmail['Body']
context_gmail['Body'] = html_to_text(context_gmail['Body'])
context_email['Body/HTML'] = context_gmail['Html']
context_email['Body/Text'] = context_gmail['Body']
demisto.debug(f"In text/html {context_gmail['Body']=}")
if 'multipart' in context_gmail['Format']: # type: ignore
context_gmail['Body'], context_gmail['Html'], context_gmail['Attachments'] = parse_mail_parts(
email_data.get('payload', {}).get('parts', []))
demisto.debug(f"In multipart {context_gmail['Body']=}")
context_gmail['Attachment Names'] = ', '.join(
[attachment['Name'] for attachment in context_gmail['Attachments']]) # type: ignore
context_email['Body/Text'], context_email['Body/HTML'], context_email['Attachments'] = parse_mail_parts(
email_data.get('payload', {}).get('parts', []))
context_email['Attachment Names'] = ', '.join(
[attachment['Name'] for attachment in context_email['Attachments']]) # type: ignore
return context_gmail, headers, context_email, occurred, occurred_is_valid
TIME_REGEX = re.compile(r'^([\w,\d: ]*) (([+-]{1})(\d{2}):?(\d{2}))?[\s\w\(\)]*$') # pylint: disable=E1101
def move_to_gmt(t):
# there is only one time refernce is the string
base_time, _, sign, hours, minutes = TIME_REGEX.findall(t)[0]
if all([sign, hours, minutes]):
seconds = -1 * (int(sign + hours) * 3600 + int(sign + minutes) * 60)
parsed_time = datetime.strptime(
base_time, '%a, %d %b %Y %H:%M:%S') + timedelta(seconds=seconds)
return parsed_time.isoformat() + 'Z'
else:
return datetime.strptime(base_time, '%a, %d %b %Y %H:%M:%S').isoformat() + 'Z'
def create_incident_labels(parsed_msg, headers):
labels = [
{'type': 'Email/ID', 'value': parsed_msg['ID']},
{'type': 'Email/subject', 'value': parsed_msg['Subject']},
{'type': 'Email/text', 'value': parsed_msg['Body']},
{'type': 'Email/from', 'value': parsed_msg['From']},
{'type': 'Email/html', 'value': parsed_msg['Html']},
]
labels.extend([{'type': 'Email/to', 'value': to}
for to in headers.get('To', '').split(',')])
labels.extend([{'type': 'Email/cc', 'value': cc}
for cc in headers.get('Cc', '').split(',')])
labels.extend([{'type': 'Email/bcc', 'value': bcc}
for bcc in headers.get('Bcc', '').split(',')])
for key, val in list(headers.items()):
labels.append({'type': 'Email/Header/' + key, 'value': val})
return labels
def mailboxes_to_entry(mailboxes: list[dict]) -> list[CommandResults]:
query = f"Query: {mailboxes[0].get('q') if mailboxes else ''}"
found_accounts = []
errored_accounts = [] # accounts not searched, due to an error accessing them
for user in mailboxes:
mailbox = user.get('Mailbox')
if (error := user.get('Error')):
errored_accounts.append({"Mailbox": mailbox, "Error": error})
elif mailbox:
found_accounts.append(mailbox)
else:
demisto.debug(f"unexpected value: neither user['Mailbox'] nor user['Error']: {user=}")
command_results = [CommandResults(
outputs_prefix='Gmail.Mailboxes',
readable_output=tableToMarkdown(
query,
[{'Mailbox': mailbox} for mailbox in found_accounts],
headers=['Mailbox'],
removeNull=True),
outputs=found_accounts
)]
if errored_accounts:
command_results.append(CommandResults(
outputs_prefix='Gmail.UnsearchedAcounts',
outputs=errored_accounts,
))
return command_results
def emails_to_entry(title, raw_emails, format_data, mailbox, fields: list[str] | None = None):
gmail_emails = []
emails = []
for email_data in raw_emails:
context_gmail, _, context_email, occurred, occurred_is_valid = get_email_context(email_data, mailbox)
if fields:
context_gmail = filter_by_fields(context_gmail, fields)
gmail_emails.append(context_gmail)
emails.append(context_email)
headers = {
'minimal': ['Mailbox', 'ID', 'Labels', 'Attachment Names', ],
'raw': ['MailBox', 'ID', 'Labels', 'Attachment Names', 'RawData'],
'metadata': ['MailBox', 'ID', 'Subject', 'From', 'To', 'Labels', 'Attachment Names', 'Format'],
'full': ['Mailbox', 'ID', 'Subject', 'From', 'To', 'Labels', 'Attachment Names', 'Format', 'Body'],
}
return {
'ContentsFormat': formats['json'],
'Type': entryTypes['note'],
'Contents': raw_emails,
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, gmail_emails, headers[format_data], removeNull=True),
'EntryContext': {
'Gmail(val.ID && val.ID == obj.ID)': gmail_emails,
'Email(val.ID && val.ID == obj.ID)': emails
}
}
def get_date_isoformat_server(dt: datetime) -> str:
"""Get the datetime str in the format a server can parse. UTC based with Z at the end
Args:
dt (datetime): datetime
Returns:
str: string representation
"""
return datetime.fromtimestamp(dt.timestamp()).isoformat(timespec='seconds') + 'Z'
def mail_to_incident(msg, service, user_key):
parsed_msg, headers, _, occurred, occurred_is_valid = get_email_context(msg, user_key)
occurred_str = get_date_isoformat_server(occurred)
file_names = []
command_args = {
'messageId': parsed_msg['ID'],
'userId': user_key,
}
for attachment in parsed_msg['Attachments']:
command_args['id'] = attachment['ID']
result = service.users().messages().attachments().get(**command_args).execute()
file_data = base64.urlsafe_b64decode(result['data'].encode('ascii'))
# save the attachment
file_result = fileResult(attachment['Name'], file_data)
# check for error
if file_result['Type'] == entryTypes['error']:
demisto.error(file_result['Contents'])
raise Exception(file_result['Contents'])
file_names.append({
'path': file_result['FileID'],
'name': attachment['Name'],
})
# date in the incident itself is set to GMT time, the correction to local time is done in Demisto
incident = {
'type': 'Gmail',
'name': parsed_msg['Subject'],
'details': parsed_msg['Body'],
'labels': create_incident_labels(parsed_msg, headers),
'occurred': occurred_str,
'attachment': file_names,
'rawJSON': json.dumps(parsed_msg),
}
return incident, occurred, occurred_is_valid
def users_to_entry(title, response, next_page_token=None):
context = []
for user_data in response:
username = dict_safe_get(user_data, ['name', 'givenName'])
display = dict_safe_get(user_data, ['name', 'fullName'])
context.append({
'Type': 'Google',
'ID': user_data.get('id'),
'UserName': username,
'Username': username, # adding to fit the new context standard
'DisplayName': display,
'Email': {'Address': user_data.get('primaryEmail')},
'Gmail': {'Address': user_data.get('primaryEmail')},
'Group': user_data.get('kind'),
'Groups': user_data.get('kind'), # adding to fit the new context standard
'CustomerId': user_data.get('customerId'),
'Domain': user_data.get('primaryEmail').split('@')[1],
'VisibleInDirectory': user_data.get('includeInGlobalAddressList'),
})
headers = ['Type', 'ID', 'Username',
'DisplayName', 'Groups', 'CustomerId', 'Domain', 'OrganizationUnit', 'Email', 'VisibleInDirectory']
human_readable = tableToMarkdown(title, context, headers, removeNull=True)
if next_page_token:
human_readable += "\nTo get further results, rerun the command with this page-token:\n" + next_page_token
return CommandResults(
outputs=context,
raw_response=response,
readable_output=human_readable,
outputs_prefix='Account',
outputs_key_field=['ID', 'Type']
)
def labels_to_entry(title, response, user_key):
context = []
for label in response:
context.append({
'UserID': user_key,
'Name': label.get('name'),
'ID': label.get('id'),
"Type": label.get('type'),
"MessageListVisibility": label.get('messageListVisibility'),
"LabelListVisibility": label.get('labelListVisibility')
})
headers = ['Name', 'ID', 'Type', 'MessageListVisibility', 'LabelListVisibility']
human_readable = tableToMarkdown(title, context, headers, removeNull=True)
return CommandResults(
outputs=context,
raw_response=response,
readable_output=human_readable,
outputs_prefix='GmailLabel',
outputs_key_field=['ID', 'Name', 'UserID']
)
def autoreply_to_entry(title, response, user_id):
autoreply_context = []
for autoreply_data in response:
autoreply_context.append({
'EnableAutoReply': autoreply_data.get('enableAutoReply'),
'ResponseBody': autoreply_data.get('responseBodyPlainText'),
'ResponseSubject': autoreply_data.get('responseSubject'),
'RestrictToContact': autoreply_data.get('restrictToContacts'),
'RestrictToDomain': autoreply_data.get('restrictToDomain'),
'StartTime': autoreply_data.get('startTime'),
'EndTime': autoreply_data.get('endTime'),
'ResponseBodyHtml': autoreply_data.get('responseBodyHtml')
})
headers = ['EnableAutoReply', 'ResponseBody', 'ResponseBodyHtml',
'ResponseSubject', 'RestrictToContact', 'RestrictToDomain',
'EnableAutoReply', 'StartTime', 'EndTime']
account_context = {
"Address": user_id,
"AutoReply": autoreply_context
}
return CommandResults(
raw_response=autoreply_context,
outputs=account_context,
readable_output=tableToMarkdown(title, autoreply_context, headers, removeNull=True),
outputs_prefix='Account.Gmail',
outputs_key_field='Address'
)
def sent_mail_to_entry(title, response, to, emailfrom, cc, bcc, body, subject):
gmail_context = []
for mail_results_data in response:
gmail_context.append({
'Type': "Gmail",
'ID': mail_results_data.get('id'),
'Labels': mail_results_data.get('labelIds', []),
'ThreadId': mail_results_data.get('threadId'),
'To': ','.join(to),
'From': emailfrom,
'Cc': ','.join(cc) if len(cc) > 0 else None,
'Bcc': ','.join(bcc) if len(bcc) > 0 else None,
'Subject': subject,
'Body': body,
'Mailbox': ','.join(to)
})
headers = ['Type', 'ID', 'To', 'From', 'Cc', 'Bcc', 'Subject', 'Body', 'Labels',
'ThreadId']
return CommandResults(
raw_response=response,
outputs=gmail_context,
readable_output=tableToMarkdown(title, gmail_context, headers, removeNull=True),
outputs_prefix='Gmail.SentMail',
outputs_key_field=['ID', 'Type']
)
def user_roles_to_entry(title, response):
context = []
for role_data in response:
context.append({
'ID': role_data['roleId'],
'AssignedTo': role_data['assignedTo'],
'RoleAssignmentId': role_data['roleAssignmentId'],
'ScopeType': role_data['scopeType'],
'Kind': role_data['kind'],
'OrgUnitId': role_data.get('orgUnitId', ''),
})
headers = ['ID', 'RoleAssignmentId',
'ScopeType', 'Kind', 'OrgUnitId']
human_readable = tableToMarkdown(title, context, headers, removeNull=True)
return CommandResults(
raw_response=context,
outputs=context,
readable_output=human_readable,
outputs_prefix='Gmail.Role',
outputs_key_field='ID'
)
def tokens_to_entry(title, response):
context = []
for token_data in response:
context.append({
'DisplayText': token_data.get('displayText'),
'ClientId': token_data.get('clientId'),
'Kind': token_data.get('kind'),
'Scopes': token_data.get('scopes', []),
'UserKey': token_data.get('userKey'),
})
headers = ['DisplayText', 'ClientId', 'Kind', 'Scopes', 'UserKey']
return CommandResults(
raw_response=context,
outputs=context,
readable_output=tableToMarkdown(title, context, headers, removeNull=True),
outputs_prefix='Tokens',
outputs_key_field='ClientId'
)
def filters_to_entry(title, mailbox, response):
context = []
for filter_data in response:
context.append({
'ID': filter_data.get('id'),
'Mailbox': mailbox,
'Criteria': filter_data.get('criteria'),
'Action': filter_data.get('action'),
})
headers = ['ID', 'Criteria', 'Action', ]
return {
'ContentsFormat': formats['json'],
'Type': entryTypes['note'],
'Contents': context,
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, context, headers, removeNull=True),
'EntryContext': {'GmailFilter(val.ID && val.ID == obj.ID)': context,
'Gmail.Filter(val.ID && val.ID == obj.ID)': context}
}
def role_to_entry(title, role):
context = {
'ETag': role.get('etag').strip('"'),
'IsSuperAdminRole': bool(role.get('isSuperAdminRole')) if role.get('isSuperAdminRole') else False,
'IsSystemRole': bool(role.get('isSystemRole')) if role.get('isSystemRole') else False,
'Kind': role.get('kind'),
'Description': role.get('roleDescription'),
'ID': role.get('roleId'),
'Name': role.get('roleName'),
'Privilege': parse_privileges(role.get('rolePrivileges', []))
}
headers = ['ETag', 'IsSuperAdminRole', 'IsSystemRole', 'Kind', 'Description',
'ID', 'Name']
details_hr = tableToMarkdown(title, context, headers, removeNull=True)
privileges = context.get('Privilege', [])
privileges_headers = ['ServiceID', 'Name']
privileges_title = f"Role {context.get('ID')} privileges:"
privileges_hr = tableToMarkdown(privileges_title, privileges, privileges_headers, removeNull=True)
return CommandResults(
raw_response=context,
outputs=context,
readable_output=details_hr + privileges_hr,
outputs_prefix='Gmail.Role',
outputs_key_field='ID'
)
def dict_keys_snake_to_camelcase(dictionary):
"""
Converts all dictionary keys from snake case (dict_key) to lower camel case(dictKey).
:param dictionary: Dictionary which may contain keys in snake_case
:return: Dictionary with snake_case keys converted to lowerCamelCase
"""
underscore_pattern = re.compile(r'_([a-z])') # pylint: disable=E1101
return {underscore_pattern.sub(lambda i: i.group(1).upper(), key.lower()): value for (key, value) in
list(dictionary.items())}
def get_millis_from_date(date, arg_name):
"""
Convert a date string into epoch milliseconds or return epoch milliseconds as int.
:param date: Date string in expected format.
:param arg_name: field_name for setting proper error message.
:return: Epoch milliseconds.
"""
try:
return date_to_timestamp(date, DATE_FORMAT)
except ValueError:
try:
return int(date)
except ValueError:
raise ValueError(f'{arg_name} argument is not in expected format.')
def cutting_for_batches(list_accounts: list) -> List[list]:
accounts: list = []
rest_accounts: list = []
batch_size = int(len(list_accounts) / BATCH_DIVIDER)
if rest := len(list_accounts) % BATCH_DIVIDER:
rest_accounts = list_accounts[-rest:]
list_accounts = list_accounts[:-rest]
accounts.extend(batch(list_accounts, batch_size))
# When the number of accounts is not exactly divisible by BATCH_DIVIDER,
# We add the remaining accounts to the first batch to avoid running another polling command.
if rest_accounts:
accounts[0].extend(rest_accounts)
return accounts
def scheduled_commands_for_more_users(accounts: list, next_page_token: str) -> List[CommandResults]:
accounts_batches = cutting_for_batches(accounts)
command_results: list[CommandResults] = []
args = copy.deepcopy(demisto.args())
for batch in accounts_batches:
args.update({'list_accounts': batch})
command_results.append(
CommandResults(
readable_output='Searching mailboxes, please wait...',
scheduled_command=ScheduledCommand(
command='gmail-search-all-mailboxes',
next_run_in_seconds=10,
args=copy.deepcopy(args),
timeout_in_seconds=600
)
)
)
args.pop('list_accounts', None)
if next_page_token:
command_results.append(
CommandResults(
outputs_key_field='PageToken',
outputs={'PageToken': {'NextPageToken': next_page_token}}
)
)
return command_results
def get_mailboxes(max_results: int, users_next_page_token: str = None):
'''
Used to fetch the list of accounts for the search-all-mailboxes command
'''
accounts: list[str] = []
accounts_counter = 0
users_next_page_token = users_next_page_token
service = get_service('admin', 'directory_v1')
while True:
command_args = {
'maxResults': min(max_results, 100),
'domain': ADMIN_EMAIL.split('@')[1],
'pageToken': users_next_page_token
}
result = service.users().list(**command_args).execute()
accounts_counter += len(result['users'])
accounts.extend([account['primaryEmail'] for account in result['users']])
users_next_page_token = result.get('nextPageToken')
if accounts_counter >= max_results:
accounts = accounts[:max_results]
break
if users_next_page_token is None:
break
return accounts, users_next_page_token
def information_search_process(length_accounts: int, search_from: int | None, search_to: int | None) -> CommandResults:
if search_from is None or search_to is None:
readable_output = f'Searching the first {length_accounts} accounts'
search_from = 0
search_to = length_accounts
else:
search_from = search_to + 1
search_to = search_to + length_accounts
readable_output = f'Searching accounts {search_from} to {search_to}'
return CommandResults(
readable_output=readable_output,
outputs={'SearchFromAccountIndex': search_from, 'SearchToAccountIndex': search_to},
)
''' FUNCTIONS '''
def list_users_command() -> CommandResults:
args = demisto.args()
domain = args.get('domain', ADMIN_EMAIL.split('@')[1])
customer = args.get('customer')
view_type = args.get('view-type-public-domain', 'admin_view')
query = args.get('query')
sort_order = args.get('sort-order')
max_results = args.get('max-results', 100)
show_deleted = bool(strtobool(args.get('show-deleted', 'false')))
projection = args.get('projection', 'basic')
custom_field_mask = args.get(
'custom_field_mask') if projection == 'custom' else None
page_token = args.get('page-token')
users, next_page_token = list_users(domain, customer, query, sort_order, view_type,
show_deleted, max_results, projection, custom_field_mask, page_token)
return users_to_entry('Users:', users, next_page_token)
def list_labels_command():
args = demisto.args()
user_key = args.get('user-id')
labels = list_labels(user_key)
return labels_to_entry(f'Labels for UserID {user_key}:', labels, user_key)
def list_users(domain, customer=None, query=None, sort_order=None, view_type='admin_view',
show_deleted=False, max_results=100, projection='basic', custom_field_mask=None, page_token=None):
command_args = {
'domain': domain,
'customer': customer,
'viewType': view_type,
'query': query,
'sortOrder': sort_order,
'projection': projection,
'showDeleted': show_deleted,
'maxResults': max_results,
'pageToken': page_token
}
if projection == 'custom':
command_args['customFieldMask'] = custom_field_mask
service = get_service('admin', 'directory_v1')
result = service.users().list(**command_args).execute()
return result['users'], result.get('nextPageToken')
def get_user_command() -> CommandResults:
args = demisto.args()
user_key = args.get('user-id')
view_type = args.get('view-type-public-domain')
projection = args.get('projection')
customer_field_mask = args.get('customer-field-mask')
result = get_user(user_key, view_type, projection, customer_field_mask)
return users_to_entry(f'User {user_key}:', [result])
def get_user(user_key, view_type, projection, customer_field_mask=None):
command_args = {
'userKey': user_key if user_key != 'me' else ADMIN_EMAIL,
'projection': projection,
'viewType': view_type,
}
if projection == 'custom':
command_args['customFieldMask'] = customer_field_mask
service = get_service('admin', 'directory_v1')
result = service.users().get(**command_args).execute()
return result
def hide_user_command() -> CommandResults:
args = demisto.args()
user_key = args.get('user-id')
hide_value = args.get('visible-globally')
result = hide_user(user_key, hide_value)
return users_to_entry(f'User {user_key}:', [result])
def hide_user(user_key, hide_value):
command_args = {