pentest monkey php reverse shell
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.
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.
Pentest monkey php reverse shell
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.
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 присутствует почти всегда, и стандартных библиотек вполне хватит, чтобы совершить бэкконнект
Pentest monkey php reverse shell
I meant to blog about this a while ago, but never got round to it. Here’s a brief post about very cool feature of a tool called mimikatz. I’m very grateful to the tool’s author for bringing it to my attention. Until that point, I didn’t realise it was possible to recover the cleartext passwords […]
windows-privesc-check
A long time ago, I started writing a tool to look for local privilege escalation vectors on Windows systems – e.g. weak permissions on files, directories, service registy keys. I never quite got round to finishing it, but the project could still be useful to pentesters and auditors in its current part-finished state. I’d suggest giving it a […]
Finding IP Addresses of Other Network Interfaces on Linux
The scenario for this post is that you’re connected to the local LAN of the systems you’re pentesting – possibly in a DMZ or multi-tiered architecture. If you’re on an externally-facing LAN, you may find that there aren’t many network services to explore. As your pentest starts to look more like a vulnerability assessment, you […]
gateway-finder
Gateway-finder is a scapy script that will help you determine which of the systems on the local LAN has IP forwarding enabled and which can reach the Internet. This can be useful during Internal pentests when you want to quickly check for unauthorised routes to the Internet (e.g. rogue wireless access points) or routes to other […]
The Science of Safely Finding an Unused IP Address
During pentests you’re often allocated an IP by the client or can get one via DHCP. There are times, however when the client might expect you find a free IP on your own. Or you might want to check that the client hasn’t assigned you an IP address that’s already in use. I’m sure we’ve […]
timing-attack-checker
timing-attack-checker is a simple PERL script that helps you check for timing attacks. The most common form of timing attack I’ve noticed while pentesting is that the server may take longer to respond to a valid username than to an invalid username. This can be handy for bruteforcing a list of valid usernames. I’ll work […]
Exposing only part of C: over Terminal Services
Ken Johnson gives a useful tip on his blog about limiting access to your local drives when you make a Terminal Services connection. This is not new, but it’s useful enough to be worth summarizing here. When I audit a system via Terminal Services, I usually map a drive to or from the system depending on […]
Post-Exploitation in Windows: From Local Admin To Domain Admin (efficiently)
There are some excellent tools and techniques available to pentesters trying to convert their local admin rights into domain admin rights. This page seeks to provide a reminder of some of the most common and useful techniques as well as rating their effectiveness to suggest which ones to try first. The premise of all the […]
Reverse Shell Cheat Sheet
“Hackers for Charity” Needs You
This is a quick post to draw attention to the request for donations from Hackers for Charity. They need to raise about 785 USD / month to fund the good work they’re doing in Uganda. Netsparker recently tweeted that they’re donating 785 USD. Rapid7 are giving 5000 USD. There are many more on the Donate […]
SSH Cheat Sheet
SSH has several features that are useful during pentesting and auditing. This page aims to remind us of the syntax for the most useful features. NB: This page does not attempt to replace the man page for pentesters, only to supplement it with some pertinent examples. SOCKS Proxy Set up a SOCKS proxy on 127.0.0.1:1080 that lets […]
Exploiting A Tricky SQL Injection With sqlmap
Like many pentesters, I’m a fan of sqlmap. It’s often the first and last tool I reach for when exploiting boolean or time-based SQL injection vulnerabilities. I wanted to briefly document a slightly tricky SQL injection issue I encountered recently and a few of the sqlmap features that impressed me most. I initially noticed that […]
The Ultimate Unix Cheat Sheet
I just stumbled across Rosetta Stone for Unix, a brilliant page that lists how to do a large number of tasks in a variety of unix-like operating systems. I wish I’d found this years ago. It should be very handy for pentesting or auditing those less familiar unix flavours. I’ll definitely taking a copy with […]