-
Notifications
You must be signed in to change notification settings - Fork 105
/
psrecon.ps1
3198 lines (2984 loc) · 228 KB
/
psrecon.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
#requires -version 2.0
#==========================================#
# LogRhythm Labs #
# Incident Response Live Data Acquisition #
# greg . foss @ logrhythm . com #
# v0.2 -- October, 2015 #
#==========================================#
# Copyright 2015 LogRhythm Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at;
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
#=======================================================================================
# CONFIGURATION
#=======================================================================================
[CmdLetBinding()]
param(
[switch]$remote = $false,
[switch]$email = $false,
[switch]$share = $false,
[switch]$sendEmail = $false,
[switch]$lockdown = $false,
[switch]$adLock = $false,
[string]$target,
[string]$username,
[string]$password,
[string]$netShare,
[string]$smtpServer,
[string]$emailFrom,
[string]$emailTo,
[string]$companyName
)
#=======================================================================================
# PSRecon
#=======================================================================================
function Invoke-Recon {
$banner = @"
____ _____ ____
/ __ \/ ___// __ \___ _________ ____
/ /_/ /\__ \/ /_/ / _ \/ ___/ __ \/ __ \
/ ____/___/ / _, _/ __/ /__/ /_/ / / / /
/_/ /____/_/ |_|\___/\___/\____/_/ /_/
]]]]]]]]]]]]============>>>>>>>>>>-----+
"@
<#
.NAME
PSRecon
.SYNOPSIS
PowerShell Incident Response -- Live Data Acquisition Tool
.DESCRIPTION
This tool pulls data from a target Windows Vista or later systems where there is suspicious of misuse and/or infection. This will extract useful forensic data that will assist IR teams in gathering quick live data on a potentially compromised host.
.NOTES
This tool is designed to be executed from a LogRhythm SmartResponse(TM) on remote hosts via the LogRhythm agent, remotely using the LogRhythm SIEM, or locally/remotely as a standalone PowerShell script.
The safest way to run this script is locally, however remote execution is possible. Realize this will open the system up to additional risk...
.EXAMPLE
PS C:\> .\PSRecon.ps1
Simply run PSRecon on the local host.
This gathers default data and stores the results in the directory that the script was executed from.
.EXAMPLE
PS C:\> .\PSRecon.ps1 -remote -target [computer] [arguments - EX: -sendEmail -share -username -password]
Run PSRecon Remotely.
This gathers default data and stores the results in the script directory.
If you do not chose the [sendEmail] and/or [share] options all local evidence will be erased on the target.
Caveats:
You will need to ensure that psremoting and unsigned execution is enabled on the remote host. // dangerous to leave enabled!
Be careful, this may inadvertently expose administrative credentials when authenticating to a remote compromised host.
.EXAMPLE
PS C:\> .\PSRecon.ps1 -sendEmail -smtpServer ["127.0.0.1"] -emailTo ["greg.foss[at]logrhythm.com"] -emailFrom ["psrecon[at]logrhythm.com"]
[sendEmail] parameter allows the script to send the HTML report over SMTP.
[smtpServer] parameter sets the remote SMTP Server that will be used to forward reports.
[emailTo] parameter deifines the email recipient. Multiple recipients can be separated by commas.
[emailFrom] parameter defines the email sender.
.EXAMPLE
PS C:\> .\PSRecon.ps1 -share -netShare ["\\share\"] -Credential Get-Credential
[share] parameter allows the script to push evidence to a remote share or send the HTML report over SMTP.
[netShare] parameter defines the remote share. This should be manually tested with the credentials you will execute the script with.
Make sure to restrict pemrissions to this location and audit all access related to the folder!
.EXAMPLE
PS C:\> .\PSRecon.ps1 -lockdown -adLock [username]
[lockdown] parameter quarantine's the workstation. This disables the NIC's, locks the host and logs the user out.
[adLock] parameter disables the target username ID within Active Directory. A username must be provided...
.EXAMPLE
PS C:\> .\PSRecon.ps1 -email
[email] parameter extracts client email data (from / to / subject / email links).
.EXAMPLE
PS C:\> .\PSRecon.ps1 -username ["admin user"] -password ["pass"]
[username] parameter can be supplied on the command-line or hard-coded into the script.
[password] parameter can be supplied on the command-line or hard-coded into the script. // Bad idea...
These parameters are used when running PSRecon on remote hosts or interacting with Active Directory; not required for local execution.
If neither parameter is supplied, you will be prompted for credentials // safest option aside from local execution
.EXAMPLE
Remotely enable PSRemoting and Unrestricted PowerShell Execution then, run PSRecon.
First, enable PSRemoting
PS C:\> .\PsExec \\10.10.10.10 -u [admin account name] -p [admin account password] -h -d powershell.exe "Enable-PSRemoting -Force"
PS C:\> Test-WSMan 10.10.10.10
PS C:\> Enter-PSSession 10.10.10.10
[10.10.10.10]: PS C:\> Set-ExecutionPolicy Unrestricted -Force
[10.10.10.10]: PS C:\> Exit
PS C:\> .\PSRecon.ps1 -remote -target "10.10.10.10" -sendEmail -smtpServer "127.0.0.1" -emailTo "greg.foss[at]logrhythm.com" -emailFrom "psrecon[at]logrhythm.com"
.OUTPUTS
The script currently gathers the following data:
-ARP Table
-AT Jobs
-Anti Virus Engine(s) installed
-Capture Host Screenshot
-Command History
-DNS Cache
-Environment Variables
-Extract Internet Explorer history
-Extract Email History and Links
-Firewall Configuration
-GPSresult
-Hash Collected Evidence Files to Verify Authenticity
-Host File Information
-IP Address
-Netstat Information
-Last File Created
-List Open Shares
-Local PowerShell Scripts
-Logon Data
-PowerShell Versioning
-PowerShell Executable Hashes
-Process Information
-Prefetch Files
-Remote Desktop Sessions
-Running Services
-Scheduled Processes
-Scheduled Tasks
-Service Details
-Startup Information
-Startup Drivers
-USB Device History
-User and Admin Information
-Windows Patches
-Windows Version Information
#>
#=======================================================================================
# Prepare to Capture Live Host Data
#=======================================================================================
# Mask errors
$ErrorActionPreference= 'silentlycontinue'
# Check for Admin Rights
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
Write-Host 'You must run PSRecon from an elevated PowerShell session...'
Exit 1
}
# Enable Logging
New-EventLog -LogName Application -Source "PSRecon"
Write-EventLog -LogName Application -Source "PSRecon" -EntryType Information -EventId 1337 -Message "Forensic Data Acquisition Initiated"
# Define the Drive
$PSReconDir = $(get-location).path
Set-Location -Path $PSReconDir -PassThru > $null 2>&1
# Create directories
function dirs {
mkdir PSRecon\ > $null 2>&1
mkdir PSRecon\config\ > $null 2>&1
mkdir PSRecon\network\ > $null 2>&1
mkdir PSRecon\process\ > $null 2>&1
mkdir PSRecon\system\ > $null 2>&1
mkdir PSRecon\web\ > $null 2>&1
mkdir PSRecon\registry\ > $null 2>&1
}
$exists = "PSRecon_*\"
If (Test-Path $exists){
Remove-Item PSRecon_*\ -Recurse -Force
dirs
}Else{
dirs
}
#=======================================================================================
# Evidence Collection
#=======================================================================================
# Get user and admin info
$whoami = $env:username
qwinsta > PSRecon\config\activeUsers.html
$activeUsersA = type PSRecon\config\activeUsers.html
$activeUsers = $activeUsersA | foreach {$_ + "<br />"}
# Set environmental variables
$ip = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
$computerName = (gi env:\Computername).Value
$userDirectory = (gi env:\userprofile).value
$user = (gi env:\USERNAME).value
$date = Get-Date -format D
$dateString = Get-Date -format MM-dd-yyyy
$dateTime = Get-Date -Format MM/dd/yyyy-H:mm:ss
if (-Not ($companyName)) {
$companyName = "Proprietary / Confidential Not For Disclosure"
} Else {
$companyCheck = "^[a-zA-Z0-9\s+]+$"
if (-not ($companyName -match $companyCheck)) {
Write-Host 'Hey now...'
Write-EventLog -LogName Application -Source "PSRecon" -EntryType Information -EventId 34405 -Message "Possible Attack Detected via companyName parameter: $companyName"
Exit 1
}
$companyName = "Proprietary / Confidential to $companyName Not For Disclosure"
}
# Display banner and host data
$banner
Write-Host ""
Write-Host "$dateTime : Capturing Host Data : $computerName - $ip"
# Get IP Address Details
ipconfig -all | ConvertTo-Html -Fragment > PSRecon\config\ipconfig.html
$ipconfig = type PSRecon\config\ipconfig.html
# Gathering Scheduled Processes
at > PSRecon\process\at-jobs.html
$atA = get-content PSRecon\process\at-jobs.html
$at = $atA | foreach {$_ + "<br />"}
# Gathering list of Scheduled Tasks
$schtasks = Get-ScheduledTask | where state -EQ 'ready' | Get-ScheduledTaskInfo | Sort TaskPath |Select TaskName, TaskPath | ConvertTo-Html -Fragment
# Extract Installed Hotfix
$hotfix = get-hotfix | Where-Object {$_.Description -ne ''} | select Description,HotFixID,InstalledBy | ConvertTo-Html -Fragment
# Gathering Process Information
$taskDetail = tasklist /V /FO CSV | ConvertFrom-Csv | ConvertTo-Html -Fragment
# Gather Windows Service Data
Get-WmiObject win32_service | Select-Object Name, DisplayName, PathName, StartName, StartMode, State, TotalSessions, Description > PSRecon\process\service-detail.html
$serviceDetailA = get-content PSRecon\process\service-detail.html
$serviceDetail = $serviceDetailA | foreach {$_ + "<br />"}
# DNS Cache
$dnsCache = Get-DnsClientCache -Status 'Success' | Select Name, Data | ConvertTo-Html -Fragment
# Netstat information
$netstat = netstat -ant | select -skip 4 | ConvertFrom-String -PropertyNames none, proto,ipsrc,ipdst,state,state2,none,none | select ipsrc,ipdst,state | ConvertTo-Html -Fragment
# Display Listening Processes
$listeningProcesses = netstat -ano | findstr -i listening | ForEach-Object { $_ -split "\s+|\t+" } | findstr /r "^[1-9+]*$" | sort | unique | ForEach-Object { Get-Process -Id $_ } | Select ProcessName,Path,Company,Description | ConvertTo-Html -Fragment > PSRecon\network\net-processes.html
# ARP table
$arp = arp -a | select -skip 3 | ConvertFrom-String -PropertyNames none,IP,MAC,Type | Select IP,MAC,Type | ConvertTo-Html -Fragment
# Gathering information about running services
$netServices = Get-Service | where-object {$_.Status -eq "Running"} | Select Name, DisplayName | ConvertTo-Html -fragment
#Gathering information about open shares
net user > PSRecon\system\netuser.html
net use > PSRecon\network\shares.html
$netUserA = get-content PSRecon\system\netuser.html
$netUser = $netUserA | foreach {$_ + "<br />"}
$sharesA = get-content PSRecon\network\shares.html
$shares = $sharesA | foreach {$_ + "<br />"}
# Gathering host file information
$hosts = Import-Csv $env:windir\system32\drivers\etc\hosts | ConvertTo-Html -Fragment
$networks = Import-Csv $env:windir\system32\drivers\etc\networks | ConvertTo-Html -Fragment
# Gather Currently Installed Software
$software = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | ConvertTo-Html -Fragment > PSRecon\process\software.html
# List Recently Used USB Devices
$usb = Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\*\* | Select FriendlyName | ConvertTo-Html -Fragment > PSRecon\system\usb.html
# Gather command history
$commandHist = Get-History | ConvertTo-Html -Fragment
# Dumping the firewall information
echo "Firewall State" > PSRecon\system\firewall-config.html
netsh firewall show state >> PSRecon\system\firewall-config.html
echo "Firewall Config" >> PSRecon\system\firewall-config.html
netsh firewall show config >> PSRecon\system\firewall-config.html
echo "Firewall Dump" >> PSRecon\system\firewall-config.html
netsh dump >> PSRecon\system\firewall-config.html
$firewallA = get-content PSRecon\system\firewall-config.html
$firewall = $firewallA | foreach {$_ + "<br />"}
$firewall > PSRecon\system\firewall-config.html
# Saving the Environment
$set = Get-ChildItem ENV: | Select Name, Value | ConvertTo-Html -Fragment
# Return GPResult Output
& $env:windir\system32\gpresult.exe /v > PSRecon\system\gpresult.html
$gpresultA = get-content PSRecon\system\gpresult.html
$gpresult = $gpresultA | foreach {$_ + "<br />"}
# Get active SMB sessions
Get-SmbSession > PSRecon\network\smbsessions.html
$smbSessionA = get-content PSRecon\network\smbsessions.html
$smbSession = $smbSessionS | foreach {$_ + "<br />"}
# Get ACL's
$acl = Get-Acl | Select AccessToString, Owner, Group, Sddl | ConvertTo-Html -Fragment
# Gathering Windows version information
$version = [Environment]::OSVersion | ConvertTo-Html -Fragment
# Dumping the startup information
type $env:SystemDrive\autoexec.bat > PSRecon\system\autoexecBat.html 2>&1
type $env:SystemDrive\config.sys > PSRecon\system\configSys.html 2>&1
type $env:windir\win.ini > PSRecon\system\winIni.html 2>&1
type $env:windir\system.ini > PSRecon\system\systemIni.html 2>&1
$autoexecA = get-content PSRecon\system\autoexecBat.html
$autoexec = $autoexecA | foreach {$_ + "<br />"}
$configSysA = get-content PSRecon\system\configSys.html
$configSys = $ConfigSysA | foreach {$_ + "<br />"}
$winIniA = get-content PSRecon\system\winIni.html
$winIni = $winIniA | foreach {$_ + "<br />"}
$systemIniA = get-content PSRecon\system\systemIni.html
$systemIni = $systemIniA | foreach {$_ + "<br />"}
$psversiontable > PSRecon\config\powershell-version.html
$powershellVersionA = type PSRecon\config\powershell-version.html
$powershellVersion = $powershellVersionA | foreach {$_ + "<br />"}
# Startup Drivers
# Thanks Mark Vankempen!
$startupDrivers = reg query hklm\system\currentcontrolset\services /s | Select-String -pattern "^\s*?ImagePath.*?\.sys$"
$shadyDrivers = $startupDrivers | Select-String -pattern "^\s*?ImagePath.*?(user|temp).*?\\.*?\.(sys|exe)$"
$startupDrivers = $startupDrivers | ConvertTo-Html -Fragment
$shadyDrivers = $shadyDrivers | ConvertTo-Html -Fragment
$startupDrivers > PSRecon\registry\startup-drivers.html
# Registry: Run
$hklmRun = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run | ConvertTo-Html -as List -Fragment
$hkcuRun = Get-ItemProperty HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run | ConvertTo-Html -as List -Fragment
# Antivirus
$antiVirus = Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct | ConvertTo-Html -as List -Fragment
# list downloaded files
$downloads = dir C:\Users\*\Downloads\* -Recurse | Select Name, CreationTime, LastAccessTime, Attributes | ConvertTo-Html -Fragment > PSRecon\web\downloads.html
# Extract Prefetch File Listing
# script stolen from:
# https://github.com/davehull/Kansa/blob/master/Modules/Process/Get-PrefetchListing.ps1
$pfconf = (Get-ItemProperty "hklm:\system\currentcontrolset\control\session manager\memory management\prefetchparameters").EnablePrefetcher
Switch -Regex ($pfconf) {
"[1-3]" {
$o = "" | Select-Object FullName, CreationTimeUtc, LastAccessTimeUtc, LastWriteTimeUtc
ls $env:windir\Prefetch\*.pf | % {
$o.FullName = $_.FullName;
$o.CreationTimeUtc = Get-Date($_.CreationTimeUtc) -format o;
$o.LastAccesstimeUtc = Get-Date($_.LastAccessTimeUtc) -format o;
$o.LastWriteTimeUtc = Get-Date($_.LastWriteTimeUtc) -format o;
$o
} | ConvertTo-Html -Fragment >> PSRecon\process\prefetch.html
}
default {
echo "" >> PSRecon\process\prefetch.html
echo "Prefetch not enabled on ${env:COMPUTERNAME}" >> PSRecon\process\prefetch.html
echo "" >> PSRecon\process\prefetch.html
}
}
$prefetch = type PSRecon\process\prefetch.html
# Extract Internet Explorer History
# script stolen from:
# https://richardspowershellblog.wordpress.com/2011/06/29/ie-history-to-csv/
function get-iehistory {
[CmdletBinding()]
param ()
$shell = New-Object -ComObject Shell.Application
$hist = $shell.NameSpace(34)
$folder = $hist.Self
$hist.Items() |
foreach {
if ($_.IsFolder) {
$siteFolder = $_.GetFolder
$siteFolder.Items() |
foreach {
$site = $_
if ($site.IsFolder) {
$pageFolder = $site.GetFolder
$pageFolder.Items() |
foreach {
$visit = New-Object -TypeName PSObject -Property @{
Site = $($site.Name)
URL = $($pageFolder.GetDetailsOf($_,0))
Date = $( $pageFolder.GetDetailsOf($_,2))
}
$visit
}
}
}
}
}
}
get-iehistory | select Date, URL | ConvertTo-Html -Fragment > PSRecon\web\ie-history.html
$ieHistory = type PSRecon\web\ie-history.html
# Take a screenshot of the current desktop
# script stolen from:
# https://gallery.technet.microsoft.com/scriptcenter/eeff544a-f690-4f6b-a586-11eea6fc5eb8
Function Take-ScreenShot {
#Requires -Version 2
[cmdletbinding(
SupportsShouldProcess = $True,
DefaultParameterSetName = "screen",
ConfirmImpact = "low"
)]
Param (
[Parameter(
Mandatory = $False,
ParameterSetName = "screen",
ValueFromPipeline = $True)]
[switch]$screen,
[Parameter(
Mandatory = $False,
ParameterSetName = "window",
ValueFromPipeline = $False)]
[switch]$activewindow,
[Parameter(
Mandatory = $False,
ParameterSetName = "",
ValueFromPipeline = $False)]
[string]$file,
[Parameter(
Mandatory = $False,
ParameterSetName = "",
ValueFromPipeline = $False)]
[string]
[ValidateSet("bmp","jpeg","png")]
$imagetype = "bmp",
[Parameter(
Mandatory = $False,
ParameterSetName = "",
ValueFromPipeline = $False)]
[switch]$print
)
# C# code
$code = @'
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace ScreenShotDemo
{
/// <summary>
/// Provides functions to capture the entire screen, or a particular window, and save it to a file.
/// </summary>
public class ScreenCapture
{
/// <summary>
/// Creates an Image object containing a screen shot the active window
/// </summary>
/// <returns></returns>
public Image CaptureActiveWindow()
{
return CaptureWindow( User32.GetForegroundWindow() );
}
/// <summary>
/// Creates an Image object containing a screen shot of the entire desktop
/// </summary>
/// <returns></returns>
public Image CaptureScreen()
{
return CaptureWindow( User32.GetDesktopWindow() );
}
/// <summary>
/// Creates an Image object containing a screen shot of a specific window
/// </summary>
/// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
/// <returns></returns>
private Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle,ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest,hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle,hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}
/// <summary>
/// Captures a screen shot of the active window, and saves it to a file
/// </summary>
/// <param name="filename"></param>
/// <param name="format"></param>
public void CaptureActiveWindowToFile(string filename, ImageFormat format)
{
Image img = CaptureActiveWindow();
img.Save(filename,format);
}
/// <summary>
/// Captures a screen shot of the entire desktop, and saves it to a file
/// </summary>
/// <param name="filename"></param>
/// <param name="format"></param>
public void CaptureScreenToFile(string filename, ImageFormat format)
{
Image img = CaptureScreen();
img.Save(filename,format);
}
/// <summary>
/// Helper class containing Gdi32 API functions
/// </summary>
private class GDI32
{
public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
int nWidth,int nHeight,IntPtr hObjectSource,
int nXSrc,int nYSrc,int dwRop);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
}
/// <summary>
/// Helper class containing User32 API functions
/// </summary>
private class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
}
}
'@
#User Add-Type to import the code
add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing'
#Create the object for the Function
$capture = New-Object ScreenShotDemo.ScreenCapture
#Take screenshot of the entire screen
If ($Screen) {
Write-Verbose "Taking screenshot of entire desktop"
#Save to a file
If ($file) {
If ($file -eq "") {
$file = "$pwd\image.bmp"
}
Write-Verbose "Creating screen file: $file with imagetype of $imagetype"
$capture.CaptureScreenToFile($file,$imagetype)
}
ElseIf ($print) {
$img = $Capture.CaptureScreen()
$pd = New-Object System.Drawing.Printing.PrintDocument
$pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)})
$pd.Print()
}
Else {
$capture.CaptureScreen()
}
}
}
Take-ScreenShot -screen -file "c:\screenshot.png" -imagetype png
# convert the image to Base64 for inclusion in the HTML report
$path = "c:\screenshot.png"
$screenshot = [convert]::ToBase64String((get-content $path -encoding byte))
move $path .\PSRecon\config\screenshot.png
# Capture Log and Registry Data using cmdlets from Get-ComputerDetails
# Awesome cmdlets stolen from:
# https://raw.githubusercontent.com/clymb3r/PowerShell/master/Get-ComputerDetails/Get-ComputerDetails.ps1
if ( $remote -eq $true ) {
# I Suck at PowerShell, anyone know how to mitigate the memory issue so that Kansa cmdlets can run remotely?
$RDPconnections = "<p>Unfortunately his data cannot be pulled when PSRecon is run remotely<br />
Unless the shell memory is expanded...<br /><br />
The workaround is to set the Shell Memory Limit using the following command on the target host:<br />
PS C:\> Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 -force</p>"
$psscripts = "<p>Unfortunately his data cannot be pulled when PSRecon is run remotely<br />
Unless the shell memory is expanded...<br /><br />
The workaround is to set the Shell Memory Limit using the following command on the target host:<br />
PS C:\> Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 -force</p>"
$4624 = "<p>Unfortunately his data cannot be pulled when PSRecon is run remotely<br />
Unless the shell memory is expanded...<br /><br />
The workaround is to set the Shell Memory Limit using the following command on the target host:<br />
PS C:\> Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 -force</p>"
$4648 = "<p>Unfortunately his data cannot be pulled when PSRecon is run remotely<br />
Unless the shell memory is expanded...<br /><br />
The workaround is to set the Shell Memory Limit using the following command on the target host:<br />
PS C:\> Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 -force</p>"
} Else {
function Find-4648Logons
{
Param(
$SecurityLog
)
$ExplicitLogons = $SecurityLog | Where {$_.InstanceID -eq 4648}
$ReturnInfo = @{}
foreach ($ExplicitLogon in $ExplicitLogons)
{
$Subject = $false
$AccountWhosCredsUsed = $false
$TargetServer = $false
$SourceAccountName = ""
$SourceAccountDomain = ""
$TargetAccountName = ""
$TargetAccountDomain = ""
$TargetServer = ""
foreach ($line in $ExplicitLogon.Message -split "\r\n")
{
if ($line -cmatch "^Subject:$")
{
$Subject = $true
}
elseif ($line -cmatch "^Account\sWhose\sCredentials\sWere\sUsed:$")
{
$Subject = $false
$AccountWhosCredsUsed = $true
}
elseif ($line -cmatch "^Target\sServer:")
{
$AccountWhosCredsUsed = $false
$TargetServer = $true
}
elseif ($Subject -eq $true)
{
if ($line -cmatch "\s+Account\sName:\s+(\S.*)")
{
$SourceAccountName = $Matches[1]
}
elseif ($line -cmatch "\s+Account\sDomain:\s+(\S.*)")
{
$SourceAccountDomain = $Matches[1]
}
}
elseif ($AccountWhosCredsUsed -eq $true)
{
if ($line -cmatch "\s+Account\sName:\s+(\S.*)")
{
$TargetAccountName = $Matches[1]
}
elseif ($line -cmatch "\s+Account\sDomain:\s+(\S.*)")
{
$TargetAccountDomain = $Matches[1]
}
}
elseif ($TargetServer -eq $true)
{
if ($line -cmatch "\s+Target\sServer\sName:\s+(\S.*)")
{
$TargetServer = $Matches[1]
}
}
}
#Filter out logins that don't matter
if (-not ($TargetAccountName -cmatch "^DWM-.*" -and $TargetAccountDomain -cmatch "^Window\sManager$"))
{
$Key = $SourceAccountName + $SourceAccountDomain + $TargetAccountName + $TargetAccountDomain + $TargetServer
if (-not $ReturnInfo.ContainsKey($Key))
{
$Properties = @{
LogType = 4648
LogSource = "Security"
SourceAccountName = $SourceAccountName
SourceDomainName = $SourceAccountDomain
TargetAccountName = $TargetAccountName
TargetDomainName = $TargetAccountDomain
TargetServer = $TargetServer
Count = 1
Times = @($ExplicitLogon.TimeGenerated)
}
$ResultObj = New-Object PSObject -Property $Properties
$ReturnInfo.Add($Key, $ResultObj)
}
else
{
$ReturnInfo[$Key].Count++
$ReturnInfo[$Key].Times += ,$ExplicitLogon.TimeGenerated
}
}
}
return $ReturnInfo
}
function Find-4624Logons
{
Param (
$SecurityLog
)
$Logons = $SecurityLog | Where {$_.InstanceID -eq 4624}
$ReturnInfo = @{}
foreach ($Logon in $Logons)
{
$SubjectSection = $false
$NewLogonSection = $false
$NetworkInformationSection = $false
$AccountName = ""
$AccountDomain = ""
$LogonType = ""
$NewLogonAccountName = ""
$NewLogonAccountDomain = ""
$WorkstationName = ""
$SourceNetworkAddress = ""
$SourcePort = ""
foreach ($line in $Logon.Message -Split "\r\n")
{
if ($line -cmatch "^Subject:$")
{
$SubjectSection = $true
}
elseif ($line -cmatch "^Logon\sType:\s+(\S.*)")
{
$LogonType = $Matches[1]
}
elseif ($line -cmatch "^New\sLogon:$")
{
$SubjectSection = $false
$NewLogonSection = $true
}
elseif ($line -cmatch "^Network\sInformation:$")
{
$NewLogonSection = $false
$NetworkInformationSection = $true
}
elseif ($SubjectSection)
{
if ($line -cmatch "^\s+Account\sName:\s+(\S.*)")
{
$AccountName = $Matches[1]
}
elseif ($line -cmatch "^\s+Account\sDomain:\s+(\S.*)")
{
$AccountDomain = $Matches[1]
}
}
elseif ($NewLogonSection)
{
if ($line -cmatch "^\s+Account\sName:\s+(\S.*)")
{
$NewLogonAccountName = $Matches[1]
}
elseif ($line -cmatch "^\s+Account\sDomain:\s+(\S.*)")
{
$NewLogonAccountDomain = $Matches[1]
}
}
elseif ($NetworkInformationSection)
{
if ($line -cmatch "^\s+Workstation\sName:\s+(\S.*)")
{
$WorkstationName = $Matches[1]
}
elseif ($line -cmatch "^\s+Source\sNetwork\sAddress:\s+(\S.*)")
{
$SourceNetworkAddress = $Matches[1]
}
elseif ($line -cmatch "^\s+Source\sPort:\s+(\S.*)")
{
$SourcePort = $Matches[1]
}
}
}
#Filter out logins that don't matter
if (-not ($NewLogonAccountDomain -cmatch "NT\sAUTHORITY" -or $NewLogonAccountDomain -cmatch "Window\sManager"))
{
$Key = $AccountName + $AccountDomain + $NewLogonAccountName + $NewLogonAccountDomain + $LogonType + $WorkstationName + $SourceNetworkAddress + $SourcePort
if (-not $ReturnInfo.ContainsKey($Key))
{
$Properties = @{
LogType = 4624
LogSource = "Security"
SourceAccountName = $AccountName
SourceDomainName = $AccountDomain
NewLogonAccountName = $NewLogonAccountName
NewLogonAccountDomain = $NewLogonAccountDomain
LogonType = $LogonType
WorkstationName = $WorkstationName
SourceNetworkAddress = $SourceNetworkAddress
SourcePort = $SourcePort
Count = 1
Times = @($Logon.TimeGenerated)
}
$ResultObj = New-Object PSObject -Property $Properties
$ReturnInfo.Add($Key, $ResultObj)
}
else
{
$ReturnInfo[$Key].Count++
$ReturnInfo[$Key].Times += ,$Logon.TimeGenerated
}
}
}
return $ReturnInfo
}
Function Find-PSScriptsInPSAppLog {
$ReturnInfo = @{}
$Logs = Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -FilterXPath "*[System[EventID=4100]]" -ErrorAction SilentlyContinue
foreach ($Log in $Logs)
{
$ContainsScriptName = $false
$LogDetails = $Log.Message -split "`r`n"
$FoundScriptName = $false
foreach($Line in $LogDetails)
{
if ($Line -imatch "^\s*Script\sName\s=\s(.+)")
{
$ScriptName = $Matches[1]
$FoundScriptName = $true
}
elseif ($Line -imatch "^\s*User\s=\s(.*)")
{
$User = $Matches[1]
}
}
if ($FoundScriptName)
{
$Key = $ScriptName + "::::" + $User
if (!$ReturnInfo.ContainsKey($Key))
{
$Properties = @{
ScriptName = $ScriptName
UserName = $User
Count = 1
Times = @($Log.TimeCreated)
}
$Item = New-Object PSObject -Property $Properties
$ReturnInfo.Add($Key, $Item)
}
else
{
$ReturnInfo[$Key].Count++
$ReturnInfo[$Key].Times += ,$Log.TimeCreated
}
}
}
return $ReturnInfo
}
Function Find-RDPClientConnections {
$ReturnInfo = @{}
New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS | Out-Null
#Attempt to enumerate the servers for all users
$Users = Get-ChildItem -Path "HKU:\"
foreach ($UserSid in $Users.PSChildName)
{
$Servers = Get-ChildItem "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers" -ErrorAction SilentlyContinue
foreach ($Server in $Servers)
{
$Server = $Server.PSChildName
$UsernameHint = (Get-ItemProperty -Path "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers\$($Server)").UsernameHint
$Key = $UserSid + "::::" + $Server + "::::" + $UsernameHint
if (!$ReturnInfo.ContainsKey($Key))
{
$SIDObj = New-Object System.Security.Principal.SecurityIdentifier($UserSid)
$User = ($SIDObj.Translate([System.Security.Principal.NTAccount])).Value
$Properties = @{
CurrentUser = $User
Server = $Server
UsernameHint = $UsernameHint
}
$Item = New-Object PSObject -Property $Properties
$ReturnInfo.Add($Key, $Item)
}
}
}
return $ReturnInfo
}
# Extract data from Get-ComputerDetails suite of cmdlets
Find-RDPClientConnections | Format-List > PSRecon\registry\RDPconnections.html
$RDPconnectionsA = Get-Content PSRecon\registry\RDPconnections.html
$RDPconnections = $RDPconnectionsA | foreach {$_ + "<br />"}
Find-PSScriptsInPSAppLog | Format-List > PSRecon\registry\psscripts.html
$psscriptsA = Get-Content PSRecon\registry\psscripts.html
$psscripts = $psscriptsA | foreach {$_ + "<br />"}
$SecurityLog = Get-EventLog -LogName Security
Find-4624Logons $SecurityLog | Format-List > PSRecon\registry\4624logons.html
$4624A = Get-Content PSRecon\registry\4624logons.html
$4624 = $4624A | foreach {$_ + "<br />"}
Find-4648Logons $SecurityLog | Format-List > PSRecon\registry\4648logons.html
$4648A = Get-Content PSRecon\registry\4648logons.html
$4648 = $4648A | foreach {$_ + "<br />"}
#>
}
# Extract Email Details
if(-Not ($email)) {
echo "<p><strong>emails not extracted...</strong><br /><br />" >> PSRecon\web\email-subjects.html
echo " To extract emails, run PSRecon with the [email] command-line switch:<br /><br />" >> PSRecon\web\email-subjects.html
echo " PS C:\> .\PSRecon.ps1 -email" >> PSRecon\web\email-subjects.html
echo "<br /><br />" >> PSRecon\web\email-subjects.html
echo " This was skipped because email extraction takes a very long time.<br />" >> PSRecon\web\email-subjects.html
echo " This also closes the user's email client and tends to leave the Outlook process hanging...</strong></p><br />" >> PSRecon\web\email-subjects.html
copy PSRecon\web\email-subjects.html PSRecon\web\email-links.html
$emailSubjects = get-content PSRecon\web\email-subjects.html
$emailLinks = get-content PSRecon\web\email-links.html
} else {
if ($email -eq $true) {
# Close outlook, so we can extract the emails
Get-Process OUTLOOK | Foreach-Object { $_.CloseMainWindow() | Out-Null } | stop-process force > $null 2>&1
Write-Host "Extracting emails... This may take a few minutes!"
Function Get-OutlookInBox {
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
$folder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$folder.items |
Select-Object -Property * -Last 50
}
$inbox = Get-OutlookInBox
$inbox | Select-Object -Property SenderName, Subject, ReceivedTime > PSRecon\web\email-subjects.html
$inbox | Select Body | findstr http > PSRecon\web\email-links.html