Permalink
Find file
14838 lines (11134 sloc) 497 KB
#requires -version 2
<#
PowerSploit File: PowerView.ps1
Author: Will Schroeder (@harmj0y)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
#>
########################################################
#
# PSReflect code for Windows API access
# Author: @mattifestation
# https://raw.githubusercontent.com/mattifestation/PSReflect/master/PSReflect.psm1
#
########################################################
function New-InMemoryModule
{
<#
.SYNOPSIS
Creates an in-memory assembly and module
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
When defining custom enums, structs, and unmanaged functions, it is
necessary to associate to an assembly module. This helper function
creates an in-memory module that can be passed to the 'enum',
'struct', and Add-Win32Type functions.
.PARAMETER ModuleName
Specifies the desired name for the in-memory assembly and module. If
ModuleName is not provided, it will default to a GUID.
.EXAMPLE
$Module = New-InMemoryModule -ModuleName Win32
#>
Param
(
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty()]
[String]
$ModuleName = [Guid]::NewGuid().ToString()
)
$LoadedAssemblies = [AppDomain]::CurrentDomain.GetAssemblies()
ForEach ($Assembly in $LoadedAssemblies) {
if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {
return $Assembly
}
}
$DynAssembly = New-Object Reflection.AssemblyName($ModuleName)
$Domain = [AppDomain]::CurrentDomain
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)
return $ModuleBuilder
}
# A helper function used to reduce typing while defining function
# prototypes for Add-Win32Type.
function func
{
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[String]
$DllName,
[Parameter(Position = 1, Mandatory = $True)]
[String]
$FunctionName,
[Parameter(Position = 2, Mandatory = $True)]
[Type]
$ReturnType,
[Parameter(Position = 3)]
[Type[]]
$ParameterTypes,
[Parameter(Position = 4)]
[Runtime.InteropServices.CallingConvention]
$NativeCallingConvention,
[Parameter(Position = 5)]
[Runtime.InteropServices.CharSet]
$Charset,
[Switch]
$SetLastError
)
$Properties = @{
DllName = $DllName
FunctionName = $FunctionName
ReturnType = $ReturnType
}
if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }
if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }
if ($Charset) { $Properties['Charset'] = $Charset }
if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }
New-Object PSObject -Property $Properties
}
function Add-Win32Type
{
<#
.SYNOPSIS
Creates a .NET type for an unmanaged Win32 function.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: func
.DESCRIPTION
Add-Win32Type enables you to easily interact with unmanaged (i.e.
Win32 unmanaged) functions in PowerShell. After providing
Add-Win32Type with a function signature, a .NET type is created
using reflection (i.e. csc.exe is never called like with Add-Type).
The 'func' helper function can be used to reduce typing when defining
multiple function definitions.
.PARAMETER DllName
The name of the DLL.
.PARAMETER FunctionName
The name of the target function.
.PARAMETER ReturnType
The return type of the function.
.PARAMETER ParameterTypes
The function parameters.
.PARAMETER NativeCallingConvention
Specifies the native calling convention of the function. Defaults to
stdcall.
.PARAMETER Charset
If you need to explicitly call an 'A' or 'W' Win32 function, you can
specify the character set.
.PARAMETER SetLastError
Indicates whether the callee calls the SetLastError Win32 API
function before returning from the attributed method.
.PARAMETER Module
The in-memory module that will host the functions. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER Namespace
An optional namespace to prepend to the type. Add-Win32Type defaults
to a namespace consisting only of the name of the DLL.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$FunctionDefinitions = @(
(func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),
(func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),
(func ntdll RtlGetCurrentPeb ([IntPtr]) @())
)
$Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
$Kernel32 = $Types['kernel32']
$Ntdll = $Types['ntdll']
$Ntdll::RtlGetCurrentPeb()
$ntdllbase = $Kernel32::GetModuleHandle('ntdll')
$Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')
.NOTES
Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189
When defining multiple function prototypes, it is ideal to provide
Add-Win32Type with an array of function signatures. That way, they
are all incorporated into the same in-memory module.
#>
[OutputType([Hashtable])]
Param(
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[String]
$DllName,
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[String]
$FunctionName,
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
[Type]
$ReturnType,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Type[]]
$ParameterTypes,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Runtime.InteropServices.CallingConvention]
$NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Runtime.InteropServices.CharSet]
$Charset = [Runtime.InteropServices.CharSet]::Auto,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[Switch]
$SetLastError,
[Parameter(Mandatory = $True)]
[ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
$Module,
[ValidateNotNull()]
[String]
$Namespace = ''
)
BEGIN
{
$TypeHash = @{}
}
PROCESS
{
if ($Module -is [Reflection.Assembly])
{
if ($Namespace)
{
$TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName")
}
else
{
$TypeHash[$DllName] = $Module.GetType($DllName)
}
}
else
{
# Define one type for each DLL
if (!$TypeHash.ContainsKey($DllName))
{
if ($Namespace)
{
$TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit')
}
else
{
$TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')
}
}
$Method = $TypeHash[$DllName].DefineMethod(
$FunctionName,
'Public,Static,PinvokeImpl',
$ReturnType,
$ParameterTypes)
# Make each ByRef parameter an Out parameter
$i = 1
ForEach($Parameter in $ParameterTypes)
{
if ($Parameter.IsByRef)
{
[void] $Method.DefineParameter($i, 'Out', $Null)
}
$i++
}
$DllImport = [Runtime.InteropServices.DllImportAttribute]
$SetLastErrorField = $DllImport.GetField('SetLastError')
$CallingConventionField = $DllImport.GetField('CallingConvention')
$CharsetField = $DllImport.GetField('CharSet')
if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }
# Equivalent to C# version of [DllImport(DllName)]
$Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
$DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,
$DllName, [Reflection.PropertyInfo[]] @(), [Object[]] @(),
[Reflection.FieldInfo[]] @($SetLastErrorField, $CallingConventionField, $CharsetField),
[Object[]] @($SLEValue, ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention), ([Runtime.InteropServices.CharSet] $Charset)))
$Method.SetCustomAttribute($DllImportAttribute)
}
}
END
{
if ($Module -is [Reflection.Assembly])
{
return $TypeHash
}
$ReturnTypes = @{}
ForEach ($Key in $TypeHash.Keys)
{
$Type = $TypeHash[$Key].CreateType()
$ReturnTypes[$Key] = $Type
}
return $ReturnTypes
}
}
function psenum
{
<#
.SYNOPSIS
Creates an in-memory enumeration for use in your PowerShell session.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
The 'psenum' function facilitates the creation of enums entirely in
memory using as close to a "C style" as PowerShell will allow.
.PARAMETER Module
The in-memory module that will host the enum. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER FullName
The fully-qualified name of the enum.
.PARAMETER Type
The type of each enum element.
.PARAMETER EnumElements
A hashtable of enum elements.
.PARAMETER Bitfield
Specifies that the enum should be treated as a bitfield.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{
UNKNOWN = 0
NATIVE = 1 # Image doesn't require a subsystem.
WINDOWS_GUI = 2 # Image runs in the Windows GUI subsystem.
WINDOWS_CUI = 3 # Image runs in the Windows character subsystem.
OS2_CUI = 5 # Image runs in the OS/2 character subsystem.
POSIX_CUI = 7 # Image runs in the Posix character subsystem.
NATIVE_WINDOWS = 8 # Image is a native Win9x driver.
WINDOWS_CE_GUI = 9 # Image runs in the Windows CE subsystem.
EFI_APPLICATION = 10
EFI_BOOT_SERVICE_DRIVER = 11
EFI_RUNTIME_DRIVER = 12
EFI_ROM = 13
XBOX = 14
WINDOWS_BOOT_APPLICATION = 16
}
.NOTES
PowerShell purists may disagree with the naming of this function but
again, this was developed in such a way so as to emulate a "C style"
definition as closely as possible. Sorry, I'm not going to name it
New-Enum. :P
#>
[OutputType([Type])]
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
$Module,
[Parameter(Position = 1, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$FullName,
[Parameter(Position = 2, Mandatory = $True)]
[Type]
$Type,
[Parameter(Position = 3, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[Hashtable]
$EnumElements,
[Switch]
$Bitfield
)
if ($Module -is [Reflection.Assembly])
{
return ($Module.GetType($FullName))
}
$EnumType = $Type -as [Type]
$EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)
if ($Bitfield)
{
$FlagsConstructor = [FlagsAttribute].GetConstructor(@())
$FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())
$EnumBuilder.SetCustomAttribute($FlagsCustomAttribute)
}
ForEach ($Key in $EnumElements.Keys)
{
# Apply the specified enum type to each element
$Null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)
}
$EnumBuilder.CreateType()
}
# A helper function used to reduce typing while defining struct
# fields.
function field
{
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[UInt16]
$Position,
[Parameter(Position = 1, Mandatory = $True)]
[Type]
$Type,
[Parameter(Position = 2)]
[UInt16]
$Offset,
[Object[]]
$MarshalAs
)
@{
Position = $Position
Type = $Type -as [Type]
Offset = $Offset
MarshalAs = $MarshalAs
}
}
function struct
{
<#
.SYNOPSIS
Creates an in-memory struct for use in your PowerShell session.
Author: Matthew Graeber (@mattifestation)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: field
.DESCRIPTION
The 'struct' function facilitates the creation of structs entirely in
memory using as close to a "C style" as PowerShell will allow. Struct
fields are specified using a hashtable where each field of the struct
is comprosed of the order in which it should be defined, its .NET
type, and optionally, its offset and special marshaling attributes.
One of the features of 'struct' is that after your struct is defined,
it will come with a built-in GetSize method as well as an explicit
converter so that you can easily cast an IntPtr to the struct without
relying upon calling SizeOf and/or PtrToStructure in the Marshal
class.
.PARAMETER Module
The in-memory module that will host the struct. Use
New-InMemoryModule to define an in-memory module.
.PARAMETER FullName
The fully-qualified name of the struct.
.PARAMETER StructFields
A hashtable of fields. Use the 'field' helper function to ease
defining each field.
.PARAMETER PackingSize
Specifies the memory alignment of fields.
.PARAMETER ExplicitLayout
Indicates that an explicit offset for each field will be specified.
.EXAMPLE
$Mod = New-InMemoryModule -ModuleName Win32
$ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{
DOS_SIGNATURE = 0x5A4D
OS2_SIGNATURE = 0x454E
OS2_SIGNATURE_LE = 0x454C
VXD_SIGNATURE = 0x454C
}
$ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{
e_magic = field 0 $ImageDosSignature
e_cblp = field 1 UInt16
e_cp = field 2 UInt16
e_crlc = field 3 UInt16
e_cparhdr = field 4 UInt16
e_minalloc = field 5 UInt16
e_maxalloc = field 6 UInt16
e_ss = field 7 UInt16
e_sp = field 8 UInt16
e_csum = field 9 UInt16
e_ip = field 10 UInt16
e_cs = field 11 UInt16
e_lfarlc = field 12 UInt16
e_ovno = field 13 UInt16
e_res = field 14 UInt16[] -MarshalAs @('ByValArray', 4)
e_oemid = field 15 UInt16
e_oeminfo = field 16 UInt16
e_res2 = field 17 UInt16[] -MarshalAs @('ByValArray', 10)
e_lfanew = field 18 Int32
}
# Example of using an explicit layout in order to create a union.
$TestUnion = struct $Mod TestUnion @{
field1 = field 0 UInt32 0
field2 = field 1 IntPtr 0
} -ExplicitLayout
.NOTES
PowerShell purists may disagree with the naming of this function but
again, this was developed in such a way so as to emulate a "C style"
definition as closely as possible. Sorry, I'm not going to name it
New-Struct. :P
#>
[OutputType([Type])]
Param
(
[Parameter(Position = 1, Mandatory = $True)]
[ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
$Module,
[Parameter(Position = 2, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$FullName,
[Parameter(Position = 3, Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[Hashtable]
$StructFields,
[Reflection.Emit.PackingSize]
$PackingSize = [Reflection.Emit.PackingSize]::Unspecified,
[Switch]
$ExplicitLayout
)
if ($Module -is [Reflection.Assembly])
{
return ($Module.GetType($FullName))
}
[Reflection.TypeAttributes] $StructAttributes = 'AnsiClass,
Class,
Public,
Sealed,
BeforeFieldInit'
if ($ExplicitLayout)
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout
}
else
{
$StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout
}
$StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)
$ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
$SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
$Fields = New-Object Hashtable[]($StructFields.Count)
# Sort each field according to the orders specified
# Unfortunately, PSv2 doesn't have the luxury of the
# hashtable [Ordered] accelerator.
ForEach ($Field in $StructFields.Keys)
{
$Index = $StructFields[$Field]['Position']
$Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}
}
ForEach ($Field in $Fields)
{
$FieldName = $Field['FieldName']
$FieldProp = $Field['Properties']
$Offset = $FieldProp['Offset']
$Type = $FieldProp['Type']
$MarshalAs = $FieldProp['MarshalAs']
$NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')
if ($MarshalAs)
{
$UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])
if ($MarshalAs[1])
{
$Size = $MarshalAs[1]
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,
$UnmanagedType, $SizeConst, @($Size))
}
else
{
$AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))
}
$NewField.SetCustomAttribute($AttribBuilder)
}
if ($ExplicitLayout) { $NewField.SetOffset($Offset) }
}
# Make the struct aware of its own size.
# No more having to call [Runtime.InteropServices.Marshal]::SizeOf!
$SizeMethod = $StructBuilder.DefineMethod('GetSize',
'Public, Static',
[Int],
[Type[]] @())
$ILGenerator = $SizeMethod.GetILGenerator()
# Thanks for the help, Jason Shirk!
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
[Type].GetMethod('GetTypeFromHandle'))
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
[Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type])))
$ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret)
# Allow for explicit casting from an IntPtr
# No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!
$ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit',
'PrivateScope, Public, Static, HideBySig, SpecialName',
$StructBuilder,
[Type[]] @([IntPtr]))
$ILGenerator2 = $ImplicitConverter.GetILGenerator()
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
[Type].GetMethod('GetTypeFromHandle'))
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
[Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder)
$ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret)
$StructBuilder.CreateType()
}
########################################################
#
# Misc. helpers
#
########################################################
filter Get-IniContent {
<#
.SYNOPSIS
This helper parses an .ini file into a proper PowerShell object.
Author: 'The Scripting Guys'
Link: https://blogs.technet.microsoft.com/heyscriptingguy/2011/08/20/use-powershell-to-work-with-any-ini-file/
.LINK
https://blogs.technet.microsoft.com/heyscriptingguy/2011/08/20/use-powershell-to-work-with-any-ini-file/
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[Alias('FullName')]
[ValidateScript({ Test-Path -Path $_ })]
[String[]]
$Path
)
ForEach($TargetPath in $Path) {
$IniObject = @{}
Switch -Regex -File $TargetPath {
"^\[(.+)\]" # Section
{
$Section = $matches[1].Trim()
$IniObject[$Section] = @{}
$CommentCount = 0
}
"^(;.*)$" # Comment
{
$Value = $matches[1].Trim()
$CommentCount = $CommentCount + 1
$Name = 'Comment' + $CommentCount
$IniObject[$Section][$Name] = $Value
}
"(.+?)\s*=(.*)" # Key
{
$Name, $Value = $matches[1..2]
$Name = $Name.Trim()
$Values = $Value.split(',') | ForEach-Object {$_.Trim()}
if($Values -isnot [System.Array]) {$Values = @($Values)}
$IniObject[$Section][$Name] = $Values
}
}
$IniObject
}
}
filter Export-PowerViewCSV {
<#
.SYNOPSIS
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.
Based partially on Dmitry Sotnikov's Export-CSV code
at http://poshcode.org/1590
.LINK
http://poshcode.org/1590
http://dmitrysotnikov.wordpress.com/2010/01/19/Export-Csv-append/
#>
Param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
[System.Management.Automation.PSObject[]]
$InputObject,
[Parameter(Mandatory=$True, Position=0)]
[String]
[ValidateNotNullOrEmpty()]
$OutFile
)
$ObjectCSV = $InputObject | ConvertTo-Csv -NoTypeInformation
# mutex so threaded code doesn't stomp on the output file
$Mutex = New-Object System.Threading.Mutex $False,'CSVMutex';
$Null = $Mutex.WaitOne()
if (Test-Path -Path $OutFile) {
# hack to skip the first line of output if the file already exists
$ObjectCSV | ForEach-Object { $Start=$True }{ if ($Start) {$Start=$False} else {$_} } | Out-File -Encoding 'ASCII' -Append -FilePath $OutFile
}
else {
$ObjectCSV | Out-File -Encoding 'ASCII' -Append -FilePath $OutFile
}
$Mutex.ReleaseMutex()
}
filter Get-IPAddress {
<#
.SYNOPSIS
Resolves a given hostename to its associated IPv4 address.
If no hostname is provided, it defaults to returning
the IP address of the localhost.
.EXAMPLE
PS C:\> Get-IPAddress -ComputerName SERVER
Return the IPv4 address of 'SERVER'
.EXAMPLE
PS C:\> Get-Content .\hostnames.txt | Get-IPAddress
Get the IP addresses of all hostnames in an input file.
#>
[CmdletBinding()]
param(
[Parameter(Position=0, ValueFromPipeline=$True)]
[Alias('HostName')]
[String]
$ComputerName = $Env:ComputerName
)
try {
# extract the computer name from whatever object was passed on the pipeline
$Computer = $ComputerName | Get-NameField
# get the IP resolution of this specified hostname
@(([Net.Dns]::GetHostEntry($Computer)).AddressList) | ForEach-Object {
if ($_.AddressFamily -eq 'InterNetwork') {
$Out = New-Object PSObject
$Out | Add-Member Noteproperty 'ComputerName' $Computer
$Out | Add-Member Noteproperty 'IPAddress' $_.IPAddressToString
$Out
}
}
}
catch {
Write-Verbose -Message 'Could not resolve host to an IP Address.'
}
}
filter Convert-NameToSid {
<#
.SYNOPSIS
Converts a given user/group name to a security identifier (SID).
.PARAMETER ObjectName
The user/group name to convert, can be 'user' or 'DOMAIN\user' format.
.PARAMETER Domain
Specific domain for the given user account, defaults to the current domain.
.EXAMPLE
PS C:\> Convert-NameToSid 'DEV\dfm'
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
[Alias('Name')]
$ObjectName,
[String]
$Domain
)
$ObjectName = $ObjectName -Replace "/","\"
if($ObjectName.Contains("\")) {
# if we get a DOMAIN\user format, auto convert it
$Domain = $ObjectName.Split("\")[0]
$ObjectName = $ObjectName.Split("\")[1]
}
elseif(-not $Domain) {
$Domain = (Get-NetDomain).Name
}
try {
$Obj = (New-Object System.Security.Principal.NTAccount($Domain, $ObjectName))
$SID = $Obj.Translate([System.Security.Principal.SecurityIdentifier]).Value
$Out = New-Object PSObject
$Out | Add-Member Noteproperty 'ObjectName' $ObjectName
$Out | Add-Member Noteproperty 'SID' $SID
$Out
}
catch {
Write-Verbose "Invalid object/name: $Domain\$ObjectName"
$Null
}
}
filter Convert-SidToName {
<#
.SYNOPSIS
Converts a security identifier (SID) to a group/user name.
.PARAMETER SID
The SID to convert.
.EXAMPLE
PS C:\> Convert-SidToName S-1-5-21-2620891829-2411261497-1773853088-1105
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
[ValidatePattern('^S-1-.*')]
$SID
)
try {
$SID2 = $SID.trim('*')
# try to resolve any built-in SIDs first
# from https://support.microsoft.com/en-us/kb/243330
Switch ($SID2) {
'S-1-0' { 'Null Authority' }
'S-1-0-0' { 'Nobody' }
'S-1-1' { 'World Authority' }
'S-1-1-0' { 'Everyone' }
'S-1-2' { 'Local Authority' }
'S-1-2-0' { 'Local' }
'S-1-2-1' { 'Console Logon ' }
'S-1-3' { 'Creator Authority' }
'S-1-3-0' { 'Creator Owner' }
'S-1-3-1' { 'Creator Group' }
'S-1-3-2' { 'Creator Owner Server' }
'S-1-3-3' { 'Creator Group Server' }
'S-1-3-4' { 'Owner Rights' }
'S-1-4' { 'Non-unique Authority' }
'S-1-5' { 'NT Authority' }
'S-1-5-1' { 'Dialup' }
'S-1-5-2' { 'Network' }
'S-1-5-3' { 'Batch' }
'S-1-5-4' { 'Interactive' }
'S-1-5-6' { 'Service' }
'S-1-5-7' { 'Anonymous' }
'S-1-5-8' { 'Proxy' }
'S-1-5-9' { 'Enterprise Domain Controllers' }
'S-1-5-10' { 'Principal Self' }
'S-1-5-11' { 'Authenticated Users' }
'S-1-5-12' { 'Restricted Code' }
'S-1-5-13' { 'Terminal Server Users' }
'S-1-5-14' { 'Remote Interactive Logon' }
'S-1-5-15' { 'This Organization ' }
'S-1-5-17' { 'This Organization ' }
'S-1-5-18' { 'Local System' }
'S-1-5-19' { 'NT Authority' }
'S-1-5-20' { 'NT Authority' }
'S-1-5-80-0' { 'All Services ' }
'S-1-5-32-544' { 'BUILTIN\Administrators' }
'S-1-5-32-545' { 'BUILTIN\Users' }
'S-1-5-32-546' { 'BUILTIN\Guests' }
'S-1-5-32-547' { 'BUILTIN\Power Users' }
'S-1-5-32-548' { 'BUILTIN\Account Operators' }
'S-1-5-32-549' { 'BUILTIN\Server Operators' }
'S-1-5-32-550' { 'BUILTIN\Print Operators' }
'S-1-5-32-551' { 'BUILTIN\Backup Operators' }
'S-1-5-32-552' { 'BUILTIN\Replicators' }
'S-1-5-32-554' { 'BUILTIN\Pre-Windows 2000 Compatible Access' }
'S-1-5-32-555' { 'BUILTIN\Remote Desktop Users' }
'S-1-5-32-556' { 'BUILTIN\Network Configuration Operators' }
'S-1-5-32-557' { 'BUILTIN\Incoming Forest Trust Builders' }
'S-1-5-32-558' { 'BUILTIN\Performance Monitor Users' }
'S-1-5-32-559' { 'BUILTIN\Performance Log Users' }
'S-1-5-32-560' { 'BUILTIN\Windows Authorization Access Group' }
'S-1-5-32-561' { 'BUILTIN\Terminal Server License Servers' }
'S-1-5-32-562' { 'BUILTIN\Distributed COM Users' }
'S-1-5-32-569' { 'BUILTIN\Cryptographic Operators' }
'S-1-5-32-573' { 'BUILTIN\Event Log Readers' }
'S-1-5-32-574' { 'BUILTIN\Certificate Service DCOM Access' }
'S-1-5-32-575' { 'BUILTIN\RDS Remote Access Servers' }
'S-1-5-32-576' { 'BUILTIN\RDS Endpoint Servers' }
'S-1-5-32-577' { 'BUILTIN\RDS Management Servers' }
'S-1-5-32-578' { 'BUILTIN\Hyper-V Administrators' }
'S-1-5-32-579' { 'BUILTIN\Access Control Assistance Operators' }
'S-1-5-32-580' { 'BUILTIN\Access Control Assistance Operators' }
Default {
$Obj = (New-Object System.Security.Principal.SecurityIdentifier($SID2))
$Obj.Translate( [System.Security.Principal.NTAccount]).Value
}
}
}
catch {
Write-Verbose "Invalid SID: $SID"
$SID
}
}
filter Convert-ADName {
<#
.SYNOPSIS
Converts user/group names from NT4 (DOMAIN\user) or domainSimple (user@domain.com)
to canonical format (domain.com/Users/user) or NT4.
Based on Bill Stewart's code from this article:
http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
.PARAMETER ObjectName
The user/group name to convert.
.PARAMETER InputType
The InputType of the user/group name ("NT4","Simple","Canonical").
.PARAMETER OutputType
The OutputType of the user/group name ("NT4","Simple","Canonical").
.EXAMPLE
PS C:\> Convert-ADName -ObjectName "dev\dfm"
Returns "dev.testlab.local/Users/Dave"
.EXAMPLE
PS C:\> Convert-SidToName "S-..." | Convert-ADName
Returns the canonical name for the resolved SID.
.LINK
http://windowsitpro.com/active-directory/translating-active-directory-object-names-between-formats
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
$ObjectName,
[String]
[ValidateSet("NT4","Simple","Canonical")]
$InputType,
[String]
[ValidateSet("NT4","Simple","Canonical")]
$OutputType
)
$NameTypes = @{
'Canonical' = 2
'NT4' = 3
'Simple' = 5
}
if(-not $PSBoundParameters['InputType']) {
if( ($ObjectName.split('/')).Count -eq 2 ) {
$ObjectName = $ObjectName.replace('/', '\')
}
if($ObjectName -match "^[A-Za-z]+\\[A-Za-z ]+") {
$InputType = 'NT4'
}
elseif($ObjectName -match "^[A-Za-z ]+@[A-Za-z\.]+") {
$InputType = 'Simple'
}
elseif($ObjectName -match "^[A-Za-z\.]+/[A-Za-z]+/[A-Za-z/ ]+") {
$InputType = 'Canonical'
}
else {
Write-Warning "Can not identify InType for $ObjectName"
return $ObjectName
}
}
elseif($InputType -eq 'NT4') {
$ObjectName = $ObjectName.replace('/', '\')
}
if(-not $PSBoundParameters['OutputType']) {
$OutputType = Switch($InputType) {
'NT4' {'Canonical'}
'Simple' {'NT4'}
'Canonical' {'NT4'}
}
}
# try to extract the domain from the given format
$Domain = Switch($InputType) {
'NT4' { $ObjectName.split("\")[0] }
'Simple' { $ObjectName.split("@")[1] }
'Canonical' { $ObjectName.split("/")[0] }
}
# Accessor functions to simplify calls to NameTranslate
function Invoke-Method([__ComObject] $Object, [String] $Method, $Parameters) {
$Output = $Object.GetType().InvokeMember($Method, "InvokeMethod", $Null, $Object, $Parameters)
if ( $Output ) { $Output }
}
function Set-Property([__ComObject] $Object, [String] $Property, $Parameters) {
[Void] $Object.GetType().InvokeMember($Property, "SetProperty", $Null, $Object, $Parameters)
}
$Translate = New-Object -ComObject NameTranslate
try {
Invoke-Method $Translate "Init" (1, $Domain)
}
catch [System.Management.Automation.MethodInvocationException] {
Write-Verbose "Error with translate init in Convert-ADName: $_"
}
Set-Property $Translate "ChaseReferral" (0x60)
try {
Invoke-Method $Translate "Set" ($NameTypes[$InputType], $ObjectName)
(Invoke-Method $Translate "Get" ($NameTypes[$OutputType]))
}
catch [System.Management.Automation.MethodInvocationException] {
Write-Verbose "Error with translate Set/Get in Convert-ADName: $_"
}
}
function ConvertFrom-UACValue {
<#
.SYNOPSIS
Converts a UAC int value to human readable form.
.PARAMETER Value
The int UAC value to convert.
.PARAMETER ShowAll
Show all UAC values, with a + indicating the value is currently set.
.EXAMPLE
PS C:\> ConvertFrom-UACValue -Value 66176
Convert the UAC value 66176 to human readable format.
.EXAMPLE
PS C:\> Get-NetUser jason | select useraccountcontrol | ConvertFrom-UACValue
Convert the UAC value for 'jason' to human readable format.
.EXAMPLE
PS C:\> Get-NetUser jason | select useraccountcontrol | ConvertFrom-UACValue -ShowAll
Convert the UAC value for 'jason' to human readable format, showing all
possible UAC values.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
$Value,
[Switch]
$ShowAll
)
begin {
# values from https://support.microsoft.com/en-us/kb/305144
$UACValues = New-Object System.Collections.Specialized.OrderedDictionary
$UACValues.Add("SCRIPT", 1)
$UACValues.Add("ACCOUNTDISABLE", 2)
$UACValues.Add("HOMEDIR_REQUIRED", 8)
$UACValues.Add("LOCKOUT", 16)
$UACValues.Add("PASSWD_NOTREQD", 32)
$UACValues.Add("PASSWD_CANT_CHANGE", 64)
$UACValues.Add("ENCRYPTED_TEXT_PWD_ALLOWED", 128)
$UACValues.Add("TEMP_DUPLICATE_ACCOUNT", 256)
$UACValues.Add("NORMAL_ACCOUNT", 512)
$UACValues.Add("INTERDOMAIN_TRUST_ACCOUNT", 2048)
$UACValues.Add("WORKSTATION_TRUST_ACCOUNT", 4096)
$UACValues.Add("SERVER_TRUST_ACCOUNT", 8192)
$UACValues.Add("DONT_EXPIRE_PASSWORD", 65536)
$UACValues.Add("MNS_LOGON_ACCOUNT", 131072)
$UACValues.Add("SMARTCARD_REQUIRED", 262144)
$UACValues.Add("TRUSTED_FOR_DELEGATION", 524288)
$UACValues.Add("NOT_DELEGATED", 1048576)
$UACValues.Add("USE_DES_KEY_ONLY", 2097152)
$UACValues.Add("DONT_REQ_PREAUTH", 4194304)
$UACValues.Add("PASSWORD_EXPIRED", 8388608)
$UACValues.Add("TRUSTED_TO_AUTH_FOR_DELEGATION", 16777216)
$UACValues.Add("PARTIAL_SECRETS_ACCOUNT", 67108864)
}
process {
$ResultUACValues = New-Object System.Collections.Specialized.OrderedDictionary
if($Value -is [Int]) {
$IntValue = $Value
}
elseif ($Value -is [PSCustomObject]) {
if($Value.useraccountcontrol) {
$IntValue = $Value.useraccountcontrol
}
}
else {
Write-Warning "Invalid object input for -Value : $Value"
return $Null
}
if($ShowAll) {
foreach ($UACValue in $UACValues.GetEnumerator()) {
if( ($IntValue -band $UACValue.Value) -eq $UACValue.Value) {
$ResultUACValues.Add($UACValue.Name, "$($UACValue.Value)+")
}
else {
$ResultUACValues.Add($UACValue.Name, "$($UACValue.Value)")
}
}
}
else {
foreach ($UACValue in $UACValues.GetEnumerator()) {
if( ($IntValue -band $UACValue.Value) -eq $UACValue.Value) {
$ResultUACValues.Add($UACValue.Name, "$($UACValue.Value)")
}
}
}
$ResultUACValues
}
}
filter Get-Proxy {
<#
.SYNOPSIS
Enumerates the proxy server and WPAD conents for the current user.
.PARAMETER ComputerName
The computername to enumerate proxy settings on, defaults to local host.
.EXAMPLE
PS C:\> Get-Proxy
Returns the current proxy settings.
#>
param(
[Parameter(ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
[String]
$ComputerName = $ENV:COMPUTERNAME
)
try {
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('CurrentUser', $ComputerName)
$RegKey = $Reg.OpenSubkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings")
$ProxyServer = $RegKey.GetValue('ProxyServer')
$AutoConfigURL = $RegKey.GetValue('AutoConfigURL')
$Wpad = ""
if($AutoConfigURL -and ($AutoConfigURL -ne "")) {
try {
$Wpad = (New-Object Net.Webclient).DownloadString($AutoConfigURL)
}
catch {
Write-Warning "Error connecting to AutoConfigURL : $AutoConfigURL"
}
}
if($ProxyServer -or $AutoConfigUrl) {
$Properties = @{
'ProxyServer' = $ProxyServer
'AutoConfigURL' = $AutoConfigURL
'Wpad' = $Wpad
}
New-Object -TypeName PSObject -Property $Properties
}
else {
Write-Warning "No proxy settings found for $ComputerName"
}
}
catch {
Write-Warning "Error enumerating proxy settings for $ComputerName : $_"
}
}
function Request-SPNTicket {
<#
.SYNOPSIS
Request the kerberos ticket for a specified service principal name (SPN).
.PARAMETER SPN
The service principal name to request the ticket for. Required.
.EXAMPLE
PS C:\> Request-SPNTicket -SPN "HTTP/web.testlab.local"
Request a kerberos service ticket for the specified SPN.
.EXAMPLE
PS C:\> "HTTP/web1.testlab.local","HTTP/web2.testlab.local" | Request-SPNTicket
Request kerberos service tickets for all SPNs passed on the pipeline.
.EXAMPLE
PS C:\> Get-NetUser -SPN | Request-SPNTicket
Request kerberos service tickets for all users with non-null SPNs.
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True, ValueFromPipelineByPropertyName = $True)]
[Alias('ServicePrincipalName')]
[String[]]
$SPN
)
begin {
Add-Type -AssemblyName System.IdentityModel
}
process {
Write-Verbose "Requesting ticket for: $SPN"
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $SPN
}
}
function Get-PathAcl {
<#
.SYNOPSIS
Enumerates the ACL for a given file path.
.PARAMETER Path
The local/remote path to enumerate the ACLs for.
.PARAMETER Recurse
If any ACL results are groups, recurse and retrieve user membership.
.EXAMPLE
PS C:\> Get-PathAcl "\\SERVER\Share\"
Returns ACLs for the given UNC share.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[String]
$Path,
[Switch]
$Recurse
)
begin {
function Convert-FileRight {
# From http://stackoverflow.com/questions/28029872/retrieving-security-descriptor-and-getting-number-for-filesystemrights
[CmdletBinding()]
param(
[Int]
$FSR
)
$AccessMask = @{
[uint32]'0x80000000' = 'GenericRead'
[uint32]'0x40000000' = 'GenericWrite'
[uint32]'0x20000000' = 'GenericExecute'
[uint32]'0x10000000' = 'GenericAll'
[uint32]'0x02000000' = 'MaximumAllowed'
[uint32]'0x01000000' = 'AccessSystemSecurity'
[uint32]'0x00100000' = 'Synchronize'
[uint32]'0x00080000' = 'WriteOwner'
[uint32]'0x00040000' = 'WriteDAC'
[uint32]'0x00020000' = 'ReadControl'
[uint32]'0x00010000' = 'Delete'
[uint32]'0x00000100' = 'WriteAttributes'
[uint32]'0x00000080' = 'ReadAttributes'
[uint32]'0x00000040' = 'DeleteChild'
[uint32]'0x00000020' = 'Execute/Traverse'
[uint32]'0x00000010' = 'WriteExtendedAttributes'
[uint32]'0x00000008' = 'ReadExtendedAttributes'
[uint32]'0x00000004' = 'AppendData/AddSubdirectory'
[uint32]'0x00000002' = 'WriteData/AddFile'
[uint32]'0x00000001' = 'ReadData/ListDirectory'
}
$SimplePermissions = @{
[uint32]'0x1f01ff' = 'FullControl'
[uint32]'0x0301bf' = 'Modify'
[uint32]'0x0200a9' = 'ReadAndExecute'
[uint32]'0x02019f' = 'ReadAndWrite'
[uint32]'0x020089' = 'Read'
[uint32]'0x000116' = 'Write'
}
$Permissions = @()
# get simple permission
$Permissions += $SimplePermissions.Keys | % {
if (($FSR -band $_) -eq $_) {
$SimplePermissions[$_]
$FSR = $FSR -band (-not $_)
}
}
# get remaining extended permissions
$Permissions += $AccessMask.Keys |
? { $FSR -band $_ } |
% { $AccessMask[$_] }
($Permissions | ?{$_}) -join ","
}
}
process {
try {
$ACL = Get-Acl -Path $Path
$ACL.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | ForEach-Object {
$Names = @()
if ($_.IdentityReference -match '^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+') {
$Object = Get-ADObject -SID $_.IdentityReference
$Names = @()
$SIDs = @($Object.objectsid)
if ($Recurse -and (@('268435456','268435457','536870912','536870913') -contains $Object.samAccountType)) {
$SIDs += Get-NetGroupMember -SID $Object.objectsid | Select-Object -ExpandProperty MemberSid
}
$SIDs | ForEach-Object {
$Names += ,@($_, (Convert-SidToName $_))
}
}
else {
$Names += ,@($_.IdentityReference.Value, (Convert-SidToName $_.IdentityReference.Value))
}
ForEach($Name in $Names) {
$Out = New-Object PSObject
$Out | Add-Member Noteproperty 'Path' $Path
$Out | Add-Member Noteproperty 'FileSystemRights' (Convert-FileRight -FSR $_.FileSystemRights.value__)
$Out | Add-Member Noteproperty 'IdentityReference' $Name[1]
$Out | Add-Member Noteproperty 'IdentitySID' $Name[0]
$Out | Add-Member Noteproperty 'AccessControlType' $_.AccessControlType
$Out
}
}
}
catch {
Write-Warning $_
}
}
}
filter Get-NameField {
<#
.SYNOPSIS
Helper that attempts to extract appropriate field names from
passed computer objects.
.PARAMETER Object
The passed object to extract name fields from.
.PARAMETER DnsHostName
A DnsHostName to extract through ValueFromPipelineByPropertyName.
.PARAMETER Name
A Name to extract through ValueFromPipelineByPropertyName.
.EXAMPLE
PS C:\> Get-NetComputer -FullData | Get-NameField
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[Object]
$Object,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[String]
$DnsHostName,
[Parameter(ValueFromPipelineByPropertyName = $True)]
[String]
$Name
)
if($PSBoundParameters['DnsHostName']) {
$DnsHostName
}
elseif($PSBoundParameters['Name']) {
$Name
}
elseif($Object) {
if ( [bool]($Object.PSobject.Properties.name -match "dnshostname") ) {
# objects from Get-NetComputer
$Object.dnshostname
}
elseif ( [bool]($Object.PSobject.Properties.name -match "name") ) {
# objects from Get-NetDomainController
$Object.name
}
else {
# strings and catch alls
$Object
}
}
else {
return $Null
}
}
function Convert-LDAPProperty {
<#
.SYNOPSIS
Helper that converts specific LDAP property result fields.
Used by several of the Get-Net* function.
.PARAMETER Properties
Properties object to extract out LDAP fields for display.
#>
param(
[Parameter(Mandatory=$True, ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
$Properties
)
$ObjectProperties = @{}
$Properties.PropertyNames | ForEach-Object {
if (($_ -eq "objectsid") -or ($_ -eq "sidhistory")) {
# convert the SID to a string
$ObjectProperties[$_] = (New-Object System.Security.Principal.SecurityIdentifier($Properties[$_][0],0)).Value
}
elseif($_ -eq "objectguid") {
# convert the GUID to a string
$ObjectProperties[$_] = (New-Object Guid (,$Properties[$_][0])).Guid
}
elseif( ($_ -eq "lastlogon") -or ($_ -eq "lastlogontimestamp") -or ($_ -eq "pwdlastset") -or ($_ -eq "lastlogoff") -or ($_ -eq "badPasswordTime") ) {
# convert timestamps
if ($Properties[$_][0] -is [System.MarshalByRefObject]) {
# if we have a System.__ComObject
$Temp = $Properties[$_][0]
[Int32]$High = $Temp.GetType().InvokeMember("HighPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
[Int32]$Low = $Temp.GetType().InvokeMember("LowPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
$ObjectProperties[$_] = ([datetime]::FromFileTime([Int64]("0x{0:x8}{1:x8}" -f $High, $Low)))
}
else {
$ObjectProperties[$_] = ([datetime]::FromFileTime(($Properties[$_][0])))
}
}
elseif($Properties[$_][0] -is [System.MarshalByRefObject]) {
# try to convert misc com objects
$Prop = $Properties[$_]
try {
$Temp = $Prop[$_][0]
Write-Verbose $_
[Int32]$High = $Temp.GetType().InvokeMember("HighPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
[Int32]$Low = $Temp.GetType().InvokeMember("LowPart", [System.Reflection.BindingFlags]::GetProperty, $null, $Temp, $null)
$ObjectProperties[$_] = [Int64]("0x{0:x8}{1:x8}" -f $High, $Low)
}
catch {
$ObjectProperties[$_] = $Prop[$_]
}
}
elseif($Properties[$_].count -eq 1) {
$ObjectProperties[$_] = $Properties[$_][0]
}
else {
$ObjectProperties[$_] = $Properties[$_]
}
}
New-Object -TypeName PSObject -Property $ObjectProperties
}
########################################################
#
# Domain info functions below.
#
########################################################
filter Get-DomainSearcher {
<#
.SYNOPSIS
Helper used by various functions that takes an ADSpath and
domain specifier and builds the correct ADSI searcher object.
.PARAMETER Domain
The domain to use for the query, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER ADSpath
The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
.PARAMETER ADSprefix
Prefix to set for the searcher (like "CN=Sites,CN=Configuration")
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-DomainSearcher -Domain testlab.local
.EXAMPLE
PS C:\> Get-DomainSearcher -Domain testlab.local -DomainController SECONDARY.dev.testlab.local
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Domain,
[String]
$DomainController,
[String]
$ADSpath,
[String]
$ADSprefix,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential
)
if(-not $Credential) {
if(-not $Domain) {
$Domain = (Get-NetDomain).name
}
elseif(-not $DomainController) {
try {
# if there's no -DomainController specified, try to pull the primary DC to reflect queries through
$DomainController = ((Get-NetDomain).PdcRoleOwner).Name
}
catch {
throw "Get-DomainSearcher: Error in retrieving PDC for current domain"
}
}
}
elseif (-not $DomainController) {
# if a DC isn't specified
try {
$DomainController = ((Get-NetDomain -Credential $Credential).PdcRoleOwner).Name
}
catch {
throw "Get-DomainSearcher: Error in retrieving PDC for current domain"
}
if(!$DomainController) {
throw "Get-DomainSearcher: Error in retrieving PDC for current domain"
}
}
$SearchString = "LDAP://"
if($DomainController) {
$SearchString += $DomainController
if($Domain){
$SearchString += '/'
}
}
if($ADSprefix) {
$SearchString += $ADSprefix + ','
}
if($ADSpath) {
if($ADSpath -Match '^GC://') {
# if we're searching the global catalog
$DN = $AdsPath.ToUpper().Trim('/')
$SearchString = ''
}
else {
if($ADSpath -match '^LDAP://') {
if($ADSpath -match "LDAP://.+/.+") {
$SearchString = ''
}
else {
$ADSpath = $ADSpath.Substring(7)
}
}
$DN = $ADSpath
}
}
else {
if($Domain -and ($Domain.Trim() -ne "")) {
$DN = "DC=$($Domain.Replace('.', ',DC='))"
}
}
$SearchString += $DN
Write-Verbose "Get-DomainSearcher search string: $SearchString"
if($Credential) {
Write-Verbose "Using alternate credentials for LDAP connection"
$DomainObject = New-Object DirectoryServices.DirectoryEntry($SearchString, $Credential.UserName, $Credential.GetNetworkCredential().Password)
$Searcher = New-Object System.DirectoryServices.DirectorySearcher($DomainObject)
}
else {
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
}
$Searcher.PageSize = $PageSize
$Searcher.CacheResults = $False
$Searcher
}
filter Convert-DNSRecord {
<#
.SYNOPSIS
Decodes a binary DNS record.
Adapted/ported from Michael B. Smith's code at https://raw.githubusercontent.com/mmessano/PowerShell/master/dns-dump.ps1
.PARAMETER DNSRecord
The domain to query for zones, defaults to the current domain.
.LINK
https://raw.githubusercontent.com/mmessano/PowerShell/master/dns-dump.ps1
#>
param(
[Parameter(Position=0, ValueFromPipelineByPropertyName=$True, Mandatory=$True)]
[Byte[]]
$DNSRecord
)
function Get-Name {
# modified decodeName from https://raw.githubusercontent.com/mmessano/PowerShell/master/dns-dump.ps1
[CmdletBinding()]
param(
[Byte[]]
$Raw
)
[Int]$Length = $Raw[0]
[Int]$Segments = $Raw[1]
[Int]$Index = 2
[String]$Name = ""
while ($Segments-- -gt 0)
{
[Int]$SegmentLength = $Raw[$Index++]
while ($SegmentLength-- -gt 0) {
$Name += [Char]$Raw[$Index++]
}
$Name += "."
}
$Name
}
$RDataLen = [BitConverter]::ToUInt16($DNSRecord, 0)
$RDataType = [BitConverter]::ToUInt16($DNSRecord, 2)
$UpdatedAtSerial = [BitConverter]::ToUInt32($DNSRecord, 8)
$TTLRaw = $DNSRecord[12..15]
# reverse for big endian
$Null = [array]::Reverse($TTLRaw)
$TTL = [BitConverter]::ToUInt32($TTLRaw, 0)
$Age = [BitConverter]::ToUInt32($DNSRecord, 20)
if($Age -ne 0) {
$TimeStamp = ((Get-Date -Year 1601 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0).AddHours($age)).ToString()
}
else {
$TimeStamp = "[static]"
}
$DNSRecordObject = New-Object PSObject
if($RDataType -eq 1) {
$IP = "{0}.{1}.{2}.{3}" -f $DNSRecord[24], $DNSRecord[25], $DNSRecord[26], $DNSRecord[27]
$Data = $IP
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'A'
}
elseif($RDataType -eq 2) {
$NSName = Get-Name $DNSRecord[24..$DNSRecord.length]
$Data = $NSName
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'NS'
}
elseif($RDataType -eq 5) {
$Alias = Get-Name $DNSRecord[24..$DNSRecord.length]
$Data = $Alias
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'CNAME'
}
elseif($RDataType -eq 6) {
# TODO: how to implement properly? nested object?
$Data = $([System.Convert]::ToBase64String($DNSRecord[24..$DNSRecord.length]))
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'SOA'
}
elseif($RDataType -eq 12) {
$Ptr = Get-Name $DNSRecord[24..$DNSRecord.length]
$Data = $Ptr
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'PTR'
}
elseif($RDataType -eq 13) {
# TODO: how to implement properly? nested object?
$Data = $([System.Convert]::ToBase64String($DNSRecord[24..$DNSRecord.length]))
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'HINFO'
}
elseif($RDataType -eq 15) {
# TODO: how to implement properly? nested object?
$Data = $([System.Convert]::ToBase64String($DNSRecord[24..$DNSRecord.length]))
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'MX'
}
elseif($RDataType -eq 16) {
[string]$TXT = ""
[int]$SegmentLength = $DNSRecord[24]
$Index = 25
while ($SegmentLength-- -gt 0) {
$TXT += [char]$DNSRecord[$index++]
}
$Data = $TXT
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'TXT'
}
elseif($RDataType -eq 28) {
# TODO: how to implement properly? nested object?
$Data = $([System.Convert]::ToBase64String($DNSRecord[24..$DNSRecord.length]))
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'AAAA'
}
elseif($RDataType -eq 33) {
# TODO: how to implement properly? nested object?
$Data = $([System.Convert]::ToBase64String($DNSRecord[24..$DNSRecord.length]))
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'SRV'
}
else {
$Data = $([System.Convert]::ToBase64String($DNSRecord[24..$DNSRecord.length]))
$DNSRecordObject | Add-Member Noteproperty 'RecordType' 'UNKNOWN'
}
$DNSRecordObject | Add-Member Noteproperty 'UpdatedAtSerial' $UpdatedAtSerial
$DNSRecordObject | Add-Member Noteproperty 'TTL' $TTL
$DNSRecordObject | Add-Member Noteproperty 'Age' $Age
$DNSRecordObject | Add-Member Noteproperty 'TimeStamp' $TimeStamp
$DNSRecordObject | Add-Member Noteproperty 'Data' $Data
$DNSRecordObject
}
filter Get-DNSZone {
<#
.SYNOPSIS
Enumerates the Active Directory DNS zones for a given domain.
.PARAMETER Domain
The domain to query for zones, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.PARAMETER FullData
Switch. Return full computer objects instead of just system names (the default).
.EXAMPLE
PS C:\> Get-DNSZone
Retrieves the DNS zones for the current domain.
.EXAMPLE
PS C:\> Get-DNSZone -Domain dev.testlab.local -DomainController primary.testlab.local
Retrieves the DNS zones for the dev.testlab.local domain, reflecting the LDAP queries
through the primary.testlab.local domain controller.
#>
param(
[Parameter(Position=0, ValueFromPipeline=$True)]
[String]
$Domain,
[String]
$DomainController,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential,
[Switch]
$FullData
)
$DNSSearcher = Get-DomainSearcher -Domain $Domain -DomainController $DomainController -PageSize $PageSize -Credential $Credential
$DNSSearcher.filter="(objectClass=dnsZone)"
if($DNSSearcher) {
$Results = $DNSSearcher.FindAll()
$Results | Where-Object {$_} | ForEach-Object {
# convert/process the LDAP fields for each result
$Properties = Convert-LDAPProperty -Properties $_.Properties
$Properties | Add-Member NoteProperty 'ZoneName' $Properties.name
if ($FullData) {
$Properties
}
else {
$Properties | Select-Object ZoneName,distinguishedname,whencreated,whenchanged
}
}
$Results.dispose()
$DNSSearcher.dispose()
}
$DNSSearcher = Get-DomainSearcher -Domain $Domain -DomainController $DomainController -PageSize $PageSize -Credential $Credential -ADSprefix "CN=MicrosoftDNS,DC=DomainDnsZones"
$DNSSearcher.filter="(objectClass=dnsZone)"
if($DNSSearcher) {
$Results = $DNSSearcher.FindAll()
$Results | Where-Object {$_} | ForEach-Object {
# convert/process the LDAP fields for each result
$Properties = Convert-LDAPProperty -Properties $_.Properties
$Properties | Add-Member NoteProperty 'ZoneName' $Properties.name
if ($FullData) {
$Properties
}
else {
$Properties | Select-Object ZoneName,distinguishedname,whencreated,whenchanged
}
}
$Results.dispose()
$DNSSearcher.dispose()
}
}
filter Get-DNSRecord {
<#
.SYNOPSIS
Enumerates the Active Directory DNS records for a given zone.
.PARAMETER ZoneName
The zone to query for records (which can be enumearted with Get-DNSZone). Required.
.PARAMETER Domain
The domain to query for zones, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-DNSRecord -ZoneName testlab.local
Retrieve all records for the testlab.local zone.
.EXAMPLE
PS C:\> Get-DNSZone | Get-DNSRecord
Retrieve all records for all zones in the current domain.
.EXAMPLE
PS C:\> Get-DNSZone -Domain dev.testlab.local | Get-DNSRecord -Domain dev.testlab.local
Retrieve all records for all zones in the dev.testlab.local domain.
#>
param(
[Parameter(Position=0, ValueFromPipelineByPropertyName=$True, Mandatory=$True)]
[String]
$ZoneName,
[String]
$Domain,
[String]
$DomainController,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential
)
$DNSSearcher = Get-DomainSearcher -Domain $Domain -DomainController $DomainController -PageSize $PageSize -Credential $Credential -ADSprefix "DC=$($ZoneName),CN=MicrosoftDNS,DC=DomainDnsZones"
$DNSSearcher.filter="(objectClass=dnsNode)"
if($DNSSearcher) {
$Results = $DNSSearcher.FindAll()
$Results | Where-Object {$_} | ForEach-Object {
try {
# convert/process the LDAP fields for each result
$Properties = Convert-LDAPProperty -Properties $_.Properties | Select-Object name,distinguishedname,dnsrecord,whencreated,whenchanged
$Properties | Add-Member NoteProperty 'ZoneName' $ZoneName
# convert the record and extract the properties
if ($Properties.dnsrecord -is [System.DirectoryServices.ResultPropertyValueCollection]) {
# TODO: handle multiple nested records properly?
$Record = Convert-DNSRecord -DNSRecord $Properties.dnsrecord[0]
}
else {
$Record = Convert-DNSRecord -DNSRecord $Properties.dnsrecord
}
if($Record) {
$Record.psobject.properties | ForEach-Object {
$Properties | Add-Member NoteProperty $_.Name $_.Value
}
}
$Properties
}
catch {
Write-Warning "ERROR: $_"
$Properties
}
}
$Results.dispose()
$DNSSearcher.dispose()
}
}
filter Get-NetDomain {
<#
.SYNOPSIS
Returns a given domain object.
.PARAMETER Domain
The domain name to query for, defaults to the current domain.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetDomain -Domain testlab.local
.EXAMPLE
PS C:\> "testlab.local" | Get-NetDomain
.LINK
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
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Domain,
[Management.Automation.PSCredential]
$Credential
)
if($Credential) {
Write-Verbose "Using alternate credentials for Get-NetDomain"
if(!$Domain) {
# if no domain is supplied, extract the logon domain from the PSCredential passed
$Domain = $Credential.GetNetworkCredential().Domain
Write-Verbose "Extracted domain '$Domain' from -Credential"
}
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain, $Credential.UserName, $Credential.GetNetworkCredential().Password)
try {
[System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
}
catch {
Write-Verbose "The specified domain does '$Domain' not exist, could not be contacted, there isn't an existing trust, or the specified credentials are invalid."
$Null
}
}
elseif($Domain) {
$DomainContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $Domain)
try {
[System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($DomainContext)
}
catch {
Write-Verbose "The specified domain '$Domain' does not exist, could not be contacted, or there isn't an existing trust."
$Null
}
}
else {
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
}
}
filter Get-NetForest {
<#
.SYNOPSIS
Returns a given forest object.
.PARAMETER Forest
The forest name to query for, defaults to the current domain.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetForest -Forest external.domain
.EXAMPLE
PS C:\> "external.domain" | Get-NetForest
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Forest,
[Management.Automation.PSCredential]
$Credential
)
if($Credential) {
Write-Verbose "Using alternate credentials for Get-NetForest"
if(!$Forest) {
# if no domain is supplied, extract the logon domain from the PSCredential passed
$Forest = $Credential.GetNetworkCredential().Domain
Write-Verbose "Extracted domain '$Forest' from -Credential"
}
$ForestContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', $Forest, $Credential.UserName, $Credential.GetNetworkCredential().Password)
try {
$ForestObject = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest($ForestContext)
}
catch {
Write-Verbose "The specified forest '$Forest' does not exist, could not be contacted, there isn't an existing trust, or the specified credentials are invalid."
$Null
}
}
elseif($Forest) {
$ForestContext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', $Forest)
try {
$ForestObject = [System.DirectoryServices.ActiveDirectory.Forest]::GetForest($ForestContext)
}
catch {
Write-Verbose "The specified forest '$Forest' does not exist, could not be contacted, or there isn't an existing trust."
return $Null
}
}
else {
# otherwise use the current forest
$ForestObject = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
}
if($ForestObject) {
# get the SID of the forest root
$ForestSid = (New-Object System.Security.Principal.NTAccount($ForestObject.RootDomain,"krbtgt")).Translate([System.Security.Principal.SecurityIdentifier]).Value
$Parts = $ForestSid -Split "-"
$ForestSid = $Parts[0..$($Parts.length-2)] -join "-"
$ForestObject | Add-Member NoteProperty 'RootDomainSid' $ForestSid
$ForestObject
}
}
filter Get-NetForestDomain {
<#
.SYNOPSIS
Return all domains for a given forest.
.PARAMETER Forest
The forest name to query domain for.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetForestDomain
.EXAMPLE
PS C:\> Get-NetForestDomain -Forest external.local
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Forest,
[Management.Automation.PSCredential]
$Credential
)
$ForestObject = Get-NetForest -Forest $Forest -Credential $Credential
if($ForestObject) {
$ForestObject.Domains
}
}
filter Get-NetForestCatalog {
<#
.SYNOPSIS
Return all global catalogs for a given forest.
.PARAMETER Forest
The forest name to query domain for.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetForestCatalog
#>
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Forest,
[Management.Automation.PSCredential]
$Credential
)
$ForestObject = Get-NetForest -Forest $Forest -Credential $Credential
if($ForestObject) {
$ForestObject.FindAllGlobalCatalogs()
}
}
filter Get-NetDomainController {
<#
.SYNOPSIS
Return the current domain controllers for the active domain.
.PARAMETER Domain
The domain to query for domain controllers, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER LDAP
Switch. Use LDAP queries to determine the domain controllers.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetDomainController -Domain 'test.local'
Determine the domain controllers for 'test.local'.
.EXAMPLE
PS C:\> Get-NetDomainController -Domain 'test.local' -LDAP
Determine the domain controllers for 'test.local' using LDAP queries.
.EXAMPLE
PS C:\> 'test.local' | Get-NetDomainController
Determine the domain controllers for 'test.local'.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$True)]
[String]
$Domain,
[String]
$DomainController,
[Switch]
$LDAP,
[Management.Automation.PSCredential]
$Credential
)
if($LDAP -or $DomainController) {
# filter string to return all domain controllers
Get-NetComputer -Domain $Domain -DomainController $DomainController -Credential $Credential -FullData -Filter '(userAccountControl:1.2.840.113556.1.4.803:=8192)'
}
else {
$FoundDomain = Get-NetDomain -Domain $Domain -Credential $Credential
if($FoundDomain) {
$Founddomain.DomainControllers
}
}
}
########################################################
#
# "net *" replacements and other fun start below
#
########################################################
function Get-NetUser {
<#
.SYNOPSIS
Query information for a given user or users in the domain
using ADSI and LDAP. Another -Domain can be specified to
query for users across a trust.
Replacement for "net users /domain"
.PARAMETER UserName
Username filter string, wildcards accepted.
.PARAMETER Domain
The domain to query for users, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER ADSpath
The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
.PARAMETER Filter
A customized ldap filter string to use, e.g. "(description=*admin*)"
.PARAMETER AdminCount
Switch. Return users with adminCount=1.
.PARAMETER SPN
Switch. Only return user objects with non-null service principal names.
.PARAMETER Unconstrained
Switch. Return users that have unconstrained delegation.
.PARAMETER AllowDelegation
Switch. Return user accounts that are not marked as 'sensitive and not allowed for delegation'
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-NetUser -Domain testing
.EXAMPLE
PS C:\> Get-NetUser -ADSpath "LDAP://OU=secret,DC=testlab,DC=local"
#>
param(
[Parameter(Position=0, ValueFromPipeline=$True)]
[String]
$UserName,
[String]
$Domain,
[String]
$DomainController,
[String]
$ADSpath,
[String]
$Filter,
[Switch]
$SPN,
[Switch]
$AdminCount,
[Switch]
$Unconstrained,
[Switch]
$AllowDelegation,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential
)
begin {
if($Domain) {
$TargetDomain = $Domain
}
else {
$TargetDomain = (Get-NetDomain).name
}
# so this isn't repeated if users are passed on the pipeline
$UserSearcher = Get-DomainSearcher -Domain $TargetDomain -ADSpath $ADSpath -DomainController $DomainController -PageSize $PageSize -Credential $Credential
$PrimaryGroups = @{}
}
process {
if($UserSearcher) {
# if we're checking for unconstrained delegation
if($Unconstrained) {
Write-Verbose "Checking for unconstrained delegation"
$Filter += "(userAccountControl:1.2.840.113556.1.4.803:=524288)"
}
if($AllowDelegation) {
Write-Verbose "Checking for users who can be delegated"
# negation of "Accounts that are sensitive and not trusted for delegation"
$Filter += "(!(userAccountControl:1.2.840.113556.1.4.803:=1048574))"
}
if($AdminCount) {
Write-Verbose "Checking for adminCount=1"
$Filter += "(admincount=1)"
}
# check if we're using a username filter or not
if($UserName) {
# samAccountType=805306368 indicates user objects
$UserSearcher.filter="(&(samAccountType=805306368)(samAccountName=$UserName)$Filter)"
}
elseif($SPN) {
$UserSearcher.filter="(&(samAccountType=805306368)(servicePrincipalName=*)$Filter)"
}
else {
# filter is something like "(samAccountName=*blah*)" if specified
$UserSearcher.filter="(&(samAccountType=805306368)$Filter)"
}
try {
$Results = $UserSearcher.FindAll()
$Results | Where-Object {$_} | ForEach-Object {
# convert/process the LDAP fields for each result
$User = Convert-LDAPProperty -Properties $_.Properties
$User | Add-Member NoteProperty 'Domain' $TargetDomain
$DomainSID = $User.objectsid.Substring(0, $User.objectsid.LastIndexOf('-'))
$PrimaryGroupSID = "$DomainSID-$($User.primarygroupid)"
$User | Add-Member NoteProperty 'PrimaryGroupSID' $PrimaryGroupSID
if($PrimaryGroups[$PrimaryGroupSID]) {
$PrimaryGroupName = $PrimaryGroups[$PrimaryGroupSID]
}
else {
$PrimaryGroupName = Get-ADObject -Domain $Domain -SID $PrimaryGroupSID | Select-Object -ExpandProperty samaccountname
$PrimaryGroups[$PrimaryGroupSID] = $PrimaryGroupName
}
$User | Add-Member NoteProperty 'PrimaryGroupName' $PrimaryGroupName
$User.PSObject.TypeNames.Add('PowerView.User')
$User
}
$Results.dispose()
}
catch {
Write-Verbose "Error building the UserSearcher searcher object!"
}
$UserSearcher.dispose()
}
}
}
function Add-NetUser {
<#
.SYNOPSIS
Adds a domain user or a local user to the current (or remote) machine,
if permissions allow, utilizing the WinNT service provider and
DirectoryServices.AccountManagement, respectively.
The default behavior is to add a user to the local machine.
An optional group name to add the user to can be specified.
.PARAMETER UserName
The username to add. If not given, it defaults to 'backdoor'
.PARAMETER Password
The password to set for the added user. If not given, it defaults to 'Password123!'
.PARAMETER GroupName
Group to optionally add the user to.
.PARAMETER ComputerName
Hostname to add the local user to, defaults to 'localhost'
.PARAMETER Domain
Specified domain to add the user to.
.EXAMPLE
PS C:\> Add-NetUser -UserName john -Password 'Password123!'
Adds a localuser 'john' to the local machine with password of 'Password123!'
.EXAMPLE
PS C:\> Add-NetUser -UserName john -Password 'Password123!' -ComputerName server.testlab.local
Adds a localuser 'john' with password of 'Password123!' to server.testlab.local's local Administrators group.
.EXAMPLE
PS C:\> Add-NetUser -UserName john -Password password -GroupName "Domain Admins" -Domain ''
Adds the user "john" with password "password" to the current domain and adds
the user to the domain group "Domain Admins"
.EXAMPLE
PS C:\> Add-NetUser -UserName john -Password password -GroupName "Domain Admins" -Domain 'testing'
Adds the user "john" with password "password" to the 'testing' domain and adds
the user to the domain group "Domain Admins"
.Link
http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/23/use-powershell-to-create-local-user-accounts.aspx
#>
[CmdletBinding()]
Param (
[ValidateNotNullOrEmpty()]
[String]
$UserName = 'backdoor',
[ValidateNotNullOrEmpty()]
[String]
$Password = 'Password123!',
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[ValidateNotNullOrEmpty()]
[Alias('HostName')]
[String]
$ComputerName = 'localhost',
[ValidateNotNullOrEmpty()]
[String]
$Domain
)
if ($Domain) {
$DomainObject = Get-NetDomain -Domain $Domain
if(-not $DomainObject) {
Write-Warning "Error in grabbing $Domain object"
return $Null
}
# add the assembly we need
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
# http://richardspowershellblog.wordpress.com/2008/05/25/system-directoryservices-accountmanagement/
# get the domain context
$Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList ([System.DirectoryServices.AccountManagement.ContextType]::Domain), $DomainObject
# create the user object
$User = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal -ArgumentList $Context
# set user properties
$User.Name = $UserName
$User.SamAccountName = $UserName
$User.PasswordNotRequired = $False
$User.SetPassword($Password)
$User.Enabled = $True
Write-Verbose "Creating user $UserName to with password '$Password' in domain $Domain"
try {
# commit the user
$User.Save()
"[*] User $UserName successfully created in domain $Domain"
}
catch {
Write-Warning '[!] User already exists!'
return
}
}
else {
Write-Verbose "Creating user $UserName to with password '$Password' on $ComputerName"
# if it's not a domain add, it's a local machine add
$ObjOu = [ADSI]"WinNT://$ComputerName"
$ObjUser = $ObjOu.Create('User', $UserName)
$ObjUser.SetPassword($Password)
# commit the changes to the local machine
try {
$Null = $ObjUser.SetInfo()
"[*] User $UserName successfully created on host $ComputerName"
}
catch {
Write-Warning '[!] Account already exists!'
return
}
}
# if a group is specified, invoke Add-NetGroupUser and return its value
if ($GroupName) {
# if we're adding the user to a domain
if ($Domain) {
Add-NetGroupUser -UserName $UserName -GroupName $GroupName -Domain $Domain
"[*] User $UserName successfully added to group $GroupName in domain $Domain"
}
# otherwise, we're adding to a local group
else {
Add-NetGroupUser -UserName $UserName -GroupName $GroupName -ComputerName $ComputerName
"[*] User $UserName successfully added to group $GroupName on host $ComputerName"
}
}
}
function Add-NetGroupUser {
<#
.SYNOPSIS
Adds a user to a domain group or a local group on the current (or remote) machine,
if permissions allow, utilizing the WinNT service provider and
DirectoryServices.AccountManagement, respectively.
.PARAMETER UserName
The domain username to query for.
.PARAMETER GroupName
Group to add the user to.
.PARAMETER ComputerName
Hostname to add the user to, defaults to localhost.
.PARAMETER Domain
Domain to add the user to.
.EXAMPLE
PS C:\> Add-NetGroupUser -UserName john -GroupName Administrators
Adds a localuser "john" to the local group "Administrators"
.EXAMPLE
PS C:\> Add-NetGroupUser -UserName john -GroupName "Domain Admins" -Domain dev.local
Adds the existing user "john" to the domain group "Domain Admins" in "dev.local"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$UserName,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[ValidateNotNullOrEmpty()]
[Alias('HostName')]
[String]
$ComputerName,
[String]
$Domain
)
# add the assembly if we need it
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
# if we're adding to a remote host's local group, use the WinNT provider
if($ComputerName -and ($ComputerName -ne "localhost")) {
try {
Write-Verbose "Adding user $UserName to $GroupName on host $ComputerName"
([ADSI]"WinNT://$ComputerName/$GroupName,group").add("WinNT://$ComputerName/$UserName,user")
"[*] User $UserName successfully added to group $GroupName on $ComputerName"
}
catch {
Write-Warning "[!] Error adding user $UserName to group $GroupName on $ComputerName"
return
}
}
# otherwise it's a local machine or domain add
else {
try {
if ($Domain) {
Write-Verbose "Adding user $UserName to $GroupName on domain $Domain"
$CT = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$DomainObject = Get-NetDomain -Domain $Domain
if(-not $DomainObject) {
return $Null
}
# get the full principal context
$Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $CT, $DomainObject
}
else {
# otherwise, get the local machine context
Write-Verbose "Adding user $UserName to $GroupName on localhost"
$Context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine, $Env:ComputerName)
}
# find the particular group
$Group = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($Context,$GroupName)
# add the particular user to the group
$Group.Members.add($Context, [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName, $UserName)
# commit the changes
$Group.Save()
}
catch {
Write-Warning "Error adding $UserName to $GroupName : $_"
}
}
}
function Get-UserProperty {
<#
.SYNOPSIS
Returns a list of all user object properties. If a property
name is specified, it returns all [user:property] values.
Taken directly from @obscuresec's post:
http://obscuresecurity.blogspot.com/2014/04/ADSISearcher.html
.PARAMETER Properties
Property names to extract for users.
.PARAMETER Domain
The domain to query for user properties, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-UserProperty -Domain testing
Returns all user properties for users in the 'testing' domain.
.EXAMPLE
PS C:\> Get-UserProperty -Properties ssn,lastlogon,location
Returns all an array of user/ssn/lastlogin/location combinations
for users in the current domain.
.LINK
http://obscuresecurity.blogspot.com/2014/04/ADSISearcher.html
#>
[CmdletBinding()]
param(
[String[]]
$Properties,
[String]
$Domain,
[String]
$DomainController,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential
)
if($Properties) {
# extract out the set of all properties for each object
$Properties = ,"name" + $Properties
Get-NetUser -Domain $Domain -DomainController $DomainController -PageSize $PageSize -Credential $Credential | Select-Object -Property $Properties
}
else {
# extract out just the property names
Get-NetUser -Domain $Domain -DomainController $DomainController -PageSize $PageSize -Credential $Credential | Select-Object -First 1 | Get-Member -MemberType *Property | Select-Object -Property 'Name'
}
}
filter Find-UserField {
<#
.SYNOPSIS
Searches user object fields for a given word (default *pass*). Default
field being searched is 'description'.
Taken directly from @obscuresec's post:
http://obscuresecurity.blogspot.com/2014/04/ADSISearcher.html
.PARAMETER SearchTerm
Term to search for, default of "pass".
.PARAMETER SearchField
User field to search, default of "description".
.PARAMETER ADSpath
The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
.PARAMETER Domain
Domain to search computer fields for, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Find-UserField -SearchField info -SearchTerm backup
Find user accounts with "backup" in the "info" field.
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipeline=$True)]
[String]
$SearchTerm = 'pass',
[String]
$SearchField = 'description',
[String]
$ADSpath,
[String]
$Domain,
[String]
$DomainController,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200,
[Management.Automation.PSCredential]
$Credential
)
Get-NetUser -ADSpath $ADSpath -Domain $Domain -DomainController $DomainController -Credential $Credential -Filter "($SearchField=*$SearchTerm*)" -PageSize $PageSize | Select-Object samaccountname,$SearchField
}
filter Get-UserEvent {
<#
.SYNOPSIS
Dump and parse security events relating to an account logon (ID 4624)
or a TGT request event (ID 4768). Intended to be used and tested on
Windows 2008 Domain Controllers.
Admin Reqd? YES
Author: @sixdub
.PARAMETER ComputerName
The computer to get events from. Default: Localhost
.PARAMETER EventType
Either 'logon', 'tgt', or 'all'. Defaults: 'logon'
.PARAMETER DateStart
Filter out all events before this date. Default: 5 days
.PARAMETER Credential
A [Management.Automation.PSCredential] object of alternate credentials
for connection to the target domain.
.EXAMPLE
PS C:\> Get-UserEvent -ComputerName DomainController.testlab.local
.LINK
http://www.sixdub.net/2014/11/07/offensive-event-parsing-bringing-home-trophies/
#>
Param(
[Parameter(ValueFromPipeline=$True)]
[String]
$ComputerName = $Env:ComputerName,
[String]
[ValidateSet("logon","tgt","all")]
$EventType = "logon",
[DateTime]
$DateStart = [DateTime]::Today.AddDays(-5),
[Management.Automation.PSCredential]
$Credential
)
if($EventType.ToLower() -like "logon") {
[Int32[]]$ID = @(4624)
}
elseif($EventType.ToLower() -like "tgt") {
[Int32[]]$ID = @(4768)
}
else {
[Int32[]]$ID = @(4624, 4768)
}
if($Credential) {
Write-Verbose "Using alternative credentials"
$Arguments = @{
'ComputerName' = $ComputerName;
'Credential' = $Credential;
'FilterHashTable' = @{ LogName = 'Security'; ID=$ID; StartTime=$DateStart};
'ErrorAction' = 'SilentlyContinue';
}
}
else {
$Arguments = @{
'ComputerName' = $ComputerName;
'FilterHashTable' = @{ LogName = 'Security'; ID=$ID; StartTime=$DateStart};
'ErrorAction' = 'SilentlyContinue';
}
}
# grab all events matching our filter for the specified host
Get-WinEvent @Arguments | ForEach-Object {
if($ID -contains 4624) {
# first parse and check the logon event type. This could be later adapted and tested for RDP logons (type 10)
if($_.message -match '(?s)(?<=Logon Type:).*?(?=(Impersonation Level:|New Logon:))') {
if($Matches) {
$LogonType = $Matches[0].trim()
$Matches = $Null
}
}
else {
$LogonType = ""
}
# interactive logons or domain logons
if (($LogonType -eq 2) -or ($LogonType -eq 3)) {
try {
# parse and store the account used and the address they came from
if($_.message -match '(?s)(?<=New Logon:).*?(?=Process Information:)') {
if($Matches) {
$UserName = $Matches[0].split("`n")[2].split(":")[1].trim()
$Domain = $Matches[0].split("`n")[3].split(":")[1].trim()
$Matches = $Null
}
}
if($_.message -match '(?s)(?<=Network Information:).*?(?=Source Port:)') {
if($Matches) {
$Address = $Matches[0].split("`n")[2].split(":")[1].trim()
$Matches = $Null
}
}
# only add if there was account information not for a machine or anonymous logon
if ($UserName -and (-not $UserName.endsWith('$')) -and ($UserName -ne 'ANONYMOUS LOGON')) {
$LogonEventProperties = @{
'Domain' = $Domain
'ComputerName' = $ComputerName
'Username' = $UserName
'Address' = $Address
'ID' = '4624'
'LogonType' = $LogonType
'Time' = $_.TimeCreated
}
New-Object -TypeName PSObject -Property $LogonEventProperties
}
}
catch {
Write-Verbose "Error parsing event logs: $_"
}
}
}
if($ID -contains 4768) {
# the TGT event type
try {
if($_.message -match '(?s)(?<=Account Information:).*?(?=Service Information:)') {
if($Matches) {
$Username = $Matches[0].split("`n")[1].split(":")[1].trim()
$Domain = $Matches[0].split("`n")[2].split(":")[1].trim()
$Matches = $Null
}
}
if($_.message -match '(?s)(?<=Network Information:).*?(?=Additional Information:)') {
if($Matches) {
$Address = $Matches[0].split("`n")[1].split(":")[-1].trim()
$Matches = $Null
}
}
$LogonEventProperties = @{
'Domain' = $Domain
'ComputerName' = $ComputerName
'Username' = $UserName
'Address' = $Address
'ID' = '4768'
'LogonType' = ''
'Time' = $_.TimeCreated
}
New-Object -TypeName PSObject -Property $LogonEventProperties
}
catch {
Write-Verbose "Error parsing event logs: $_"
}
}
}
}
function Get-ObjectAcl {
<#
.SYNOPSIS
Returns the ACLs associated with a specific active directory object.
Thanks Sean Metcalf (@pyrotek3) for the idea and guidance.
.PARAMETER SamAccountName
Object name to filter for.
.PARAMETER Name
Object name to filter for.
.PARAMETER DistinguishedName
Object distinguished name to filter for.
.PARAMETER ResolveGUIDs
Switch. Resolve GUIDs to their display names.
.PARAMETER Filter
A customized ldap filter string to use, e.g. "(description=*admin*)"
.PARAMETER ADSpath
The LDAP source to search through, e.g. "LDAP://OU=secret,DC=testlab,DC=local"
Useful for OU queries.
.PARAMETER ADSprefix
Prefix to set for the searcher (like "CN=Sites,CN=Configuration")
.PARAMETER RightsFilter
Only return results with the associated rights, "All", "ResetPassword","WriteMembers"
.PARAMETER Domain
The domain to use for the query, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.EXAMPLE
PS C:\> Get-ObjectAcl -SamAccountName matt.admin -domain testlab.local
Get the ACLs for the matt.admin user in the testlab.local domain
.EXAMPLE
PS C:\> Get-ObjectAcl -SamAccountName 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
PS C:\> Get-NetOU -FullData | Get-ObjectAcl -ResolveGUIDs
Enumerate the ACL permissions for all OUs in the domain.
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
$SamAccountName,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
$Name = "*",
[Parameter(ValueFromPipelineByPropertyName=$True)]
[String]
$DistinguishedName = "*",
[Switch]
$ResolveGUIDs,
[String]
$Filter,
[String]
$ADSpath,
[String]
$ADSprefix,
[String]
[ValidateSet("All","ResetPassword","WriteMembers")]
$RightsFilter,
[String]
$Domain,
[String]
$DomainController,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200
)
begin {
$Searcher = Get-DomainSearcher -Domain $Domain -DomainController $DomainController -ADSpath $ADSpath -ADSprefix $ADSprefix -PageSize $PageSize
# get a GUID -> name mapping
if($ResolveGUIDs) {
$GUIDs = Get-GUIDMap -Domain $Domain -DomainController $DomainController -PageSize $PageSize
}
}
process {
if ($Searcher) {
if($SamAccountName) {
$Searcher.filter="(&(samaccountname=$SamAccountName)(name=$Name)(distinguishedname=$DistinguishedName)$Filter)"
}
else {
$Searcher.filter="(&(name=$Name)(distinguishedname=$DistinguishedName)$Filter)"
}
try {
$Results = $Searcher.FindAll()
$Results | Where-Object {$_} | ForEach-Object {
$Object = [adsi]($_.path)
if($Object.distinguishedname) {
$Access = $Object.PsBase.ObjectSecurity.access
$Access | ForEach-Object {
$_ | Add-Member NoteProperty 'ObjectDN' $Object.distinguishedname[0]
if($Object.objectsid[0]){
$S = (New-Object System.Security.Principal.SecurityIdentifier($Object.objectsid[0],0)).Value
}
else {
$S = $Null
}
$_ | Add-Member NoteProperty 'ObjectSID' $S
$_
}
}
} | ForEach-Object {
if($RightsFilter) {
$GuidFilter = Switch ($RightsFilter) {
"ResetPassword" { "00299570-246d-11d0-a768-00aa006e0529" }
"WriteMembers" { "bf9679c0-0de6-11d0-a285-00aa003049e2" }
Default { "00000000-0000-0000-0000-000000000000"}
}
if($_.ObjectType -eq $GuidFilter) { $_ }
}
else {
$_
}
} | ForEach-Object {
if($GUIDs) {
# if we're resolving GUIDs, map them them to the resolved hash table
$AclProperties = @{}
$_.psobject.properties | ForEach-Object {
if( ($_.Name -eq 'ObjectType') -or ($_.Name -eq 'InheritedObjectType') ) {
try {
$AclProperties[$_.Name] = $GUIDS[$_.Value.toString()]
}
catch {
$AclProperties[$_.Name] = $_.Value
}
}
else {
$AclProperties[$_.Name] = $_.Value
}
}
New-Object -TypeName PSObject -Property $AclProperties
}
else { $_ }
}
$Results.dispose()
$Searcher.dispose()
}
catch {
Write-Warning $_
}
}
}
}
function Add-ObjectAcl {
<#
.SYNOPSIS
Adds an ACL for a specific active directory object.
AdminSDHolder ACL approach from Sean Metcalf (@pyrotek3)
https://adsecurity.org/?p=1906
ACE setting method adapted from 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.
'ResetPassword' doesn't need to know the user's current password
'WriteMembers' allows for the modification of group membership
.PARAMETER TargetSamAccountName
Target object name to filter for.
.PARAMETER TargetName
Target object name to filter for.
.PARAMETER TargetDistinguishedName
Target object distinguished name to filter for.
.PARAMETER TargetFilter
A customized ldap filter string to use to find a target, e.g. "(description=*admin*)"
.PARAMETER TargetADSpath
The LDAP source for the target, e.g. "LDAP://OU=secret,DC=testlab,DC=local"
.PARAMETER TargetADSprefix
Prefix to set for the target searcher (like "CN=Sites,CN=Configuration")
.PARAMETER PrincipalSID
The SID of the principal object to add for access.
.PARAMETER PrincipalName
The name of the principal object to add for access.
.PARAMETER PrincipalSamAccountName
The samAccountName of the principal object to add for access.
.PARAMETER Rights
Rights to add for the principal, "All","ResetPassword","WriteMembers","DCSync"
.PARAMETER Domain
The domain to use for the target query, defaults to the current domain.
.PARAMETER DomainController
Domain controller to reflect LDAP queries through.
.PARAMETER PageSize
The PageSize to set for the LDAP searcher object.
.EXAMPLE
Add-ObjectAcl -TargetSamAccountName matt -PrincipalSamAccountName john