H Nd Edition Hacking - Lagout

Transcription

International Best-Seller!the fundamental techniques of Serious hackingRather than merely showing how to run existingexploits, author Jon Erickson explains how arcanehacking techniques actually work. To share the artand science of hacking in a way that is accessibleto everyone, Hacking: The Art of Exploitation, 2ndEdition introduces the fundamentals of C programming from a hacker’s perspective.j Program computers using C, assembly language,and shell scriptsj Corrupt system memory to run arbitrary codeusing buffer overflows and format stringsj Gain access to a remote server using port-bindingor connect-back shellcode, and alter a server’s logging behavior to hide your presencej Redirect network traffic, conceal open ports, andhijack TCP connectionsj Crack encrypted wireless traffic using the FMSattack, and speed up brute-force attacks using apassword probability matrixHackers are always pushing the boundaries, investigating the unknown, and evolving their art. Evenif you don’t already know how to program, Hacking:The Art of Exploitation, 2nd Edition will give you acomplete picture of programming, machine architecture, network communications, and existinghacking techniques. Combine this knowledge withthe included Linux environment, and all you need isyour own creativity.about the authorJon Erickson has a formal education in computerscience and has been hacking and programmingsince he was five years old. He speaks at computer security conferences and trains securityteams around the world. Currently, he works as avulnerability researcher and security specialist inNorthern California.j Inspect processor registers and system memorywith a debugger to gain a real understanding ofwhat is happeninglivecd provides a complete linux programming and debugging environmentT H E F I N E ST I N G E E K E N T E RTA I N M E N T w w w.nostarch.com“I LAY FLAT.”This book uses RepKover—a durable binding that won’t snap shut.Printed on recycled paper 49.95 ( 54.95 cdn)shelve in : computer security/network security2nd Editionthe art of exploitationThe included LiveCD provides a complete Linuxprogramming and debugging environment—allwithout modifying your current operating system.Use it to follow along with the book’s examples asyou fill gaps in your knowledge and explore hacking techniques on your own. Get your hands dirtydebugging code, overflowing buffers, hijackingnetwork communications, bypassing protections,exploiting cryptographic weaknesses, and perhapseven inventing new exploits. This book will teachyou how to:j Outsmart common security measures like nonexecutable stacks and intrusion detection systemsCD INsideHACKINGHacking is the art of creative problem solving,whether that means finding an unconventionalsolution to a difficult problem or exploiting holes insloppy programming. Many people call themselveshackers, but few have the strong technical foundation needed to really push the envelope.CD INsideerickson2nd EditionHackingthe art of exploitationjon erickson

PRAISE FOR THE FIRST EDITION OFHACKING: THE ART OF EXPLOITATION“Most complete tutorial on hacking techniques. Finally a book that does notjust show how to use the exploits but how to develop them.”—PHRACK“From all the books I’ve read so far, I would consider this the seminalhackers handbook.”—SECURITY FORUMS“I recommend this book for the programming section alone.”—UNIX REVIEW“I highly recommend this book. It is written by someone who knows of whathe speaks, with usable code, tools and examples.”—IEEE CIPHER“Erickson’s book, a compact and no-nonsense guide for novice hackers,is filled with real code and hacking techniques and explanations of howthey work.”—COMPUTER POWER USER (CPU) MAGAZINE“This is an excellent book. Those who are ready to move on to [the nextlevel] should pick this book up and read it thoroughly.”—ABOUT.COM INTERNET/NETWORK SECURITY

San Francisco

