-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget-read-links.py
375 lines (282 loc) · 13.9 KB
/
get-read-links.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
#!/usr/bin/python
import csv
import json
import pprint
import datetime
import re
import sys
import time
import configparser
import adal
import requests
from argparse import ArgumentParser
from urllib.parse import urlparse
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
"""
Scan a single user's office 365 email account for read emails since the specified date and before an optional end date.
Export a list of URL links in format: url,domain,receivedDateTime,mailId,subject,sender
Usage:
get-read-links -u [email protected] -c cert1.pem -s 2018-08-01T6:00:00Z -e 2018-08-03T20:00:00Z
This will scan [email protected] for all messages received between the two date times (inclusive)
and return URLs or Fileshare links in the messages read, along with the message metadata all in csv.
"""
def get_paged_data(r, headers):
""" Handle API query data retrieval that could be paginated or throttled
We assume an initial query has already been made, with response object r.
We check this response and fetch additional response pages as needed.
"""
data = []
if r.status_code == 429:
print("WARNING throttling imposed! waiting " + str(r.headers['Retry-After']) + " seconds.\n")
time.sleep(int(r.headers['Retry-After']))
elif r.status_code != 200:
print("ERROR " + str([r.status_code, r.text]) + "\n" + str(r.url))
sys.exit(1)
response = r.json()
if 'value' not in response and 'body' not in response:
# paginated queries have value attribute, single message queries do not
print("ERROR no data response\n " + str(r.url))
sys.exit(1)
elif 'value' in response:
for message in response['value']:
data.append(message)
while '@odata.nextLink' in response:
r = requests.get(response['@odata.nextLink'], headers=headers)
if r.status_code == 429:
print("WARNING throttling imposed! waiting " + str(r.headers['Retry-After']) + " seconds.\n")
time.sleep(int(r.headers['Retry-After']))
# sys.exit(0)
elif r.status_code != 200:
print("ERROR " + str([r.status_code, r.text]) + "\n" + str(r.url))
response = r.json()
if 'value' not in response and 'body' not in response:
print("ERROR no data response from " + str(r.url))
sys.exit(1)
else:
for message in response['value']:
data.append(message)
return data
elif 'body' in response:
data.append(r.json())
while '@odata.nextLink' in response:
r = requests.get(response['@odata.nextLink'], headers=headers)
if r.status_code == 429:
print("WARNING throttling imposed! waiting " + str(r.headers['Retry-After']) + " seconds.\n")
time.sleep(int(r.headers['Retry-After']))
# sys.exit(0)
elif r.status_code != 200:
print("ERROR " + str([r.status_code, r.text]) + "\n" + str(r.url))
response = r.json()
if 'value' not in response and 'body' not in response:
print("ERROR no data response from " + str(r.url))
sys.exit(1)
else:
data.append(r.json())
return data
def get_links(body):
""" Find all url or fileshare links in message body
:param body: body of message in text format
:return: list of links
"""
MATCH_LINK = re.compile("<(\S*\:\/\/\S*)>")
MATCH_SHARE = re.compile("(\S*\\\\\S*)")
links = re.findall(MATCH_LINK, body)
shares = re.findall(MATCH_SHARE, body)
return links + shares
def main():
parser = ArgumentParser()
parser.add_argument('-r', '--resource', default='config.ini',
help='resource file with info unique to your environment')
parser.add_argument('-u', '--user', help='upn to run queries against')
parser.add_argument('-s', '--start', help='start time: ex 2018-01-02T01:00:00Z - Jan 2 2018, 1 AM GMT')
parser.add_argument('-e', '--end', help='end time: ex 2018-01-02T01:00:00Z - Jan 2 2018, 1 AM GMT. Default=now')
parser.add_argument('-o', '--output', help='output .csv to write. Defaults to user+timestamp.csv')
parser.add_argument('-c', '--certificate', help='certificate file you uploaded to azure and registered with app')
parser.add_argument('-p', '--cert-password', help='password to read your certificate file')
parser.add_argument('--silent', help='squelch all cli output', action="store_true")
parser.add_argument('-t', '--token-only', help='print out token and quit', action="store_true")
parser.add_argument('--token-only-outlook', help='print out token to legacy outlook api and quit',
action="store_true")
parser.add_argument('--nopii', action="store_true", help='do not output any email addresses')
parser.add_argument('--rules', action="store_true", help='get inbox rules with external forwarding enabled instead')
args = parser.parse_args()
# Ensure enough paramters are specified
if not (args.token_only or args.token_only_outlook):
if not (args.user and args.start and args.certificate):
print("ERROR: When not running in --token-only, the following arguments are required:")
print("--user, --start, --certificate")
sys.exit(1)
elif args.token_only or args.token_only_outlook:
if not args.certificate:
print("ERROR: When running --token-only you must specify --certificate as well")
sys.exit(1)
# Load variables
QUERY_TIME_START = args.start
QUERY_TIME_END = args.end
QUERY_USER = args.user
RESOURCE_FILE = args.resource
TOKEN_ONLY = args.token_only
SILENT = args.silent
CERT_FILE = args.certificate
CERT_PWD = args.cert_password
# define query constants
url1 = '/messages?$filter=receivedDateTime ge '
url2 = ' and receivedDateTime le '
urlFolderFilter = ' and parentFolderId ne '
url4 = '&$select=id,lastModifiedDateTime,receivedDateTime,hasAttachments,internetMessageId,subject,isRead,sender,' \
'from,toRecipients,replyTo'
if args.end:
QUERY_TIME_END = args.end
else:
QUERY_TIME_END = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
if args.output:
OUTPUT_FILE = args.output
elif not (args.token_only or args.token_only_outlook):
OUTPUT_FILE = QUERY_USER.split('@')[0] + datetime.datetime.now().strftime("%Y-%m-%dT%H-%M") + ".csv"
if RESOURCE_FILE:
config = configparser.ConfigParser()
try:
config.read(filenames=RESOURCE_FILE)
except IOError:
print("ERROR reading resource file")
sys.exit(1)
AUTHORITY_URL = config.get('DEFAULT', 'authority_url')
TENANT_GUID = config.get('DEFAULT', 'tenant_guid')
GRAPH_URL = config.get('DEFAULT', 'graph_url')
OUTLOOK_URL = config.get('DEFAULT', 'outlook_url')
CERTIFICATE_KEY = config.get('DEFAULT', 'certificate_key')
API_VERSION = config.get('DEFAULT', 'api_version')
URL_FILTER = config.get('DEFAULT', 'url_filter')
APPLICATION_GUID = config.get('DEFAULT', 'application_guid')
else:
raise ValueError('ERROR Please provide config file with resource information.')
## load cert file
try:
with open(CERT_FILE, "rb") as f:
key = serialization.load_pem_private_key(f.read(), password=CERT_PWD, backend=default_backend())
except IOError:
print("ERROR unable to open " + CERT_FILE + " or certificate problem")
sys.exit(1)
except TypeError:
print("ERROR Invalid filename specified for certificate")
sys.exit(1)
# Main logic begins
if not SILENT:
print(time.ctime() + ": Authorizing")
context = adal.AuthenticationContext(AUTHORITY_URL, validate_authority=TENANT_GUID != 'adfs')
# Get the GRAPH token or legacy Outlook token if requested.
if args.token_only_outlook:
token = context.acquire_token_with_client_certificate(OUTLOOK_URL, APPLICATION_GUID, key, CERTIFICATE_KEY)
else:
token = context.acquire_token_with_client_certificate(GRAPH_URL, APPLICATION_GUID, key, CERTIFICATE_KEY)
if TOKEN_ONLY or args.token_only_outlook:
print(token)
print("Done")
sys.exit(0)
# get FolderID of SentItems folder
headers = {'Authorization': 'Bearer ' + token['accessToken']}
r = requests.get(GRAPH_URL + '/' + API_VERSION + '/users/' + QUERY_USER +
'/mailFolders?$filter=displayName eq \'Sent Items\'&$select=id', headers=headers)
if r.status_code != 200:
if not args.nopii:
print("ERROR failed to retrieve mailFolders for user " + QUERY_USER)
else:
print("ERROR failed to retrieve mailFolders")
if not args.nopii:
print(" query: " + str(r.url))
sys.exit(1)
sentFolderId = r.json()['value'][0]['id']
urlFolderFilter += '\'' + sentFolderId + '\''
endpoint_url = GRAPH_URL + '/' + API_VERSION + '/users/' + QUERY_USER + url1 + QUERY_TIME_START + \
url2 + QUERY_TIME_END + urlFolderFilter + url4
if not SILENT:
print(time.ctime() + ": Fetching list of emails")
r = requests.get(endpoint_url, headers=headers)
data = get_paged_data(r, headers)
if not SILENT:
print(time.ctime() + ": " + str(len(data)) + " messages found.")
read = [] # list of read messages
read_data = [] # body of read messages
for message in data:
if message['isRead']:
read.append(message)
if not SILENT:
print(time.ctime() + ": " + str(len(read)) + " messages read.")
headers['Prefer'] = "outlook.body-content-type=\"text\""
for email in read:
# Need to filter out SENT messages!
endpoint_url = GRAPH_URL + '/' + API_VERSION + '/users/' + QUERY_USER + '/messages/' + \
email['id'] + \
'?$select=id,lastModifiedDateTime,receivedDateTime,hasAttachments,internetMessageId,subject,' \
'parentFolderId,isRead,isDraft,inferenceClassification,sender,from,toRecipients, ccRecipients,' \
'bccRecipients,replyTo,body'
r = requests.get(endpoint_url, headers=headers)
read_data.append(get_paged_data(r, headers))
if not SILENT:
print(time.ctime() + ": " + str(len(read_data)) + " messages retrieved.")
emailswithlinks = 0 # number of discrete emails with URLS discovered
all_links = [] # list of [URL, domain, email rx time, message id, subject, from address]
# parse out the URLs from the message body
for message in read_data:
# scan for a URL in the message
if "://" in message[0]['body']['content']:
emailswithlinks += 1
try:
links = get_links(message[0]['body']['content'])
except:
print("call to get_links failed: " + str(message))
for item in links:
urlobj = urlparse(item)
if not args.nopii:
all_links.append([item, urlobj.netloc, message[0]['receivedDateTime'], message[0]['id'],
message[0]['subject'], message[0]['from']['emailAddress']])
else:
all_links.append([item, urlobj.netloc, message[0]['receivedDateTime'], message[0]['id'],
message[0]['subject']])
if not SILENT:
print(" Found " + str(emailswithlinks) + " emails with links and " + str(len(all_links)) + " links")
numberfilteredlinks = 0
filteredlinks = {} # dict of domain, [link ane email info from above]
for link in all_links:
urlobj = urlparse(link[0])
# if domain is not in filter and parent domain + TLD is not in filter
# ex: if link domain is api.www.gmail.com, and www.gmail.com is in filter... skip link.
if (urlobj.netloc not in URL_FILTER) and '.'.join(urlobj.netloc.split('.')[-2::]) not in URL_FILTER:
# skip if domain is in filter
numberfilteredlinks += 1
# if we've already scanned this link AND domain+path is not already present, append
if urlobj.netloc in filteredlinks and urlobj.netloc + urlobj.path not in filteredlinks[urlobj.netloc]:
filteredlinks[urlobj.netloc].append(link)
# otherwise, if we don't have this link domain yet, insert
elif urlobj.netloc not in filteredlinks:
filteredlinks[urlobj.netloc] = [link]
if not SILENT:
pp = pprint.PrettyPrinter(width=80)
print(" filtered out " + str(len(all_links) - len(all_links)) + " out of " + str(len(all_links)))
for key in sorted(filteredlinks.items()):
x = [key[0], filteredlinks[key[0]]]
pp.pprint(x)
print(str(len(filteredlinks)) + " domains and " + str(numberfilteredlinks) + " links output")
# no file output if no results
if len(filteredlinks) > 0:
with open(OUTPUT_FILE, 'w', encoding="utf-8") as f:
if not args.nopii:
fieldnames = ['url', 'domain', 'receivedDateTime', 'mailId', 'subject', 'sender']
else:
fieldnames = ['url', 'domain', 'receivedDateTime', 'mailId', 'subject']
w = csv.writer(f, lineterminator='\n', delimiter='|')
w.writerow(fieldnames)
for key, value in filteredlinks.items():
for item in value:
w.writerow(item)
else:
if not SILENT:
print("INFO No results, output file omitted")
if not SILENT:
if len(filteredlinks) > 0:
print("INFO wrote output " + OUTPUT_FILE)
print(time.ctime() + ": Done.")
# check failures for permission full delegation on mailbox???
if __name__ == "__main__":
main()