From 59e6f94e763d40614284d43823a391cafd384c4c Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 18:50:58 -0500 Subject: For ./ScriptModification/ : -PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- ScriptModification/Out-CompressedDll.ps1 | 20 ++-- ScriptModification/Out-EncodedCommand.ps1 | 19 ++-- ScriptModification/Out-EncryptedScript.ps1 | 42 ++++---- ScriptModification/Remove-Comment.ps1 | 158 +++++++++++++++++++++++++++++ ScriptModification/Remove-Comments.ps1 | 156 ---------------------------- ScriptModification/ScriptModification.psd1 | 2 +- 6 files changed, 204 insertions(+), 193 deletions(-) create mode 100644 ScriptModification/Remove-Comment.ps1 delete mode 100644 ScriptModification/Remove-Comments.ps1 (limited to 'ScriptModification') diff --git a/ScriptModification/Out-CompressedDll.ps1 b/ScriptModification/Out-CompressedDll.ps1 index 5e6897d..8608956 100644 --- a/ScriptModification/Out-CompressedDll.ps1 +++ b/ScriptModification/Out-CompressedDll.ps1 @@ -5,12 +5,12 @@ function Out-CompressedDll Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory. -PowerSploit Function: Out-CompressedDll -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None - +PowerSploit Function: Out-CompressedDll +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + .DESCRIPTION Out-CompressedDll outputs code that loads a compressed representation of a managed dll in memory as a byte array. @@ -21,7 +21,7 @@ Specifies the path to a managed executable. .EXAMPLE -C:\PS> Out-CompressedDll -FilePath evil.dll +Out-CompressedDll -FilePath evil.dll Description ----------- @@ -36,7 +36,9 @@ Only pure MSIL-based dlls can be loaded using this technique. Native or IJW ('it http://www.exploit-monday.com/2012/12/in-memory-dll-loading.html #> - [CmdletBinding()] Param ( + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [CmdletBinding()] + Param ( [Parameter(Mandatory = $True)] [String] $FilePath @@ -51,7 +53,7 @@ http://www.exploit-monday.com/2012/12/in-memory-dll-loading.html $FileBytes = [System.IO.File]::ReadAllBytes($Path) - if (($FileBytes[0..1] | % {[Char]$_}) -join '' -cne 'MZ') + if (($FileBytes[0..1] | ForEach-Object {[Char]$_}) -join '' -cne 'MZ') { Throw "$Path is not a valid executable." } diff --git a/ScriptModification/Out-EncodedCommand.ps1 b/ScriptModification/Out-EncodedCommand.ps1 index 04e8c12..6f21391 100644 --- a/ScriptModification/Out-EncodedCommand.ps1 +++ b/ScriptModification/Out-EncodedCommand.ps1 @@ -5,12 +5,12 @@ function Out-EncodedCommand Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. -PowerSploit Function: Out-EncodedCommand -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None - +PowerSploit Function: Out-EncodedCommand +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + .DESCRIPTION Out-EncodedCommand prepares a PowerShell script such that it can be pasted into a command prompt. The scenario for using this tool is the following: You compromise a machine, have a shell and want to execute a PowerShell script as a payload. This technique eliminates the need for an interactive PowerShell 'shell' and it bypasses any PowerShell execution policies. @@ -49,13 +49,13 @@ Base-64 encodes the entirety of the output. This is usually unnecessary and effe .EXAMPLE -C:\PS> Out-EncodedCommand -ScriptBlock {Write-Host 'hello, world!'} +Out-EncodedCommand -ScriptBlock {Write-Host 'hello, world!'} powershell -C sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String('Cy/KLEnV9cgvLlFQz0jNycnXUSjPL8pJUVQHAA=='),[IO.Compression.CompressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() .EXAMPLE -C:\PS> Out-EncodedCommand -Path C:\EvilPayload.ps1 -NonInteractive -NoProfile -WindowStyle Hidden -EncodedOutput +Out-EncodedCommand -Path C:\EvilPayload.ps1 -NonInteractive -NoProfile -WindowStyle Hidden -EncodedOutput powershell -NoP -NonI -W Hidden -E cwBhAGwAIABhACAATgBlAHcALQBPAGIAagBlAGMAdAA7AGkAZQB4ACgAYQAgAEkATwAuAFMAdAByAGUAYQBtAFIAZQBhAGQAZQByACgAKABhACAASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4ARABlAGYAbABhAHQAZQBTAHQAcgBlAGEAbQAoAFsASQBPAC4ATQBlAG0AbwByAHkAUwB0AHIAZQBhAG0AXQBbAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACcATABjAGkAeABDAHMASQB3AEUAQQBEAFEAWAAzAEUASQBWAEkAYwBtAEwAaQA1AEsAawBGAEsARQA2AGwAQgBCAFIAWABDADgAaABLAE8ATgBwAEwAawBRAEwANAAzACsAdgBRAGgAdQBqAHkAZABBADkAMQBqAHEAcwAzAG0AaQA1AFUAWABkADAAdgBUAG4ATQBUAEMAbQBnAEgAeAA0AFIAMAA4AEoAawAyAHgAaQA5AE0ANABDAE8AdwBvADcAQQBmAEwAdQBYAHMANQA0ADEATwBLAFcATQB2ADYAaQBoADkAawBOAHcATABpAHMAUgB1AGEANABWAGEAcQBVAEkAagArAFUATwBSAHUAVQBsAGkAWgBWAGcATwAyADQAbgB6AFYAMQB3ACsAWgA2AGUAbAB5ADYAWgBsADIAdAB2AGcAPQA9ACcAKQAsAFsASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAE0AbwBkAGUAXQA6ADoARABlAGMAbwBtAHAAcgBlAHMAcwApACkALABbAFQAZQB4AHQALgBFAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkAKQAuAFIAZQBhAGQAVABvAEUAbgBkACgAKQA= @@ -72,7 +72,8 @@ This cmdlet was inspired by the createcmd.ps1 script introduced during Dave Kenn http://www.exploit-monday.com #> - [CmdletBinding( DefaultParameterSetName = 'FilePath')] Param ( + [CmdletBinding( DefaultParameterSetName = 'FilePath')] + Param ( [Parameter(Position = 0, ValueFromPipeline = $True, ParameterSetName = 'ScriptBlock' )] [ValidateNotNullOrEmpty()] [ScriptBlock] diff --git a/ScriptModification/Out-EncryptedScript.ps1 b/ScriptModification/Out-EncryptedScript.ps1 index eba48f7..c24b126 100644 --- a/ScriptModification/Out-EncryptedScript.ps1 +++ b/ScriptModification/Out-EncryptedScript.ps1 @@ -5,11 +5,11 @@ function Out-EncryptedScript Encrypts text files/scripts. -PowerSploit Function: Out-EncryptedScript -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None +PowerSploit Function: Out-EncryptedScript +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None .DESCRIPTION @@ -36,7 +36,8 @@ is randomly generated by default. .EXAMPLE -C:\PS> Out-EncryptedScript .\Naughty-Script.ps1 password salty +$Password = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +Out-EncryptedScript .\Naughty-Script.ps1 $Password salty Description ----------- @@ -48,10 +49,10 @@ function 'de' and the base64-encoded ciphertext. .EXAMPLE -C:\PS> [String] $cmd = Get-Content .\evil.ps1 -C:\PS> Invoke-Expression $cmd -C:\PS> $decrypted = de password salt -C:\PS> Invoke-Expression $decrypted +[String] $cmd = Get-Content .\evil.ps1 +Invoke-Expression $cmd +$decrypted = de password salt +Invoke-Expression $decrypted Description ----------- @@ -64,34 +65,39 @@ unencrypted script is called via Invoke-Expression This command can be used to encrypt any text-based file/script #> - [CmdletBinding()] Param ( + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [CmdletBinding()] + Param ( [Parameter(Position = 0, Mandatory = $True)] [String] $ScriptPath, - + [Parameter(Position = 1, Mandatory = $True)] - [String] + [Security.SecureString] $Password, - + [Parameter(Position = 2, Mandatory = $True)] [String] $Salt, - + [Parameter(Position = 3)] [ValidateLength(16, 16)] [String] - $InitializationVector = ((1..16 | % {[Char](Get-Random -Min 0x41 -Max 0x5B)}) -join ''), - + $InitializationVector = ((1..16 | ForEach-Object {[Char](Get-Random -Min 0x41 -Max 0x5B)}) -join ''), + [Parameter(Position = 4)] [String] $FilePath = '.\evil.ps1' ) + $TempCred = New-Object System.Management.Automation.PSCredential('a', $Password) + $PlaintextPassword = $TempCred.GetNetworkCredential().Password + $AsciiEncoder = New-Object System.Text.ASCIIEncoding $ivBytes = $AsciiEncoder.GetBytes($InitializationVector) # While this can be used to encrypt any file, it's primarily designed to encrypt itself. [Byte[]] $scriptBytes = Get-Content -Encoding Byte -ReadCount 0 -Path $ScriptPath - $DerivedPass = New-Object System.Security.Cryptography.PasswordDeriveBytes($Password, $AsciiEncoder.GetBytes($Salt), "SHA1", 2) + $DerivedPass = New-Object System.Security.Cryptography.PasswordDeriveBytes($PlaintextPassword, $AsciiEncoder.GetBytes($Salt), "SHA1", 2) $Key = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider $Key.Mode = [System.Security.Cryptography.CipherMode]::CBC [Byte[]] $KeyBytes = $DerivedPass.GetBytes(16) diff --git a/ScriptModification/Remove-Comment.ps1 b/ScriptModification/Remove-Comment.ps1 new file mode 100644 index 0000000..6194419 --- /dev/null +++ b/ScriptModification/Remove-Comment.ps1 @@ -0,0 +1,158 @@ +function Remove-Comment +{ +<# +.SYNOPSIS + +Strips comments and extra whitespace from a script. + +PowerSploit Function: Remove-Comment +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + +.DESCRIPTION + +Remove-Comment strips out comments and unnecessary whitespace from a script. This is best used in conjunction with Out-EncodedCommand when the size of the script to be encoded might be too big. + +A major portion of this code was taken from the Lee Holmes' Show-ColorizedContent script. You rock, Lee! + +.PARAMETER ScriptBlock + +Specifies a scriptblock containing your script. + +.PARAMETER Path + +Specifies the path to your script. + +.EXAMPLE + +$Stripped = Remove-Comment -Path .\ScriptWithComments.ps1 + +.EXAMPLE + +Remove-Comment -ScriptBlock { +### This is my awesome script. My documentation is beyond reproach! + Write-Host 'Hello, World!' ### Write 'Hello, World' to the host +### End script awesomeness +} + +Write-Host 'Hello, World!' + +.EXAMPLE + +Remove-Comment -Path Inject-Shellcode.ps1 | Out-EncodedCommand + +Description +----------- +Removes extraneous whitespace and comments from Inject-Shellcode (which is notoriously large) and pipes the output to Out-EncodedCommand. + +.INPUTS + +System.String, System.Management.Automation.ScriptBlock + +Accepts either a string containing the path to a script or a scriptblock. + +.OUTPUTS + +System.Management.Automation.ScriptBlock + +Remove-Comment returns a scriptblock. Call the ToString method to convert a scriptblock to a string, if desired. + +.LINK + +http://www.exploit-monday.com +http://www.leeholmes.com/blog/2007/11/07/syntax-highlighting-in-powershell/ +#> + + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] + [CmdletBinding( DefaultParameterSetName = 'FilePath' )] + Param ( + [Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'FilePath' )] + [ValidateNotNullOrEmpty()] + [String] + $Path, + + [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $True, ParameterSetName = 'ScriptBlock' )] + [ValidateNotNullOrEmpty()] + [ScriptBlock] + $ScriptBlock + ) + + Set-StrictMode -Version 2 + + if ($PSBoundParameters['Path']) + { + Get-ChildItem $Path -ErrorAction Stop | Out-Null + $ScriptBlockString = [IO.File]::ReadAllText((Resolve-Path $Path)) + $ScriptBlock = [ScriptBlock]::Create($ScriptBlockString) + } + else + { + # Convert the scriptblock to a string so that it can be referenced with array notation + $ScriptBlockString = $ScriptBlock.ToString() + } + + # Tokenize the scriptblock and return all tokens except for comments + $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptBlock, [Ref] $Null) | Where-Object { $_.Type -ne 'Comment' } + + $StringBuilder = New-Object Text.StringBuilder + + # The majority of the remaining code comes from Lee Holmes' Show-ColorizedContent script. + $CurrentColumn = 1 + $NewlineCount = 0 + foreach($CurrentToken in $Tokens) + { + # Now output the token + if(($CurrentToken.Type -eq 'NewLine') -or ($CurrentToken.Type -eq 'LineContinuation')) + { + $CurrentColumn = 1 + # Only insert a single newline. Sequential newlines are ignored in order to save space. + if ($NewlineCount -eq 0) + { + $StringBuilder.AppendLine() | Out-Null + } + $NewlineCount++ + } + else + { + $NewlineCount = 0 + + # Do any indenting + if($CurrentColumn -lt $CurrentToken.StartColumn) + { + # Insert a single space in between tokens on the same line. Extraneous whiltespace is ignored. + if ($CurrentColumn -ne 1) + { + $StringBuilder.Append(' ') | Out-Null + } + } + + # See where the token ends + $CurrentTokenEnd = $CurrentToken.Start + $CurrentToken.Length - 1 + + # Handle the line numbering for multi-line strings + if(($CurrentToken.Type -eq 'String') -and ($CurrentToken.EndLine -gt $CurrentToken.StartLine)) + { + $LineCounter = $CurrentToken.StartLine + $StringLines = $(-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd] -split '`r`n') + + foreach($StringLine in $StringLines) + { + $StringBuilder.Append($StringLine) | Out-Null + $LineCounter++ + } + } + # Write out a regular token + else + { + $StringBuilder.Append((-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd])) | Out-Null + } + + # Update our position in the column + $CurrentColumn = $CurrentToken.EndColumn + } + } + + Write-Output ([ScriptBlock]::Create($StringBuilder.ToString())) +} diff --git a/ScriptModification/Remove-Comments.ps1 b/ScriptModification/Remove-Comments.ps1 deleted file mode 100644 index 45a9746..0000000 --- a/ScriptModification/Remove-Comments.ps1 +++ /dev/null @@ -1,156 +0,0 @@ -function Remove-Comments -{ -<# -.SYNOPSIS - -Strips comments and extra whitespace from a script. - -PowerSploit Function: Remove-Comments -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None - -.DESCRIPTION - -Remove-Comments strips out comments and unnecessary whitespace from a script. This is best used in conjunction with Out-EncodedCommand when the size of the script to be encoded might be too big. - -A major portion of this code was taken from the Lee Holmes' Show-ColorizedContent script. You rock, Lee! - -.PARAMETER ScriptBlock - -Specifies a scriptblock containing your script. - -.PARAMETER Path - -Specifies the path to your script. - -.EXAMPLE - -C:\PS> $Stripped = Remove-Comments -Path .\ScriptWithComments.ps1 - -.EXAMPLE - -C:\PS> Remove-Comments -ScriptBlock { -### This is my awesome script. My documentation is beyond reproach! - Write-Host 'Hello, World!' ### Write 'Hello, World' to the host -### End script awesomeness -} - -Write-Host 'Hello, World!' - -.EXAMPLE - -C:\PS> Remove-Comments -Path Inject-Shellcode.ps1 | Out-EncodedCommand - -Description ------------ -Removes extraneous whitespace and comments from Inject-Shellcode (which is notoriously large) and pipes the output to Out-EncodedCommand. - -.INPUTS - -System.String, System.Management.Automation.ScriptBlock - -Accepts either a string containing the path to a script or a scriptblock. - -.OUTPUTS - -System.Management.Automation.ScriptBlock - -Remove-Comments returns a scriptblock. Call the ToString method to convert a scriptblock to a string, if desired. - -.LINK - -http://www.exploit-monday.com -http://www.leeholmes.com/blog/2007/11/07/syntax-highlighting-in-powershell/ -#> - - [CmdletBinding( DefaultParameterSetName = 'FilePath' )] Param ( - [Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'FilePath' )] - [ValidateNotNullOrEmpty()] - [String] - $Path, - - [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $True, ParameterSetName = 'ScriptBlock' )] - [ValidateNotNullOrEmpty()] - [ScriptBlock] - $ScriptBlock - ) - - Set-StrictMode -Version 2 - - if ($PSBoundParameters['Path']) - { - Get-ChildItem $Path -ErrorAction Stop | Out-Null - $ScriptBlockString = [IO.File]::ReadAllText((Resolve-Path $Path)) - $ScriptBlock = [ScriptBlock]::Create($ScriptBlockString) - } - else - { - # Convert the scriptblock to a string so that it can be referenced with array notation - $ScriptBlockString = $ScriptBlock.ToString() - } - - # Tokenize the scriptblock and return all tokens except for comments - $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptBlock, [Ref] $Null) | Where-Object { $_.Type -ne 'Comment' } - - $StringBuilder = New-Object Text.StringBuilder - - # The majority of the remaining code comes from Lee Holmes' Show-ColorizedContent script. - $CurrentColumn = 1 - $NewlineCount = 0 - foreach($CurrentToken in $Tokens) - { - # Now output the token - if(($CurrentToken.Type -eq 'NewLine') -or ($CurrentToken.Type -eq 'LineContinuation')) - { - $CurrentColumn = 1 - # Only insert a single newline. Sequential newlines are ignored in order to save space. - if ($NewlineCount -eq 0) - { - $StringBuilder.AppendLine() | Out-Null - } - $NewlineCount++ - } - else - { - $NewlineCount = 0 - - # Do any indenting - if($CurrentColumn -lt $CurrentToken.StartColumn) - { - # Insert a single space in between tokens on the same line. Extraneous whiltespace is ignored. - if ($CurrentColumn -ne 1) - { - $StringBuilder.Append(' ') | Out-Null - } - } - - # See where the token ends - $CurrentTokenEnd = $CurrentToken.Start + $CurrentToken.Length - 1 - - # Handle the line numbering for multi-line strings - if(($CurrentToken.Type -eq 'String') -and ($CurrentToken.EndLine -gt $CurrentToken.StartLine)) - { - $LineCounter = $CurrentToken.StartLine - $StringLines = $(-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd] -split '`r`n') - - foreach($StringLine in $StringLines) - { - $StringBuilder.Append($StringLine) | Out-Null - $LineCounter++ - } - } - # Write out a regular token - else - { - $StringBuilder.Append((-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd])) | Out-Null - } - - # Update our position in the column - $CurrentColumn = $CurrentToken.EndColumn - } - } - - Write-Output ([ScriptBlock]::Create($StringBuilder.ToString())) -} diff --git a/ScriptModification/ScriptModification.psd1 b/ScriptModification/ScriptModification.psd1 index 923c874..07cd0bf 100644 --- a/ScriptModification/ScriptModification.psd1 +++ b/ScriptModification/ScriptModification.psd1 @@ -26,6 +26,6 @@ FunctionsToExport = '*' # List of all files packaged with this module FileList = 'ScriptModification.psm1', 'ScriptModification.psd1', 'Out-CompressedDll.ps1', 'Out-EncodedCommand.ps1', - 'Out-EncryptedScript.ps1', 'Remove-Comments.ps1', 'Usage.md' + 'Out-EncryptedScript.ps1', 'Remove-Comment.ps1', 'Usage.md' } -- cgit v1.2.3