HACKING: THE ART OF EXPLOITATION, 2ND EDITION. Copyright 2008 by Jon Erickson.All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic ormechanical, including photocopying, recording, or by any information storage or retrieval system, without the priorwritten permission of the copyright owner and the publisher.Printed on recycled paper in the United States of America11 10 09 08 07123456789ISBN-10: 1-59327-144-1ISBN-13: 978-1-59327-144-2Publisher: William PollockProduction Editors: Christina Samuell and Megan DunchakCover Design: Octopod StudiosDevelopmental Editor: Tyler OrtmanTechnical Reviewer: Aaron AdamsCopyeditors: Dmitry Kirsanov and Megan DunchakCompositors: Christina Samuell and Kathleen MishProofreader: Jim BrookIndexer: Nancy GuentherFor information on book distributors or translations, please contact No Starch Press, Inc. directly:No Starch Press, Inc.555 De Haro Street, Suite 250, San Francisco, CA 94107phone: 415.863.9900; fax: 415.863.9950; info@nostarch.com; www.nostarch.comLibrar y of Congress Cataloging-in-Publication DataErickson, Jon, 1977Hacking : the art of exploitation / Jon Erickson. -- 2nd ed.p. cm.ISBN-13: 978-1-59327-144-2ISBN-10: 1-59327-144-11. Computer security. 2. Computer hackers. 3. Computer networks--Security measures.QA76.9.A25E75 2008005.8--dc222007042910I. Title.No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product andcompany names mentioned herein may be the trademarks of their respective owners. Rather than use a trademarksymbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to thebenefit of the trademark owner, with no intention of infringement of the trademark.The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has beentaken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to anyperson or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by theinformation contained in it.

BRIEF CONTENTSPreface . xiAcknowledgments . xii0x100Introduction .10x200Programming .50x300Exploitation .1150x400Networking .1950x500Shellcode .2810x600Countermeasures.3190x700Cryptology .3930x800Conclusion .451Index .455

CONTENTS IN DETAILP R E F A CExiA CK N O W LE D G M E N T x2300x2400x2500x2600x2700x280What Is Programming? . 6Pseudo-code . 7Control Structures . 80x231 If-Then-Else. 80x232 While/Until Loops . 90x233 For Loops . 10More Fundamental Programming Concepts . 110x241 Variables . 110x242 Arithmetic Operators . 120x243 Comparison Operators . 140x244 Functions. 16Getting Your Hands Dirty . 190x251 The Bigger Picture . 200x252 The x86 Processor . 230x253 Assembly Language. 25Back to Basics. 370x261 Strings . 380x262 Signed, Unsigned, Long, and Short . 410x263 Pointers . 430x264 Format Strings. 480x265 Typecasting . 510x266 Command-Line Arguments . 580x267 Variable Scoping . 62Memory Segmentation . 690x271 Memory Segments in C . 750x272 Using the Heap . 770x273 Error-Checked malloc() . 80Building on Basics . 810x281 File Access . 810x282 File Permissions . 870x283 User IDs . 880x284 Structs. 960x285 Function Pointers . 1000x286 Pseudo-random Numbers . 1010x287 A Game of Chance . 102

viii115Generalized Exploit Techniques . 118Buffer Overflows . 1190x321 Stack-Based Buffer Overflow Vulnerabilities . 122Experimenting with BASH. 1330x331 Using the Environment. 142Overflows in Other Segments . 1500x341 A Basic Heap-Based Overflow . 1500x342 Overflowing Function Pointers . 156Format Strings. 1670x351 Format Parameters. 1670x352 The Format String Vulnerability. 1700x353 Reading from Arbitrary Memory Addresses . 1720x354 Writing to Arbitrary Memory Addresses . 1730x355 Direct Parameter Access . 1800x356 Using Short Writes . 1820x357 Detours with .dtors. 1840x358 Another notesearch Vulnerability . 1890x359 Overwriting the Global Offset Table . 1900x4000x4100x420E X PL O I T A T I O NN E T W O RK IN G195OSI Model . 196Sockets . 1980x421 Socket Functions. 1990x422 Socket Addresses . 2000x423 Network Byte Order . 2020x424 Internet Address Conversion . 2030x425 A Simple Server Example . 2030x426 A Web Client Example . 2070x427 A Tinyweb Server . 213Peeling Back the Lower Layers. 2170x431 Data-Link Layer. 2180x432 Network Layer . 2200x433 Transport Layer . 221Network Sniffing . 2240x441 Raw Socket Sniffer. 2260x442 libpcap Sniffer . 2280x443 Decoding the Layers . 2300x444 Active Sniffing. 239Denial of Service . 2510x451 SYN Flooding . 2520x452 The Ping of Death. 2560x453 Teardrop . 2560x454 Ping Flooding . 2570x455 Amplification Attacks . 2570x456 Distributed DoS Flooding. 258TCP/IP Hijacking. 2580x461 RST Hijacking . 2590x462 Continued Hijacking . 263C on t en t s in D et ai l

