metasploit php reverse shell

Php reverse shell with metasploit

After hacking a web application or server to such an extent that you can upload files to it, the next thing to try is get a proper shell on the system. The most common approach is to create reverse shells. In this approach first a listener program is run on the hacker’s machine and then a program/payload/script is run on the target machine such that it connects back to the hacker’s machine to offer a shell/terminal.

Creating reverse shells using php scripts is generally quite easy and can be accomplished with just a small php and a program like netcat. Netcat would run as a listener (a socket server actually) and the php script has to be run on the victim server so that it connects back.

In this example we are going to create reverse shells in php using metasploit. Yes, its too big a tool for such a small task but looks cool anyway.

To brief up the basics about reverse shells remember that it has 2 components. First is the listener on local/hacker system that waits for incoming connections, and the second is the payload script/program that runs on target computer and is configured to connect to the listener and offer a shell.

Once the listener is connected, it can gets a shell which can be used to run any command (limited to the user privilege) on the target system.

php payload

So the first step is to create our payload program. This is done using the msfpayload command and looks like this

The above command would create a file called exploit.php which is the reverse shell payload. It is just a plain php script that is configured according to the LHOST and LPORT parameters.

Now upload the exploit.php to the target system. Wait, do not run it yet. First we need to start the listener as shown in the next step.

Start listener

Once the payload is uploaded, the next thing to do is to start our listener which will catch the incoming connection offer. Start msfconsole and run the following commands

Now the listener is ready. Now its time to run the php script on the server. Its uploaded, and now can be run by opening from the browser like a normal url.

As soon as the script starts running, msfconsole will indicate connection and meterpreter session would come up

Now that meterpreter is up, its time to play with the system.
Since it is a php based reverse shell, it is not dependant on the target platform OS in anyways and can run on windows and linux alike.

5 thoughts on “ Php reverse shell with metasploit ”

Pls Add me in group for hcking learning etc

Hi, am getting no socket
What might be the issue

Do we need to port forward port 6000?

If you are behind NAT yes

msf exploit(handler) > set LPORT 6000
LPORT => 6666
.

Источник

PHP Reverse Shell is not working #8964

Comments

ghost commented Sep 14, 2017 •

Steps to reproduce

Therefore, everythings is fine.

Calling the PHP script directly in Browser to trigger:
http://10.14.11.150/admin/uploads/shell5.PHP

This section should also tell us any relevant information about the
environment; for example, if an exploit that used to work is failing,
tell us the victim operating system and service versions.

Expected behavior

Shell should come up

Current behavior

