📖
레드팀 플레이북
깃허브기여하는 방법WhoAreWe블로그
  • 레드팀 플레이북
  • 레드팀이란
  • 레드팀 글로벌 동향 (2024)
  • 베이직 레드팀(Basic Redteam)
    • 개요
    • 1. 공격자 인프라 구성
    • 2. 초기 침투
    • 3. 정보 수집
    • 4. 권한 상승 - US
    • 5. 횡적 이동: USWKSTN01 -> SQL01
    • 6. 권한 상승 - SQL01
    • 7. 도메인 장악 WEB01
    • 8. US -> RT 장악
    • 9. RT -> DEV 정보 수집
    • 10. 권한 상승 및 목표 달성
  • 🚧인프라 (Infrastructure)
    • 개념
    • 예시 인프라
    • 팀 서버 - Sliver
      • 스테이저 (Stager) 사용
    • 도메인 분류와 신뢰도
    • HTTP 리다이렉터
    • HTTPS 리다이렉터
    • SMTP Gophish + Mail
    • SMTP Gophish + ESP
    • SMTP Gophish + Relay + ESP
    • 인프라 구축 자동화
      • 테라폼 (Terraform)
      • SMTP 테라폼 자동화
      • HTTPS 리다이렉터 자동화 (AWS)
    • old-네뷸라를 이용한 인프라 구축
      • 도메인과 리다이렉터 설정
      • 중립 공간 (클라우드) 설정
      • 네뷸라 (Nebula)
      • 네뷸라 설정
    • 도메인 프론팅 (Domain Fronting)
    • 도메인 프론팅 - Azure Edgio CDN
    • Cloudflared Tunnel과 Worker
    • Cloudflared Tunnel과 Pages
  • 🔎초기 정찰
    • 개념
    • 타겟 발견
    • OSINT
      • 작전보안
      • 자산 정보 수집
      • 구글 도킹
  • ⚔️초기 침투 (Initial Access)
    • 개념
    • 피싱 첨부파일
      • 오피스 VBA 매크로
      • XLM Excel 4.0 매크로
      • 원격 템플렛 인젝션
      • VBA Stomping
      • HTA
      • LNK
      • ISO
      • VBA Purging - TODO
      • DotNetToJS - TODO
      • Follina - TODO
    • HTML 스머글링 (Smuggling)
    • 피싱 - AitM (Adversary in the Middle)
    • Living Off Trusted Sites (LOTS)
  • 🐳정보 수집 - 내부망
    • 개념
    • 로컬 호스트 정보 수집
    • 블러드하운드
    • SMB 쉐어 수집
    • 정보 수집 - 파워쉘
    • 정보 수집 - C# - TODO
    • 커버로스 유저 이름 정보수집
    • CME - 호스트이름과 IP주소
    • LDAP Anonymous Bind
  • 🐴실행 (Execution)
    • 개념
    • 파워쉘
      • 인메모리 실행
      • C# 실행
      • 윈도우 API 실행
    • LOLBAS
    • Native API - TODO
  • 🙃지속성 (Persistence)
    • 개념
    • 골든 티켓 (Golden Ticket)
    • DLL 사이드로딩 (DLL Side-Loading)
    • DLL Search Order Hijacking - TODO
    • 레지스트리 / 스타트업 폴더
  • ⬆️권한 상승
    • 개념
    • AD 권한 상승
      • Active Directory Certificate Services (ADCS)
        • ESC1
        • ESC8
      • Shadow Credentials
      • noPac
      • Kerberoasting
      • AS-REP Roasting
      • DHCPv6 포이즈닝
      • Resource-Based Constrained Delegation (RBCD)
      • SCCM
    • AD-DACL
      • AddAllowedToAct
      • AddKeyCredentialLink
      • GenericAll
      • GenericWrite
      • WriteDACL
      • AllExtendedRights
      • WriteAccountRestrictions
      • WriteOwner
      • AddMember
    • 로컬 권한 상승 - TODO
      • 잘못된 서비스 설정
      • Unquoted Service Path
      • Always Install Elevated
      • PrintNightmare
  • 🐍보안 우회 (Defense Evasion)
    • 쉘코드 암호화
    • 런타임 다이나믹 링킹 (Run-time Dynamic Linking)
    • AMSI 우회
    • 유저랜드 후킹 - 역사
    • 유저랜드 커널랜드 윈도우API 개념
    • 유저랜드 후킹
    • DInvoke - 시스템 콜
    • 페이로드 크기
    • 가변적 C2 프로필
    • 프로세스 인젝션
      • CreateRemoteThread
      • NtMapViewOfSection
    • 간단 디펜더 우회 - 쉘코드
    • 간단 디펜더 우회 - C#
    • MSIExec
    • 다형성 코드
  • 👿후속 공격 (Post Exploitation)
    • 후속 공격의 진화
    • External SID Golden Ticket
  • 🎭계정 정보 탈취 (Credential Access)
    • 커버로스
      • 커버로스팅 (Kerberoasting)
      • AS-Rep Roasting
    • 비밀번호 스프레이 공격
    • LLMNR/NBT-NS 포이즈닝
    • NTLM 릴레이 (NTLM Relay)
      • SMB to SMB
      • SMB to LDAP/S
      • HTTP to LDAP
      • SMB to HTTP
      • SMB to SCCM
    • 강제 인증 (Authentication Coercion)
      • MS-RPRN - Printerbug / Print Spooler
      • MS-EFSRPC - Petitpotam
      • MS-FSRVP - ShadowCoerce
      • MS-DFSNM - DFSCoerce
    • NTLM 다운그레이드
    • DHCPv6 포이즈닝
    • LAPS - TODO
    • DCSync
    • DPAPI
  • ↔️횡적 이동 (Lateral Movement)
    • 개념
    • Pass-the-Hash
    • SMB 와 PsExec
    • WMI
    • WinRM / Powershell Remoting
    • RDP
    • SSH Port Forwarding & Tunneling
    • Dynamic Port Forwarding & ProxyChains
    • 네트워크 피버팅 - 툴
    • Network Pivoting (피벗) - TODO
  • 개념
    • 윈도우 사용자 인증
      • NTLM 인증
      • 커버로스 (Kerberos) 인증 - TODO
      • ADCS 인증서 기반 인증
    • AD 관련 용어 해설
  • 실 공격 TTP와 대응방안 - TODO
    • 개념
  • 🧑‍🔬홈 랩 (Home lab)
    • 시스몬 (sysmon) 설치
    • SIEM과 EDR 솔루션 설치
    • 취약한 랩을 위한 설정 커맨드
    • 말웨어 자동 분석툴 Cuckoo 샌드박스 설치
  • 기본 개념
    • DNS
      • 사이버 보안에 필요한 DNS 개념 편 #1
      • 해킹에 필요한 DNS 공격 & 우회 기법 편 #2
      • 방어에 필요한 DNS 탐지 편 #3
  • 웹 & 모바일
    • 01-계정관리
      • 통신 과정 흐름 훑어보기
      • 첫번쩨, payload설정 방법
      • 두번째, 세션을 유지하는 방법
      • CSRF Token에 관하여
      • 세번째, OWASP Juice Shop 로그인 페이지에서의 통신 흐름과 구조 알아보기
  • 🎅MISC
    • Host-based 공격 CheatSheet (FEAT. OSCP)
      • Enumeration (정보 수집 및 열거)
      • Exploitation (공격)
      • Post Exploitation (후속공격)
    • Changelog
    • 기여하는 방법
    • 레퍼런스와 크레딧
    • C# snippets
    • winapi 리스트
      • original notes from obsidian
    • 파워쉘 원라이너 (oneliner)
  • 📖Personal-Research
    • README-and-Template
      • HellsGate
      • HalosGate
      • FreshyCall
