-
Notifications
You must be signed in to change notification settings - Fork 280
/
osxauditor.py
executable file
·1697 lines (1338 loc) · 74.3 KB
/
osxauditor.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 python
# -*- encoding: utf-8 -*-
#
# OS X Auditor
#
# Author: Jean-Philippe Teissier ( @Jipe_ ) & al.
#
# This work is licensed under the GNU General Public License
#
__description__ = 'OS X Auditor'
__author__ = '@Jipe_ & al.'
__version__ = '0.4.4'
ROOT_PATH = '/'
HOSTNAME = ''
HASHES = []
LOCAL_HASHES_DB = {}
HTML_LOG_FILE = False
HTML_LOG_CONTENT = u''
HTML_LOG_MENU = u''
HTML_EVENTS_TL = u''
HTML_EVENTS_LANES = []
HTML_EVENTS_ITEMS = u''
FOUNDATION_IS_IMPORTED = False
BIPLIST_IS_IMPORTED = False
PLISTLIB_IS_IMPORTED = False
SYSLOG_SERVER = False
SYSLOG_PORT = 514 #You can change your SYSLOG port here
MRH_HOST = u'hash.cymru.com'
MRH_PORT = 43
GEOLOCATE_WIFI_AP = False
GEOMENA_API_HOST = u'http://geomena.org/ap/'
VT_HOST = u'https://www.virustotal.com/vtapi/v2/file/report'
ADMINS = []
OSX_VERSION = []
import sys
reload(sys)
sys.setdefaultencoding('UTF8')
import optparse
import os
import hashlib
import logging
from logging.handlers import SysLogHandler
import sqlite3
import socket
import time
import json
import zipfile
import codecs #binary plist parsing does not work well in python3.3 so we are stuck in 2.7 for now
from functools import partial
import re
import bz2
import binascii
import platform
import gzip
VT_API_KEY = os.getenv('VT_API_KEY', False)
try:
from urllib.request import urlopen #python3
except ImportError:
import urllib, urllib2 #python2
try:
import Foundation #It only works on OS X
FOUNDATION_IS_IMPORTED = True
print(u'DEBUG: Mac OS X Obj-C Foundation successfully imported')
except ImportError:
print(u'DEBUG: Cannot import Mac OS X Obj-C Foundation. Installing PyObjC on OS X is highly recommended')
try:
import biplist
BIPLIST_IS_IMPORTED = True
except ImportError:
print(u'DEBUG: Cannot import the biplist lib. I may not be able to properly parse a binary pblist')
try:
import plistlib
PLISTLIB_IS_IMPORTED = True
except ImportError:
print(u'DEBUG: Cannot import the plistlib lib. I may not be able to properly parse a binary pblist')
def HTMLLogFlush():
''' Flush the HTML report '''
global HTML_LOG_CONTENT
global HTML_LOG_MENU
if HTML_LOG_FILE:
HTML_LOG_HEADER = u"""<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>OS X Auditor Report</title>
<link rel=\"stylesheet\" type=\"text/css\" href=\"bootstrap/css/bootstrap.min.css\">
<script type=\"text/javascript\" src=\"jquery/jquery-1.10.2.min.js\"></script>
<script type=\"text/javascript\" src=\"bootstrap/js/bootstrap.min.js\"></script>
<script type=\"text/javascript\" src=\"d3-3.2.8/d3.min.js\"></script>
<style type="text/css">
.chart {
shape-rendering: crispEdges;
}
.mini text {
font: 9px sans-serif;
}
.main text {
font: 12px sans-serif;
}
.miniItem0 {
fill: darksalmon;
stroke-width: 6;
}
.miniItem1 {
fill: darkolivegreen;
fill-opacity: .7;
stroke-width: 6;
}
.miniItem2 {
fill: slategray;
fill-opacity: .7;
stroke-width: 6;
}
.brush .extent {
stroke: gray;
fill: dodgerblue;
fill-opacity: .365;
}
</style>
</head>
<body data-spy=\"scroll\" data-target=\".navbar\" style=\"margin:0 20px 0 20px; padding-top:110px;\">
<div class=\"container\">
<div class=\"navbar navbar-inverse navbar-fixed-top\">
<div class=\"navbar-inner\">
<a class=\"brand\" href="#">OS X Auditor</a>
<ul class=\"nav\">"""
HTML_LOG_FOOTER = u'</body></html>'
HTML_LOG_MENU = HTML_LOG_MENU[10:]
HTML_LOG_MENU += '''</ul>
</div>
</div>
</div>'''
HTML_LOG_FILE.write(HTML_LOG_HEADER)
HTML_LOG_FILE.write(HTML_LOG_MENU)
HTML_LOG_FILE.write(HTML_LOG_CONTENT)
HTML_LOG_FILE.write(HTML_LOG_FOOTER)
HTML_LOG_FILE.close()
def HTMLLog(LogStr, TYPE):
''' Write a string of HTML log depending of its type '''
global HTML_LOG_CONTENT
global HTML_LOG_MENU
if TYPE == 'INFO':
Splitted = LogStr.split(' ')
if re.match('[A-Fa-f\d]{32}', Splitted[0]): #Should be a md5
Link = u'<a href=\'https://www.virustotal.com/fr/file/' + Splitted[0] + u'/analysis/\'>' + Splitted[0] + u'</a> '
HTML_LOG_CONTENT += u"<i class='icon-file'></i> " + Link + u" ".join(Splitted[1:]) + u"<br>"
else:
HTML_LOG_CONTENT += u"<i class='icon-file'></i> " + LogStr + u"<br>"
elif TYPE == "INFO_RAW":
HTML_LOG_CONTENT += u"<pre>" + LogStr + u"</pre><br>"
elif TYPE == "WARNING":
HTML_LOG_CONTENT += u"<div class=\"alert alert-error\"><i class='icon-fire'></i> "+ LogStr + u"</div>"
elif TYPE == "ERROR":
HTML_LOG_CONTENT += u"<div class=\"alert\"><i class='icon-warning-sign'></i> "+ LogStr + u"</div>"
elif TYPE == "SECTION":
HTML_LOG_CONTENT += u"<h2 id=\"" + LogStr + u"\">" + LogStr + u"</h2>"
HTML_LOG_MENU += u"</ul></li><li class=\"dropdown\"><a href=\"#\" role=\"button\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">" + LogStr + u"<b class=\"caret\"></b></a><ul class=\"dropdown-menu\">"
HTML_LOG_MENU += u"<li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"#" + LogStr + u"\">" + LogStr + u"</a></li><li class=\"divider\"></li>"
elif TYPE == "SUBSECTION":
HTML_LOG_CONTENT += u"<h3 id=\"" + LogStr + u"\">" + LogStr + u"</h3>"
HTML_LOG_MENU += u"<li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"#" + LogStr + u"\">" + LogStr + u"</a></li>"
elif TYPE == "DEBUG":
HTML_LOG_CONTENT += u"<i class='icon-wrench'></i> " + LogStr + u"<br>"
def SyslogSetup(SyslogServer):
''' Set the Syslog handler up'''
global SYSLOG_SERVER
try:
Logger = logging.getLogger()
Syslog = logging.handlers.SysLogHandler(address=(SyslogServer, SYSLOG_PORT))
Formatter = logging.Formatter('OS X Auditor: ' + HOSTNAME + ' %(levelname)s: %(message)s')
Syslog.setFormatter(Formatter)
Logger.addHandler(Syslog)
SYSLOG_SERVER = True
except:
PrintAndLog(u'Syslog setup failed, Syslog is disabled', 'ERROR')
SYSLOG_SERVER = False
def PrintAndLog(LogStr, TYPE):
''' Write a string of log depending of its type and call the function to generate the HTML log or the Syslog if needed '''
global HTML_LOG_FILE
global SYSLOG_SERVER
if TYPE == 'INFO' or 'INFO_RAW':
print(u'[INFO] ' + LogStr)
logging.info(LogStr)
elif TYPE == 'ERROR':
print(u'[ERROR] ' + LogStr)
logging.error(LogStr)
elif TYPE == 'WARNING':
print(u'[WARNING] ' + LogStr)
logging.warning(LogStr)
elif TYPE == 'DEBUG':
print(u'[DEBUG] ' + LogStr)
logging.debug(LogStr)
elif TYPE == 'SECTION' or TYPE == 'SUBSECTION':
SectionTitle = u'\n#########################################################################################################\n'
SectionTitle += '# #\n'
SectionTitle += '# ' +LogStr+ ' '*(94-len(LogStr)) + '#\n'
SectionTitle += '# #\n'
SectionTitle += '#########################################################################################################\n'
print(SectionTitle)
logging.info(u'\n' + SectionTitle)
if HTML_LOG_FILE:
HTMLLog(LogStr, TYPE)
def MHRLookup():
''' Perform of lookup in Team Cymru\'s MHR '''
PrintAndLog(u'Team Cymru MHR lookup', 'SECTION')
PrintAndLog(u'Got %s hashes to verify' % len(HASHES), 'DEBUG')
Query = 'begin\r\n'
for Hash in HASHES:
Query += Hash + '\r\n'
Query += 'end\r\n'
S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
S.connect((MRH_HOST, MRH_PORT))
S.sendall(Query)
Response = u''
while True:
Data = S.recv(4096)
Response += Data
if not Data: break
S.close()
Lines = Response.split('\n')
Lines = Lines[2:-1]
for line in Lines:
Status = line.split(' ')
if Status[2] == 'NO_DATA':
PrintAndLog(line.decode('utf-8'), 'INFO')
else:
PrintAndLog(line.decode('utf-8'), 'WARNING')
def VTLookup():
''' Perform of lookup in VirusTotal database '''
PrintAndLog(u'Virustotal lookup', 'SECTION')
PrintAndLog(u'Got %s hashes to verify' % len(HASHES), 'DEBUG')
try:
param = { 'resource': ','.join(HASHES), 'apikey': VT_API_KEY }
data = urllib.urlencode(param)
f = urllib2.urlopen(VT_HOST, data)
data = f.read()
except (urllib2.HTTPError, e):
if e.code == 401:
PrintAndLog(u'Wrong VirusTotal key', 'ERROR')
else:
PrintAndLog(u'VirusTotal error '+str(e.code)+' '+str(e.reason).decode('utf-8'), 'ERROR')
Ret = json.loads(data)
Results = []
if type(Ret) is dict:
Results.append(Ret)
elif type(Ret) is list:
Results = Ret
for Entry in Results:
if Entry['response_code'] == 1:
if Entry['positives'] > 0:
PrintAndLog(Entry['md5'] + u' ' + Entry['scan_date'] + u' ' + str(Entry['positives']) + u'/' + str(Entry['total']), 'WARNING')
else:
PrintAndLog(Entry['md5'] + u' '+ Entry['scan_date'] +' '+ str(Entry['positives']) + u'/' + str(Entry['total']), 'INFO')
elif Entry['response_code'] == 0:
PrintAndLog(Entry['resource'] + u' Never seen 0/0', 'INFO')
else:
PrintAndLog(u'Got a weird answer from Virustotal\n', 'ERROR')
def LocalLookup(HashDBPath):
''' Perform of lookup in a local database '''
global LOCAL_HASHES_DB
PrintAndLog(u'Local hashes DB lookup', 'SECTION')
PrintAndLog(u'Got %s hashes to verify' % len(HASHES), 'DEBUG')
with open(HashDBPath, 'r') as f:
Data = f.readlines()
for Line in Data:
if Line[0] != '#':
Line = Line.split(' ')
LOCAL_HASHES_DB[Line[0]] = Line[1]
PrintAndLog(str(len(LOCAL_HASHES_DB)) + u' hashes loaded from the local hashes database', 'DEBUG')
for Hash in HASHES:
if Hash in LOCAL_HASHES_DB:
PrintAndLog(Hash + u' '+ LOCAL_HASHES_DB[Hash], 'WARNING')
def BigFileMd5(FilePath):
''' Return the md5 hash of a big file '''
Md5 = hashlib.md5()
try:
with open(FilePath, 'rb') as f:
for Chunk in iter(partial(f.read, 1048576), ''):
Md5.update(Chunk)
return Md5.hexdigest()
except:
PrintAndLog(u'Cannot hash ' + FilePath.decode('utf-8'), 'ERROR')
return False
def UniversalReadPlist(PlistPath):
''' Try to read a plist depending of the plateform and the available libs. Good luck Jim... '''
plistDictionary = False
if FOUNDATION_IS_IMPORTED:
plistNSData, errorMessage = Foundation.NSData.dataWithContentsOfFile_options_error_(PlistPath, Foundation.NSUncachedRead, None)
if errorMessage is not None or plistNSData is None:
PrintAndLog(u'Unable to read in the data from the plist file: ' + PlistPath.decode('utf-8'), 'ERROR')
plistDictionary, plistFormat, errorMessage = Foundation.NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(plistNSData, Foundation.NSPropertyListMutableContainers, None, None)
if errorMessage is not None or plistDictionary is None:
PrintAndLog(u'Unable to read in the data from the plist file: ' + PlistPath.decode('utf-8'), 'ERROR')
if not hasattr(plistDictionary, 'has_key'):
PrintAndLog(u'The plist does not have a dictionary as its root as expected: ' + PlistPath.decode('utf-8'), 'ERROR')
return plistDictionary
else:
if BIPLIST_IS_IMPORTED:
try:
plistDictionary = biplist.readPlist(PlistPath)
except (IOError):
PrintAndLog (u'Cannot open ' + PlistPath.decode('utf-8') , 'ERROR')
except:
PrintAndLog(u'Cannot parse ' + PlistPath.decode('utf-8') + u' (Binary or JSON plist may FAIL) \n', 'ERROR')
return plistDictionary
elif PLISTLIB_IS_IMPORTED:
try:
plistDictionary = plistlib.readPlist(PlistPath)
except (IOError):
PrintAndLog (u'Cannot open ' + PlistPath.decode('utf-8') , 'ERROR')
except:
PrintAndLog(u'Cannot parse ' + PlistPath.decode('utf-8') + u' (Binary or JSON plist may FAIL) \n', 'ERROR')
return plistDictionary
else:
PrintAndLog(u'Cannot parse ' + PlistPath.decode('utf-8') + u'. No plist lib available.\n', 'ERROR')
return None
def ParseQuarantines():
''' Parse users\' quarantines '''
PrintAndLog(u'Quarantines', 'SECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users/')):
if User[0] != '.':
PrintAndLog(User.decode('utf-8') +'\'s quarantine', 'SUBSECTION')
DbPathV2 = os.path.join(ROOT_PATH, 'Users', User, 'Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2') # OS X >= 10.7
DbPathV1 = os.path.join(ROOT_PATH, 'Users', User, 'Library/Preferences/com.apple.LaunchServices.QuarantineEvents') # OS X <= 10.6
if os.path.isfile(DbPathV2):
DbPath = DbPathV2
elif os.path.isfile(DbPathV1):
DbPath = DbPathV1
else:
PrintAndLog(u'No quarantined files for user ' + User.decode('utf-8') + u'\n', 'INFO')
continue
DbConnection = sqlite3.connect(DbPath)
DbCursor = DbConnection.cursor()
LSQuarantineEvents = DbCursor.execute('SELECT * from LSQuarantineEvent')
for LSQuarantineEvent in LSQuarantineEvents:
JointLSQuarantineEvent = u''
for Q in LSQuarantineEvent:
decoded = str(Q).decode('UTF-8', 'ignore')
JointLSQuarantineEvent += u';' + decoded
PrintAndLog(JointLSQuarantineEvent[1:] + u'\n'.decode('utf-8'), 'INFO')
DbConnection.close()
def ParseStartupItems(StartupItemsPath):
''' Parse the StartupItems plist and hash its program argument '''
StartupItemsPlist = False
NbStartupItems = 0
for StartupItems in os.listdir(StartupItemsPath):
StartupItemsPlistPath = os.path.join(StartupItemsPath, StartupItems, 'StartupParameters.plist')
PrintAndLog(StartupItemsPlistPath, 'DEBUG')
StartupItemsPlist = UniversalReadPlist(StartupItemsPlistPath)
if StartupItemsPlist:
if 'Provides' in StartupItemsPlist:
FilePath = os.path.join(StartupItemsPath, StartupItems, StartupItemsPlist['Provides'][0])
Md5 = BigFileMd5(FilePath)
if Md5:
if Md5 not in HASHES:
HASHES.append(Md5)
PrintAndLog(Md5 + u' '+ FilePath.decode('utf-8') + u' - ' + time.ctime(os.path.getmtime(FilePath)) + u' - ' + time.ctime(os.path.getctime(FilePath))+ u'\n', 'INFO')
NbStartupItems += 1
if NbStartupItems == 0:
PrintAndLog(StartupItemsPath.decode('utf-8') + u' is empty', 'INFO')
def ParseLaunchAgents(AgentsPath):
''' Parse a LanchAgent plist and hash its program argument. Also look for suspicious keywords in the plist itself '''
SuspiciousPlist = ['exec', 'socket' ,'open', 'connect', '/dev/tcp/', '/bin/sh']
LaunchAgentPlist = False
NbLaunchAgents = 0
for LaunchAgent in os.listdir(AgentsPath):
LaunchAgentPlistpath = os.path.join(AgentsPath, LaunchAgent)
PrintAndLog(LaunchAgentPlistpath, 'DEBUG')
LaunchAgentPlist = UniversalReadPlist(LaunchAgentPlistpath)
if LaunchAgentPlist:
if 'Program' in LaunchAgentPlist and 'Label' in LaunchAgentPlist:
FilePath = LaunchAgentPlist['Program']
Md5 = BigFileMd5(FilePath)
if Md5:
if Md5 not in HASHES:
HASHES.append(Md5)
PrintAndLog(Md5 + u' '+ FilePath.decode('utf-8') + u' - ' + time.ctime(os.path.getmtime(FilePath)) + u' - ' + time.ctime(os.path.getctime(FilePath)) + u'\n', 'INFO')
continue
if 'ProgramArguments' in LaunchAgentPlist and 'Label' in LaunchAgentPlist:
FilePath = LaunchAgentPlist['ProgramArguments'][0]
Md5 = BigFileMd5(FilePath)
if Md5:
if Md5 not in HASHES:
HASHES.append(Md5)
PrintAndLog(Md5 + u' '+ FilePath.decode('utf-8') + u' - ' + time.ctime(os.path.getctime(FilePath)) + u' - ' + time.ctime(os.path.getmtime(FilePath)) + u'\n', 'INFO')
if len(LaunchAgentPlist['ProgramArguments']) >= 3:
if any(x in LaunchAgentPlist['ProgramArguments'][2] for x in SuspiciousPlist):
PrintAndLog(LaunchAgentPlist['ProgramArguments'][2].decode('utf-8')+ u' in ' + LaunchAgentPlistpath.decode('utf-8') + u' looks suspicious', 'WARNING')
NbLaunchAgents += 1
if NbLaunchAgents == 0:
PrintAndLog(AgentsPath.decode('utf-8') + u' is empty', 'INFO')
def ParseStartup():
''' Parse the different LauchAgents and LaunchDaemons '''
PrintAndLog(u'Startup', 'SECTION')
PrintAndLog(u'System agents', 'SUBSECTION')
ParseLaunchAgents(os.path.join(ROOT_PATH, 'System/Library/LaunchAgents/'))
PrintAndLog(u'System daemons', 'SUBSECTION')
ParseLaunchAgents(os.path.join(ROOT_PATH, 'System/Library/LaunchDaemons/'))
PrintAndLog(u'Third party agents', 'SUBSECTION')
ParseLaunchAgents(os.path.join(ROOT_PATH, 'Library/LaunchAgents/'))
PrintAndLog(u'Third party daemons', 'SUBSECTION')
ParseLaunchAgents(os.path.join(ROOT_PATH, 'Library/LaunchDaemons/'))
PrintAndLog(u'System ScriptingAdditions', 'SUBSECTION')
ParsePackagesDir(os.path.join(ROOT_PATH, 'System/Library/ScriptingAdditions/'))
PrintAndLog(u'Third party ScriptingAdditions', 'SUBSECTION')
ParsePackagesDir(os.path.join(ROOT_PATH, 'Library/ScriptingAdditions/'))
# Parse the old and deprecated Startup Items
PrintAndLog(u'Deprecated system StartupItems', 'SUBSECTION')
ParseStartupItems(os.path.join(ROOT_PATH, 'System/Library/StartupItems/'))
PrintAndLog(u'Deprecated third party StartupItems', 'SUBSECTION')
ParseStartupItems(os.path.join(ROOT_PATH, 'Library/StartupItems/'))
PrintAndLog(u'Users\' agents', 'SUBSECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
UserLAPath = os.path.join(ROOT_PATH, 'Users', User, 'Library/LaunchAgents/')
if User[0] != '.' and os.path.isdir(UserLAPath):
PrintAndLog(User.decode('utf-8') + u'\'s agents', 'SUBSECTION')
ParseLaunchAgents(UserLAPath)
PrintAndLog(u'Users\' LoginItems', 'SUBSECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
LoginItemsPlistPath = os.path.join(ROOT_PATH, 'Users', User, 'Library/Preferences/com.apple.loginitems.plist')
if User[0] != '.' and os.path.isfile(LoginItemsPlistPath):
PrintAndLog(User + u'\'s LoginItems', 'SUBSECTION')
PrintAndLog(LoginItemsPlistPath, 'DEBUG')
LoginItemsPlist = UniversalReadPlist(LoginItemsPlistPath)
if LoginItemsPlist and 'SessionItems' in LoginItemsPlist:
CustomListItems = LoginItemsPlist['SessionItems']['CustomListItems']
for CustomListItem in CustomListItems:
PrintAndLog(CustomListItem['Name'].decode('utf-8') + u' - ' + binascii.hexlify(CustomListItem['Alias']).decode('hex').decode('utf-8', 'ignore'), 'INFO')
def HashDir(Title, Path):
''' Hash a direrctory and add the hashes'''
PrintAndLog(Title.decode('utf-8'), 'SUBSECTION')
NbFiles = 0
for Root, Dirs, Files in os.walk(Path):
for File in Files:
FilePath = os.path.join(Root, File)
Md5 = BigFileMd5(FilePath)
if Md5:
if Md5 not in HASHES:
HASHES.append(Md5)
PrintAndLog(Md5 +' '+ FilePath.decode('utf-8') + u' - ' + time.ctime(os.path.getmtime(FilePath)) + u' - ' + time.ctime(os.path.getctime(FilePath)) + u'\n', 'INFO')
NbFiles += 1
if NbFiles == 0:
PrintAndLog(Path.decode('utf-8') + u' is empty', 'INFO')
def ParseDownloads():
''' Hash all users\' downloaded files '''
PrintAndLog(u'Users\' downloads', 'SECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
if User[0] != '.':
DlUserPath = os.path.join(ROOT_PATH, 'Users', User, 'Downloads')
if os.path.isdir(DlUserPath):
HashDir(User + u'\'s downloads', DlUserPath)
else:
PrintAndLog(DlUserPath + u' does not exist', 'DEBUG')
OldEmailUserPath = os.path.join(ROOT_PATH, 'Users', User, 'Library/Mail Downloads/')
if os.path.isdir(OldEmailUserPath):
HashDir(User + u'\'s old email downloads', OldEmailUserPath)
else:
PrintAndLog(OldEmailUserPath + u' does not exist', 'DEBUG')
EmailUserPath = os.path.join(ROOT_PATH, 'Users', User, 'Library/Containers/com.apple.mail/Data/Library/Mail Downloads')
if os.path.isdir(EmailUserPath):
HashDir(User + u'\'s email downloads', EmailUserPath)
else:
PrintAndLog(EmailUserPath + u' does not exist', 'DEBUG')
def DumpSQLiteDb(SQLiteDbPath):
''' Dump a SQLite database file '''
PrintAndLog(SQLiteDbPath, 'DEBUG')
if os.path.isfile(SQLiteDbPath):
try:
DbConnection = sqlite3.connect(SQLiteDbPath)
DbCursor = DbConnection.cursor()
DbCursor.execute("SELECT * from sqlite_master WHERE type = 'table'")
Tables = DbCursor.fetchall()
for Table in Tables:
PrintAndLog(u'Table ' + Table[2].decode('utf-8'), 'DEBUG')
DbCursor.execute("SELECT * from " + Table[2])
Rows = DbCursor.fetchall()
if len(Rows) == 0:
PrintAndLog(u'Table ' + Table[2].decode('utf-8') + u' is empty', 'INFO')
else:
for Row in Rows:
PrintAndLog(str(Row).decode('utf-8') + u'\n', 'INFO_RAW')
DbConnection.close()
except Exception as e:
PrintAndLog(u'Error with ' + SQLiteDbPath.decode('utf-8') + u': ' + str(e.args).decode('utf-8'), 'ERROR')
else:
PrintAndLog(SQLiteDbPath.decode('utf-8') + u' not found\n', 'ERROR')
def ParseFirefoxProfile(User, Profile):
''' Parse the different SQLite databases in a Firefox profile '''
PrintAndLog(User + u'\'s Firefox profile (' + Profile.decode('utf-8') + u')', 'SUBSECTION')
#Most useful See http://kb.mozillazine.org/Profile_folder_-_Firefox
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'cookies.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'downloads.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'formhistory.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'places.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'signons.sqlite'))
#Secondary
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'permissions.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'addons.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'extensions.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'content-prefs.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'healthreport.sqlite'))
DumpSQLiteDb(os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles/', Profile, 'webappsstore.sqlite'))
def ParseFirefox():
''' Walk in all users' FireFox profiles and call ParseFirefoxProfile() '''
PrintAndLog(u'Users\' Firefox profiles', 'SUBSECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
UserFFProfilePath = os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Firefox/Profiles')
if User[0] != '.' and os.path.isdir(UserFFProfilePath):
PrintAndLog(User + u'\'s Firefox', 'SUBSECTION')
for Profile in os.listdir(UserFFProfilePath):
if Profile[0] != '.' and os.path.isdir(os.path.join(UserFFProfilePath, Profile)):
ParseFirefoxProfile(User, Profile)
def ParseSafariProfile(User, Path):
''' Parse the different plist and SQLite databases in a Safari profile '''
HistoryPlist = False
DownloadsPlist = False
NbFiles = 0
PrintAndLog(User + u'\'s Safari profile', 'SUBSECTION')
PrintAndLog(User + u'\'s Safari downloads', 'SUBSECTION')
DownloadsPlistPath = os.path.join(Path, 'Downloads.plist')
PrintAndLog(DownloadsPlistPath.decode('utf-8'), 'DEBUG')
DownloadsPlist = UniversalReadPlist(DownloadsPlistPath)
if DownloadsPlist:
if 'DownloadHistory' in DownloadsPlist:
Downloads = DownloadsPlist['DownloadHistory']
for DL in Downloads:
DlStr = u''
DlStr += DL['DownloadEntryURL'].decode('utf-8') + u' -> ' + DL['DownloadEntryPath'].decode('utf-8') + u' (' + DL['DownloadEntryIdentifier'].decode('utf-8') + u')\n'
PrintAndLog(DlStr, 'INFO')
PrintAndLog(User + u'\'s Safari history', 'SUBSECTION')
HistoryPlistPath = os.path.join(Path, 'History.plist')
PrintAndLog(HistoryPlistPath.decode('utf-8'), 'DEBUG')
HistoryPlist = UniversalReadPlist(HistoryPlistPath)
if HistoryPlist:
if 'WebHistoryDates' in HistoryPlist:
History = HistoryPlist['WebHistoryDates']
for H in History:
HStr = u''
if 'title' in H:
HStr += unicode(H['title']) + u' - '
if 'diplayTitle' in H:
HStr += unicode(H['diplayTitle']) + u' - '
HStr += unicode(H['']) + u'\n'
PrintAndLog(HStr, 'INFO')
PrintAndLog(User + u'\'s Safari TopSites', 'SUBSECTION')
TopSitesPlistPath = os.path.join(Path, 'TopSites.plist')
PrintAndLog(TopSitesPlistPath.decode('utf-8'), 'DEBUG')
TopSitesPlist = UniversalReadPlist(TopSitesPlistPath)
if TopSitesPlist:
if 'TopSites' in TopSitesPlist:
TopSites = TopSitesPlist['TopSites']
for T in TopSites:
TStr = u''
if 'TopSiteTitle' in T:
TStr += unicode(T['TopSiteTitle']) + u' - '
TStr += unicode(T['TopSiteURLString']) + u'\n'
PrintAndLog(TStr , 'INFO')
PrintAndLog(User + u'\'s Safari LastSession', 'SUBSECTION')
LastSessionPlistPath = os.path.join(Path, 'LastSession.plist')
PrintAndLog(LastSessionPlistPath.decode('utf-8'), 'DEBUG')
LastSessionPlist = UniversalReadPlist(LastSessionPlistPath)
if LastSessionPlist and 'SessionWindows' in LastSessionPlist:
try:
SessionWindows = LastSessionPlist['SessionWindows']
if len(SessionWindows) > 0:
TabStates = SessionWindows[0].get('TabStates', [])
if len(TabStates) > 0:
LastSession = TabStates[0]
PrintAndLog(LastSession.get('TabURL', '').decode('utf-8') + u' - ' + binascii.hexlify(LastSession['SessionState']).decode('hex').decode('utf-8', 'ignore'), 'INFO')
except:
PrintAndLog('EXCEPTION on LastSession for Safari !!! ', 'INFO')
PrintAndLog(User + u'\'s Safari databases', 'SUBSECTION')
NbFile = 0
if os.path.isfile(os.path.join(Path, 'Databases')):
for Db in os.listdir(os.path.join(Path, 'Databases')):
DumpSQLiteDb(os.path.join(Path, 'Databases', Db))
NbFiles += 1
if NbFiles == 0:
PrintAndLog(User + u'\'s Safari databases is empty', 'INFO')
NbFile = 0
PrintAndLog(User + u'\'s Safari LocalStorage', 'SUBSECTION')
if os.path.isfile(os.path.join(Path, 'LocalStorage')):
for Db in os.listdir(os.path.join(Path, 'LocalStorage')):
if os.path.isfile(os.path.join(Path, 'LocalStorage', Db)):
DumpSQLiteDb(os.path.join(Path, 'LocalStorage', Db))
NbFiles += 1
if NbFiles == 0:
PrintAndLog(User + u'\'s Safari LocalStorage is empty', 'INFO')
def ParseSafari():
PrintAndLog(u'Users\' Safari profiles', 'SUBSECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
UserSafariProfilePath = os.path.join(ROOT_PATH, 'Users', User, 'Library/Safari')
if User[0] != '.' and os.path.isdir(UserSafariProfilePath):
ParseSafariProfile(User, UserSafariProfilePath)
def ParseChromeProfile(User, Path):
''' Parse the different SQLite databases in a Chrome profile '''
NbFiles = 0
PrintAndLog(User + u'\'s Chrome profile', 'SUBSECTION')
PrintAndLog(User + u'\'s Chrome history', 'SUBSECTION')
DumpSQLiteDb(os.path.join(Path, 'History'))
PrintAndLog(User + u'\'s Chrome archived history', 'SUBSECTION')
DumpSQLiteDb(os.path.join(Path, 'Archived History'))
PrintAndLog(User + u'\'s Chrome cookies', 'SUBSECTION')
DumpSQLiteDb(os.path.join(Path, 'Cookies'))
PrintAndLog(User + u'\'s Chrome login data', 'SUBSECTION')
DumpSQLiteDb(os.path.join(Path, 'Login Data'))
PrintAndLog(User + u'\'s Chrome Top Sites', 'SUBSECTION')
DumpSQLiteDb(os.path.join(Path, 'Top Sites'))
PrintAndLog(User + u'\'s Chrome web data', 'SUBSECTION')
DumpSQLiteDb(os.path.join(Path, 'Web Data'))
PrintAndLog(User + u'\'s Chrome databases', 'SUBSECTION')
for Db in os.listdir(os.path.join(Path, 'databases')):
CurrentDbPath = os.path.join(Path, 'databases', Db)
if CurrentDbPath[-8:] != '-journal' and not os.path.isdir(CurrentDbPath):
DumpSQLiteDb(CurrentDbPath)
NbFiles += 1
if NbFiles == 0:
PrintAndLog(User + u'\'s Chrome databases is empty', 'INFO')
NbFiles = 0
PrintAndLog(User + u'\'s Chrome LocalStorage', 'SUBSECTION')
for Db in os.listdir(os.path.join(Path, 'Local Storage')):
CurrentDbPath = os.path.join(Path, 'Local Storage', Db)
if CurrentDbPath[-8:] != '-journal' and not os.path.isdir(CurrentDbPath):
DumpSQLiteDb(CurrentDbPath)
NbFiles += 1
if NbFiles == 0:
PrintAndLog(User + u'\'s Chrome LocalStorage is empty', 'INFO')
def ParseChrome():
''' Parse the different files in a Chrome profile '''
PrintAndLog(u'Users\' Chrome profiles', 'SUBSECTION')
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
UsersChromePath = os.path.join(ROOT_PATH, 'Users', User, 'Library/Application Support/Google/Chrome/Default')
if User[0] != '.' and os.path.isdir(UsersChromePath):
ParseChromeProfile(User, UsersChromePath)
def ParseBrowsers():
''' Call the different functions to parse the browsers '''
PrintAndLog(u'Browsers', 'SECTION')
ParseSafari()
ParseFirefox()
ParseChrome()
def ParsePackagesDir(PackagesDirPath):
''' Parse the packages in a directory '''
plistfile = 'Info.plist'
IgnoredFiles = ['.DS_Store', '.localized']
PackagePlistPath = ''
CFBundleExecutablepath = ''
NbPackages = 0
for PackagePath in os.listdir(PackagesDirPath):
if PackagePath not in IgnoredFiles:
if PackagePath[-4:] == '.app' or PackagePath[-5:] == '.kext':
if os.path.isfile(os.path.join(PackagesDirPath, PackagePath, plistfile)):
PackagePlistPath = os.path.join(PackagesDirPath, PackagePath, plistfile)
CFBundleExecutablepath = ''
elif os.path.isfile(os.path.join(PackagesDirPath, PackagePath, 'Contents', plistfile)):
PackagePlistPath = os.path.join(PackagesDirPath, PackagePath, 'Contents', plistfile)
CFBundleExecutablepath = 'Contents/MacOS/'
else:
PrintAndLog(os.path.join(PackagesDirPath, PackagePath).decode('utf-8'), 'DEBUG')
PrintAndLog(u'Cannot find any Info.plist in ' + PackagePath.decode('utf-8'), 'ERROR')
continue
PrintAndLog(os.path.join(PackagesDirPath, PackagePath).decode('utf-8'), 'DEBUG')
PackagePlist = UniversalReadPlist(PackagePlistPath)
if PackagePlist:
if 'CFBundleExecutable' in PackagePlist:
if PackagePlist['CFBundleExecutable'] != '':
FilePath = os.path.join(PackagesDirPath, PackagePath, CFBundleExecutablepath, PackagePlist['CFBundleExecutable'])
Md5 = BigFileMd5(FilePath)
if Md5:
if Md5 not in HASHES:
HASHES.append(Md5)
PrintAndLog(Md5 + u' '+ FilePath.decode('utf-8') + u' - ' + time.ctime(os.path.getmtime(FilePath)) + u' - ' + time.ctime(os.path.getctime(FilePath)) + u'\n', 'INFO')
else:
PrintAndLog(u'The CFBundleExecutable key in ' + PackagePlistPath.decode('utf-8') + u' is empty\n', 'ERROR')
else:
PrintAndLog(u'Cannot find the CFBundleExecutable key in ' + PackagePlistPath.decode('utf-8') + u'\n', 'ERROR')
NbPackages += 1
if os.path.isdir(os.path.join(PackagesDirPath, PackagePath)) and not os.path.islink(os.path.join(PackagesDirPath, PackagePath)):
ParsePackagesDir(os.path.join(PackagesDirPath, PackagePath))
else: continue
if NbPackages == 0:
PrintAndLog(PackagesDirPath.decode('utf-8') + u' is empty (no package found)', 'INFO')
def ParseKext():
''' Parse the Kernel extensions '''
PrintAndLog(u'Kernel extensions', 'SECTION')
ParsePackagesDir(os.path.join(ROOT_PATH, 'System/Library/Extensions/'))
def AggregateLogsDir(ZipHandle, LogDirPath):
''' Aggregate all logs found in a directory to a zipball '''
NbLogFiles = 0
for Root, Dirs, Files in os.walk(LogDirPath):
for File in Files:
FilePath = os.path.join(Root, File)
try:
ZipHandle.write(FilePath)
PrintAndLog(u'Log file ' + FilePath.decode('utf-8') + u' added to the logs zipball', 'INFO')
except:
PrintAndLog(FilePath.decode('utf-8') + u' aggregation FAILED', 'ERROR')
NbLogFiles += 1
if NbLogFiles == 0:
PrintAndLog(LogDirPath.decode('utf-8') + u' is empty', 'INFO')
def AggregateLogs(ZipLogsFile):
''' Walk in the different log directories to add all logs to a zipball '''
PrintAndLog(u'Log files aggregation', 'SECTION')
if not os.path.isdir(ZipLogsFile):
os.makedirs(ZipLogsFile)
ZipLogsFilePath = os.path.join(ZipLogsFile, 'OSXAuditor_report_' + HOSTNAME + '_' + time.strftime('%Y%m%d-%H%M%S', time.gmtime()) + '.zip')
PrintAndLog(u'All log files are aggregated in ' + ZipLogsFilePath.decode('utf-8'), 'DEBUG')
try:
with zipfile.ZipFile(ZipLogsFilePath, 'w') as ZipLogsFile:
PrintAndLog(os.path.join(ROOT_PATH, 'var/log').decode('utf-8') + u' files aggregation', 'SUBSECTION')
AggregateLogsDir(ZipLogsFile, os.path.join(ROOT_PATH, 'var/log'))
PrintAndLog(os.path.join(ROOT_PATH, 'Library/logs').decode('utf-8') + u' files aggregation', 'SUBSECTION')
AggregateLogsDir(ZipLogsFile, os.path.join(ROOT_PATH, 'Library/logs'))
for User in os.listdir(os.path.join(ROOT_PATH, 'Users')):
if User[0] != '.':
PrintAndLog(os.path.join(ROOT_PATH, 'Users', User, 'Library/logs').decode('utf-8') + u' files aggregation', 'SUBSECTION')
AggregateLogsDir(ZipLogsFile, os.path.join(ROOT_PATH, 'Users', User, 'Library/logs'))
except Exception as e:
PrintAndLog(u'Log files aggregation FAILED ' + str(e.args).decode('utf-8'), 'ERROR')
def GeomenaApiLocation(Ssid):
''' Perform a geolocation query on Geomena'''
NormalizedSsid = ''
Latitude = 'Not found'
Longitude = 'Not found'
Ssid = Ssid.split(':')
for i in Ssid:
if len(i) == 1:
i = '0'+i
NormalizedSsid += i
PrintAndLog(u'Geomena query for ' + ''.join(NormalizedSsid), 'DEBUG')
try:
F = urllib2.urlopen(GEOMENA_API_HOST + NormalizedSsid)
Data = F.read()
except urllib2.HTTPError as e:
PrintAndLog(u'Geomena API error ' + str(e.code) + ' ' + str(e.reason).decode('utf-8'), 'ERROR')
M = re.match('.+\sLatitude:\s([-\d\.]{1,19})\s.+\sLongitude:\s([-\d\.]{1,19})\s.+', Data, re.DOTALL)
if M:
Latitude = M.group(1)
Longitude = M.group(2)
return u'Latitude: ' + Latitude + u' Longitude: ' + Longitude
def ParseAirportPrefs():
''' Parse Airport preferences and try to extract geolocation information '''
global HTML_LOG_FILE
AirportPrefPlist = False
NbAirportPrefs = 0
PrintAndLog(u'Airport preferences', 'SECTION')
AirportPrefPlistPath = os.path.join(ROOT_PATH, 'Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist')
PrintAndLog(AirportPrefPlistPath, 'DEBUG')
AirportPrefPlist = UniversalReadPlist(AirportPrefPlistPath)
if AirportPrefPlist:
if 'KnownNetworks' in AirportPrefPlist:
KnownNetworks = AirportPrefPlist['KnownNetworks']
for KnownNetwork in KnownNetworks: #TODO: Add ChannelHistory
if GEOLOCATE_WIFI_AP:
Geolocation = GeomenaApiLocation(KnownNetworks[KnownNetwork]['SSIDString'])
else:
Geolocation = 'N/A (Geolocation disabled)'
print sys.getsizeof(KnownNetworks[KnownNetwork]['SSID'])
AirportPref = u'SSID: ' + KnownNetworks[KnownNetwork]['SSIDString'].decode('utf-8') + u' - SSID: ' + str(KnownNetworks[KnownNetwork]['SSID'])
if KnownNetworks[KnownNetwork]['LastConnected']:
AirportPref = AirportPref + u' - Last connected: '+ str(KnownNetworks[KnownNetwork]['LastConnected'])
AirportPref = AirportPref + u' - Security type: ' + KnownNetworks[KnownNetwork]['SecurityType'] + u' - Geolocation: ' + Geolocation
PrintAndLog(AirportPref, 'INFO')
NbAirportPrefs += 1
if NbAirportPrefs == 0:
PrintAndLog(AirportPrefPlistPath + u' is empty (no WiFi AP saved)', 'INFO')
def ParseMailAppAccount(MailAccountPlistPath):
''' Parse a Mail Account plist '''
MailAccountPlist = False
NbMailAccounts = 0
NbSmtpAccounts = 0
PrintAndLog(MailAccountPlistPath, 'DEBUG')
MailAccountPlist = UniversalReadPlist(MailAccountPlistPath)
if MailAccountPlist:
PrintAndLog(u'Email accounts', 'SUBSECTION')
if 'MailAccounts' in MailAccountPlist:
MailAccounts = MailAccountPlist['MailAccounts']
for MailAccount in MailAccounts:
MAccountPref = ''
if 'AccountName' in MailAccount:
MAccountPref = 'AccountName: ' + MailAccount['AccountName'] + ' - '
if 'AccountType' in MailAccount: MAccountPref += 'AccountType: ' + MailAccount['AccountType'] + ' - '
if 'SSLEnabled' in MailAccount: MAccountPref += 'SSLEnabled: ' + MailAccount['SSLEnabled'] + ' - '
if 'Username' in MailAccount: MAccountPref += 'Username: ' + MailAccount['Username'] + ' - '
if 'Hostname' in MailAccount: MAccountPref += 'Hostname: ' + MailAccount['Hostname'] + ' - '
if 'PortNumber' in MailAccount: MAccountPref += '(' + str(MailAccount['PortNumber']) + ') - '
if 'SMTPIdentifier' in MailAccount: MAccountPref += 'SMTPIdentifier: ' + MailAccount['SMTPIdentifier'] + ' - '
if 'EmailAddresses' in MailAccount:
for EmailAddresse in MailAccount['EmailAddresses']:
MAccountPref += 'EmailAddresse: ' + EmailAddresse + ' - '
PrintAndLog(MAccountPref.decode('utf-8'), 'INFO')
NbMailAccounts += 1
if NbMailAccounts == 0:
PrintAndLog(u'No email account)','INFO')
PrintAndLog(u'SMTP accounts', 'SUBSECTION')
if 'DeliveryAccounts' in MailAccountPlist:
DeliveryAccounts = MailAccountPlist['DeliveryAccounts']