0x4700x480Port Scanning . 2640x471 Stealth SYN Scan . 2640x472 FIN, X-mas, and Null Scans . 2640x473 Spoofing Decoys . 2650x474 Idle Scanning. 2650x475 Proactive Defense (shroud). 267Reach Out and Hack Someone . 2720x481 Analysis with GDB. 2730x482 Almost Only Counts with Hand Grenades . 2750x483 Port-Binding Shellcode . 6600x6700x6800x690281Assembly vs. C . 2820x511 Linux System Calls in Assembly . 284The Path to Shellcode. 2860x521 Assembly Instructions Using the Stack . 2870x522 Investigating with GDB. 2890x523 Removing Null Bytes . 290Shell-Spawning Shellcode. 2950x531 A Matter of Privilege . 2990x532 And Smaller Still. 302Port-Binding Shellcode . 3030x541 Duplicating Standard File Descriptors. 3070x542 Branching Control Structures . 309Connect-Back Shellcode . 3140x6000x6100x620SH E L L CO D EC O U N T E R M E AS U R E S319Countermeasures That Detect . 320System Daemons . 3210x621 Crash Course in Signals . 3220x622 Tinyweb Daemon . 324Tools of the Trade. 3280x631 tinywebd Exploit Tool. 329Log Files. 3340x641 Blend In with the Crowd . 334Overlooking the Obvious . 3360x651 One Step at a Time . 3360x652 Putting Things Back Together Again . 3400x653 Child Laborers . 346Advanced Camouflage . 3480x661 Spoofing the Logged IP Address . 3480x662 Logless Exploitation . 352The Whole Infrastructure . 3540x671 Socket Reuse . 355Payload Smuggling . 3590x681 String Encoding . 3590x682 How to Hide a Sled. 362Buffer Restrictions . 3630x691 Polymorphic Printable ASCII Shellcode. 366C on t en ts in D et ailix

0x6a00x6b00x6c0Hardening Countermeasures. 376Nonexecutable Stack . 3760x6b1 ret2libc . 3760x6b2 Returning into system(). 377Randomized Stack Space . 3790x6c1 Investigations with BASH and GDB . 3800x6c2 Bouncing Off linux-gate . 3840x6c3 Applied Knowledge . 3880x6c4 A First Attempt. 3880x6c5 Playing the Odds . 3900x7000x7100x7200x7300x7400x7500x7600x7700x780C O N C LU S I O N451References. 452Sources . 454I ND E Xx393Information Theory . 3940x711 Unconditional Security . 3940x712 One-Time Pads. 3950x713 Quantum Key Distribution. 3950x714 Computational Security . 396Algorithmic Run Time . 3970x721 Asymptotic Notation . 398Symmetric Encryption. 3980x731 Lov Grover’s Quantum Search Algorithm. 399Asymmetric Encryption . 4000x741 RSA . 4000x742 Peter Shor’s Quantum Factoring Algorithm . 404Hybrid Ciphers . 4060x751 Man-in-the-Middle Attacks . 4060x752 Differing SSH Protocol Host Fingerprints . 4100x753 Fuzzy Fingerprints . 413Password Cracking. 4180x761 Dictionary Attacks . 4190x762 Exhaustive Brute-Force Attacks. 4220x763 Hash Lookup Table . 4230x764 Password Probability Matrix . 424Wireless 802.11b Encryption . 4330x771 Wired Equivalent Privacy . 4340x772 RC4 Stream Cipher . 435WEP Attacks. 4360x781 Offline Brute-Force Attacks. 4360x782 Keystream Reuse . 4370x783 IV-Based Decryption Dictionary Tables . 4380x784 IP Redirection. 4380x785 Fluhrer, Mantin, and Shamir Attack . 4390x8000x8100x820C R YP T O LO G YC on t en ts in D et ai l455