Powered by GitBook
On this page
  • 개념
  • 주의
  • 잘못된 설정
  1. 홈 랩 (Home lab)

취약한 랩을 위한 설정 커맨드

개념

홈 랩을 만들어 내부망 관련된 모의해킹을 하려면 실무에서 마주칠 수 있는 잘못된 설정을 홈랩에 "심어야"한다. 대부분의 모의해커들은 공격할 줄은 알지만, 공격이 가능한 잘못된 설정이 어디서 왜 발생한 것인지는 모르는 경우가 많다. 다음은 AD 공격과 관련된 잘못된 설정을 하는 명령어들이다.

주의

다음의 설정들은 자신의 홈랩이 아니라면 절대로 적용해서는 안된다. 이에 따라 발생할 수 있는 피해와 관련해 레드팀 프로젝트는 책임을 지지 않는다.

잘못된 설정

LDAP Signing on/off

# GPO 
Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options
Domain Controller: LDAP Server Signing Requirements 

LDAP Channel Binding

# Registry 
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\NTDS\Parameters" -Name "LdapEnforceChannelBinding" -Value 3

LDAP Anonymous Bind Enabled


# Powershell 
$directoryServicesDN = "CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration," + (Get-ADDomain).DistinguishedName

$currentValue = (Get-ADObject -Identity $directoryServicesDN -Properties "dSHeuristics").dSHeuristics
if ($currentValue -ne "0000002") {
    Set-ADObject -Identity $directoryServicesDN -Replace @{dSHeuristics="0000002"}
    Write-Output "dSHeuristics updated successfully."
} else {
    Write-Output "dSHeuristics is already set to the desired value."
}

$domainDN = (Get-ADDomain).DistinguishedName
& dsacls "CN=Users,$domainDN" /G 'ANONYMOUS LOGON:GR'

# --------- GUI -----------
# ADSI and dSHeurstics setting 
ADSI Edit > Connection Settings + Select A Well known Naming Context "Configuration > 
CN=Services > CN=Windos NT > CN=Directory Services > Properties > dSHeuristics set to 0000002 (seven zeros)

# Anonymous Logon READ permission on Users Container  
ADUC > Advanced > Users Container > Properties > Permissions > Add > Anonymous Logon > "READ" permission

# ------- DEBUG --------
crackmapexec ldap <Dc> -u '' -p '' --users

SMB signing off

set-smbserverconfiguration -requiresecuritysignature $False 

Defender off

set-mppreference -disablerealtimemonitoring $true -DisableScriptScanning $true -DisableIOAVProtection $true

Set-ItemProperty -Path 'HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender' -name "DisableAntiSpyware" -value 1 -Type DWORD

Windows update off

reg.exe add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUOptions /t REG_DWORD /d 1 /f

reg.exe delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" /f

sc.exe config wuauserv start= disabled
net.exe stop wuauserv

Firewall off

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

Winrm

Enable-PSRemoting -Force
winrm set winrm/config/Client '@{AllowUnencrypted = "true"}'
Set-Item WSMan:localhost\client\trustedhosts -value * -Force
winrm set winrm/config/client/auth '@{Basic="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'

Password Policy

Computer Configuration\Policies\Windows Settings\Security Settings\Account Policies\Password Policy

Computer Configuration\Policies\Windows Settings\Security Settings\Account Policies\Account Lockout Policy 

NTLMv1 - server

reg add HKLM\SYSTEM\CurrentControlSet\Control\Lsa\ /v lmcompatibilitylevel /t REG_DWORD /d 0 /f

Two-way Trust

1. Allow zone transfer on the DCs (to any server for more misconfiguration!). DNS -> Domain -> Properties -> Zone Transfer -> Allow to any. Do this for both forest's DCs. 

2. Create secondary zone for each DCs. DNS -> Forward Lookup Zones -> ?New zones -> secondary zone -> name blahblah -> type in each others' DC ip -> good! 

3. Create two-way trust! 
- I did selective trust, but more misconfiguration would be forest-wide trust. 
- For some reason, creating domain trust from domainA -> domainB worked, but domainB -> domainA resulted in "domain cannot be contacted". Even after dns restart, reboot, etc. ??? 

ShadowCoerce - FSRVP

File and Storage service -> File and iSCSI service -> File Server VSS Agent Service 

DFSCoerce - DFSNM

File and Storage service -> File and iSCSI service -> DFS Replication

ADCS Various ESC

# Create Cert Template 
- certtmpl.msc -> Duplicate User -> Subject Name -> Supply in request (required for ESC1,2,3) 
- Extensions -> Application Policies -> Edit this for EKU (client auth, any purpose) 
- Security -> Give write/enroll permission to Domain Users (various ESC)
- Change the name of the template 

# Publish Cert Template 
- Use Enterprise admin. Even domain admin doesn't work. 
- certsrv.msc -> Certificate Templates -> New -> the template that we created above 

-------


# ESC6 
- certutil -setreg policy\EditFlags +EDITF_ATTRIBUTESUBJECTALTNAME2
- This requires a reboot. 

--- 

# ESC8 
Install Web Enrollment and Web Service. 
Make sure to install CA first, separately. When CA is installed and configured, then install Web Enrollment and Web Service. 

LLMNR powershell scuffed version

while($true)
{
  ls \\doesntexist\share\update.ps1
  start-sleep -seconds 5
}

--- 

# Setting the GPO for batch job rights 

Running from a DC -> Assign the user a "Batch job rights" through GPO 

Either open domain policy (if not DC) or Default Domain Controller policy (if DC) 

Computer Configuration > Windows Settings > Security Settings > Local Policies > User Rights Assignment node > Log on as a batch job > specify the user that's running the task 

gpupdate.exe /force 
--- 

# Actually creating Task Scheduler 

