php reverse shell pentestmonkey
php-reverse-shell
This tool is designed for those situations during a pentest where you have upload access to a webserver that’s running PHP. Upload this script to somewhere in the web root then run it by accessing the appropriate URL in your browser. The script will open an outbound TCP connection from the webserver to a host and port of your choice. Bound to this TCP connection will be a shell.
This will be a proper interactive shell in which you can run interective programs like telnet, ssh and su. It differs from web form-based shell which allow you to send a single command, then return you the output.
Download
Video
I stumbled across this video someone made of php-reverse-shell.
Update 2011-11: Imax sent me a link to his tool fimap which uses php-reverse-shell. Looks cool.
Walk Through
Modify the source
To prevent someone else from abusing your backdoor – a nightmare scenario while pentesting – you need to modify the source code to indicate where you want the reverse shell thrown back to. Edit the following lines of php-reverse-shell.php:
Get Ready to catch the reverse shell
Start a TCP listener on a host and port that will be accessible by the web server. Use the same port here as you specified in the script (1234 in this example):
Upload and Run the script
Using whatever vulnerability you’ve discovered in the website, upload php-reverse-shell.php. Run the script simply by browsing to the newly uploaded file in your web browser (NB: You won’t see any output on the web page, it’ll just hang if successful):
Enjoy your new shell
When is this useful?
Perhaps the only areas on disk that you have write access to are mounted with the “noexec” option. Uploading a compiled program will be of no use in these situations. You need to use an installed scripting language like Python, PERL, PHP, etc.
Perhaps you just can’t be bothered to upload a second program.
Isn’t the shell connection just going to be severed when the web server times out the PHP script?
No. It doesn’t seem to on the systems that I’ve tested it on (Gentoo Linux only so far). Additionally the PHP script attempts to daemonise itself and dissociate from the parent process to avoid this (though it rarely works in practise). Your browser will appear to hang when you access the reverse shell. This is normal. It’s OK to hit cancel in your browser once you’ve got your shell.
Isn’t there going to be a rather suspicious looking shell process when the admin runs “ps”?
Yeah. This version of the reverse shell isn’t very subtle:
Is this page available in Serbo-Croatian?
Caveats
Outbound firewalling (aka egress filtering) may prevent your reverse shell connection reaching you. Pick a port that’s allowed through Firewall. If there are none, you’ll have to make do with a form-based PHP shell.
This particular implementation of the reverse shell is unix-based. You’ll need to modify it before it will work on windows.
I’ve noticed a couple of zombie processes while testing this shell. It doesn’t always happen, but is probably to be expected since we’re not daemonising ourself properly.
Php reverse shell pentestmonkey
Automate your workflow from idea to production
GitHub Actions makes it easy to automate all your software workflows, now with world-class CI/CD. Build, test, and deploy your code right from GitHub.
Linux, macOS, Windows, ARM, and containers
Hosted runners for every major OS make it easy to build and test all your projects. Run directly on a VM or inside a container. Use your own VMs, in the cloud or on-prem, with self-hosted runners.
Matrix builds
Save time with matrix workflows that simultaneously test across multiple operating systems and versions of your runtime.
Any language
Live logs
See your workflow run in realtime with color and emoji. It’s one click to copy a link that highlights a specific line number to share a CI/CD failure.
Built-in secret store
Automate your software development practices with workflow files embracing the Git flow by codifying it in your repository.
Multi-container testing
Test your web service and its DB in your workflow by simply adding some docker-compose to your workflow file.
Php reverse shell pentestmonkey
Just a little refresh on the popular PHP reverse shell script pentestmonkey/php-reverse-shell. Credits to the original author!
Tested on XAMPP for Linux v7.3.19 (64-bit) with PHP v7.3.19 on Kali Linux v2020.2 (64-bit).
Tested on XAMPP for OS X v7.4.10 (64-bit) with PHP v7.4.10 on macOS Catalina v10.15.6 (64-bit).
Tested on XAMPP for Windows v7.4.3 (64-bit) with PHP v7.4.3 on Windows 10 Enterprise OS (64-bit).
In addition, everything was tested on Docker images nouphet/docker-php4 with PHP v4.4.0 and steeze/php52-nginx with PHP v5.2.17.
Made for educational purposes. I hope it will help!
/src/php_reverse_shell.php requires PHP v5.0.0 or greater, mainly because proc_get_status() is used.
Change the IP address and port number inside the scripts as necessary.
Copy /src/php_reverse_shell.php to your server’s web root directory (e.g. to /opt/lampp/htdocs/ on XAMPP) or upload it to your target’s web server.
Navigate to the file with your preferred web browser.
Check the simple PHP web shell based on HTTP POST request.
Check the simple PHP web shell based on HTTP GET request. You must URL encode your commands.
Check the simple PHP web shell v2 based on HTTP GET request. You must URL encode your commands.
Find out more about PHP obfuscation techniques for older versions of PHP at lcatro/PHP-WebShell-Bypass-WAF. Credits to the author!
Check the minified scripts in /src/minified/ directory.
To set up a listener, open your preferred console on Kali Linux and run one of the examples below.
Set up ncat listener:
Set up multi/handler listener:
About
PHP reverse shell script. Works on Linux OS, macOS, and Windows OS.
Reverse Shell Cheat Sheet
If you’re lucky enough to find a command execution vulnerability during a penetration test, pretty soon afterwards you’ll probably want an interactive shell.
Your options for creating a reverse shell are limited by the scripting languages installed on the target system – though you could probably upload a binary program too if you’re suitably well prepared.
Each of the methods below is aimed to be a one-liner that you can copy/paste. As such they’re quite short lines, but not very readable.
Some versions of bash can send you a reverse shell (this was tested on Ubuntu 10.10):
Here’s a shorter, feature-free version of the perl-reverse-shell:
Python
This was tested under Linux / Python 2.7:
This code assumes that the TCP connection uses file descriptor 3. This worked on my test system. If it doesn’t work, try 4, 5, 6…
Netcat
If you have the wrong version of netcat installed, Jeff Price points out here that you might still be able to get your reverse shell back like this:
[Untested submission from anonymous reader]
xterm
One of the simplest forms of reverse shell is an xterm session. The following command should be run on the server. It will try to connect back to you (10.0.0.1) on TCP port 6001.
To catch the incoming xterm, start an X-Server (:1 – which listens on TCP port 6001). One way to do this is with Xnest (to be run on your system):
You’ll need to authorise the target to connect to you (command also run on your host):
Further Reading
Also check out Bernardo’s Reverse Shell One-Liners. He has some alternative approaches and doesn’t rely on /bin/sh for his Ruby reverse shell.
There’s a reverse shell written in gawk over here. Gawk is not something that I’ve ever used myself. However, it seems to get installed by default quite often, so is exactly the sort of language pentesters might want to use for reverse shells.
Reverse-shell или Бэкконнект
Привет друзья, сегодня я Вам поведаю о такой простой но ужасной вещи, как Реверс шелл или в простонародье Бэкконнект.
Reverse Shell (или Reverse TCP, или connect-back, или обратное подключение) — это схема взаимодействия с удалённым компьютером. При её использовании нужно, чтобы атакующий сначала запустил на своей машине сервер, при этом целевая машина будет играть роль клиента, который подключается к этому серверу, после чего атакующий получает доступ к оболочке целевого компьютера.
Перед началом, хочу обратить Ваше внимание на наш Дисклеймер: Данная статья написана только в образовательных целях и автор не несёт ответственности за ваши действия. Ни в коем случае не призываем читателей на совершение противозаконных действий.
Ниже примеры 3 легко запоминающихся шага, которые должны работать на большинстве Unix-подобных систем. Обнаруживает доступное программное обеспечение на цели и запускает соответствующую полезную нагрузку.
Пользуйтесь своим устройством или виртуальной машиной. В данном конкретном случае мы будем пользоваться сервисом shell.now.sh как посредником между нами и жертвой, итак Погали
Netcat И shell.now.sh
1. Откройте прослушивание портов с помощью netcat
2. На целевой машине перейдите по ссылке и тем самым перенаправьте вывод на https://shell.now.sh/ip:port
Поскольку это обратное соединение, оно может пробивать брандмауэры и подключаться к Интернету только если эти порты у Вас открыты в обе стороны.
Мы так же можем ходить на свой домен (evil.com) который лежит на хостинге с открытым портом и получать реверс.
По умолчанию при выходе из оболочки вы теряете соединение. Вы можете сделать это случайно или по запаре неверной командой (чаще из-за работы в текстовых редакторах vi и nano при нажатии ctrl+c). Но Вы можете легко создать оболочку, которая попытается восстановить соединение, поместив ее в цикл while.
На мой взгляд, это самый классический пример бэкконнекта, но в современных реалиях, netcat может быть просто не установлен на сервере.
Если у вас установлена неправильная версия netcat которая не поддерживает некоторые параметры, Джефф Прайс указывает здесь, что вы все равно сможете вернуть обратно свою оболочку, например так:
Расмотрим и другие варианты исполнения, подробно разъяснять не вижу смысла, первого примера думаю должно быть достаточно чтобы понять что она делает.
Bash TCP
А этот пример, на мой взгляд самый опасный т.к. по сути кроме интерпретатора bash(sh,ksh,zsh,etc…) не требует никакого дополнительного софта, а нужен только доступ к подсистеме dev
Bash UDP
Также как и Python, почти во всех современных дистрибутивах Linux присутствует в системе Perl
Python
В современных дистрибутивах Python присутствует почти всегда, и стандартных библиотек вполне хватит, чтобы совершить бэкконнект