PREFACEThe goal of this book is to share the art of hackingwith everyone. Understanding hacking techniquesis often difficult, since it requires both breadth anddepth of knowledge. Many hacking texts seem esotericand confusing because of just a few gaps in this prerequisite education. Thissecond edition of Hacking: The Art of Exploitation makes the world of hackingmore accessible by providing the complete picture—from programming tomachine code to exploitation. In addition, this edition features a bootableLiveCD based on Ubuntu Linux that can be used in any computer withan x 86 processor, without modifying the computer’s existing OS. This CDcontains all the source code in the book and provides a development andexploitation environment you can use to follow along with the book’sexamples and experiment along the way.

ACKNOWLEDGMENTSI would like to thank Bill Pollock and everyone else atNo Starch Press for making this book a possibility andallowing me to have so much creative control in theprocess. Also, I would like to thank my friends Seth Benson and Aaron Adamsfor proofreading and editing, Jack Matheson for helping me with assembly,Dr. Seidel for keeping me interested in the science of computer science, myparents for buying that first Commodore VIC-20, and the hacker communityfor the innovation and creativity that produced the techniques explained inthis book.

0x100INTRODUCTIONThe idea of hacking may conjure stylized images ofelectronic vandalism, espionage, dyed hair, and bodypiercings. Most people associate hacking with breakingthe law and assume that everyone who engages in hacking activities is a criminal. Granted, there are people outthere who use hacking techniques to break the law, but hacking isn’t reallyabout that. In fact, hacking is more about following the law than breaking it.The essence of hacking is finding unintended or overlooked uses for thelaws and properties of a given situation and then applying them in new andinventive ways to solve a problem—whatever it may be.The following math problem illustrates the essence of hacking:Use each of the numbers 1, 3, 4, and 6 exactly once with anyof the four basic math operations (addition, subtraction,multiplication, and division) to total 24. Each number must beused once and only once, and you may define the order ofoperations; for example, 3 * (4 6) 1 31 is valid, howeverincorrect, since it doesn’t total 24.

The rules for this problem are well defined and simple, yet the answereludes many. Like the solution to this problem (shown on the last page ofthis book), hacked solutions follow the rules of the system, but they use thoserules in counterintuitive ways. This gives hackers their edge, allowing them tosolve problems in ways unimaginable for those confined to conventionalthinking and methodologies.Since the infancy of computers, hackers have been creatively solvingproblems. In the late 1950s, the MIT model railroad club was given a donation of parts, mostly old telephone equipment. The club’s members used thisequipment to rig up a complex system that allowed multiple operators to control different parts of the track by dialing in to the appropriate sections. Theycalled this new and inventive use of telephone equipment hacking ; manypeople consider this group to be the original hackers. The group moved onto programming on punch cards and ticker tape for early computers like theIBM 704 and the TX-0. While others were content with writing programs thatjust solved problems, the early hackers were obsessed with writing programsthat solved problems well. A new program that could achieve the same resultas an existing one but used fewer punch cards was considered better, eventhough it did the same thing. The key difference was how the programachieved its results—elegance.Being able to reduce the number of punch cards needed for a programshowed an artistic mastery over the computer. A nicely crafted table can holda vase just as well as a milk crate can, but one sure looks a lot better than theother. Early hackers proved that technical problems can have artistic solutions, and they thereby transformed programming from a mere engineeringtask into an art form.Like many other forms of art, hacking was often misunderstood. The fewwho got it formed an informal subculture that remained intensely focusedon learning and mastering their art. They believed that information shouldbe free and anything that stood in the way of that freedom should be circumvented. Such obstructions included authority figures, the bureaucracy ofcollege classes, and discrimination. In a sea of graduation-driven students,this unofficial group of hackers defied conventional goals and instead pursuedknowledge itself. This drive to continually learn and explore transcendedeven the conventional boundaries drawn by discrimination, evident in theMIT model railroad club’s acceptance of 12-year-old Peter Deutsch whenhe demonstrated his knowledge of the TX-0 and his desire to learn. Age,race, gender, appearance, academic degrees, and social status were notprimary criteria for judging another’s worth—not because of a desire forequality, but because of a desire to advanc

HACKING: THE ART OF EXPLOITATION “Most complete tutorial on hacking techniques. Finally a book that does not just show how to use the exploits but how to develop them.” —PHRACK “From all the books I’ve read so far, I would cons