New Task -> Run whether user is logged on or not -> Change User or group to whatever user to run 

Triggers -> At Startup 

Actions -> start a program -> powershell.exe (-execution bypass c:\scripts\check.ps1) 

DCSync - domain user

# Powerview ez clap 
Add-ObjectACL -PrincipalIdentity spotless -Rights DCSync

# Using Active Directory Administrative Center because no internet :sadge: 

domain right click -> properties -> scroll down -> security -> Add specific domain user or group -> Allow the following 
- Replicating Directory Changes 
- Replicating Directory Changes All 
- replicating Directory Chagnes in Filtered Set 

Sometimes ADAC might just crash, but the change goes through (wtf)

LSA configuration

# Optional (I think) 
Default Domain GPO -> Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > User Rights Assignment > Log on as a service > specify domain user here 

gpupdate.exe /force 

# Go to whatever host and just change print spooler because it's easy
services.msc > UPNP Device Host or Print Spooler > properties > logon > domain/user user + password 
restart > fails. doens't matter, creds are stored in plaintext in lsa secrets hive. 

Disable SMBv1 for no MS17-010 (shikata)

Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force	

Shadow Credentials & GenericAll

# Giving permissions on user A to have genericAll rights on user B 
ADAC -> Domain -> Users -> user B -> Properties -> scroll down to Extensions -> Security -> Advanced -> user A -> check genericAll rights 

# Remember, add rights on user B that will ALLOW user A to genericAll. So edit user B. 

Netlogon share

c:\windows\sysvol\sysvol\<domain>\scripts

RBCD

# ty ired.team - spotless 
# pre-reqs
1. User has local admin rights on WS02 
2. User has WRITE privilege on target WS01 
3. WS02 (or other machines) vulnerable to auth coercion and has WebDAV installed 

seems like the target need to be a privileged box like DC for RBCD to be useful? 

LDAP Signing off

Default Domain Controller Policy > Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options > Domain Controller: LDAP server signing requirements -> None

Default Domain Controller Policy > Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options > Network security: LDAP client signing requirements -> None 

gpupdate.exe /force 

WebDAV

Features -> IIS -> WebDAV, basic auth, windows auth 

IIS -> Default Web site -> WebDAV authoring rules -> *, All Users, read+write+source, then "Enable WebDAV"

IIS -> Default Web Site -> Authentication -> Enable Anonymous, Basic, and Windows auth 

IIS -> Default Web site -> Advanced (WebDAV Settings) -> Allow Anonymous Property Queries "True" 

IIS -> Default WEb site -> WebDAV authoring rules -> Disable and Enable webdav (restart) 

Fingers crossed it works now 

# Having WebDAV on CA server with Web Enrollment may not work - need more testing. 

MachineAccountQuota - for shared lab environment

Get-ADObject -Identity ((Get-ADDomain).distinguishedname) -Properties ms-DS-MachineAccountQuota
Set-ADDomain -Identity <DomainName> -Replace @{"ms-DS-MachineAccountQuota"="500"}

Adding Users

# Loop this with random passwords from rockyou.txt 

New-ADUser -Name "username" -Accountpassword (Read-Host -AsSecureString "password") -Enabled $true -PasswordNeverExpires $true 

See my license

slmgr /dlv 

Rearm

slmgr.vbs -rearm 

Full clone machine Sysprep change SID

# Sometimes, fully cloned machines have duplicate SID, which prevents the machines from joining the domain. Use Sysprep to change that. 

c:\windows\system32\sysprep\sysprep.exe /oobe /generalize /reboot 

# change the hostname and the static ip address after the sysprep reboot 

# get machine sid for sanity check 
get-adcomputer computername -prop sid

Allow Anonymous access on shares

Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -name "everyoneincludesanonymous" -value 1 -Type DWORD
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -name "restrictanonymous" -value 0 -Type DWORD
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -name "restrictanonymoussam" -value 0 -Type DWORD
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -name "LimitBlankPasswordUse" -value 0 -Type DWORD
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' -name "requiresecuritysignature" -value 0 -Type DWORD
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' -name "restrictnullsessaccess" -value 0 -Type DWORD
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' -name "NullSessionPipes" -value "*" -Type String
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' -name "NullSessionShares" -value "*" -Type String

# Right click on share -> Properties 
- "Security" > Add Everyone and add all permissions
- "Sharing" > Advanced Sharing > permissions > Add Everyone and all permissions

# Test it, or use cme 
net use \\servername\sharename "" /user:""

Guest/Anonymous access on shares ver.2