Error message comes up
Parse error: syntax error, unexpected ‘[‘ in /var/www/admin/uploads/shell5.PHP on line 1

Linux 54784584 4.12.0-kali1-amd64 #1 SMP Debian 4.12.6-1kali1 (2017-08-18) x86_64 GNU/Linux

thanks fo rchecking

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

AlistairXX commented Sep 15, 2017

jvoisin commented Sep 18, 2017

Rogdham commented Sep 22, 2017

Notice that one has a _ between meterpreter and reverse while the other has a / …

Could you try and use the same version in both msfvenom and msfconsole (e.g. php/meterpreter/reverse_tcp in both cases)?

ghost commented Oct 9, 2017

Hello,
i tested your recommendation with no luck. to be more detailed: i followed your directions:
Could you try and use the same version in both msfvenom and msfconsole (e.g. php/meterpreter/reverse_tcp in both cases)?

and as the result, the session dies
my full log:

Источник

Reverse TCP shell with Metasploit

Metasploit is an awesome tool. It can be used to automate the exploitation process, generate shellcodes, use as a listener, etc. I hope to start a tutorial serious on the Metasploit framework and it’s partner programs. So in today’s tutorial, we are going to see how we can build a reverse TCP shell with Metasploit. As an example, we use msfvenom for creating a web shell in PHP and use Metasploit to get the session. It can create a reverse TCP connection to our mashing.

Reverse TCP vs Bind TCP shell

First of all let’s clarify what is a reverse TCP shell, What’s a bind shell and how they work. In both of these situations, there is an Attacker mashing and a victim server. In a reverse shell, we open a connection from the victim server to the attacker’s mashing. We set up a listener on the attacker’s mashing. It waits for an incoming connection from the victim. When it receives the TCP connection it serves as a shell to access the victim server.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

A bind shell works in a different way. The payload will bind a shell to a specific port on the victim server. So the attacker can use his mashing to connect back to the victim server.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

Generating the exploit using Msfvenom

First, we use msfvenom for create our shell. This tool is packed with the Metasploit framework and can be used to generate exploits for multi-platforms such as Android, Windows, PHP servers, etc.

Following is the syntax for generating an exploit with msfvenom.

Here we have supplied many arguments to msfvenom tool. Let’s see what they do. At the moment we don’t use any encoding. In later we can use them.

-o This is an output format. We have specified shell.php. So our output file will be saved as shell.php.

In the following list we can see some payload types we use often.

Web servers

Most Web servers run PHP as there server-side language. We can build a PHP web shell with MSFvenom by using «php/meterpreter_reverse_tcp» as the payload. Since we are uploading it to a PHP server the extension of the shell should be «PHP«.

What about a JSP server. We can build a web shell as a JSP file and try to upload it. So we want to use «java/jsp_shell_reverse_tcp» as our payload and the output file type should be «.jsp«.

Linux platforms

If we want to attack a Linux server we can use «linux/x86/meterpreter/reverse_tcp» as our payload. Also we an use «.elf» as the output file.

Windows mashings

For Windows, we can use meterpreter as the payload. So we should select «windows/meterpreter/reverse_tcp«. As you know the extension should be «.exe«.

Android devices

We know that Android is the world’s most popular mobile operating system. Metasploit has various payloads for Android. vCommonly we use «android/meterpreter_reverse_tcp» to attack Android devices. The output file type should be «.APK«.

LHOST is the IP of attacker mashing. It should be our public IP. Because a reverse shell is connected from victim mashing to our mashing.

LPORT is any opened port on our mashing.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

In the above pic, we can see we need to set LHOST and LPORT. Let’s set them. Both of them are the same as what we used in generating our shell.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

OK now is the time to attack. We use the command run to start the process.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

It is waiting for an incoming connection. Now we can execute our shell on a web server.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

Inputs in C

In this tutorial I’ll explain you how to get an input from the user in C language. You know that in.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

Introduction to Assembly language

Assembly is a low level programming language. You already know that low level programming languages.

metasploit php reverse shell. Смотреть фото metasploit php reverse shell. Смотреть картинку metasploit php reverse shell. Картинка про metasploit php reverse shell. Фото metasploit php reverse shell

Assembly system calls

When we talk about computer programs, they do various tasks. Like printing a string to screen.

Источник

Metasploit php reverse shell

1 contributor

Users who have contributed to this file

The php/meterpreter/reverse_tcp is a staged payload used to gain meterpreter access to a compromised system. This is a unique payload in the Metasploit Framework because this payload is one of the only payloads that are used in RFI vulnerabilities in web apps. This module can be cross platform, but the target needs to be able to run php code.

The PHP Meterpreter is suitable for any system that supports PHP. For example, the module can be used against webservers which run PHP code for a website. OS X has PHP installed by default.

Specific demo of using the module that might be useful in a real world scenario.

Generating a file with msfvenom

Starting a listener

Important Basic Commands

Compared to a native Meterpreter such as windows/meterpreter/reverse_tcp, the PHP Meterpreter has less commands, but here’s a list of all the common ones you might need:

pwd command

The pwd command tells you the current working directory. For example:

cd command

The cd command allows you to change directories. Example:

cat command

The cat command allows you to see the content of a file:

upload command

The upload command allows you to upload a file to the remote target. This is useful for uploading additional payload files. For example:

download command

The download command allows you to download a file from the remote target to your machine. For example:

search command

The search command allows you to find files on the remote file system. For example, this shows how to find all text files in the current directory:

getuid command

The getuid command tells you the current user that Meterpreter is running on. For example:

execute command

The execute command allows you to execute a command or file on the remote machine.

The following examples uses the command to create a text file:

ps command

The ps command lists the running processes on the remote machine.

shell command

The shell command allows you to interact with the remote machine’s command prompt (or shell). For example:

If you wish to get back to Meterpreter, do [CTRL]+[Z] to background the channel.

sysinfo

The sysinfo command shows you basic information about the remote machine. Such as:

Using post modules

When using the PHP Meterpreter, you have the feature of using Metasploit’s post modules on that specific session. By default, most multi post modules will work; however, you can also use OS specific modules depending on the OS of the compromised system. For example, if you have a PHP Meterpreter session running on OS X, you can use osx post modules on that session.

Don’t forget to:

Источник

Анонимное подключение к meterpreter/reverse_tcp через промежуточный сервер с помощью SSH-туннелей

Всем привет! Эта статья рассчитана скорее на новичков, которые только начинают своё знакомство с Metasploit Framework, но уже кое-что понимают. Если вы считаете себя опытным специалистом и вас заинтересовало название, можете сразу перейти к TL;DR; в конце. Речь в этой статье пойдет о том, как устроить анонимный доступ к meterpriter оболочке посредством reverse tcp с использованием промежуточного сервера и SSH туннелей.

Дисклеймер: чукча не писатель, не безопасник и вообще с трудом может причислить себя к профессионалам в какой-либо сфере. Но чукча захотел reverse tcp через tor и сделал, а вам теперь это читать. А так же помните, что производить подобные действия можно только в разрешенных вам местах, иначе вам грозят несколько статей уголовного кодекса.

Вступление

Допустим, мы нашли дыру на виндовой машине и хотим на неё проникнуть. Рассмотрим варианты, причем обычный cmd нам неинтересен, то ли дело meterpreter, о нём и поговорим.

Есть два основных принципа соединения с оболочкой meterpreter: прямое и обратное. В meterpreter’е есть множество вариантов подключения, но в рамках этой статьи мы будем говорить только о bind tcp(прямой) и reverse tcp(обратный).

Какие подводные камни нас ждут, если мы хотим использовать bind tcp, открыв таким образом порт у жертвы и потом через прокси или тор подключиться? Во-первых, брэндмауэр жертвы поинтересуется, зачем эта непонятная программа пытается выйти в интернет и можно ли ей тут хозяйничать? Допустим, пользователь глуп(что скорее всего так и есть) настолько, чтобы разрешить нашей программе открыть порт, спросите себя, кто нынче выходит в интернет напрямую и имеет белый ip? Мало таких осталось, сейчас везде роутеры, а следовательно наш порт будет доступен только во внутренней сети. Если мы заморочились и прокинули порт наружу, то остаётся полследняя проблемы: нужно знать ip, чтобы подключиться, а он может периодически меняться. Зато, если все перечисленные выше условия выполнены, то можно подключиться через цепочку проксей из любого места.

Что насчет reverse tcp подключения? Брэндмауэр не ругается, роутер тоже не помеха — жертва сама подключится к нам, поэтому же отпадает необходимость следить за её ip адресом. Но возникает проблема посерьёзнее — анонимность. Нам нужно указать, куда жертва будет подключаться, то есть написать свой ip, который можно будет увидеть через тот же netstat. И тогда дяди в чистых костюмах или мстительная жертва с нужными знакомыми смогут, как говорится, вычислить по ip и начистить ботинки сами знаете что сделать. Ещё один минус — наш айпи должен быть постоянным, чтобы иметь возможность подключаться к жертве повторно.

Как же быть? Как сохранить анонимность и иметь возможность входа из любого места?

Начальные условия

Весь процесс я буду демонстрировать в следующих условиях:

Для начала запустим handler — программу, которая будет ждать соединения от жертвы на 4444 порту, чтобы при подключении отправить ей meterpreter. Для этого в командной строке Kali запустим msfconsole и в ней выполним следующие команды:

Сообщаем, что на жертве у нас будет запущена полезная нагрузка meterpreter с обратным соединением:

Указываем параметры нагрузки — будем слушать на порту 4444 нашего ip адреса(почему не 127.0.0.1 расскажу позже).

Запускаем и оставляем в таком виде до лучших времен.

Создание exe с полезной нагрузкой

Затем сгенерируем программулину, которая и будет подключаться через прокси к нам. Открываем новую вкладку терминала и набираем следующее:

Кратко расскажу об аргументах.

Аваст не повелся и гордо сообщил об угрозе, поэтому и был убит на месте, дабы не мешать испытаниям. Файл на месте, теперь займемся подготовкой нашего сервера.

Настройка сервера

Мы будем использовать статический проброс портов.

В созданном нами exe порт был 22222, а на Kali мы слушаем порт 4444. Значит-с, чтобы все запросы идущие на серверный порт 22222 транслировались на наш порт 4444, в Kali нужно написать такую команду:

Нюанс в том, что по умолчанию проброшенный таким образом порт на сервере будет доступен только с серверного же localhost’а и при попытке подключиться извне ничего не произойдет и никаких ошибок не будет.

Поправим ситуацию — открываем на прокси-сервере конфиг ssh демона — /etc/ssh/sshd_config, ищем строку GatewayPorts, раскомментируем её и устанавливаем в yes. Переподгружаем конфиг через service sshd reload и теперь со спокойной душей запускаем команду.

А теперь интересный момент. Когда я только это всё изучал, то подобными манипуляциями у меня получилось добиться подключения жертвы к моему хэндлеру и успешно открыть командную строку метерпритера, но при вводе любой команды(даже help) он с дикими ошибками закрывал соединение. Сейчас же, когда я пишу статью, всё работает. Даже если у вас всё заработало и так, всё равно рекомендую к прочтению следующий абзац.

После долгих часов гугления был найден комментарий разработчика метерпритера о том, что не стоит указывать LHOST(то есть адрес хоста, на котором слушать) 127.0.0.1. Нужно писать либо что-то типа 127.0.0.2, либо 0.0.0.0. Но если мы выбираем первый вариант, то и прокидывать порты нужно на 127.0.0.2. Но и с таким вариантом у меня выпадали ошибки. После ещё более долгих часов гугления был найден комментарий другого разработчика, который сказал чуть больше: нельзя вешать не только на 127.0.0.1, но и в принципе на интерфейс loopback, потому что он зарезервирован и работать будет не стабильно, и порекомендовал вешать хэндлер на другой сетевой интерфейс, например eth0. Так что прокидывать мы будем на него же. Команда приобретает следующий вид:

Уже лучше, но через proxychains её всё равно не получится запустить. Чтобы поправить это, пробросим через проксичейнс ssh сервера себе, и через него уже пробросим порт метерпритера.

Говорят, proxychains, входящий в стандартную сборку Kali 2 уже староват и давно заброшен. У меня он периодически падал с ошибкой segfault. Поэтому я поставил себе proxychains4(proxychains-ng) отсюда, а старый снёс к чертям и остался доволен, чего и вам советую.

Заметьте, что мы подключаемся именно на 127.0.0.1:42022, а не на 192.168.1.10:22. Всё готово! Выпускайте Кракена Запускаем HarmlessFile.exe у жертвы и наслаждаемся результатом.

Используем левый сервер в качестве прокси, к которому будет цепляться meterpreter жертвы с помощью reverse tcp.

Оговорюсь повторно, что я описал метод, который сработал для меня и выполнил нужную мне задачу — анонимность и мобильной. Может быть есть и другие, более простые пути добиться того же самого, но мне не удалось их раскопать.

Моя первая статья на ваш суд — конструктивная критика приветствуется, об опечатках прошу сообщать в личку.

Полезные ссылки:

Памятка пользователям ssh — замечательное описание возможностей SSH, в частности о SSH-туннелях.
Meterpreter базовые команды — описание базовых команд Meterpreter’a.

И ещё 2 слегка устаревшие статьи, но в них есть описание более интересных фич Meterpreter.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *