📖
레드팀 플레이북
깃허브기여하는 방법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
  • OffensiveCSharpCheatsheet
  • Converting
  • Memory
  • Memory Calculations
  • Process (debugging)
  • Encryption & Decryption
  • Web
  • DInvoke
  • MISC
  • References
  1. MISC

C# snippets

OffensiveCSharpCheatsheet

C# Cheatsheet with useful code snippets and oneliners

Converting

IntPtr -> String

// 1 
string intptrString = intPtrVar.ToInt64().ToString("x2");
Console.WriteLine("0x{0}", intptrString);

// 2 
IntPtr intPtr = <something>;
Console.WriteLine("{0}", String.Format("0x{0:X}", intPtr.ToInt64()));

Byte[] -> String - Hex (useful for debugging)

public static string ByteArrayToString(byte[] ba)
{
    byte[] returnArray = new byte[ba.Length];
    returnArray = ba.ToArray();
    Array.Reverse(returnArray);
    return "0x" + String.Concat(Array.ConvertAll(returnArray, x => x.ToString("X2")));
}

Console.WriteLine("[+] something: {0}", ByteArrayToString(someBA));

String -> Byte[]

// ascii 
byte[] ba = Encoding.ASCII.GetBytes("string");

// utf8
byte[] ba = Encoding.UTF8.GetBytes("string");

Byte[] -> String

byte[] ba = <something>;
string baToStr = System.Text.Encoding.Default.GetString(ba); 

Base64String -> Byte[]

byte[] ba = Convert.FromBase64String("something");

Byte[] -> Base64String

string b64Str = Convert.ToBase64String(byte[] ba);

UInt -> String

string uintToStr = String.Format("0x{0:X}", uint something));

Byte[] -> IntPtr

// 32bit 
IntPtr baPtr = new IntPtr(BitConverter.ToInt32(byteArray, 0));

// 64bit 
IntPtr baPtr = new IntPtr(BitConverter.ToInt64(byteArray, 0));

IntPtr -> Byte[]

byte[] ba = new byte[<size>];
Marshal.Copy(intPtr, ba, 0, size);

ex)

byte[] ba = new byte[IntPtr.Size];
Marshal.Copy(intPtr, ba, 0, IntPtr.Size);

String -> Byte[]

byte[] ba = Encoding.Unicode.GetBytes("C:\\windows\\explorer.exe");

Memory

Allocate unmanaged memory

int size = 0x100;
IntPtr pSize = Marshal.AllocHGlobal(size);

Read memory from IntPtr

// 32bit - Read 4 bytes 
IntPtr pBuf = <something>;
int something = Marshal.ReadInt32(pBuf);

// 64bit - Read 8 bytes
IntPtr pBuf = <something>;
long something = Marshal.ReadInt64(pBuf);

Write memory to IntPtr

// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.writeint32?view=net-6.0

IntPtr pSource = <something>;
int offset = <something>;
int value = <something>; 

Marshal.WriteInt32(pSource, offset, value)

Write IntPtr

IntPtr lpValuePointer = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(lpValuePointer, parentHandle);

Memory Calculations

IntPtr + UInt

IntPtr a = <something>;
uint b = <some uint32>;

IntPtr newA = (IntPtr)( (UInt64)a + b );

ByteArray + Int

// 32bit 
byte[] oldBa = <something>; 
int addition = <something>; 
byte[] newBa = BitConverter.GetBytes(BitConverter.ToInt32(oldBa, 0) + addition);

Process (debugging)

Find Process by name

Process explorer = Process.GetProcessByName("explorer")[0];

Start Process (Notepad)

Process notepad = Process.Start("c:\\windows\\system32\\notepad.exe"); 

Kill Process

// by name 
Process[] processes = Process.GetProcessByName("notepad");
foreach(var proc in processes)
{
    proc.Kill(); 
}

// by Id 
int pid = <something>;
Process proc = Process.GetProcessById(pid);
proc.Kill();

Encryption & Decryption

XOR ByteArray

// --encrypt-key - bash -c 'echo $RANDOM | md5sum | head -c 32; echo;'
// --encrypt-iv - bash -c 'echo $RANDOM | md5sum | head -c 16; echo;'
public static byte[] xorByteArray(byte[] sc, int scLength, byte[] key, int keyLength)
{
    byte[] decryptedSC = new byte[scLength];
    int j = 0;

    int c = 0;
    for (int i = 0; i < scLength; i++)
    {
        if (j == keyLength - 1)
        {
            j = 0;
        }

        decryptedSC[i] = (byte)(sc[i] ^ key[j]);
        j++;
    }
    return decryptedSC;
}

AES CBC mode Decrypt

// https://stackoverflow.com/questions/53653510/c-sharp-aes-encryption-byte-array
// byte[] buf = Aes256Decrypt(bufEncrypted, Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(iv));
public static byte[] Aes256Decrypt(byte[] data, byte[] key, byte[] iv)
{
    using (var aes = Aes.Create())
    {
        aes.KeySize = 128;
        aes.BlockSize = 128;
        aes.Padding = PaddingMode.Zeros;

        aes.Key = key;
        aes.IV = iv;

        using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
        {
            return PerformCryptography(data, decryptor);
        }
    }
}

public static byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
{
    using (var ms = new MemoryStream())
    using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
    {
        cryptoStream.Write(data, 0, data.Length);
        cryptoStream.FlushFinalBlock();

        return ms.ToArray();
    }
}

AES CBC mode Encrypt

// https://stackoverflow.com/questions/53653510/c-sharp-aes-encryption-byte-array
// byte[] buf = Aes256Decrypt(bufEncrypted, Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(iv));
public byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
{
    using (var aes = Aes.Create())
    {
        aes.KeySize = 128;
        aes.BlockSize = 128;
        aes.Padding = PaddingMode.Zeros;

        aes.Key = key;
        aes.IV = iv;

        using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
        {
            return PerformCryptography(data, encryptor);
        }
    }
}

public static byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
{
    using (var ms = new MemoryStream())
    using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
    {
        cryptoStream.Write(data, 0, data.Length);
        cryptoStream.FlushFinalBlock();

        return ms.ToArray();
    }
}

Web

DownloadData - HTTP

string urlString = "http://127.0.0.1:9999/something";
WebClient webclient = new WebClient();
byte[] downloadData = webclient.DownloadData(urlString);

DownloadData - HTTPS

// TODO 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string urlString = "https://127.0.0.1:9999/something";
WebClient webclient = new WebClient();
byte[] downloadData = webclient.DownloadData(urlString);

DInvoke


MISC

is64Bit

public static bool is64Bit()
{
    if(IntPtr.Size == 8)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Sleep

// ms 
System.Threading.Thread.Sleep(1000);

References

Previous레퍼런스와 크레딧Nextwinapi 리스트

Last updated 2 years ago

🎅
AES Encrypt, Decrypt
SharpSploit
SharpBlock
Sharp-Suite