# Allow anonymous on Windows 10
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters" -Name "AllowInsecureGuestAuth" -Value 1 -Type DWord

# Activate guest account
net user guest /active:yes

# Ensure directory structure for SMB share exists
New-Item -Path "C:\" -ItemType Directory -Force

# Add Everyone full control to the directory
$acl = Get-Acl -Path "C:\"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.SetAccessRule($accessRule)
Set-Acl -Path "C:\" -AclObject $acl

# Create SMB share
New-SmbShare -Name "C" -Path "C:\" -FullAccess "Everyone" -Description "Entier C Filesystem"

Remove History

echo "hi" >> (Get-PSReadlineOption).HistorySavePath
clear-history 

SCCM Server Installation

References: 
- https://www.prajwaldesai.com/sccm-1902-install-guide-using-baseline-media/#Step-by-Step-SCCM-1902-Install-Guide
- https://www.prajwal.org/sccm-network-access-account/

The references are pretty straight forward. 
- Domain container, user, group configuration 
- Install SQL server on the server that SCCM will be also installed. (SQL2017, SCCM 2203 worked) 
- If SCCM complains about not finding the correct MSSQL instance, 
do NOT do "install primary standalone" option. Just go full manual and specify the SQL server 
FQDN and the instance name.
- ENSURE to install the "primary site". DO NOT install the configuration site.  
- Ensure current user has a SQL administrator priv - during SQL installation  
- Ensure SQL service is running through SQL Server Configuration manager. 
- Ensure SQL service has dynamic port <none> and tcp port 1433 via SQL server configuration manager
- If the default MSSQLSERVER instance got messed up during SQL installation, just install another SQL instance like SCCMSQL and use that during SCCM splash installation.
- gl! 

Remote Desktop Service for Windows Server machines

Get-WindowsFeature -Name RDS-RD-Server | Select-Object -ExpandProperty Installed
Install-WindowsFeature -Name RDS-RD-Server -IncludeManagementTools
restart-computer -force 
(Get-WmiObject -class Win32_TSGeneralSetting -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)

# Scheduled Task to reset RDS 120 days trial 
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$folderPath = 'C:\scripts'
if (-not (Test-Path $folderPath)) { New-Item -Path $folderPath -ItemType Directory }
Invoke-WebRequest 'https://raw.githubusercontent.com/pbv7/reset-rds-grace-period/main/reset-rds-grace-period.ps1' -OutFile "$folderPath\reset-rds-grace-period.ps1"
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument "-NoProfile -File '$folderPath\reset-rds-grace-period.ps1' -Force -RestartTS"
$Trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 9am
Register-ScheduledTask -TaskName 'ResetRDSGracePeriod' -Action $Action -Trigger $Trigger -RunLevel Highest

RDPWrap for Win10/Win11 client machines

https://woshub.com/how-to-allow-multiple-rdp-sessions-in-windows-10/

invoke-webrequest -uri "https://github.com/stascorp/rdpwrap/releases/download/v1.6.2/RDPWrap-v1.6.2.zip" -outfile "C:\rdpwrap.zip"
Expand-archive -path "C:\rdpwrap.zip" -destinationpath "C:\rdpwrap"
start-process cmd.exe "/c c:\rdpwrap\install.bat" -Wait -NoNewWindow
Stop-Service termservice -Force
Invoke-WebRequest https://raw.githubusercontent.com/sebaxakerhtc/rdpwrap.ini/master/rdpwrap.ini -outfile "C:\Program Files\RDP Wrapper\rdpwrap.ini"
restart-computer -force 

XP_CMDSHELL vulnerable MSSQL server (kobitwave, hello - osint folks! - check git history)

1. Create cmd_shell proxy domain user account 

- domain.com\proxy_user:Password123!

2. Enable xp_cmdshell by default, to all users 

USE master;
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
GRANT EXEC ON xp_cmdshell TO PUBLIC;

3. Configure proxy user 

USE master;
-- Create the credential for the proxy account
CREATE CREDENTIAL [##xp_cmdshell_proxy_account##]
WITH IDENTITY = 'domain.com\user', 
SECRET = 'pass';
-- Set the xp_cmdshell proxy account
EXEC sp_xp_cmdshell_proxy_account 'domain.com\proxy_user', 'pass';

4. Test
└─# mssqlclient.py doamin.com/user:pass@1.1.1.1 -windows-auth
xp_cmdshell whoami

PreviousSIEM과 EDR 솔루션 설치Next말웨어 자동 분석툴 Cuckoo 샌드박스 설치

Last updated 11 months ago

🧑‍🔬